mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 02:27:26 +01:00
4a38e5cbcef9dc2268249e4e6d97a48cb6805ff9
120
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
4a38e5cbce |
G5-5C #1: probe loop skeleton + lifecycle tests
First production batch for the G5-5C primary-side degraded-peer probe loop, per the architect-bound mini-plan v0.5 §1.A binding (Option B, core/replication/ ownership) and §1.H audit-PASS verdict at seaweedfs@9245446b5. Files: - core/replication/probe_loop.go (new): ProbeLoop struct with config + start/stop lifecycle (sync.Once on both); per-iteration tick that snapshots peers via PeerSourceFn, gates each via CooldownFn, dispatches via ProbeFn; CP4B-2 lessons applied (zero-interval rejected at construction; stop-before-start no deadlock; callback panic isolated via recover). - core/replication/probe_loop_test.go (new): seven lifecycle tests covering Start/Stop happy path, stop-before-start, idempotent concurrent stop, zero-interval rejection, callback panic isolation, cooldownFn gating, empty peer set, and probeFn-error-doesn't-stop. Design: - ProbeLoop is runtime/wiring only. No engine FSM, no transport. - Seams (PeerSourceFn / ProbeFn / CooldownFn) injected by host so the loop knows nothing about adapter, executor, or engine. - Default config: Interval 5s, MaxConcurrent 1, CooldownBase 5s, CooldownCap 60s — architect-bound G5-5C v0.5 §1.A shape. - Authority-bound (§1.E): peersFn snapshots ReplicationVolume.peers under lock; loop never enumerates network-discoverable addresses. - All G5-5C INVs map cleanly to existing engine/replication state per the §1.H audit; this skeleton adds NO recovery substrate. Tests verified: - go test ./core/replication/ -run TestProbeLoop -count=1: PASS (7/7) - go test ./core/replication/ -count=1: PASS (no regression on existing T4a-5/T4b/T4c suites) Next batch (G5-5C #2): peer.go::ProbeIfDegraded() + cooldown state-machine + in-flight guard tests. |
||
|
|
6729babae5 |
G5-5 round 14: pre-flight stale-iptables cleanup in start_cluster
Investigation found root cause of round-13 silent failures: M02 had a leftover INPUT DROP rule from an earlier run's verify_network_catchup that used the OLD pattern (`iptables -I INPUT` on M02). When that earlier run aborted via set -e before reaching its cleanup `iptables -D`, the rule persisted across runs. Round 13's rewrite changed to OUTPUT-on-m01 but didn't clean up the legacy INPUT-on-M02 leftover. The stale rule blocked m01→M02:9221 ship/barrier traffic for ALL subsequent runs; primary's peer entered degraded state on first ship attempt; all rounds after the original poisoning incident saw the symptom "replica daemon dies silently" because the SCRIPT's pkill found nothing (replica had been killed by the script's own pkill but no ship traffic ever flowed during the run). Diagnosis sequence: 1. ssh m01→M02:9221 TCP test: timeout (FAIL=124) 2. m01 iptables: empty (rules out m01-side block) 3. M02 iptables INPUT: `DROP tcp dpt:9221` (~50 dropped pkts) 4. `iptables -D INPUT -p tcp --dport 9221 -j DROP` on M02 5. Re-test: ssh→TCP echo OK 6. Re-run: chain flows through to all 3 verify steps Fix: start_cluster() now drops both possible patterns pre-flight: - sudo iptables -D OUTPUT -d -p tcp --dport -j DROP (round-13 pattern) - sudo iptables -D INPUT -p tcp --dport -j DROP (round-12 leftover) Both with || true so missing rules don't fail set -e. Round-14 result on m01: ✓ verify_cluster_ready ✓ verify_byte_equal (LBA[0]=0xab) ✓ verify_network_catchup (LBA[1]=0xcd byte-equal in 8s after iptables disconnect+heal) ✗ verify_restart_catchup (LBA[2]=0xef MISMATCH — real recovery-path finding) The verify_restart_catchup failure is exactly the case architect ruling 2 named: 'run #4 naively first; if it doesn't converge, that is a real recovery-path finding to surface, not a test flaw.' Primary's log evidence: After replica killed → ship attempt → barrier timeout → peer invalidated (degraded). Primary writes LBA[2]=0xef while replica down → 'ship gate-degraded peer=r2 lba=2 lsn=3 (peer degraded)' — ship is gated out before any TCP attempt. Replica restarts; no mechanism triggers primary to re-establish the peer connection or re-ship the missed entries. Architecturally the engine-driven catch-up path needs a trigger (probe success, assignment re-emit, etc.) to bring a degraded peer back online + replay missed LSNs. G5-5 surfaces that this trigger isn't wired into the binary's runtime — surface for architect / QA decision: (a) defer #4 to a follow-up batch with a dedicated peer-recovery fix; (b) implement now within G5-5 scope. Refs: round 14 m01 self-iteration; investigation traced 4 indirection layers to find the leftover iptables rule. |
||
|
|
b3f90387e3 |
G5-5 round 13: rewrite #3/#4 to byte-equal pattern + helpers
Per architect ratification round 13 + QA planning input:
- Add wait_until_byte_equal(lba, pattern, deadline_s) helper —
cycles kill→m01verify→restart per poll until match or timeout.
Caller-side honest about OpenReadOnly's no-concurrent-writer
assumption.
- Add iscsi_write_pattern(lba, count, pattern) helper using
python3 binary write (byte-exact pattern; tr does not grok
\xHH escapes per round-12 finding).
- Rewrite verify_network_catchup with iptables OUTPUT drop on
m01 toward M02_IP:M02_REPLICA_DATA_PORT. trap RETURN ensures
iptables -D runs on any exit path. Pass condition is direct
byte-equal at LBA[1]=0xcd, not engine-state H/R polling.
- Rewrite verify_restart_catchup with replica killall+restart
pattern. Run NAIVELY first per architect ruling — if catch-up
doesn't converge with BestEffort durability, that is a real
recovery-path finding to surface, not a test flaw.
- Diagnostic snapshots from /status/recovery kept as supporting
evidence only, not pass/fail oracle.
KNOWN ISSUE — round 13 self-test on m01: even verify_byte_equal
(which worked on round 12 part C) now fails before reaching
m01verify. Replica daemon on M02 dies silently after recording
supersede; subsequent SSH_M02 pkill matches nothing → set -e
exit. Replica's primary log ends at 'recording supersede, not
applying to adapter'; no exit/panic/SIGSEGV trace in journalctl
or dmesg. Needs further investigation:
- Is replica daemon exiting cleanly via some path I'm not aware of?
- Is there an unbuffered panic going to /dev/null because of
setsid+nohup+</dev/null?
- Was round-12-part-C's success actually flaky?
Pausing self-iteration here. Round 13 rewrite is complete in
script; #2 byte-equal already proven on hardware in round 12
part C (committed at
|
||
|
|
82e9018bae |
G5-5 round 12 part C: fix dd 0xab fill (tr lacks \xHH escape support)
QA round 12 self-test on m01: m01verify reported MISMATCH on LBA 0 — but inspecting the bytes via xxd showed the primary's on-disk file matched the replica's, both 0x78 (ASCII 'x') × 4096. Replication chain is correct; the script wrote the wrong bytes. Root cause: the script used 'tr "\0" "\xab"' which DOES NOT produce 0xab. tr's escape grammar recognizes only octal (\NNN) and a small set of letter escapes (\n, \t, ...); \xHH is not understood — tr substitutes with the literal first char of the replacement string, which is '\' parsed loosely giving 'x' (0x78). Verified empirically on m01: $ dd if=/dev/zero bs=4096 count=1 2>/dev/null | tr "\0" "\xab" | xxd | head -1 00000000: 7878 7878 7878 7878 7878 7878 7878 7878 xxxxxxxxxxxxxxxx Fix: use python3 binary write — guaranteed byte-exact 0xab fill: python3 -c "...sys.stdout.buffer.write(b'\xab' * 4096)..." Round 12 part C result on m01: ✓ verify_cluster_ready ✓ verify_byte_equal — m01verify reports 'OK 1 LBA(s) byte-equal' This is the FIRST end-to-end PASS of acceptance criterion #2 on real hardware. The replication chain (lineage latch + ship + barrier + apply) is verified working. verify_network_catchup still hits H-advance false-positive (engine state semantic is probe-driven, not local-write-driven; same as fix in #2 but applied per-step); will address next. Refs: round 12 m01 self-test full progression (rounds 1-11 surfaced 14 distinct bugs each isolated and fixed). |
||
|
|
8d6c4a807b |
G5-5 round 12 part B: fix walstore filename v1.walstore → v1.bin
m01verify in verify_byte_equal expected v1.walstore but durable provider's volumePath uses VolumeID+".bin" (provider.go:133). Same fix in verify_network_catchup and verify_restart_catchup helpers if they reference the file path. |
||
|
|
2c1ee6e3e5 |
G5-5 round 12: drop H-advance preflight in verify_byte_equal
Engine's Recovery.H is updated by probe events (RecoveryFactsObserved), not by local writes. At adoption time engine sets H = walHead = nextLSN (already 1 for empty walstore); local write at LSN=1 advances nextLSN to 2 internally, but Recovery.H stays at 1 until a probe re-reads boundaries. Using H-advance as a 'silent write failure' preflight produces a false positive — H stays at 1, check fails, but the actual write + ship + barrier all completed (per primary log evidence). Round 11+12 m01 evidence shows the full chain flows: durable: dp.Open latching identity volume=v1 replica=r1 epoch=1 ev=1 durable: StorageBackend.SetIdentity latched ... iscsi: SCSI WRITE handler lba=0 transferLen=8 dataOut=4096 durable: StorageBackend.Write entry offset=0 len=4096 durable: write observer dispatch lba=0 lsn=1 replication: OnLocalWrite volume=v1 lba=0 lsn=1 peers=1 transport: ship lazy-dial replica=r2 ok replication: ship ok peer=r2 lba=0 lsn=1 iscsi: SCSI WRITE backend.Write ok lba=0 iscsi: SCSI SYNCHRONIZE_CACHE handler entry replication: barrier wait peer=r2 targetLSN=1 epoch=1 replication: barrier ack peer=r2 targetLSN=1 achievedLSN=1 iscsi: SCSI SYNCHRONIZE_CACHE backend.Sync ok Replication is working end-to-end on m01+M02 hardware. Fix: replace H-advance check with informational log; let m01verify byte-equal compare be the actual proof. Same change unchanged for verify_network_catchup and verify_restart_catchup (they still use H comparisons but for different semantics — catch-up convergence, where H is the engine-level boundary and the comparison is against replica's R, which the engine DOES update on session completion). Refs: round 12 self-test on m01 cross-node — chain flows end-to-end; H-advance was the only false-positive blocking m01verify from running. |
||
|
|
2e8c3a0469 |
G5-5 fix v2: latch on Epoch=0, not all-fields-zero (round-11 bug)
QA round 11 reported the
|
||
|
|
41045e542f |
G5-5 fix: latch StorageBackend.Identity post-Healthy via dp.Open
QA round 10 disambiguated: the iSCSI write reached
StorageBackend.Write but gate-rejected with 'frontend: stale
primary lineage'. Root cause: G5-5 introduced EnsureStorage which
constructs the StorageBackend BEFORE the assignment fact lands.
Original V3 design: dp.Open blocks on waitHealthy; the backend
is constructed AFTER projection.Healthy=true; wrap() captures
proj.Epoch/EV at that moment as the immutable Identity.
G5-5 changed: replicas need open storage even when projection
won't reach Healthy (their authority is the bound primary).
EnsureStorage opens storage role-agnostically. But it ALSO
constructs the backend at construction time — and at that
moment view.Projection() returns zero values (no assignment
landed yet). The captured Identity is zero. Once the assignment
lands and projection flips Healthy with Epoch=1/EV=1, every
subsequent gate compares proj{Epoch:1, EV:1, ...} against
b.id{Epoch:0, ...} and returns ErrStalePrimary.
V2 reference confirms: V2's iscsi.BlockDevice → vol.WriteLBA path
uses the engine's CURRENT epoch (not a captured one), so V2
doesn't have this issue. V3's snapshot model is sound; what's
missing is a re-stamp on first promotion to Healthy.
Fix: add SetIdentity(id) to StorageBackend with latch-from-zero
semantic.
- Latch-from-zero: zero-id backend transitions to the supplied
identity. One-shot — subsequent calls with a different id
are REJECTED (returns false). Preserves the failover safety
net (lineage drift past the latched value still fails closed
via lineageCheck → ErrStalePrimary).
- dp.Open's success path (after waitHealthy) now calls
h.backend.SetIdentity() with the current projection's lineage.
Idempotent for already-latched same-value backends.
Test: TestG5_5_SetIdentity_LatchFromZero — covers (a) zero →
first identity (allowed), (b) same identity again (no-op), (c)
drift attempt (rejected, identity unchanged so lineageCheck
fail-closed still works). Runs against both walstore + smartwal.
Tests still green: durable (0.6s), blockvolume (16.5s, G5-4
integration test still PASS), master, authority.
Refs: QA round 10 — gate-rejected disambiguation; V2 reference
read confirms architectural diff (V2 vol.WriteLBA uses live
epoch; V3 captures snapshot).
|
||
|
|
4ec7bd0c2e |
G5-5 instrumentation: SCSI handler + StorageBackend.Write entry
QA round 9 confirmed: even durable: write observer line is missing.
The iSCSI WRITE never reaches StorageBackend.writeBytes. Need to
walk further upstream — either the iSCSI handler isn't getting the
SCSI WRITE command, or it's getting it but using the wrong backend.
Add 6 instrumentation lines across two layers:
core/frontend/iscsi/scsi.go (doWrite):
- SCSI WRITE handler entry (fires on every WRITE_10/16 arrival)
- SCSI WRITE rejected (LBA out of range)
- SCSI WRITE rejected (short dataOut)
- SCSI WRITE backend.Write FAILED
- SCSI WRITE backend.Write ok
core/frontend/iscsi/scsi.go (handleSCSI SYNC_CACHE branch):
- SCSI SYNCHRONIZE_CACHE handler entry
- SCSI SYNCHRONIZE_CACHE backend.Sync FAILED
- SCSI SYNCHRONIZE_CACHE backend.Sync ok
core/frontend/durable/storage_adapter.go (Write):
- StorageBackend.Write entry (every Write call)
- StorageBackend.Write gate-rejected (gate() returned err)
Disambiguation matrix for QA's next run:
No 'iscsi: SCSI WRITE handler' line:
→ iSCSI session/login layer rejects command before SCSI handler.
Check if Normal session established correctly; check whether
initiator's volume sees the right size via READ_CAPACITY.
iscsi: SCSI WRITE handler line present, but no
durable: StorageBackend.Write entry:
→ SCSI handler reaches a DIFFERENT backend instance (not the
observer-wired StorageBackend). Wiring fix in main.go required.
iscsi: SCSI WRITE handler + durable: StorageBackend.Write entry,
but no observer dispatch:
→ backend gate() rejected (closed/non-operational/lineage drift).
gate-rejected line fires.
All instrumentation fires through to ship/barrier:
→ Replication is working.
Tests still green: iscsi (30.9s), durable (0.5s), blockvolume (16.7s).
Refs: QA round 9 — observer line missing from upstream
instrumentation; need iSCSI-side disambiguation.
|
||
|
|
c6bace4e79 |
G5-5 upstream instrumentation: observer + OnLocalWrite + ship gates
QA round 8: ALL 6 ship/dial/barrier lines from |
||
|
|
7a3996d2b0 |
G5-5 ship/dial/barrier instrumentation (suspect B disambig)
QA round 7 confirmed peers=1 — master delivers peer set correctly, including routable address (r2@192.168.1.184:9221). The fsync I/O error is on the SHIP side. Sub-suspects: (a) lazy-dial never triggered (e.g., peer state == Degraded before first ship; ShipEntry returns early) (b) lazy-dial triggered but TCP dial failed (c) dial succeeded but frame write failed (handshake/framing) (d) ship ok, but barrier wait never gets ack (timeout silently) Add 6 INFO log lines at the suspect surfaces so the next re-run disambiguates which sub-case is firing: core/replication/peer.go (ShipEntry): - on ship FAILED: peer + addr + lba + lsn + err - on ship ok: peer + lba + lsn core/replication/peer.go (Barrier): - on barrier wait: peer + addr + targetLSN + epoch - on barrier FAILED: peer + addr + targetLSN + err - on barrier ack: peer + targetLSN + achievedLSN core/transport/ship_sender.go (Ship lazy-dial): - on lazy-dial entry: replica + addr + sessionID + lsn - on lazy-dial FAILED: replica + addr + err - on lazy-dial ok: replica + addr Replica-side already logs replica_apply on receive (existing). With both sides logged, QA's next run should clearly show the failing hop. No behavior change; small log footprint. Tests still green: core/replication, core/transport, cmd/blockvolume (incl. G5-4 integration test). Refs: QA round 7 disambiguation (peers=1 confirmed; ship-side instrumentation needed). |
||
|
|
5187083fc6 |
G5-5 logging: INFO line on UpdateReplicaSet success + adopted-as-primary
QA round 6 finding: primary log silent on replication; can't
disambiguate 'peers=0 delivered' (timing gap) from 'peers=N delivered
but ship failed' (TCP/network). Pre-existing log discipline only
emits on the FAILURE branches:
- line 488: recording supersede (when fact.ReplicaID != self)
- line 502: UpdateReplicaSet failed
Add INFO logs on the success path so operators / hardware-test
harness can see what's actually being installed without -v / debug
flags:
blockvolume: volume v1 replication UpdateReplicaSet ok (gen=N,
peers=K): [r2@192.168.1.184:9221 ...]
blockvolume: volume v1 adopted as PRIMARY at r1@1 (EV=1)
Small log footprint (one line per fact emission, fact emissions
are rare). Production-acceptable verbosity. No behavior change.
Tests: cmd/blockvolume integration test still PASS (16.4s);
core/host/volume green.
Refs: QA round 6 — primary-fail.log silence.
|
||
|
|
2347ccb72d |
G5-5A round 54 follow-ups: freshness gate + lineage rule + comment
Architect review round 54 findings (3 items, all addressed):
HIGH 1 — SlotFact ignores freshness:
ObservationStore explicitly says expired observations stay
visible but are 'semantically ineligible for supported snapshot
synthesis'. SlotFact was scanning the full observation map
without checking ExpiresAt. For peer-set construction this is
wrong: a stale heartbeat addr is unsafe to dial.
Fix: SlotFact now skips observations where now > obs.ExpiresAt.
New test TestObservationStore_SlotFact_ExpiredObservation_FailsClosed
verifies the boundary (ok=true within FreshnessWindow,
ok=false past expiry).
HIGH 2 — path 1 mis-stamps live-ship lineage:
resolvePeers path 1 was using the peer's OWN LastPublished
Epoch/EV. If LastPublished(v1, r2) returns r2's retained
historical authority line (e.g., r2 was previously bound at
Epoch=N before reassignment to r1 at Epoch=N+1), primary r1
would stamp live-ship frames under r2's old N — breaks the
apply gate at the replica which expects current authority.
Fix: BOTH paths now stamp peer.Epoch/EV with subscriber's
lineage. Authority/observation supplies addresses only;
subscriber stamps lineage. Updated TestResolvePeers_BothBound
to pin this (peer's old 4/1 must NOT win over subscriber's
5/2). path-1-preferred test still passes — it's about which
ADDR wins, not lineage.
LOW 3 — stale comment:
collectPeers godoc still claimed observation-derived peers
'carry Epoch=0 + EndpointVersion=0 to mark observation-derived'.
Out of date since round-54 inheritance fix. Rewrote comment
block to reflect current rule: both paths stamp subscriber's
lineage; authority/observation supplies addresses only.
All G5-5A tests still pass (10/10); cmd/blockvolume G5-4
integration test PASS; full V3 suite green.
Refs: architect round 54 review of
|
||
|
|
61f5ff62a8 |
G5-5A: master peer-set from observed supporting replicas
Architect ratification round 54 (2026-04-27): collectPeers may
synthesize peer descriptors for topology slot members observed by
heartbeat even when they don't have a bound authority publication.
Root cause from QA round 54: V3 controller only mints
AssignmentInfo for the BOUND replica (Publisher.apply path).
Supporting replicas have no published authority line, so
master.collectPeers' pub.LastPublished returns false for them,
peers list is empty, primary's ReplicationVolume has no peers,
fan-out/Sync barrier has no acks → iSCSI fsync I/O error.
Architect Option A (chosen): collectPeers falls back to
ObservationStore for slot members without published lines.
Topology membership is the allow-list (option R / arbitrary
observed nodes still rejected). Authority state stays clean —
Option B (mint presence records into pub.state) was rejected.
Implementation:
core/authority/observation_store.go:
+ SlotFact(volumeID, replicaID) — returns latest-observation
SlotFact across all servers; fail-closed on empty DataAddr.
core/host/master/services.go:
collectPeers signature changes from (volumeID, selfReplicaID
string) to (volumeID string, selfInfo adapter.AssignmentInfo)
so observation-derived peers can inherit subscriber's Epoch/EV.
Body extracted to pure helper resolvePeers() for testability.
Peer construction policy:
Path 1: pub.LastPublished hits → use authority Epoch/EV/addrs
Path 2: SlotFact hits → use heartbeat addrs + INHERIT
SUBSCRIBER'S Epoch/EV (live ships carry primary's
lineage; replica validates against it)
Else: skip fail-closed
Inheriting subscriber's Epoch/EV is required because
ReplicaPeer constructor (replication/peer.go:130) rejects
zero values — the lineage stamps every outgoing live-ship
frame, and primary's authority is what the supporting replica
validates against.
Tests:
core/authority/observation_store_slotfact_test.go: 5 tests
(round trip, empty store, fail-closed empty addr,
latest-wins across servers, vol/replica mismatch)
core/host/master/services_g5_5a_test.go: 5 tests
(headline r1-bound + r2-observed-only, both bound,
neither bound nor observed, nil obs store, path-1 wins
over path-2)
All 10 G5-5A tests pass; full V3 suite green (23/23 packages
incl. cmd/blockvolume G5-4 integration test still green).
No engine/adapter behavior change — touches master/observation
peer-set construction only.
Refs: QA round 54 finding (cross-host fsync I/O error);
architect Option A ratification 2026-04-27.
|
||
|
|
715ed15abf |
G5-5 script: bind+advertise routable IP, not 0.0.0.0 (cross-host fix)
QA round 54: cluster came up, iSCSI session established, but
fsync (SYNCHRONIZE CACHE) returned I/O error. Root cause: replica
bound --data-addr 0.0.0.0:9221 AND advertised that string to master
heartbeat. Master minted AssignmentFact.peers[*].DataAddr=0.0.0.0:9221.
Primary's BlockExecutor tried to dial 0.0.0.0:9221 — unroutable
destination — connection failed. Replication fan-out + Sync barriers
silently failed (best-effort log line; the fsync gets I/O error).
The daemon advertises the literal --data-addr string verbatim:
cmd/blockvolume/main.go:230 → cfg.DataAddr = f.dataAddr
→ host heartbeats DataAddr to master
→ master.collectPeers copies it into AssignmentFact.peers
→ primary dials peers[*].DataAddr
So for cross-host the bind addr MUST be a routable IP, not 0.0.0.0.
On Linux, binding to a specific local-interface IP works fine and
ensures the literal advertised string is routable.
Fix: extract M01_IP / M02_IP from M01_HOST / M02_HOST and use as
both bind and advertise:
Tier 2: M01_PRIMARY_BIND_IP=${M01_IP}, M02_REPLICA_BIND_IP=${M02_IP}
Tier 1: M01_PRIMARY_BIND_IP=127.0.0.1, M02_REPLICA_BIND_IP=127.0.0.1
start_primary / start_replica now use the IP variables for both
--ctrl-addr and --data-addr. Master's --listen stays 0.0.0.0 (it's
the destination of heartbeats, not advertised).
This is a script-side fix only; daemon code unchanged. Refs QA
round 54.
|
||
|
|
e83827a102 |
G5-5 script: drop -n from launch ssh (conflicts with bash -s stdin)
QA round 53 isolation: SSH_OPTS included -n which redirects ssh stdin from /dev/null. With bash -s, remote bash reads script from stdin — stdin is EOF (because -n) so bash exits immediately, daemon never starts, master.log stays empty. QA evidence: dbg.sh on m01 reproduced heredoc form WITHOUT -n; bash -s correctly read heredoc, blockmaster launched, port 9180 bound, proof.txt confirmed heredoc execution. Fix per architect option (A): split SSH options into two sets: SSH_OPTS_BASE — shared: -T (no PTY) + BatchMode=yes SSH_OPTS — base + -n; for ssh host CMD patterns SSH_OPTS_LAUNCH — base only (no -n); for ssh host bash -s launch_m01 / launch_m02 use SSH_OPTS_LAUNCH. PTY-hang protection comes from -T alone, present in both sets. Verified: launch_m01 heredoc body executes; variable expansion works; remote-shell PID resolves correctly. |
||
|
|
20d04965d9 |
G5-5 script: bash -s heredoc launch (option A) — fix line-collapse hang
QA round 53 finding (Tier 2 m01 → M02): start_replica's SSH session
hung even on Linux (m01 native ssh, no Windows-Git-Bash quirks).
Root cause is a `\<newline>` line-collapse hazard in the
double-quoted SSH command argument:
$SSH_LAUNCH_M02 "
setsid nohup /tmp/g5-blockvolume \
--master ... \
...
> .../replica.log 2>&1 </dev/null &
disown \$! 2>/dev/null || true
sleep 1
exit 0"
The local shell processes `\<newline>` as line continuation INSIDE
the double-quoted string. The `\` at end of every option line
collapses lines, which can in some bash interactions produce a
joined argv where `&` runs into `disown` directly with no
separator. Remote bash then parses the joined statement
incorrectly, never executes `disown $!` / `sleep 1` / `exit 0`,
remains attached to the bg daemon, and SSH hangs.
The `\<newline>` substitution happens in the LOCAL shell (the one
running iterate.sh), so it's not Windows-Git-Bash-specific —
reproduces on m01 (Linux) too.
Fix per architect option (A) round 53: pipe the command body to
remote bash via `bash -s` heredoc instead of double-quoted ssh
argument.
launch_m01 <<EOF
setsid nohup CMD ARG1 ARG2 ... > LOG 2>&1 </dev/null &
disown \$! 2>/dev/null || true
sleep 1
exit 0
EOF
With heredoc + `bash -s`:
- body is piped to remote bash's stdin verbatim
- newlines are preserved literally regardless of any local
shell processing
- statement boundaries are unambiguous
- daemon command on a single line (no `\<newline>` continuations)
eliminates the entire ambiguity class
Implementation:
- new launch_m01() / launch_m02() functions handle Tier 1
(LOCAL_MODE=1, run via local `bash -s`) and Tier 2 (run via
`ssh ... bash -s`) with shared timeout-prefix logic
- start_master / start_primary / start_replica use the new
helpers + heredoc body
- removed SSH_LAUNCH_M01 / SSH_LAUNCH_M02 vars (subsumed by
launch_m01 / launch_m02)
Verified: local Tier-1-style smoke test launches a `sleep 30` bg
process, disowns it, and exits within 1.08s (the explicit `sleep
1` + overhead). Pre-fix this took ~5s (timeout fallback). The bg
process detached and ran independently. This proves all three
post-`&` statements (disown / sleep / exit) execute as separate
commands — the line-collapse hazard is structurally eliminated.
Refs: QA Tier 2 round 53 finding (Linux SSH hang); architect
option (A) ratified; option (B) `;<newline>` rejected per QA's
clarification (newlines also stripped by `\<newline>` so
semicolons alone don't help).
|
||
|
|
994ad4e842 |
G5-5 script: PREBUILT_BIN_DIR Tier 2 fast-path + SRC_DIR safety guard
Architect option (a) ratified round 53. Two changes to sync_and_build:
1. PREBUILT_BIN_DIR fast-path for Tier 2 (cross-node m01+M02):
When PREBUILT_BIN_DIR is set, skip source-tar + remote-build
entirely. scp the 3 pre-built binaries (g5-blockmaster,
g5-blockvolume, g5-m01verify) directly to m01:/tmp/ and onward
to M02. Mirrors the existing LOCAL_MODE branch pattern.
Use case: Windows workstation cross-compiles via
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o ...
then sets PREBUILT_BIN_DIR=/path/to/bins. No m01-side source
tree or `go` install needed. Also works for CI artifact paths.
2. SRC_DIR safety guard (the bug QA hit round 53):
When iterate.sh is copied away from the repo and run with
SRC_DIR resolving to "" or "/" (e.g., bash /tmp/iterate.sh
without overriding SRC_DIR), the prior code called
`cd "$SRC_DIR" && tar -czf /tmp/g5-src.tgz .`
which tarred the root filesystem. QA killed it before damage,
but the unsafety must not exist.
Guard sequence (refuses with named error before any tar):
- SRC_DIR empty or "/" → die
- SRC_DIR/go.mod missing → die
- SRC_DIR/cmd/blockvolume/ → die
- else → safe to tar
Verified all 4 die paths fire with clear messages: empty, "/",
non-repo path, PREBUILT_BIN_DIR with missing binary.
Acceptance criteria #1-#7 unaffected; only the build/sync mechanism
changes. The 4 verify_* scenario bodies are untouched.
Refs: QA Tier 2 round 53 finding (SMB-driven iterate.sh attempted
to tar root filesystem); architect option (a) binding.
|
||
|
|
0769d67fa5 |
G5-5 script: fix Windows-Git-Bash SSH-launch hang (-T -n + timeout)
QA Tier 2 m01 cross-node verification surfaced: cluster comes up
correctly (master + primary + replica all start, replica logs
"authority is now r1@1; recording supersede" — exactly the
architect-binding role split), but the Windows Git Bash side of
start_replica's SSH session never returns even though the remote
process is detached via setsid+nohup+disown.
Root cause: OpenSSH on Windows Git Bash allocates a PTY for the
remote shell (default behavior when stdin is a terminal); the
local ssh client waits for the PTY to detach, which never happens
even after setsid. Standard Git Bash quirk; well-documented but
not previously hit by V3 because prior cross-node scripts used
short-lived SSH calls only.
Two-layer fix:
1. Add -T (no PTY) and -n (close local stdin) to all SSH commands
via shared SSH_OPTS variable. -T is the primary fix; -n was
already added by prior edit but is insufficient alone.
2. Wrap launch-and-detach SSH calls (start_master/_primary/_replica)
with `timeout 15 --preserve-status` as defense-in-depth. If SSH
still hangs (rare with -T -n applied), the script moves on after
15s. Remote process is already disown'd so the only stale state
is a local ssh client process — harmless. Falls back to no-op
wrapper if `timeout` isn't installed (Git Bash without coreutils).
Also tightens remote launch heredoc:
- explicit `disown $!` after backgrounding to detach from job table
- explicit `exit 0` to force the wrapping shell to exit cleanly
even if any prior command had a non-zero status
Tested: bash -n syntax clean; timeout available on local box; no
local-mode regression (LOCAL_MODE=1 path uses bash -c, not ssh).
Refs: QA Tier 2 round 53 finding; environmental, not a product bug
(daemon comes up correctly on cross-node hardware per the same
session's logs).
|
||
|
|
71f93f6cd8 |
G5-5 script: two-tier (LOCAL_MODE) + architect findings + SSH detach
Architect round-52 findings absorbed:
- iscsi-listen 0.0.0.0 → 127.0.0.1 (T2 iSCSI loopback-only rule)
- remote SSH bash blocks: set -euo pipefail + DEV non-empty assert
+ primary.H advancement check (catches silent dd failure masking)
- RecoveryDecision empty no longer acceptable: must observe
explicit catch_up transition or fail
- (walstore.OpenReadOnly already correct per sw earlier commit)
Two-tier mode added:
- LOCAL_MODE=1: single Linux host (e.g. WSL); both processes on
localhost; iSCSI/race/full-suite skip if iscsiadm/Go-too-old
- LOCAL_MODE=0 (default): m01 cross-node Tier 2
Tier 1 verified PASS on WSL (cluster bring-up + role split; iSCSI
tests cleanly skip).
SSH detach fixes:
- pkill -f '[g]5-block' (regex character class avoids self-match)
- setsid nohup ... & (replaces & disown; full process group break)
- ssh -n (no stdin; helps SSH session cleanup on Windows Git Bash)
Tier 2 (m01) status: cluster comes up correctly end-to-end (master +
primary + replica all running; replica logs role-split supersede),
but SSH session for start_replica step doesn't return cleanly from
Windows Git Bash — known SSH-from-Windows quirk. Tier 2 should run
from a Linux SSH host OR with ProxyJump to avoid Windows-side hang.
Tier 1 evidence is sufficient for criteria #1 (cluster ready, role
split). Criteria #2/#3/#4 require iSCSI which neither WSL (no
open-iscsi) nor Tier 2 (Windows-SSH hang) currently runs end-to-end.
Carry: Tier 2 on Linux-host SSH OR install open-iscsi on WSL.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
1caaf9c291 |
G5-5 script: LOCAL_MODE Tier 1 (localhost) for fast dev iteration
Add two-tier test mode to iterate-m01-replicated-write.sh:
Tier 1 (LOCAL_MODE=1): both processes on localhost, no SSH/scp
- drives faster dev iteration (no cross-node sync overhead)
- iSCSI tests skip with explicit message if iscsiadm not present
- intended for WSL/Linux dev workstation iteration before
escalating to cross-node m01/M02 verification
Tier 2 (default, LOCAL_MODE=0): m01 (192.168.1.181) + M02
(192.168.1.184) cross-node — deployment-realism close evidence
Implementation:
- SSH_M01/SSH_M02 redefined as `bash -c` in LOCAL_MODE
- sync_and_build skips tar/scp in LOCAL_MODE; builds locally
- master subscribe target switched to 127.0.0.1 vs 192.168.1.181
- HAS_ISCSI sentinel set per-mode for skip messaging
|
||
|
|
94edc46197 |
G5-5 round-52 fixes: read-only opener no goroutines + script fail-closed
Addresses architect/QA review round 52 findings:
MEDIUM — OpenReadOnly inherited writer machinery:
Original implementation reused openInitialized which started
flusher + committer + admission goroutines and persisted the
superblock back through Close. Those writes target the fd
opened O_RDONLY — silent OS-layer failure but a "read-only
verifier" leak.
Rewrite: WALStoreReader is now a minimal handle (fd + sb + dm)
with its own Read/Close paths. No openInitialized call, no
background goroutines, Close only releases the fd. Same
WAL-then-extent merge semantic for Read(lba); recoverWAL is
invoked directly to populate the dirty map (it's a pure read
pass over WAL frames — no fd writes).
Pinned by new TestOpenReadOnly_NoBackgroundGoroutines that
snapshots runtime.NumGoroutine() before/after Open+Read+Close
and asserts no growth (tolerance 1 for runtime jitter; flusher
+ committer alone would add 2).
HIGH — verify_byte_equal could false-pass on silent write failure:
Same hardening pattern already applied to verify_network_catchup
+ verify_restart_catchup (user-applied edits) now extended to
verify_byte_equal:
- remote SSH heredoc uses `set -euo pipefail`
- DEV non-empty assertion before dd
- primary.H captured before + after, asserted strictly greater
(catches silent-write-failure masking before the byte-equal
check ever runs)
- explicit echo "WROTE-LBA-0-PATTERN-AB" stamped on success
so the surrounding script can grep for the marker if needed
BLOCKER from round 51 (--iscsi-listen 0.0.0.0:) was already
resolved in the prior commit (file edit set 127.0.0.1).
Tests: core/storage 3/3 PASS (incl. new goroutine fence);
core/host/volume + cmd/blockvolume + smartwal all green.
Script syntax-checked clean (bash -n).
Refs: sw-block/design/v3-phase-15-g5-5-mini-plan.md v0.3 §6
risks (architect REVIEW round 52 findings)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
702c661f87 |
G5-5 implementation: instrumentation + verifier + m01 orchestration
Per architect-ratified mini-plan v0.3 §1 file map. Three additions
(no engine/adapter behavior changes per architect §6 binding):
1. /status/recovery endpoint (opt-in, loopback-only, default off)
- core/host/volume/status_server.go: handler + EnableRecoveryEndpoint()
- core/host/volume/projection_bridge.go: AdapterProjectionView.EngineProjection()
accessor returns the underlying engine.ReplicaProjection (Mode/R/S/H/
RecoveryDecision/Reason). Surfaces existing engine state via HTTP;
no engine code change.
- cmd/blockvolume/main.go: --status-recovery CLI flag (default off);
calls status.EnableRecoveryEndpoint() when set
- core/host/volume/status_server_test.go: 3 new tests
(Disabled→404, Enabled→200+fields, WrongVolume→404)
2. core/storage.OpenReadOnly + WALStoreReader
- Read-only walstore opener for hardware byte-equal verification.
Opens O_RDONLY, runs Recover() to populate dirty map, exposes
Read(lba) only (no Write/Sync surface). Caller must ensure no
concurrent writer.
- core/storage/walstore_readonly.go + walstore_readonly_test.go
(round-trip write→close→OpenReadOnly→Read passes; missing-file
fence)
3. cmd/m01verify standalone helper (build-tag m01verify)
- Separate cmd subpackage so it doesn't collide with blockvolume's
main(). Builds only with `go build -tags m01verify`.
- Opens replica's walstore via storage.OpenReadOnly, calls Read(lba)
per LBA in target range, SHA-256 vs --expected-pattern (single hex
byte) or --expected-file (binary payload). Prints OK / MISMATCH +
exit 0/1.
- Architect REVISE round 51: NO raw .extent peek; storage abstraction
is the only authoritative read path.
4. scripts/iterate-m01-replicated-write.sh — full G5-5 orchestration
- Replaces v0.1 skeleton's TODO scenario bodies with real verify
steps matching mini-plan v0.3 §2 acceptance criteria #1-#6.
- 6 verify functions: cluster_ready, byte_equal (kernel iSCSI write
+ m01verify storage-aware compare), network_catchup (iptables
drop + /status/recovery R/H polling), restart_catchup (SIGTERM
replica + restart same --durable-root + R/H polling), race_stress
(TestG54_BinaryWiring x10 -race on m01), full_suite (go test ./...).
- Build phase compiles all 3 binaries on m01 (master + volume + verify)
and scp blockvolume + m01verify to M02. SMB share path used in
prior smoke is replaced by direct scp for simpler dependency.
Acceptance gates per mini-plan v0.3 §2:
#1-#6 covered by script verify steps; m01 hardware run is QA's
responsibility per `v3-batch-process.md §14` (sw drafts, QA verifies).
#7 (v3-dev-roadmap.md update at gate-close) deferred to §close.
Full V3 regression: 23/23 packages green from local Windows run
(includes G5-4 binary integration test still passing at 16.4s; new
status_server tests pass; new walstore_readonly tests pass; m01verify
builds clean under -tags m01verify).
Hard binding preserved: zero engine/adapter behavior changes. The
/status/recovery endpoint surfaces an already-computed projection;
walstore.OpenReadOnly is a new read-only wrapper around existing Recover
+ Read; no semantic changes to either.
Refs: sw-block/design/v3-phase-15-g5-5-mini-plan.md v0.3
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
be9823b872 |
G5-4: bind T4 replication stack into cmd/blockvolume
Mirror T4d-4 part B's WithEngineDrivenRecovery() (component framework
binding at core/replication/component/cluster.go:357-369) into the
production binary. Constructs ReplicationVolume + ReplicaListener
per volume and wires both into the host lifecycle, so replicas can
accept incoming WAL traffic and primaries can fan out writes.
Architect bindings (mini-plan v0.4 §7.1 round 50):
Replica readiness — frontend.Projection.Healthy is reused with
role-aware semantics: primary reaches Healthy=true via the existing
caught-up + fence-acked path (engine.ModeHealthy); replica role
(assigned to SUPPORTING; engine apply skips OnAssignment via
recordOtherLine) keeps Healthy=false indefinitely. Frontend bind
(--iscsi-listen / --nvme-listen) is operator-controlled per role:
not passed for replicas. G5-4.5 integration test uses precise
assertion names (replica MUST NOT report Healthy=true).
--ctrl-addr reuse REJECTED — verified ReplicaListener should bind
on --data-addr instead. transport executor's Probe + Ship paths
dial peer.DataAddr (executor.go:303); listener must bind on the
address master mints into AssignmentFact.peers[*].DataAddr — i.e.,
--data-addr. --ctrl-addr stays reserved for future control-plane
split (no current binder; verified no conflict with NVMe / iSCSI
/ status: each has its own dedicated --*-listen / --status-addr
flag). Mini-plan v0.4 said "reuse --ctrl-addr"; correct answer
found during code is --data-addr. PR description carries this
finding for ratification.
Files changed:
- core/host/volume/host.go: SetReplicationVolume(rv) + RWMutex
around h.replication so binary can wire post-New (storage opens
after host construction).
- core/frontend/durable/provider.go: EnsureStorage(volumeID) opens
LogicalStorage role-agnostically (without waiting for Healthy);
Backend(volumeID) accessor returns the same StorageBackend
instance dp.Open returns later. Both used by binary main.go.
- cmd/blockvolume/main.go: after EnsureStorage + RecoverVolume,
construct ReplicationVolume(volumeID, store) + h.SetReplicationVolume,
SetWriteObserver on the backend for fan-out, ReplicaListener on
--data-addr + Serve. Cleanup chain (LIFO): listener.Stop +
rv.Close BEFORE durableProv.Close (storage borrowed by both).
- cmd/blockvolume/g5_4_l2_replication_test.go: NEW. L2 subprocess
integration test — real cmd/blockmaster + 2× cmd/blockvolume over
TCP with --expected-slots-per-volume 2; asserts primary reaches
Healthy=true, replica does NOT (role split per architect
binding), replica's --data-addr accepts TCP (listener bound).
Acceptance criteria status (mini-plan v0.4 §4):
#1 binary constructs ReplicationVolume ✅ verified by code review
#2 in-process role-appropriate ready ✅ G5-4.5 PASS
#3 byte-equal primary→replica ⏸ deferred to G5-5 m01
(in-process test would need iSCSI/NVMe Go client to drive
frontend writes; subprocess pin for wiring + role split is in;
m01 hardware has the kernel iSCSI client tooling)
#4 stop-restart catch-up convergence ⏸ deferred to G5-5 m01
(depends on #3 frontend write driver)
#5 no regressions ✅ full V3 suite green
#6 10x -race stress ⏳ pending m01 verification
#7 invariant ledger inscription ✅ 5 INV-BIN-WIRING-* in
v3-invariant-ledger.md (companion commit in seaweedfs repo)
Refs: sw-block/design/v3-phase-15-g5-4-mini-plan.md v0.4
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
2d86f3ba5b |
G5-1 QA scenarios: 2 distinct-from-sw component tests + 1 known-gap skip
Per architect round-49 G5 v0.3 ratification: G5-1 cleared to start
immediately (no architect dependency; component framework binds T4d-4
part B WithEngineDrivenRecovery directly).
Background: T4d catalogue had 9 scenarios; sw absorbed most into batch
test files (apply_gate_scenarios_test.go, t4d3_scenarios_test.go,
t4d4_engine_driven_test.go, t4d4_full_l2_matrix_test.go,
stale_entry_adversarial_test.go, frontier_regression_test.go). Real
QA distinct-value scenarios remaining:
PASSING:
- TestG5_QA_LifecycleStop_DuringActiveCatchUp_NoHandleLeak (matrix)
Adversarial timing: sever mid-catch-up; verify substrate handle
survives + remains functional. Pins INV-REPL-LIFECYCLE-HANDLE-
BORROWED-001 (BUG-005 non-repeat) under timing pressure.
Not covered by sw's batch tests.
- TestG5_QA_RF2_BothReplicasReachByteEqual (matrix)
G5 multi-replica fan-out scope: 2 replicas catch up independently
and both converge byte-exact with primary. Sw covers single-
replica; this verifies multi-replica independence.
SKIPPED (known framework gap):
- TestG5_QA_LaneDiscipline_LiveAndRecoveryConcurrent_MultiReplica
Live-ship + concurrent CatchUp share sessionID=1; receiver rejects
second session as "stale ship session=1". Same gap as T4c §I
cross-orchestration carry + CARRY-T4D-LANE-CONTEXT-001 territory.
When framework gains per-call session minting, scenario unblocks.
Gate API itself pinned by sw's TestComponent_LanePurity_
CallerControlsDispatch — durable fence; composition test waits.
Framework workarounds (per T4d catalogue §7 missing primitives):
- WithBlockGeometry(256, 4096) for scenarios touching LBA > 64
- replicasFirstNLBAsEqual local helper instead of
AssertNoPerLBARegression
- Single catch-up per replica per test (avoids sessionID=1 collision)
22 packages green; full component package smoke passes.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
02fdb71c7d |
blockmaster: --expected-slots-per-volume flag (was hardcoded 3)
cmd/blockmaster/main.go hardcoded ExpectedSlotsPerVolume: 3 in the TopologyControllerConfig. The TopologyController's validateVolumeTopology rejects every observation snapshot whose slot count differs from this value, returning an error from SubmitObservedState that propagates back to the observation host without a master-log line. Result with a 2-node smoke topology (m01-primary + m02-replica): master is silent, no assignments minted, volumes timeout at durable open with frontend.ErrNotReady — the symptom QA hit during G5-4 cross-node bring-up. Fix: add --expected-slots-per-volume CLI flag, default 3 (production RF=3 unchanged). 2-node smoke clusters pass --expected-slots-per-volume 2. Long-term refactor (separate ticket): the validator should compare snapshot slot count against the topology's per-volume slot count, not a single global config — that's the real per-volume RF model. Refs: sw-block/design/v3-phase-15-g5-m0102-bringup-answer.md Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
6ce708bb64 |
G5-4 m01 hardware first-light harness — DRAFT v0.1 skeleton
QA-authored skeleton mirroring T2 iterate-m01-nvme.sh pattern; awaiting
G5 mini-plan ratification for scenario bodies (marked TODO(G5-arch-ratify)).
Architecture (per QA infra verification 2026-04-26):
- primary blockvolume on m01 (192.168.1.181)
- replica blockvolume on M02 (192.168.1.184)
- blockmaster on m01 (single master, both nodes connect)
- build on m01 (Go 1.26.2 installed); scp blockvolume binary to M02
(Go NOT installed there — same pattern T2 uses for iSCSI target)
Substrate matrix: walstore + smartwal × 4 scenarios (8 total).
Default extent: 1 GiB at 4 KiB blocks (262144 blocks).
Scenario stubs (TODO bodies await G5-4 architect ratification per
g5-kickoff.md §3 / §4 #1):
1. ShortDisconnect_DeltaCatchUp — iptables block + drive writes +
unblock + verify engine catch-up to delta-only convergence
2. LongDisconnect_RebuildEscalation — fill retention window +
verify WAL recycled → rebuild path
3. MidStreamDisconnect_Recovery — engine retry budget under
intermittent fault
4. SteadyStateLiveShip_Throughput — sustained write load (relevant
to G5-2 walstore flusher cadence verification)
Framework gaps surfaced for sw G5-4 work (in skeleton TODO comments):
- Workload driver decision (iSCSI? gRPC admin? test-only RPC?)
- Replica state inspector (extend --status-addr endpoint?)
- Byte-exact verifier across nodes
Diagnostics: master + primary + replica logs + dmesg from both nodes
collected on any scenario failure to ARTIFACT_DIR (default:
seaweedfs/sw-block/design/g5-artifacts/).
Status: ⏸ DRAFT skeleton — no scenarios runnable yet. Ready for
sw + architect review of structure; scenario bodies land in G5-4 PR.
Refs: g5-kickoff.md §3 batch G5-4 + §7a infra verification.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
1be5da483d |
nvme test fixture: atomic.Pointer for lastWrite (race under TestT2A_ConcurrentQueueStress)
writeCountingBackend.lastWrite was a plain []byte field. The
chunked-R2T integrity tests drive Writes serially (assumption
documented in the original code), but TestT2A_ConcurrentQueueStress
shares one writeCountingBackend across 8 IO queues, violating that
assumption — m01 -race reported a write-write race on the field.
Race report (m01, T4d-4 verification):
WARNING: DATA RACE on writeCountingBackend.lastWrite
Both goroutines: nvme_test.(*writeCountingBackend).Write
Stack: dispatchIO → handleWrite → IOHandler.Handle → ...
Fix: replace plain field with atomic.Pointer[[]byte]. Each Write
Stores a fresh copied slice (never mutated after store); readers
Load() to observe a stable snapshot. Semantics preserved for the
chunked-R2T integrity check sites.
Production code untouched. Production session model already
correctly synchronized (per QA's race triage during T4d closure).
Refs §8B.4 Discovery Bridge: QA-owned NVMe test fixture lastWrite
race. Architect-approved 2026-04-26 (pingqiu). Verify on m01:
go test -race -count=10 -run TestT2A_ConcurrentQueueStress \
./core/frontend/nvme/
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
4d73c3978e |
T4d-4 part C: full L2 matrix + 2 engine bug fixes (HARD GATE #3)
HARD GATE #3 surfaced 2 real bugs in engine-driven recovery flow that synthetic OnSessionClose injection didn't expose. Both fixed here. Bug #1 — catch-up exhaustion missed escalation when Decision was re-classified mid-flight: Symptom: stray auto-probe arriving between catch-up retries re-classified Recovery.Decision (R<S → Rebuild). Exhaustion-branch checked stale Decision and fell through to terminal-degraded instead of round-47 escalation. Fix: key on st.Session.Kind == SessionCatchUp (truth = what session actually failed), not on mutable Recovery.Decision. Bug #2 — WALRecycled set Decision=Rebuild but never emitted StartRebuild; subsequent probe could downgrade: Symptom: WALRecycled escalation only emitted PublishDegraded; no rebuild command. A subsequent probe with R>=S could re-classify back to CatchUp before any rebuild fired. Fix: new RecoveryTruth.RebuildPinned sticky bool. Set by both WALRecycled escalation AND catch-up exhaustion. decide() honors it as override — forces Decision=Rebuild + emits StartRebuild regardless of R/S/H. Cleared by successful rebuild SessionCompleted (or identity reset). WALRecycled also now emits StartRebuild immediately (in addition to PublishDegraded for diagnostic surface). Bug #3 (architect-required rule) — already correct: Rebuild's MaxRetries=0 routes the first rebuild failure to the existing terminal-degraded branch. No code change needed. New invariants pinned: INV-REPL-REBUILD-DECISION-STICKY — once escalated to rebuild (WALRecycled or exhaustion), probe re-classification cannot downgrade to CatchUp before rebuild completes. INV-REPL-REBUILD-EMITTED-ON-WAL-RECYCLED — WALRecycled escalation emits StartRebuild immediately, not just PublishDegraded. Full L2 tests (HARD GATE #3) — all PASS through real engine→adapter→executor wiring (NOT synthetic injection): - TestT4d4_FullL2_CatchupRetryExhausted_EscalatesToRebuild - TestT4d4_FullL2_WALRecycled_EscalatesImmediate - TestT4d4_FullL2_LastSentMonotonic_AcrossRetries (QA #8 full form) Files: - core/engine/state.go — RebuildPinned field with invariant doc - core/engine/apply.go — sticky-rebuild gate in decide(); WALRecycled emits StartRebuild + pins; exhaustion uses Session.Kind + pins; rebuild SessionCompleted clears pin - core/engine/recovery_test.go — fixtures set Session.Kind: SessionCatchUp (was relying on old Decision-based check) - core/replication/component/t4d4_full_l2_matrix_test.go — NEW, 3 HARD GATE #3 tests via engine-driven flow with substrate fault injection wraps Verified: full V3 suite green; m01 -race ×20 stress on the 3 HARD GATE tests, no flakes. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
028ea64fc6 |
T4d-4 part B: engine-driven recovery wiring + rebuild-on-exhaustion + G5-DECISION-001 serializability
Per T4d mini-plan v0.5 §2.4 (architect round-47 expanded scope).
Closes 3 of 4 HARD CLOSE GATE items (#1 #2 #4); #3 full L2 matrix
+ QA #8 LastSentMonotonic full form deferred to part C with
substrate fault injection.
ROUND-47 ENGINE CHANGE — catchup-exhaustion escalates to rebuild:
- core/engine/apply.go applySessionFailed: catch-up budget exhaustion
now DIRECTLY emits StartRebuild (Decision flips to Rebuild,
StartRebuild command emitted with current Recovery.H as TargetLSN).
Pre-round-47: cleared Decision + emitted PublishDegraded; rebuild
only fired if a fresh probe arrived. Round-47: rebuild path becomes
engine-driven end-to-end without probe dependency.
- Rebuild has MaxRetries=0 per DefaultRuntimePolicyFor; rebuild
failure terminates (Decision cleared, PublishDegraded emitted).
Pinned by INV-REPL-CATCHUP-EXHAUSTION-ESCALATES-TO-REBUILD +
INV-REPL-REBUILD-FAILURE-TERMINAL.
- Existing TestSessionFailed_NonRecycled_RetriesUntilBudget updated
for round-47 escalation (asserts StartRebuild emit on attempt #4
+ Decision=Rebuild + DecisionReason="catchup_budget_exhausted").
WITHENGINEDRIVENRECOVERY() REAL — round-47 HARD GATE #1 + #2:
- core/replication/component/cluster.go: WithEngineDrivenRecovery()
now installs ONE VolumeReplicaAdapter per replica at Start.
Adapters are wired to executors via the constructor's
executor-callback registration (existing adapter ctor behavior).
- New PrimaryNode.adapters field + Cluster.Adapter(idx) accessor.
- New Cluster.DriveAssignment / Cluster.DriveProbeResult helpers
for test scenarios driving engine state through real adapter.
- Stub warning text + log message removed; engine-driven recovery
is now the real path when opted in.
G5-DECISION-001 SERIALIZABILITY — round-47 obligation:
- core/engine/g5_decision_001_serializability_test.go pins that
engine.ReplicaState (+ all nested truth structs) round-trips
through encoding/json cleanly. T4d-4 obligation: keep struct
serializable so G5 can choose Path A (persist recovery state
across primary restart) without structural rewrite.
- 2 tests: full-state round-trip + zero-value round-trip
- T4d-4 does NOT implement persistence — just maintains the
serializability property.
NEW TESTS (9):
core/engine/recovery_test.go (2 new + 1 updated):
- TestT4d4_CatchupExhaustionEscalatesToRebuild (round-47 #4 pin)
- TestT4d4_RebuildExhaustionIsTerminal (rebuild MaxRetries=0
termination)
- (existing) TestSessionFailed_NonRecycled_RetriesUntilBudget
updated for round-47 escalation semantic
core/engine/g5_decision_001_serializability_test.go (2):
- TestG5Decision001_ReplicaState_RoundTripJSON
- TestG5Decision001_ReplicaState_ZeroValueStable
core/replication/component/t4d4_engine_driven_test.go (5):
- TestT4d4_WithEngineDrivenRecovery_IsReal (HARD GATE #1)
- TestT4d4_AdapterWithoutWithEngineDrivenRecovery_IsNil (fence)
- TestT4d4_DriveAssignment_EngineEmitsProbeReplica
- TestT4d4_RoundTrip_AssignmentToProbeToCatchUp_EngineDriven
- TestT4d4_CatchupBudgetExhausted_EngineEmitsRebuild
Existing test updated for round-47:
- core/adapter/adapter_test.go
TestPreparedNeverStarted_FailsClosedOnImmediateStartError:
set rebuildErr matching catchUpErr; assert chain ends at
Degraded after retry+escalate+rebuild-terminal (was: assert
PhaseFailed after first attempt — round-47 makes that
intermediate not terminal).
NOT in part B (deferred to part C):
- HARD GATE #3: Full L2 matrix incl QA #8 LastSentMonotonic full form
— needs substrate fault injection wrapping engine-driven flow
- Windows TempDir cleanup race + sessionID coordination + test rename
Forward-carry status:
- Round-47 engine change preserves all prior round-43/44/46
invariants (lane purity, stale-skip, no per-LBA regression)
- T4d-1 typed-kind contract: forward-carries
- T4d-2 lane-pure apply gate: forward-carries
- T4d-3 R+1 threading: forward-carries
- T4d-4 part A (RecoveryMode + Stop lifecycle): forward-carries
- 22 packages green; 0 failures
Refs: T4d mini-plan v0.5 §2.4 (architect-ratified expanded scope);
round-47 architect ruling (catchup-exhaustion escalates to rebuild +
G5-DECISION-001); G-1 sign
|
||
|
|
e8aec8b954 |
T4d-4 part A: RecoveryMode interface method + Stop lifecycle (BUG-005 non-repeat) + framework wrap fix
Per T4d mini-plan v0.4 §2.4 expanded scope. Part A of three: smaller
substrate cleanups + lifecycle hardening land first; Path B fold
(ReplicationVolume↔adapter wiring + WithEngineDrivenRecovery real)
follows as part B; Windows cleanup + L2 matrix as part C.
T4c §I row 6 closure (RecoveryMode interface method):
- core/storage/logical_storage.go — add RecoveryMode() to
LogicalStorage interface (returns substrate's tier-1 sub-mode
per memo §5.1 / §13.0a)
- core/storage/store.go BlockStore.RecoveryMode() →
RecoveryModeStateConvergence (in-memory; ScanLBAs synthesizes)
- core/storage/walstore.go WALStore.RecoveryMode() →
RecoveryModeWALReplay (V2-faithful per-LSN)
- core/storage/smartwal/store.go Store.RecoveryMode() →
RecoveryModeStateConvergence (per-LBA dedup)
- core/transport/catchup_sender.go — replace duck-typed
CheckpointLSN probe with e.primaryStore.RecoveryMode() interface
call. Forwards cleanly through component framework wraps via
embedded LogicalStorage.
- core/replication/component/faults.go godoc — replace stale
"MASKED by wrap" limitation note with T4d-4 closure note;
AssertSawRecoveryMode now works correctly under wraps
T4d-4 lifecycle (BUG-005 non-repeat):
- core/replication/volume.go — Stop() canonical entry point added
(delegates to existing Close); semantic clarity over Close().
Both methods are equivalent in T4d-4; Stop() is the named entry
for "stop volume lifecycle activity" while Close() retained for
backward compatibility. Future expansions (drain pending I/O,
stop background goroutines) land in Stop().
- INV-REPL-LIFECYCLE-HANDLE-BORROWED-001 pinned by
TestReplicationVolume_Stop_DoesNotCloseBorrowedStore: store is
STILL usable after volume.Stop (substrate handle is borrowed,
never closed by us — BUG-005 discipline)
- TestReplicationVolume_Stop_Idempotent: second + later Stop calls
are no-ops returning nil
- TestReplicationVolume_Stop_TearsDownPeers: empty-set lifecycle pin
Tests added (5 new):
- TestReplicationVolume_Stop_Idempotent
- TestReplicationVolume_Stop_DoesNotCloseBorrowedStore
- TestReplicationVolume_Stop_TearsDownPeers
- TestStorageRecoveryMode_BlockStore_StateConvergence
- TestStorageRecoveryMode_Walstore_WALReplay
- TestStorageRecoveryMode_LogicalStorageInterface_HasMethod
(compile-time fence pinning RecoveryMode is on the interface,
not just on substrate impls)
NOT in part A (deferred to part B / C):
- ReplicationVolume↔adapter wiring (Path B fold, part B)
- WithEngineDrivenRecovery real binding (Path B fold, part B)
- Full L2 integration matrix (part C)
- Windows TempDir cleanup race (part C)
- Test rename per kickoff §5 (part C)
- sessionID coordination (T4c §I row 5; part C — minor)
22 packages green; 0 failures. Forward-carries: T4c-2 + T4d-1 +
T4d-2 + T4d-3 invariants all green; new RecoveryMode plumbing
preserves T4c-2 INV-REPL-RECOVERY-MODE-OBSERVABLE.
Refs: T4d mini-plan v0.4 §2.4 (architect-ratified expanded scope);
T4c §I row 6 (substrate RecoveryMode method); kickoff §2.1 (BUG-005
non-repeat lifecycle); G-1 sign
|
||
|
|
3351a66ff2 |
T4d-3: R+1 threading + import-discipline fence (G-1 v0.2 PORT items 1-5; CARRY-T4D-LANE-CONTEXT-001 Option B)
Per T4d mini-plan v0.3 §2.3 + G-1 v0.2 (architect+QA-signed
2026-04-25). Refs G-1 sign: pending hash (G-1 doc lives in
seaweedfs sw-block/design/v3-phase-15-t4d-3-g1-v2-read.md v0.2);
QA approval round-46 cleared T4d-3 start.
PORT items landed (G-1 v0.2 §3, items 1-5):
Item 1 — start boundary: engine.StartCatchUp gains FromLSN field;
engine emits Recovery.R + 1 (decide path + retry-loop re-emit).
Pinned by INV-REPL-CATCHUP-FROMLSN-IS-REPLICA-FLUSHED-PLUS-1 +
INV-REPL-CATCHUP-FROMLSN-FROM-ENGINE-STATE-NOT-PROBE.
Item 2 — per-call deadline: preserved unchanged (T4c-2 INV-REPL-
CATCHUP-DEADLINE-PER-CALL-SCOPE forward-carries).
Item 3 — last-sent monotonic + completion: preserved unchanged
(T4c-2 invariants forward-carry; barrier ack remains completion
truth).
Item 4 — retry budget: engine retry-loop reuses ORIGINAL Recovery.R
+ 1 on re-emit per G-1 §6.2 architect Option A (no inter-attempt
re-probe; apply gate handles over-ship). Pinned by
TestT4d3_CatchUp_RetryReusesOriginalRPlus1.
Item 5 — retention-miss escalation: T4d-1 typed-kind contract
already in place; engine branches on FailureKind. Forward-carry.
V3-NATIVE items (no V2 source per G-1 v0.2 §4):
- Engine-owned retry loop (Q1) — already in place at T4c-3
- Unified recovery command model — T4c-pre-B
- Lane-aware apply gate integration — T4d-2
- BarrierResponse.AchievedLSN as completion truth — T4c-2
- Package-boundary discipline — pinned by new
TestT4d3_Catchup_TransportNeverImportsSubstrateInternals
(parses transport .go files via go/parser; fails if any
substrate-internal package import surfaces)
Signature ripple (10 files):
- engine.StartCatchUp{FromLSN uint64} added (no removals)
- adapter.CommandExecutor.StartCatchUp interface +1 param
- transport.BlockExecutor.StartCatchUp + doCatchUp +1 param
- 4 test executor stubs (mockExecutor, closureExecutor,
policyClosureExecutor, restartExecutor) + production
HealthyPathExecutor + noopExecutor + ops nopExecutor
- transport.recovery_session.go bridge passes fromLSN=1 (legacy
StartRecoverySession path; forward-carry to T4e for explicit
fromLSN field on StartRecovery)
- adapter.adapter_test.go bridge passes fromLSN=1
- 5 transport test call sites + 3 component integration test sites
- component framework CatchUpReplica helper passes fromLSN=1
(transitional shim; tests needing explicit R+1 use direct
executor invocation per G-1 §7)
NEW TESTS (G-1 §7 test parity matrix):
- core/engine/t4d3_rplus1_test.go (3 tests):
- TestT4d3_CatchUp_Engine_RPlus1_FromOwnState_NotProbeDirectly
(pins INV-REPL-CATCHUP-FROMLSN-FROM-ENGINE-STATE-NOT-PROBE)
- TestT4d3_CatchUp_RetryReusesOriginalRPlus1 (G-1 §6.2 Option A)
- TestT4d3_StartCatchUpStruct_HasFromLSNField (compile fence)
- core/transport/t4d3_rplus1_test.go (3 tests):
- TestT4d3_CatchUp_ScansFromReplicaR_NotGenesis (substrate
receives caller-supplied fromLSN; sender does NOT add +1)
- TestT4d3_CatchUp_StartCatchUpSignature_FromLSNRequired
- TestT4d3_CatchUp_NonEmptyReplica_BlockStoreOverShipsExpected
(round-46 ADDITION 2 substrate-bound naming — opposing-
assertion regression fence per §9 caveat)
- core/transport/import_discipline_test.go (1 test):
- TestT4d3_Catchup_TransportNeverImportsSubstrateInternals
(Q3 INV-REPL-TRANSPORT-STORAGE-CONTRACT-ONLY; parses transport
sources, fails on substrate-internal imports)
- core/replication/component/t4d3_scenarios_test.go (4 tests):
- TestT4d3_CatchUp_NonEmptyReplica_ShortGap_BandwidthBounded_
Walstore (substrate-bound bandwidth observation)
- TestT4d3_CatchUp_NonEmptyReplica_ShortGap_BandwidthBounded_
Smartwal (mirror)
- TestT4d3_RetryAfterReplicaAdvanced_OverScansHandledByApplyGate
(round-46 ADDITION 1 — pins §6.2 Option A safety claim:
over-scan + apply gate per-LBA stale-skip; assertions cover
byte-exact convergence + no per-LBA regression + coverage
union completeness)
- TestT4d3_RecoveryTargetLSN1_KnownGap (CARRY-T4D-LANE-CONTEXT-
001 Option B close — SKIPPED with explicit forward-binding
for the T4e or beyond fix; gate API itself is already
lane-pure, only caller's signal source needs upgrading)
CARRY-T4D-LANE-CONTEXT-001 close (round-46 architect HARD CLOSE
CONDITION): Option B chosen (NOT Option A) because true handler/
session-context lane signal is a much larger refactor (separate
listener ports OR per-connection lane tag via session-registration
handshake OR new MessageType — all wire/transport-architectural
changes). Architect listed Option B as acceptable. The skip-marked
test documents the H=1 known gap; godoc cites
CARRY-T4D-LANE-CONTEXT-001 explicitly for catalogue cross-reference.
NOT in T4d-3 scope (deferred):
- Engine-driven recovery wiring through ReplicationVolume↔adapter
(G-1 §4 Item A integration scope) — engine retry-loop is
unit-tested; full ReplicationVolume↔adapter binding is a
follow-up task. Rationale: this commit is large enough; landing
the R+1 threading + import discipline as one piece + adding
end-to-end engine-driven recovery wiring as another keeps
reviewability tractable. T4d-4 owns the lifecycle integration;
the engine-driven-recovery wiring fits naturally there OR as a
T4d-3-followup.
Forward-carry status:
- T4d-1 typed-kind contract: forward-carries unchanged
- T4d-2 lane-pure apply gate: forward-carries; round-46 lane
discipline still honored (gate doesn't sniff lineage)
- All round-43/44 stale-skip invariants: forward-carry green
- T4c-2 6 catch-up invariants: forward-carry under R+1 threading
(verified via T4c muscle tests still passing)
- 22 packages green; 0 failures
Tests added: 11 (per G-1 §7 matrix).
Refs: T4d mini-plan v0.3 §2.3 (architect-ratified); G-1 v0.2
QA-signed (CARRY-T4D-LANE-CONTEXT-001 close condition Option B);
round-46 architect ruling (lane-pure gate); kickoff §9 (Q1/Q2/Q3).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
8e30a497ff |
T4d-2 doc fix: stale godoc post-round-46 (gate is lane-pure; CARRY-T4D-LANE-CONTEXT-001)
Per QA T4d-2 final closure: pre/with-T4d-3 doc fixes. apply_gate.go (lines 38-43): the godoc on ReplicaApplyGate still described "lane discrimination" as the gate reading lineage.TargetLSN — that text predated the round-46 rework. Replaced with a clear statement of the lane-pure contract: - Gate is LANE-PURE; caller decides - Caller invokes ApplyRecovery vs ApplyLive explicitly - Gate does NOT inspect lineage payload to discriminate - Today's caller (transport replica.go) uses a transitional TargetLSN-based shim — but the shim lives at the CALLER - The architectural fence (gate is lane-pure) is durable; the caller's signal source is replaceable - Reference to CARRY-T4D-LANE-CONTEXT-001 for the future fix replica.go NewReplicaListenerWithApplyHook godoc: previously described `hook.Apply(lineage, lba, data, lsn)` as the dispatch mechanism — that signature no longer exists post-round-46. Replaced with: - Handler dispatches caller-side to hook.ApplyRecovery / hook.ApplyLive - Hook itself is LANE-PURE - Today's caller-side decision is a transitional shim based on TargetLSN==liveShipTargetLSNSentinel - Reference to CARRY-T4D-LANE-CONTEXT-001 Both godoc updates inscribe the architectural fence + name the named carry by ID so future readers find the gap tracking via catalogue cross-reference. 22 packages green; 0 failures. Refs: round-46 architect ruling (lane-pure gate); CARRY-T4D-LANE- CONTEXT-001 (catalogue §3.3 — QA-inscribed named carry). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
c0cccb0947 |
T4d-2 follow-up: lane-pure gate API (round-46 architect rework)
Architect round-46 rejected my lane-discriminator implementation: the gate inspecting `lineage.TargetLSN > 1` to dispatch lane was a "payload-derived signal" — wrong placement. The fix: gate is LANE-PURE; CALLER decides lane from connection/session handler context. GATE API REWORKED: - Removed: Apply(lineage, ...) + isRecoveryLane(lineage) helper - Added: ApplyRecovery(lineage, lba, data, lsn) — explicit recovery lane (stale → skip data + advance recoveryCovered) - Added: ApplyLive(lineage, lba, data, lsn) — explicit live lane (stale → return error fail-loud; never advance recoveryCovered) - Gate methods do NOT inspect lineage.TargetLSN for lane decisions TRANSPORT INTERFACE REWORKED: - transport.ApplyHook becomes 2-method interface (ApplyRecovery + ApplyLive) - replica.go MsgShipEntry handler dispatches CALLER-SIDE based on TargetLSN==liveShipTargetLSNSentinel; this is a TRANSITIONAL SHIM with explicit TODO marking it as caller-side-only — the architectural fence (gate is lane-pure) is the durable property - TODO references future fix: true handler-context lane via per-connection lane tag, separate live/recovery handler routes, or distinct listener ports (T4e or post-G5 refactor) - liveShipTargetLSNSentinel const lives in transport (NOT importing replication for the value; same wire-stable constant) REGRESSION TESTS (architect round-46 HARD GATE): - TestApplyGate_RecoveryWithTargetLSN1_RoutesToRecoveryLane — recovery lineage with TargetLSN=1 (the OLD live-ship sentinel value): pre-rework this routed to live and fail-loud'd a stale recovery entry; post-rework gate honors caller's ApplyRecovery choice → stale skips silently + recovery coverage advances - TestApplyGate_LiveWithTargetLSN100_RoutesToLiveLane — mirror: live lineage with TargetLSN=100 (would have been recovery pre-rework): post-rework gate honors caller's ApplyLive choice → stale fail-louds + recovery coverage NOT advanced TESTS REPLACED / RENAMED: - TestApplyGate_LaneDiscriminator_RecoveryWhenTargetLSNAboveLive REMOVED (the gate no longer has a lane discriminator helper) - TestComponent_LaneDerivedFromTargetLSN renamed → TestComponent_LanePurity_CallerControlsDispatch — repurposed: uses identical lineage payload across two test paths, only the caller's choice of method differs; gate honors choice; pins INV-REPL-LANE-DERIVED-FROM-HANDLER-CONTEXT (round-46 strengthened meaning: handler context, NOT payload-derived signals) REMAINING TESTS UPDATED: - All gate.Apply(...) call sites in apply_gate_test.go + apply_gate_scenarios_test.go updated to use ApplyRecovery / ApplyLive based on the test's intended lane (recoveryLineage → ApplyRecovery; liveLineage → ApplyLive) Forward-carry status: - T4d-1 typed-kind contract unaffected (gate orthogonal to failure classification) - All round-43/44 invariants still pinned by the 16 tests; lane- routing now via explicit method instead of payload sniffing - 22 packages green; 0 failures - T4d-3 G-1 sign HARD GATE now satisfied per round-46 QA call T4d-3 unblocked. T4d-4 unblocked + parallel-eligible. Refs: round-46 architect ruling (rework lane discriminator); mini-plan v0.3 §2.2 (apply gate); kickoff §9.3 #2 (Q2 — lane implicit from handler context). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
1a6c508226 |
T4d-2: replica recovery apply gate (lane-aware, 2-map split, Option C hybrid)
Per T4d mini-plan v0.3 §2.2 (architect-ratified). Round-43 lock + round-44 refinement: lane-aware per-LBA stale-skip with coverage- advance on skip; live-lane stale fail-loud; 2-map split. The correctness boundary for "no per-LBA data regression." NEW core/replication/apply_gate.go: - ReplicaApplyGate component + per-session state (applyGateSession with appliedLSN + liveTouched + recoveryCovered maps) - Apply(lineage, lba, data, lsn) routes by lane (Q2: lane derived from lineage.TargetLSN signal — > liveShipTargetLSN = recovery; == liveShipTargetLSN = live; no wire byte added) - applyRecovery: if lsn <= appliedLSN[lba] → skip data + advance recoveryCovered (round-44 #1); else apply + update both maps - applyLive: if lsn <= appliedLSN[lba] → return error (round-44 #2 INV-REPL-LIVE-LANE-STALE-FAILS-LOUD); else apply + update appliedLSN + liveTouched ONLY (NOT recoveryCovered) - initSessionLocked: queries store.AppliedLSNs() at session init (Option C hybrid per kickoff §2.5 #1); falls back to empty map on ErrAppliedLSNsNotTracked (BlockStore) with INFO log - SessionState / SessionRecoveryCoverage / SessionAppliedLSN — read-only inspection helpers for tests + ops Pinned invariants (T4d mini-plan §4 #6): - INV-REPL-NO-PER-LBA-DATA-REGRESSION (goal-level) - INV-REPL-RECOVERY-STALE-ENTRY-SKIP-PER-LBA (mechanism) - INV-REPL-RECOVERY-COVERAGE-ADVANCES-ON-SKIP (round-44) - INV-REPL-LIVE-LANE-STALE-FAILS-LOUD (round-44) - INV-REPL-RECOVERY-COVERAGE-RESTART-SAFE (Option C makes pinnable) - INV-REPL-LANE-DERIVED-FROM-HANDLER-CONTEXT (Q2) Transport wiring (core/transport/replica.go): - New transport.ApplyHook interface (Apply method); duck-typed adapter so replication.ReplicaApplyGate satisfies it without an import cycle (replication already imports transport) - New NewReplicaListenerWithApplyHook constructor; existing NewReplicaListener delegates with hook=nil (preserves T4a/T4b/T4c behavior — direct apply when no gate installed) - MsgShipEntry handler: if hook installed, delegate; live-lane fail-loud error → log + drop conn (round-44 #2) Component framework wiring (core/replication/component/cluster.go): - WithApplyGate() builder option installs the gate on every replica's listener - ReplicaNode gains ApplyGate field - Cluster.ApplyGate(idx) accessor for tests asserting per-session gate state Tests (16 new): - core/replication/apply_gate_test.go (13 unit tests on the gate): lane discriminator (5 cases), recovery stale-skip data + coverage advance, fresh apply advances both, live stale fail-loud, live stale doesn't advance recoveryCovered, lane independence across distinct sessions, Option C BlockStore fallback, Option C substrate-seed honored, restart-mid-recovery (BlockStore documented limitation), restart-safe via substrate seed (full Option C path), substrate apply error propagates, CloseSession releases state - core/replication/component/apply_gate_scenarios_test.go (4 integration scenarios): RecoveryStaleSkip_CoverageStillAdvances (round-44 #1), LiveLaneStaleEntry_FailsLoud (round-44 #2), LaneDerivedFromTargetLSN (Q2), OptionCHybrid_WalstoreSeed (substrate-seed integration) - core/replication/component/stale_entry_adversarial_test.go: TestComponent_Adversarial_StaleEntryDoesNotRegress UN-SKIPPED (round-46) — now uses cluster.WithApplyGate(); pin INV-REPL-RECOVERY-STALE-ENTRY-SKIP-PER-LBA at integration scope Forward-carry status (preserved): - All T4a/T4b/T4c invariants forward-carry green - T4d-1 typed-kind contract unaffected (gate orthogonal to failure classification) - T4c apply path unchanged when WithApplyGate not requested NOT in T4d-2 scope (deferred per mini-plan §1.2): - Engine-driven full-flow integration (T4d-3 wires ReplicationVolume↔adapter; T4d-2's WithEngineDrivenRecovery hook remains stub) - Substrate-side stale-skip in walstore/smartwal ApplyEntry (T4d-1 caveat: where practical; gate is the authoritative correctness boundary) 22 packages green; 16 new tests; 1 previously-skipped test now PASSING. Refs: T4d mini-plan v0.3 §2.2 (architect-ratified 2026-04-25); kickoff §9 Q1/Q2/Q3; round-43/44 architect text; round-46 QA approval clearing T4d-2 start. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
27130c2f62 |
T4d-1 follow-up: 2 QA HARD GATE tests for classifier discipline (round-46)
Per QA T4d-1 approval round-46: 2 follow-up tests bound as HARD
GATE before T4d-3 G-1 sign. Sw-discretion landing site = T4d-1
patch (clean closure before T4d-2 starts).
(1) TestT4d1_TargetNotReached_DistinctKindFromWALRecycled
Pin: classifyRecoveryFailure produces DISTINCT engine kinds for
superficially-similar catch-up failure surfaces. WAL-recycled
escalates to Rebuild (tier-class change); target-not-reached is
retryable per RecoveryRuntimePolicy.MaxRetries. Conflating them
would either retry forever past the retention boundary OR
prematurely escalate transient stream failures. Three assertions:
(a) WAL-recycled → engine.RecoveryFailureWALRecycled
(b) target-not-reached → engine.RecoveryFailureTargetNotReached
(c) the two engine kinds are DISTINCT + symmetric
(2) TestT4d1_StorageFailureKindMapper_AllKnownKinds
Fence: catches future StorageRecoveryFailureKind additions that
silently fall through to Transport because the transport mapper
switch wasn't extended. The test enumerates known storage kinds +
expected engine mappings; if a future commit adds
StorageRecoveryFailureFoo to storage but doesn't extend the
mapper, this test fails loudly ("silently fell back to Transport
— mapper missing a switch case"). Two-sided update requirement
(test scaffold + mapper) is the desired discipline.
StorageRecoveryFailureUnknown explicitly excluded from the loop
(zero-value, legitimately maps to Transport catch-all); separate
sanity assertion verifies that mapping.
Both tests pass at HEAD 5ca1d11+this commit.
22 packages green; 0 failures. Net change: +1 file, +135 lines test
code. No production change.
T4d-3 G-1 sign GATE now satisfied (per round-46 QA binding).
T4d-2 + T4d-4 remain unblocked + parallel-eligible.
Refs: T4d mini-plan v0.3 §7.1 (G-1 procedural binding); QA round-46
approval (HARD GATE before T4d-3 G-1 sign).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
5ca1d1193e |
T4d-1: structured RecoveryFailureKind end-to-end + AppliedLSNs interface (Option C hybrid)
Per T4d mini-plan v0.3 §2.1 (architect-ratified). Closes T4c §I forward-carry "structured RecoveryFailureKind" + lands the LogicalStorage AppliedLSNs() addition T4d-2 needs at session start. ARCHITECTURAL CONTRACT (v0.3 boundary discipline): - core/engine MUST NOT import core/storage - storage owns substrate-side StorageRecoveryFailureKind + RecoveryFailure - transport extracts substrate kind via errors.As, maps to engine kind - adapter.SessionCloseResult.FailureKind = engine.RecoveryFailureKind - engine.SessionClosedFailed.FailureKind = engine.RecoveryFailureKind - Reason / FailReason text remains DIAGNOSTIC ONLY — engine MUST NOT parse Storage side (core/storage/recovery_contract.go): - StorageRecoveryFailureKind enum (Unknown / WALRecycled / SubstrateIO) - RecoveryFailure typed-error struct with Unwrap() preserving errors.Is(_, ErrWALRecycled) compatibility for migration window - NewWALRecycledFailure / NewSubstrateIOFailure helpers - ErrAppliedLSNsNotTracked sentinel for substrates without per-LBA applied-LSN metadata LogicalStorage interface gains AppliedLSNs() method (Option C hybrid per kickoff §2.5 #1 architect ratification): - BlockStore: explicit (nil, ErrAppliedLSNsNotTracked) — in-memory, no per-LBA tracking; gate falls back to session-only map - walstore: dirty-map snapshot reduction (PARTIAL VIEW per kickoff §2.5 #3 caveat — only in-WAL LBAs reported; flushed LBAs lose per-LBA LSN tracking; defense-in-depth, gate is authoritative) - smartwal: ring.scanValid() per-LBA last-writer-wins reduction Substrate ScanLBAs error wrapping: - walstore: NewWALRecycledFailure(ErrWALRecycled, "fromLSN=... checkpointLSN=...") at retention boundary - smartwal: NewWALRecycledFailure(ErrWALRecycled, "fromLSN=... oldestPreserved=...") at retention boundary Engine side (core/engine/events.go + apply.go): - New engine-owned RecoveryFailureKind enum (Unknown / WALRecycled / Transport / SubstrateIO / TargetNotReached / StartTimeout / SessionInvalidated) - SessionClosedFailed gains FailureKind field (typed branch) - applySessionFailed branches on e.FailureKind, NOT on Reason text - Substring helpers REMOVED: isWALRecycledFailure / isStartTimeoutFailure / containsAny — engine no longer parses Reason Transport side (core/transport/recovery_session.go + executor.go finishSession): - New classifyRecoveryFailure helper at the boundary: errors.As to extract *storage.RecoveryFailure, map StorageRecoveryFailureKind → engine.RecoveryFailureKind; fallbacks for errSessionInvalidated + target-not-reached error message (transport-internal, acceptable) - finishSession populates SessionCloseResult.FailureKind via classifier Adapter side (core/adapter/normalize.go + adapter.go): - SessionCloseResult gains FailureKind engine.RecoveryFailureKind - NormalizeSessionClose copies FailureKind into SessionClosedFailed - adapter dispatch failure paths (start_catchup_failed / start_rebuild_failed / start_recovery_failed) tag Transport kind - Watchdog timeout path tags StartTimeout kind (engine bypasses retry for this kind per existing T4c-3 design) Tests (10 new, mini-plan §2.1 budget met): - Storage: TestStorageRecoveryFailure_WALRecycled_ErrorsIsCompatible, TestStorageRecoveryFailure_WALRecycled_ErrorsAsExposesKind, TestStorageRecoveryFailure_SubstrateIO_ErrorsAsExposesKind, TestStorageRecoveryFailureKind_StringForms, TestBlockStore_AppliedLSNs_ReturnsErrAppliedLSNsNotTracked, TestStorageRecoveryFailureKind_Walstore_RecycleWrappedAsKind, TestWalstore_AppliedLSNs_ReportsDirtyMapEntries, TestStorageRecoveryFailureKind_Smartwal_RecycleWrappedAsKind, TestSmartwal_AppliedLSNs_ReportsRingEntries - Adapter: TestAdapter_SessionCloseResult_TypedKindEndToEnd (×6 subtests, one per kind), TestAdapter_SessionCloseResult_ SuccessIgnoresFailureKind - Engine: TestSessionFailed_WALRecycled_EscalatesToRebuild (rewritten — typed branch), TestSessionFailed_WALRecycled_ NoSubstringMatchUsed (negative pin: text-only without typed kind must NOT escalate), TestEngine_SessionFailed_NoMoreSubstringMatch (source-grep fence with comment-stripping helper to avoid false-positive on godoc mentions of removed helpers) Existing tests preserved: - T4c-2 / T4c-3 tests pass under new contract (existing close-result builders default FailureKind to Unknown which falls into the Transport-kind retry path — matches their pre-T4d-1 substring- match behavior on non-recycled failures) INV-REPL-CATCHUP-RECYCLE-ESCALATES updated: pinning method changed from substring to typed kind (per T4d mini-plan §2.1). go test ./... -count=1 → all 22 packages green. Refs: T4d mini-plan v0.3 (architect-ratified 2026-04-25); kickoff §9.3 #1 (Q1 engine-owned recovery decisions); kickoff §2.5 #1 (Option C hybrid AppliedLSNs); memory feedback_engine_no_storage_ import.md (round-45 architect lock). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
dea8481bb6 |
BlockStore: gate walHead update on lsn > walHead (round-43 substrate hardening, defense-in-depth)
Pre-T4d-1 hotfix per architect-ratified kickoff sequencing
(round-44 governance call): substrate-level guard lands ahead of
the larger T4d-2 replica recovery apply gate work. Closes a
production storage-contract violation independent of the larger
T4d batch.
Bug (round-41 architect-identified, round-43 demo-confirmed):
core/storage/store.go:264 set s.walHead = lsn unconditionally.
Older-LSN ApplyEntry regressed walHead, violating
LogicalStorage contract §3 rule 3 ("stable frontier never goes
backward").
Empirically demonstrated live at round-43:
ApplyEntry(LSN=10) → walHead=10
ApplyEntry(LSN=5) → walHead=5 ← REGRESSION
Fix:
if lsn > s.walHead {
s.walHead = lsn
}
Same monotonic-update pattern as walstore.ApplyEntry:544 and
smartwal.ApplyEntry:358 already use. Brings BlockStore in line.
Architectural placement (round-43 sign):
Replica recovery apply gate (T4d-2 primary fix) is the primary
correctness boundary; this guard is defense-in-depth for paths
that may bypass the gate (live duplicate, retry, future
cross-substrate scenarios). Inline godoc comment names the
T4d-2 gate as the primary boundary so the role is clear.
Test (un-skipped from round-41/43 adversarial set):
TestComponent_BlockStore_ApplyEntry_OldLSN_DoesNotRegressWalHead
(renamed from TestComponent_Adversarial_BlockStoreApplyEntry
RegressesWalHead — the bug name no longer applies).
Pre-fix: t.Skip + T4d TODO. Post-fix: passes; pins the
monotonic guard against regression.
Zero semantic change to any code that worked before. T4d-1 / T4d-2
will not conflict with this hotfix — different files, different
layers.
go test ./... -count=1 → 22 packages green (regression test
passes; no other test affected).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
360e540c76 |
component: round-43 architect sign — fix shape inscribed (recovery apply gate)
Architect round-43 signed the T4d fix shape:
T4d stale-entry safety belongs at the REPLICA RECOVERY APPLY
GATE (a NEW component, lane-aware), with substrate fixes as
defense-in-depth. The invariant is about NO PER-LBA DATA
REGRESSION, not just frontier monotonicity.
The gate is lane-aware:
live lane:
use existing lineage/session/live-order rules
do not use recovery stale-skip; do not update recovery coverage
recovery lane:
always update recovery accounting / coverage
if entry.LSN <= perLBAAppliedLSN[LBA]:
skip data write
else:
ApplyEntry(...)
update perLBAAppliedLSN[LBA] = entry.LSN
perLBAAppliedLSN source: from storage if exposed cleanly; else
session-local map seeded from recovery/live applies. Pre-existing
state correctness eventually requires substrate to expose per-LBA
applied LSN metadata.
T4d task list (round-43 final):
1. PRIMARY FIX — replica recovery apply gate (new component)
- Lane-aware (live vs recovery)
- Per-LBA applied LSN tracking
- Recovery: skip data write on stale; always update accounting
- Live: passes through unchanged
2. DEFENSE-IN-DEPTH — substrate hardening:
- BlockStore.ApplyEntry: gate walHead = lsn on lsn > walHead
- walstore + smartwal: substrate-level stale-protection or
per-LBA applied LSN exposure
3. 5 adversarial tests un-skipped + extended (architect set +
QA refinement set, unchanged from round-42)
Files updated:
- stale_entry_adversarial_test.go: TestComponent_StaleEntrySkip_
RuleStatement extended with round-43 gate shape (verbatim) +
task list
- memory feedback_recovery_stale_entry_skip.md: round-43 fix
shape + perLBAAppliedLSN source caveat + substrate triage table
- design memo v3-phase-15-t4c-architect-review-changelist.md §3:
round-43 sign inscribed; substrate triage table replaces older
per-substrate-action table
22 packages green.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
357f286eae |
component: round-42 QA refinements — data-only skip + recovery-lane scope
QA round-42 refined the round-41 invariant
INV-REPL-RECOVERY-STALE-ENTRY-SKIP-PER-LBA with two scoping rules
that must be honored at T4d implementation:
(1) INV-REPL-RECOVERY-STALE-SKIP-DATA-ONLY-NOT-ACCOUNTING:
Stale skip applies to DATA WRITE only. Per-session accounting
(bitmap, completion mask, scan coverage) MUST update as though
the entry was processed. Otherwise:
- Recovery session's completion logic thinks LBA wasn't reached
- Bitmap signals "recovery hasn't covered this slot" to live lane
- Barrier achievedLSN judgment is wrong
Skip means: don't write data. Still mark "I saw this LBA."
(2) INV-REPL-LIVE-LANE-NEVER-SKIPS-LSN:
Per-LBA-LSN skip rule applies to RECOVERY lane ONLY. Live ship
lane MUST NOT skip on stale LSN — live writes are authoritative
on (lineage, session) grounds and that gating is sufficient.
An "old LSN" on live is a duplicate/replay; per-LBA-LSN
comparison is recovery-lane-only.
Files updated:
- stale_entry_adversarial_test.go: TestComponent_StaleEntrySkip_
RuleStatement extended with both refinements + 2 new T4d
adversarial test requirements (recovery-stale-skip-still-marks-
bitmap; live-lane-old-LSN-applies-normally)
- memory feedback_recovery_stale_entry_skip.md: refinements +
expanded T4d blocker list
T4d blocker list now (round-42 revision):
1. Per-LBA applied LSN tracking at replica apply layer
2. Recovery apply skips entries whose LSN <= per-LBA applied LSN
3. Skip data write but UPDATE per-session accounting (refinement #1)
4. Apply skip rule on recovery lane only; live keeps current
lineage-gated apply (refinement #2)
5. BlockStore.ApplyEntry: gate walHead update on lsn > walHead
6. 5 adversarial tests un-skipped + extended (architect set + QA
refinement set)
22 packages green.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
d2d765a7f3 |
component: round-41 stale-entry invariant — frontier partial-pin + adversarial skip-tests
Architect round-41 corrected my earlier "frontier monotonicity is
sufficient" answer. Two real concerns surfaced + inscribed:
(1) Frontier-monotonicity tests are PARTIAL PINS only.
They cover benign full-replay shape (over-scan completes through
to the restoring entry). They do NOT prove safety under
INTERRUPTED replay where a stale entry overwrites newer state and
the conn dies before the restoring entry arrives. File header on
frontier_regression_test.go now says so explicitly.
(2) BlockStore.ApplyEntry sets walHead = lsn UNCONDITIONALLY.
Older-LSN apply regresses walHead, violating logical_storage.go §3
rule 3 ("stable frontier never goes backward"). My earlier "BlockStore
is idempotent" claim was wrong.
Architect rule (revised T4d blocker): pinLSN < replicaLSN is
LEGAL and EXPECTED (probe-time R can advance during recovery via
live lane / barrier / prior partial catch-up). Don't fight it;
make recovery apply stale-safe per LBA.
Required invariant — INV-REPL-RECOVERY-STALE-ENTRY-SKIP-PER-LBA:
A replica MUST NOT apply a recovery-stream entry if that LBA is
already known to contain data from an equal or higher LSN.
Substrate behavior verified at round-41:
- walstore: per-LSN scan emits BOTH old + new → vulnerable to
interrupted-replay corruption (T4d must add per-LBA stale skip)
- smartwal: state-convergence emits scan-time LSN with current
data → stale-safe by construction (current data only)
- BlockStore: walHead regresses on older-LSN apply → contract
violation; T4d must gate walHead update on lsn > walHead
Files added:
stale_entry_adversarial_test.go (3 tests):
- TestComponent_Adversarial_StaleEntryDoesNotRegress (skipped
with T4d TODO; expected to FAIL on walstore today; T4d
un-skips when per-LBA stale skip lands)
- TestComponent_Adversarial_BlockStoreApplyEntryRegressesWalHead
(skipped; pins the BlockStore bug for T4d fix)
- TestComponent_StaleEntrySkip_RuleStatement (always passes;
godoc-style searchable inscription of the architect rule)
frontier_regression_test.go header updated:
- File-level "PARTIAL PIN" notice naming the limitation
- TestComponent_CatchupFromBelowReplicaLSN_NoFrontierRegression
godoc clarifies "FULL successful replay" scope
Memory updated:
- feedback_recovery_stale_entry_skip.md captures the architect
rule + required invariant + T4d blocker shape
T4d blocker list (round-41 revision):
1. Per-LBA applied LSN tracking at replica apply layer
2. Recovery apply skips entries whose LSN <= per-LBA applied LSN
3. BlockStore.ApplyEntry: gate walHead update on lsn > walHead
4. 3 adversarial tests un-skipped + extended:
- same LBA old/new + sever before new → no regression
- repeated recovery window → byte state stable
- live races recovery old → live wins
go test ./... -count=1 → 22 packages green (adversarial tests
skipped with explicit T4d TODOs).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
1be3c134ba |
T4c QA Stage-1: 3 round-40 scenarios using gap-closure primitives
Round 40 follows up commit
|
||
|
|
370a0e8de9 |
component framework: close 3 of 4 QA-flagged gaps; stub 4th for T4d
QA round-39 Stage 1 flagged 4 framework gaps blocking deferred scenarios. This commit closes 3 of 4 with primitives + demos; 4th (engine-driven recovery) is API-stubbed pending T4d wiring. Closed gaps: (1) WithPrimaryStorageWrap(fn) builder option - Cluster.WithPrimaryStorageWrap installs a substrate transform before BlockExecutors bind; wraps may override any LogicalStorage method. Three pre-built wraps in faults.go: - NewRecycledScanWrap() — always returns ErrWALRecycled - NewSeverDuringScanWrap(N, err) — emits N entries then severs - NewObservedScanWrap(*atomic.Int32) — counts emit observations - Demos: TestComponent_RecycledScanWrap_EscalatesToRebuild, TestComponent_SeverDuringScan_PartialProgress, TestComponent_ObservedScanWrap_CountsEmits (2) Live-ship primitive driving ReplicationVolume.OnLocalWrite - Cluster.WithLiveShip() builder option spins up StorageBackend + ReplicationVolume; configured replicas auto-registered as peers - PrimaryWriteViaBackend(lba, data) writes through the production data-plane entry → WriteObserver hook → fan-out to replicas - PrimaryWriteViaBackendN(n) batch helper - Demo: TestComponent_LiveShip_PrimaryWriteViaBackend_FansOut (4) Mid-stream drop helper SeverDuringScan - Implemented as NewSeverDuringScanWrap above; counts entries via atomic.Int32 inside the substrate wrap and returns the configured sever error after N successful emits - Robust to substrates with fewer than N entries (no-op rather than fail-closed, so scenarios are emit-count-tolerant) API-stubbed for T4d: (3) WithEngineDrivenRecovery() — option records intent, emits a one-shot t.Logf warning at Start, runs as direct-executor mode. Forward-carry: when T4d wires ReplicationVolume↔adapter, this option swaps the adapter-aware constructor in. Demo: TestComponent_EngineDrivenRecovery_StubWarning pins the API shape so scenarios authored today won't need to change when behavior lands. Known limitation documented in faults.go: substrate-extension methods (e.g. walstore.CheckpointLSN) are MASKED by the wrap because Go embedding only exposes interface methods. The catch-up sender's recovery_mode label probe duck-types CheckpointLSN; under a wrap, it always sees state_convergence regardless of underlying substrate. Forward-carry: refactor mode-label detection behind a substrate-reported RecoveryMode() method that wraps can forward. 5 new demos = 9 matrix rows (smartwal+walstore where applicable). go test ./... -count=1 → 22 packages green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
6a3b84cd29 |
component test framework: cluster harness + 7 demo scenarios
QA-requested (round-39): build a component test framework so QA can author T4c-follow-up + T4d scenarios in ~20-30 lines without re-deriving cluster setup boilerplate. Lands `core/replication/component/` package with: - Cluster builder: NewCluster(t, factory).WithReplicas(n).Start() → fully wired primary + N replicas over real localhost TCP using production code paths (BlockStore + ReplicaListener + BlockExecutor) - RunMatrix(t, scenario): runs the scenario across smartwal + walstore; both substrates gate per round-22 sign-bearing discipline - RunSubstrate(t, name, factory, scenario): single-substrate runner for substrate-specific pins - Write/sync primitives: PrimaryWrite, PrimaryWriteN, PrimarySync, ReplicaApply (for setting up pre-existing replica state) - Recovery primitives: CatchUpReplica, ProbeReplica - Fault injection: KillReplicaListener, SeverConnection - Convergence assertions: WaitForConverge, AssertReplicaConverged - Mode-label assertions: AssertSawRecoveryMode with ExpectAnyMode / ExpectWALReplay / ExpectStateConvergence constants - Log capture: tees log.Default writer into per-test buffer so mode- label assertions don't need stderr parsing - Mode-constant init-time pin: panics if ExpectWALReplay / ExpectStateConvergence drift from storage.RecoveryMode* values 7 demo scenarios in cluster_test.go double as smoke for the framework + copy-paste templates for QA: - TestComponent_HappyCatchUp — simplest scenario shape - TestComponent_GapExceedsRetention_Recycled — substrate fault wrap pattern (recycledScanStub demonstrates ScanLBAs override for ErrWALRecycled injection) - TestComponent_ProbeHappy — probe wire smoke across substrates - TestComponent_TwoReplicas_BothConverge — multi-replica fan-out - TestComponent_PartialReplicaThenCatchUp — ReplicaApply for pre-existing partial state setup - TestComponent_RecoveryModeLabel_Walstore — per-substrate label pin (wal_replay) - TestComponent_RecoveryModeLabel_Smartwal — per-substrate label pin (state_convergence) - TestComponent_ModeConstantsStable — drift fence Authoring guide: sw-block/design/v3-phase-15-component-test-guide.md documents the API + common patterns + extension discipline. Aim: ~20-30 lines per new scenario. Forward-carry items (sw will add when needed): - WithPrimaryStorageWrap(wrap) option — substrate fault injection at the executor layer (today the wrap pattern only works at the storage layer; substrate-level executor-test integration needs the option) - WithEngineDrivenRecovery() option — when T4d lands the ReplicationVolume↔adapter wiring, the framework gains the engine- driven recovery flow as an opt-in mode go test ./... -count=1 → all 22 packages green (component is the new package). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
5cbe7cf6db |
T4c-3: engine retry-loop wiring + L2 integration matrix
Per QA T4c-2 sign forward-carry binding (round-37): retry-loop
wiring deferred from T4c-2 §4.1 lands here. Integration matrix
covers mini-plan §2 T4c-3 scenarios at the executor surface.
Engine retry-loop (G-1 §4.1 architect Option B, round-38):
- RecoveryTruth.Attempts counter added
- applySessionFailed: on non-recycled non-start_timeout failure,
increment Attempts; while Attempts <= DefaultRuntimePolicyFor(
contentKindFor(Decision)).MaxRetries, re-emit StartCatchUp /
StartRebuild
- Budget exhaustion clears Attempts + Decision (reset to Unknown)
+ emits PublishDegraded("retry_budget_exhausted")
- ErrWALRecycled bypasses retry — tier-class change escalates to
Decision=Rebuild and resets Attempts (sentinel takes precedence)
- start_timeout (watchdog-synthesized) bypasses retry — executor
never started; retrying an unreachable executor doesn't help
- applySessionCompleted clears Attempts on success
L2 integration matrix (mini-plan §2 T4c-3, 4 scenarios × 2
substrates = 8 matrix rows):
- TestT4c3_Catchup_ShortDisconnect_DeltaOnly — primary writes 20
LBAs, replica empty, executor StartCatchUp streams the window
via ScanLBAs → MsgShipEntry; replica converges byte-exact
- TestT4c3_Catchup_GapExceedsRetention_EscalatesToNeedsRebuild —
substrate ErrWALRecycled propagates through SessionClose's
FailReason; engine SessionFailed handler maps to Rebuild
- TestT4c3_Probe_HappyPath_AcrossBothSubstrates — wire shape works
end-to-end across smartwal + walstore
- TestT4c3_Catchup_RecoveryModeLabelSurfaced — substrate-mode
introspection probe completes catch-up under both substrates
(label visible in success log; no panic / no error)
Engine unit tests (3 new):
- TestSessionFailed_NonRecycled_RetriesUntilBudget — pin: 3 retries
re-emit StartCatchUp; 4th exhausts budget → PublishDegraded
- TestSessionCompleted_ClearsAttemptCounter — success resets
- (existing TestSessionFailed_NonRecycled_DoesNotEscalate continues
to pass under retry path)
Mini-plan §2 T4c-3 scenarios coverage:
- (1) ShortDisconnect → covered, both substrates
- (2) GapExceedsRetention → covered, both substrates
- (3) RetryBudgetExhausted → covered at engine unit scope
(TestSessionFailed_NonRecycled_RetriesUntilBudget); integration-
scope coverage requires engine→adapter→executor full-flow wiring
not present in current ReplicationVolume (forward-carry to T4d)
- (4) Probe_LineageMismatch_FailsClosed → covered by T4c-1 unit
tests + integration smoke (Probe_HappyPath_AcrossBothSubstrates)
- (5) RecoveryModeLabelSurfaced → covered, both substrates
Catchup sender minor fix:
- ScanLBAs(0, ...) → ScanLBAs(1, ...) — LSN=0 is not a real entry;
smartwal's oldestPreserved=1 default would spuriously trip
ErrWALRecycled at fromLSN=0. TODO comment marks the future
threading of replica's flushed-LSN through StartCatchUp (post-T4d
engine→adapter→executor recovery wiring).
L3 m01 disconnect/reconnect script: deferred to follow-up; mini-plan
§2 T4c-3 specifies it as an artifact for QA's hardware run, not as
a build-time test. The L2 matrix in this commit is the unit-test-
time gate.
go test ./... -count=1 → all 21 packages green.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
3b54576e2f |
T4c-2: catch-up muscle port + state machine + ScanLBAs interface seam
Per design memo §7a + G-1 V2 read signed at v3-phase-15-t4c-2-g1-v2-read.md. Round-35 architect collapse: T4c-2 covers walstore wal_replay inner-loop muscle port (V2-faithful, narrow G-1 scope), smartwal state_convergence production promotion, peer state machine extensions (CatchingUp / NeedsRebuild), and observability surfacing. Storage substrate (G-1 §3 row #4 — interface seam): - Unified RecoveryEntry + ErrWALRecycled + RecoveryMode types in core/storage/recovery_contract.go (memo §5.1, §13.0a) - LogicalStorage.ScanLBAs interface method added; substrate dispatch is via interface, not type-switch - walstore POC promoted: walstore_recovery_poc.go → walstore_recovery.go; ScanFrom → ScanLBAs; uses unified storage.RecoveryEntry - smartwal POC promoted: recovery_poc.go → recovery_scan.go; ScanFrom → ScanLBAs; type alias to storage.RecoveryEntry - BlockStore implements ScanLBAs (state-convergence-equivalent synthesis since in-memory has no WAL retention; uses walHead as scan-time LSN so caller's targetLSN cap doesn't accidentally skip every entry) Catch-up sender muscle port (G-1 §3 narrow-scope inner loop): - core/transport/catchup_sender.go body rewritten: replaces AllBlocks-walk with primaryStore.ScanLBAs(0, fn) + per-entry ShipEntry write - INV-REPL-CATCHUP-CALLBACK-RETURN-NIL-CONTINUES honored: callback skips entries past targetLSN by returning nil (not error) - INV-REPL-CATCHUP-LASTSENT-MONOTONIC honored: lastSent only advances after successful frame write - INV-REPL-CATCHUP-DEADLINE-PER-CALL-SCOPE honored: SetDeadline at entry, cleared at exit (deferred) - INV-REPL-CATCHUP-TARGET-NOT-REACHED-VS-RECYCLED-DISTINGUISHED: ErrWALRecycled wrapped as tier-class change; target-not-reached surfaces as separate stream-level error - INV-REPL-CATCHUP-COMPLETION-FROM-BARRIER-ACHIEVED-LSN (§4.2 binding): completion judged from BarrierResponse.AchievedLSN, not from a separate MsgCatchupDone marker; recovery_mode label surfaces in success log per memo §5.1 Engine (G-1 §4.1, §4.3): - RecoveryRuntimePolicy.MaxRetries field added; per-kind defaults match V2 maxCatchupRetries=3 (wal_delta), 0 (full_extent), 1 (partial_lba) - applySessionFailed maps ErrWALRecycled in failure reason → recovery.Decision = Rebuild (G-1 §4.3 Option B); engine→storage decoupling preserved by string-match on the sentinel text rather than importing storage package Peer state machine (memo §2.2): - ReplicaCatchingUp + ReplicaNeedsRebuild states added - SetState method with table-driven replicaStateTransitionAllowed gate; rejects illegal transitions (NeedsRebuild is terminal in T4c per memo) Tests (15 new): - core/transport/catchup_sender_test.go (8 tests: 2 V2-mirror + 6 invariant pins for §5.1-§5.5 + §4.2 binding + sentinel + mode-label) - core/replication/peer_state_machine_test.go (4 tests: allowed transitions, rejected transitions, NeedsRebuild terminal, String forms) - core/engine/recovery_test.go (3 new: MaxRetries per-kind defaults pin, WAL-recycled escalation pin, non-recycled non-escalation pin) go test ./... -count=1 → all 21 packages green. Catalogue invariants queued for §3.3 inscription at T4c batch close: INV-REPL-CATCHUP-CALLBACK-RETURN-NIL-CONTINUES, INV-REPL-CATCHUP-LASTSENT-MONOTONIC, INV-REPL-CATCHUP-DEADLINE-PER-CALL-SCOPE, INV-REPL-CATCHUP-TARGET-NOT-REACHED-VS-RECYCLED-DISTINGUISHED, INV-REPL-CATCHUP-RECYCLE-ESCALATES, INV-REPL-CATCHUP-COMPLETION-FROM-BARRIER-ACHIEVED-LSN, INV-REPL-PEER-STATE-CATCHINGUP, INV-REPL-RECOVERY-MODE-OBSERVABLE. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
71e2e082c0 |
T4c-1: ProbeReq + ProbeResponse symmetric full-lineage wire + validation
Per architect round-26 Item C.3 (symmetric pair) + round-21 uniform rule
(every authority-bearing wire surface carries full RecoveryLineage).
Probe lineage source per architect Option D (post-QA-sign clarification):
adapter mints transient probe sessionID; executor reads primaryStore
boundary for TargetLSN; engine stays pure semantic reducer; probe
lineage NOT registered in executor.sessions; no SessionPrepared /
Started / Closed lifecycle for probe.
Wire (T4c-1):
- ProbeReq: 32B body — [SessionID][Epoch][EndpointVersion][TargetLSN]
- ProbeResp: 56B body — [32B echoed lineage][8B R][8B S][8B H]
- Both directions: strict decode (short / zeroed lineage / field-order
drift rejected) mirrored from BarrierResp (T4b-1)
Replica side (replica.go MsgProbeReq):
- decodes lineage; validates via new validateProbeLineage (rejects
zeros + strictly older epoch/endpointVersion); does NOT advance
activeLineage (probe is non-mutating; advancing would race ahead of
in-flight catch-up/rebuild sessionIDs and stale-reject their frames)
- echoes lineage in 32B prefix of response
Primary side (executor.go BlockExecutor.Probe):
- new sessionID parameter (adapter-minted); reads primaryStore.Boundaries()
for TargetLSN floor (max(1, primaryH)); builds full RecoveryLineage
- sends EncodeProbeReq; validates echoed lineage on response;
ErrProbeLineageMismatch surfaces in FailReason on mismatch (mirrors
T4b-2 ErrBarrierLineageMismatch)
Adapter (adapter.go):
- prepareQueuedCommands mints transient probe sessionID for ProbeReplica
(parallel to FenceAtEpoch); executeCommand passes sessionID through
- CommandExecutor.Probe interface gains sessionID parameter; all test
executor stubs updated (mockExecutor, closureExecutor, policyClosure,
restartExecutor, HealthyPath, noop, ops nopExecutor)
INV-REPL-LINEAGE-BORNE-ON-PROBE-PAIR inscribed at catalogue §3.3 close
(both directions carry full lineage; both fail-closed on
short/zeroed/malformed; primary-side filters by full-lineage match).
Tests (21 new across 3 files):
- core/transport/probe_wire_test.go (12 wire pins)
- core/transport/probe_validation_test.go (7 replica + primary contract)
- core/adapter/probe_session_test.go (2 transient sessionID)
Existing test fix:
- TestFailClosed_ProbeDuringRebuild_DoesNotDisturbActiveLineage rewritten
as TestFailClosed_StaleProbeDuringRebuild_RejectedAndRebuildContinues —
pre-T4c-1 premise ("probe is observation only, no lineage") is
invalidated; new contract: stale probe rejected without echo,
fresh probe authority-bearing
- protocol_test envelope round-trip uses new probe shapes
- transport_test.go probe call passes sessionID
go test ./... -count=1 → all 21 packages green.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
eadc113697 |
T4c-pre-B: unified StartRecovery command + per-kind runtime policy
Per design memo §7a (architect rounds 29-30): introduce semantic unification at the command boundary — one StartRecovery covers catch-up / rebuild / partial-LBA — without unifying runtime behavior. RecoveryRuntimePolicy carries per-content-kind envelope (timeout / progress cadence / cancellation mode); engine populates via DefaultRuntimePolicyFor at emit time. - core/engine: StartRecovery + RecoveryContentKind (wal_delta / full_extent / partial_lba) + DurationClass + CancellationMode + RecoveryRuntimePolicy + DefaultRuntimePolicyFor. - core/adapter: CommandExecutor.StartRecoverySession; adapter dispatch wired (queue + execute + start watchdog). - core/transport: BlockExecutor.StartRecoverySession bridges wal_delta → catch-up sender, full_extent → rebuild sender; partial_lba returns explicit Stage-2 error; validateRecoveryPolicy enforces non-empty envelope + wal_delta+CancelOnTimeout requires Timeout > 0. - Test executors (authority, host/volume, ops) updated with stub StartRecoverySession. - 10 new engine tests (command shape, per-kind defaults, label strings, cadence/timeout consistency); 8 new transport tests (policy validation, dispatch contract — partial_lba rejected, unknown kind rejected, policy-validates-before-dispatch). Legacy StartCatchUp / StartRebuild retained as engine emit shape; T4c-3 muscle port migrates engine emission to StartRecovery. go test ./... -count=1 → all 21 packages green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
9ffc149293 |
T4c-pre-A POC walstore — wal_replay tier-1 mode validation (round 34)
Confirmatory POC for walstore substrate per memo §12 + §13.0a +
§5.1. Validates V2-faithful per-LSN tier-1 mode (`wal_replay`)
in contrast to smartwal's `state_convergence` mode.
Code (POC, NOT production):
core/storage/walstore_recovery_poc.go (~240 LOC)
New types:
- RecoveryEntry{LSN, LBA, Flags, Data} — sibling to smartwal's
type; same shape, different package; T4c-3 muscle port will
unify behind LogicalStorage.ScanLBAs
- ErrWALRecycled (sentinel; mirrors V2 walstore semantics)
New methods on *WALStore:
- ScanFrom(fromLSN, fn) error — walks WAL physical region
between logicalTail and logicalHead, decodes each record,
filters LSN >= fromLSN && < headLSN, emits in LSN-ascending
order. Per-LSN, NOT deduped. Returns ErrWALRecycled if
fromLSN <= checkpointLSN.
- WALCapacityBytes() — POC retention characterization
- CheckpointLSNForPOC() — sibling for retention boundary tests
core/storage/walstore_recovery_poc_test.go (~440 LOC)
8 POC tests, all pass:
#1 — TestPOC_Walstore_ScanFrom_BasicRange
#1 — TestPOC_Walstore_ScanFrom_FromHeadOrAbove_Empty (3 sub)
#1 KEY PIN —
TestPOC_Walstore_ScanFrom_PerLSNNotDeduped: 3 writes to
LBA=0 → 3 entries with markers 0xA1/0xA2/0xA3. Pins
V2-faithful per-LSN semantic and confirms
INV-REPL-RECOVERY-STREAM-LBA-DEDUP is NOT applicable to
walstore (smartwal-mode-scoped per memo §13.6 round-34).
#1+#4 — TestPOC_Walstore_ScanFrom_ErrWALRecycled: boundary
fires at fromLSN <= checkpointLSN
#2 — TestPOC_Walstore_AllBlocks_DeterministicOrdering
#3 — TestPOC_Walstore_ScanFrom_ConcurrentLiveWrite_Safe:
no deadlock, no torn reads; emitted Data contemporaneous
with emitted LSN (data-staleness from smartwal §3.2 does
NOT apply to walstore — append-only WAL slots are
immutable once written)
#4 — TestPOC_Walstore_RetentionBoundary_Characterized:
deterministic boundary at checkpointLSN
sanity — TestPOC_Walstore_Sanity_ExistingAPIsUnchanged
Findings (per POC report §3.b):
- V2-faithful per-LSN tier-1: walstore preserves entry data IN
the WAL (LBA + LSN + Data), so 3 writes to same LBA produce
3 emitted RecoveryEntry, each with the data that LSN actually
wrote. Contrast with smartwal which emits 1 entry with current
extent data.
- ErrWALRecycled boundary: dynamic, advances with flusher
activity. Contrast with smartwal's fixed walSlots window.
- Concurrent live-write: walstore's append-only WAL records are
immutable; concurrent live-write doesn't rewrite slots. Per-
LSN data preservation makes data-staleness a non-issue. POC
finds no torn reads, no deadlock, contemporaneous data
labeling.
- BUG-007 not exercised (Windows/dev-loop only); deferred to
T4c-5 L3 m01 integration matrix per memo §5.
POC report (sw-block/design/v3-phase-15-t4c-pre-poc-report.md)
extended:
- §1 executive summary expanded to 8-case 2-substrate matrix
- New §3.b walstore findings section
- §5 substrate-specific concerns: walstore concerns now ✅
addressed (ring-buffer recycling consistency verified)
- §6 acceptance: clean on both substrates
- §7 next steps: T4c-pre-B in flight; T4c mini-plan follows
- §8 sign + §9 change log entries for round-34 walstore POC
Verification: full 21-package repo suite green. POC code isolated
to walstore + smartwal POC files; no impact on production paths.
T4c-pre-A POC closed. T4c-pre-B engine command model upgrade
proceeds next.
|
||
|
|
9d894c4ecf |
T4c-pre-A POC: smartwal recovery scan capability validation
Per design memo §12 (`v3-phase-15-t4c-recovery-protocol-design.md`):
substrate-level POC validating that smartwal can support the four
operations the unified recovery protocol requires. Discovers + pins
a critical semantic question that gates T4c-1 wire coding.
Code (POC, NOT production — file names + godoc mark POC):
core/storage/smartwal/recovery_poc.go (~220 LOC)
New types:
- RecoveryEntry{LSN, LBA, Flags, Data}
- ErrWALRecycled (sentinel; mirrors V2 walstore semantics)
New methods on *Store:
- ScanFrom(fromLSN, fn) error — emits per-LBA last-writer-wins
within LSN range; returns ErrWALRecycled if fromLSN below
retention boundary; mid-scan recycle re-checked
- RingCapacity() uint64 — exposes slot count for retention
characterization tests
core/storage/smartwal/recovery_poc_test.go (~450 LOC)
8 POC tests, all pass:
#1 — TestPOC_ScanFrom_BasicRange (capability #1)
#1 — TestPOC_ScanFrom_FromHeadOrAbove_Empty (3 sub)
§3.1 finding pin —
TestPOC_ScanFrom_LastWriterWinsPerLBA: 3 writes to same
LBA in range emit 1 entry (not 3) — pins smartwal-specific
semantic that V2 wire-parity-strict cannot be delivered
#1+#4 — TestPOC_ScanFrom_ErrWALRecycled
#2 — TestPOC_AllBlocks_DeterministicOrdering
#3 — TestPOC_ScanFrom_ConcurrentLiveWrite_DataStaleness:
no deadlock, no torn reads; documents the data-staleness
semantic where emitted LSN labels reflect slot-record at
scan-time but emitted Data may belong to a newer LSN
(cross-lane bitmap reconciliation handles this)
#4 — TestPOC_RetentionBoundary_Characterized: 8/16/64
slot characterization; ErrWALRecycled fires precisely at
head-walSlots
sanity — TestPOC_Sanity_ExistingAPIsUnchanged
POC report at sw-block/design/v3-phase-15-t4c-pre-poc-report.md
documents:
§3.1 Critical finding — architect decision required:
smartwal's WAL stores metadata only; extent holds only the
latest data per LBA. Tier-1 recovery cannot deliver every-LSN-
entry-in-range (V2 strict-parity); CAN deliver last-writer-
wins per LBA in range (state-convergence-equivalent). Two
options surfaced; sw recommends Option A (state-convergence)
because: (a) replica state convergence identical, (b) bitmap
mask rule keyed on LBA so cross-lane reconciliation
unaffected, (c) keeps smartwal as sign-bearing substrate
without architectural change, (d) bandwidth-efficient.
§3.2 Concurrent live-write data staleness:
Within recovery-stream lane, emitted LSN may not match
emitted Data. Bitmap mask rule (memo §2.2) handles this
correctly at the replica because it's keyed on LBA. Recovery
handler at T4c-2 must NOT rely on per-entry LSN-vs-data
consistency.
§3.3 Retention characterization:
Deterministic — `walSlots` slots = `walSlots` LSNs of
retention. ErrWALRecycled fires precisely when
fromLSN < head - walSlots.
Walstore POC deferred per §4 of report — pending architect
decision on §3.1. If Option A: walstore POC is straightforward
mirror of smartwal scope (1 day). If Option B: walstore is
primary path and smartwal requires substrate work first.
Verification: full 21-package repo suite green. POC code is
isolated to smartwal package; no impact on production paths.
T4c-pre-A POC complete pending architect §3.1 decision. Standing
by for architect ruling, then walstore POC, then T4c-pre-B engine
command model upgrade, then T4c-1 wire.
|