From f6ae66254fe2c225f352d215f71d3dc1b095bba7 Mon Sep 17 00:00:00 2001 From: wzcheng99 Date: Thu, 23 Apr 2026 17:30:53 -0700 Subject: [PATCH] T4a-6 follow-up: four QA spot-check fixes (install-or-refuse, uint32 assertions, host-level tests, matrix honesty) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit QA round-21 spot-check flagged four issues in the T4a-6 landing. All four confirmed correct; this commit addresses them as one reviewable unit per QA's recommended batch. Finding #1 (HIGH) — install-or-refuse ordering in Host.streamOnce. Previous order was OnAssignment → UpdateReplicaSet, creating a window where the adapter's projection flipped Healthy before the peer set was installed. StorageBackend.lineageCheck would then pass and admit local-only writes with zero fan-out. V2 atomically set replicas before admitting writes; V3 had drifted. Fix: - Extract applyFact(fact) from streamOnce's inner loop so the handler logic is testable in isolation. - Invert order: if h.replication != nil, call UpdateReplicaSet FIRST. On failure, LOG and RETURN without calling OnAssignment. Adapter projection stays at its prior (not-Healthy until a fact fully installs) state; StorageBackend keeps writes blocked; master's stream replay redelivers the fact and natural convergence resumes on the next cycle. - Introduce narrow collaborator interfaces (assignmentConsumer, replicaSetUpdater) on Host so test doubles can drive applyFact without spinning up a real adapter + transport listener. The concrete adapter reference is retained as realAdpt for the existing Adapter() accessor. Finding #2 (MEDIUM) — generation aliasing at the uint32 boundary. `(epoch << 32) | uint32(ev)` silently aliased distinct authority lines whenever either field exceeded 2^32. Fix: - Extract generationFitsUint32(epoch, ev) as a named package- level function with a descriptive reason string. - SubscribeAssignments calls generationFitsUint32 before minting the fact; on rejection, logs a structured diagnostic + skips the fact (master keeps running — this is a fail-fast on an invariant violation upstream, not a master-side error). - Pin with two adversarial tests: TestGenerationFitsUint32_ MaxValidAccepted (epoch = 2^32-1, ev = 2^32-1 passes) and _OverflowRejected (epoch = 2^32 and ev = 2^32 each reject with reasons naming the offending field). Finding #3 (MEDIUM) — T4a-5 host wire was uncovered by T4a-6. The L2 integration test bypassed Host.streamOnce entirely, so the "all T4a commits compose correctly" claim in commit 420a5a1 was stronger than what the test proved. Fix: - New apply_fact_test.go in core/host/volume with five pins: * TestHost_ApplyFact_Self_InstallsReplicaSetBeforeAssignment (ordering recorder proves UpdateReplicaSet before OnAssignment in the happy path). * TestHost_ApplyFact_Self_UpdateReplicaSetFailure_SkipsOnAssignment (fail-closed pin for finding #1). * TestHost_ApplyFact_Supersede_NeverCallsAdapterOrReplication (the supersede branch is unaffected by the reordering). * TestHost_ApplyFact_ObserverOnly_NoReplicationCallsOnAssignment (nil replication seam still flows to OnAssignment as before). * TestDecodeReplicaTargets_FieldCopy (auxiliary; catches decoder drift). - The commit message and batch-close story now honestly reflect that host ordering is covered. Full master → gRPC → host subprocess L2 integration deferred to T4b/T4c where the durability/recovery path makes it materially more valuable (per QA round-21 guidance). Finding #4 (LOW) — matrix 'non-gating' fiction removed. The earlier runMatrix harness had walstore_nongating that claimed to demote subtest failures. Go's testing has no clean demote-subtest-failure API; the defer-based logic didn't actually demote. Replaced with honest naming: walstore is a second gating row (passes today under T4a best-effort paths; if it ever regresses under BUG-007 the test fails honestly and we invest in a real demotion harness then). File header comment updated to match. Verification: full 21-package repo suite green including core/host (122s integration run) and the 5 new host tests. No regressions. --- seaweed-block/core/host/master/services.go | 46 ++- .../core/host/master/services_test.go | 110 ++++++ .../core/host/volume/apply_fact_test.go | 335 ++++++++++++++++++ seaweed-block/core/host/volume/host.go | 147 +++++--- .../core/replication/l2_integration_test.go | 41 +-- 5 files changed, 604 insertions(+), 75 deletions(-) create mode 100644 seaweed-block/core/host/master/services_test.go create mode 100644 seaweed-block/core/host/volume/apply_fact_test.go diff --git a/seaweed-block/core/host/master/services.go b/seaweed-block/core/host/master/services.go index cb7657f782..47e9e4eef4 100644 --- a/seaweed-block/core/host/master/services.go +++ b/seaweed-block/core/host/master/services.go @@ -178,6 +178,20 @@ func (s *services) SubscribeAssignments(req *control.SubscribeRequest, stream co continue } } + // T4a-5 P-refined generation derivation requires each of + // Epoch and EndpointVersion to fit in uint32; aliasing at + // the 2^32 boundary would silently collapse distinct + // authority lines onto the same generation and break the + // monotonic stale-replay guard on the volume side. We + // assert + skip rather than panic: the fact has no valid + // generation, so we can't send it, but the master should + // keep running so operators can page + fix upstream. + if reason, ok := generationFitsUint32(info.Epoch, info.EndpointVersion); !ok { + fmt.Printf("services: volume %s replica %s: %s; skipping fact\n", + info.VolumeID, info.ReplicaID, reason) + continue + } + lastEpoch = info.Epoch lastEV = info.EndpointVersion sentAny = true @@ -193,13 +207,12 @@ func (s *services) SubscribeAssignments(req *control.SubscribeRequest, stream co // LastPublished queries for every non-self replica slot in // this volume's topology. peer_set_generation is derived // from the authoritative line's (Epoch, EndpointVersion) - // so it is monotonic across process lifetimes (the - // publisher's lex-dedupe upstream guarantees strictly- - // increasing (Epoch, EV) pairs within the stream, and the - // same ordering is preserved across master restarts - // because Epoch/EV are durable authority facts). + // packed into one uint64 as (epoch<<32 | ev). Assertion + // above guarantees each fits in uint32 so no aliasing. + // Monotonic across process lifetimes because Epoch/EV are + // durable authority facts preserved across master restart. fact.Peers = s.collectPeers(req.VolumeId, info.ReplicaID) - fact.PeerSetGeneration = (info.Epoch << 32) | uint64(uint32(info.EndpointVersion)) + fact.PeerSetGeneration = (info.Epoch << 32) | info.EndpointVersion if err := stream.Send(fact); err != nil { return err } @@ -275,6 +288,27 @@ func validateHeartbeat(r *control.HeartbeatReport) error { return nil } +// generationFitsUint32 reports whether the (epoch, endpointVersion) +// pair can be safely packed into one uint64 as `(epoch<<32) | ev`. +// Returns (reason, false) when either exceeds 2^32-1 — in that case +// SubscribeAssignments skips the fact rather than silently alias +// distinct authority lines onto the same peer_set_generation. +// +// Assertion landed at T4a-5.0 follow-up (QA finding #2). Paired with +// TestGenerationFitsUint32_* pins in services_test.go. Named as a +// pure function so tests can exercise boundary cases without +// driving a full gRPC stream. +func generationFitsUint32(epoch, endpointVersion uint64) (reason string, ok bool) { + const uint32Max = uint64(1) << 32 + if epoch >= uint32Max { + return fmt.Sprintf("epoch %d exceeds uint32 — peer_set_generation would alias", epoch), false + } + if endpointVersion >= uint32Max { + return fmt.Sprintf("endpoint_version %d exceeds uint32 — peer_set_generation would alias", endpointVersion), false + } + return "", true +} + // collectPeers builds the AssignmentFact.peers list for a volume // from the publisher's most-recent authoritative lines. Only // replicas OTHER than self_replica are included — the primary diff --git a/seaweed-block/core/host/master/services_test.go b/seaweed-block/core/host/master/services_test.go new file mode 100644 index 0000000000..b6629130ff --- /dev/null +++ b/seaweed-block/core/host/master/services_test.go @@ -0,0 +1,110 @@ +package master + +// T4a-5.0 follow-up: boundary pins for generationFitsUint32. The +// SubscribeAssignments publisher packs (epoch, endpoint_version) +// into a single uint64 as peer_set_generation; each half must fit +// in uint32 or distinct authority lines alias to the same +// generation and break the monotonic stale-replay guard on the +// volume side. QA finding #2 required this be asserted with +// explicit max-valid + overflow-rejected tests rather than +// comment-only. + +import "testing" + +// --- Test 1: max-valid pair accepted --- + +// TestGenerationFitsUint32_MaxValidAccepted — the largest pair that +// still packs without aliasing. Epoch = 2^32 - 1, EV = 2^32 - 1. +// Must pass. Any tightening of the bound (e.g., adding <= instead +// of <) would fail this test, so the max-valid edge is pinned. +func TestGenerationFitsUint32_MaxValidAccepted(t *testing.T) { + const maxU32 = uint64(1<<32) - 1 + + reason, ok := generationFitsUint32(maxU32, maxU32) + if !ok { + t.Fatalf("max-valid pair (epoch=%d, ev=%d) rejected: %s", maxU32, maxU32, reason) + } + if reason != "" { + t.Fatalf("max-valid returned non-empty reason: %q", reason) + } + + // Individually at max: also valid. + if _, ok := generationFitsUint32(maxU32, 1); !ok { + t.Fatal("(max, 1) rejected") + } + if _, ok := generationFitsUint32(1, maxU32); !ok { + t.Fatal("(1, max) rejected") + } + + // Zero is valid at this level (generation==0 has its own + // semantics on the volume side; this assertion is purely + // about alias safety). + if _, ok := generationFitsUint32(0, 0); !ok { + t.Fatal("(0, 0) rejected") + } +} + +// --- Test 2: overflow rejected --- + +// TestGenerationFitsUint32_OverflowRejected — 2^32 is the smallest +// value that would alias. Must be rejected with a descriptive +// reason that names the offending field + value. If either field +// slips past the check, the aliasing hazard returns silently. +func TestGenerationFitsUint32_OverflowRejected(t *testing.T) { + const over = uint64(1) << 32 + + // Epoch overflow. + reason, ok := generationFitsUint32(over, 0) + if ok { + t.Fatal("epoch=2^32 must be rejected") + } + if reason == "" { + t.Fatal("overflow must return non-empty reason") + } + if !containsAll(reason, "epoch", "alias") { + t.Fatalf("epoch-overflow reason should mention 'epoch' + 'alias', got: %q", reason) + } + + // EndpointVersion overflow. + reason, ok = generationFitsUint32(0, over) + if ok { + t.Fatal("endpoint_version=2^32 must be rejected") + } + if !containsAll(reason, "endpoint_version", "alias") { + t.Fatalf("ev-overflow reason should mention 'endpoint_version' + 'alias', got: %q", reason) + } + + // Both overflow: still rejected (epoch check fires first — + // either check firing is acceptable, we just pin "rejected"). + if _, ok := generationFitsUint32(over, over); ok { + t.Fatal("both-overflow must be rejected") + } + + // Far above threshold still rejected. + if _, ok := generationFitsUint32(uint64(1)<<40, 0); ok { + t.Fatal("epoch=2^40 must be rejected") + } + if _, ok := generationFitsUint32(0, ^uint64(0)); ok { + t.Fatal("endpoint_version=uint64 max must be rejected") + } +} + +// --- helpers --- + +func containsAll(s string, subs ...string) bool { + for _, sub := range subs { + if !stringContains(s, sub) { + return false + } + } + return true +} + +func stringContains(s, sub string) bool { + for i := 0; i+len(sub) <= len(s); i++ { + if s[i:i+len(sub)] == sub { + return true + } + } + return false +} diff --git a/seaweed-block/core/host/volume/apply_fact_test.go b/seaweed-block/core/host/volume/apply_fact_test.go new file mode 100644 index 0000000000..23f4bc6177 --- /dev/null +++ b/seaweed-block/core/host/volume/apply_fact_test.go @@ -0,0 +1,335 @@ +package volume + +// T4a-6 follow-up: host-level tests for the install-or-refuse +// ordering fix. Exercises Host.applyFact directly (extracted from +// streamOnce) with stub adapter + stub ReplicationVolume so the +// ordering and failure-skip semantics can be asserted without a +// real gRPC stream or a real transport listener. +// +// Covers QA finding #1 (ordering + fail-closed) and QA finding #3 +// (real coverage of the T4a-5 host seam beyond just the +// decodeReplicaTargets field-copy). + +import ( + "errors" + "io" + "log" + "sync" + "sync/atomic" + "testing" + + "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/replication" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +// newDiscardLogger returns a logger that discards all output. Keeps +// the stub-host tests quiet. +func newDiscardLogger() *log.Logger { + return log.New(io.Discard, "", 0) +} + +// --- Stubs --- + +// orderingRecorder logs the sequence of collaborator method calls so +// tests can assert "UpdateReplicaSet happened before OnAssignment". +type orderingRecorder struct { + mu sync.Mutex + sequence []string +} + +func (o *orderingRecorder) record(event string) { + o.mu.Lock() + defer o.mu.Unlock() + o.sequence = append(o.sequence, event) +} + +func (o *orderingRecorder) snapshot() []string { + o.mu.Lock() + defer o.mu.Unlock() + out := make([]string, len(o.sequence)) + copy(out, o.sequence) + return out +} + +type stubAdapter struct { + rec *orderingRecorder + callCount atomic.Int64 + lastInfo adapter.AssignmentInfo +} + +func (s *stubAdapter) OnAssignment(info adapter.AssignmentInfo) adapter.ApplyLog { + s.callCount.Add(1) + s.lastInfo = info + s.rec.record("OnAssignment") + return adapter.ApplyLog{} +} + +type stubReplication struct { + rec *orderingRecorder + callCount atomic.Int64 + lastGeneration uint64 + lastTargetIDs []string + returnErr error +} + +func (s *stubReplication) UpdateReplicaSet(generation uint64, targets []replication.ReplicaTarget) error { + s.callCount.Add(1) + s.lastGeneration = generation + s.lastTargetIDs = nil + for _, t := range targets { + s.lastTargetIDs = append(s.lastTargetIDs, t.ReplicaID) + } + s.rec.record("UpdateReplicaSet") + return s.returnErr +} + +// newStubbedHost builds a Host shell suitable for driving applyFact +// directly. Avoids grpc.NewClient + adapter.NewVolumeReplicaAdapter, +// which want real network / executor wiring. +func newStubbedHost(t *testing.T, volumeID, replicaID string, rec *orderingRecorder) (*Host, *stubAdapter, *stubReplication) { + t.Helper() + a := &stubAdapter{rec: rec} + r := &stubReplication{rec: rec} + h := &Host{ + cfg: Config{ + VolumeID: volumeID, + ReplicaID: replicaID, + }, + log: newDiscardLogger(), + adpt: a, + replication: r, + } + return h, a, r +} + +// --- Test 1: install-or-refuse ordering --- + +// TestHost_ApplyFact_Self_InstallsReplicaSetBeforeAssignment — the +// primary QA finding #1 pin. For a self-replica fact, +// UpdateReplicaSet MUST run before OnAssignment so the adapter's +// projection cannot flip Healthy before peers are installed. +func TestHost_ApplyFact_Self_InstallsReplicaSetBeforeAssignment(t *testing.T) { + rec := &orderingRecorder{} + h, a, r := newStubbedHost(t, "vol1", "r1", rec) + + fact := &control.AssignmentFact{ + VolumeId: "vol1", + ReplicaId: "r1", // self + Epoch: 5, + EndpointVersion: 2, + DataAddr: "127.0.0.1:1000", + CtrlAddr: "127.0.0.1:1001", + Peers: []*control.ReplicaDescriptor{{ + ReplicaId: "r2", + Epoch: 5, + EndpointVersion: 2, + DataAddr: "127.0.0.1:2000", + CtrlAddr: "127.0.0.1:2001", + }}, + PeerSetGeneration: 42, + } + + h.applyFact(fact) + + // Both collaborators called exactly once. + if got := r.callCount.Load(); got != 1 { + t.Fatalf("UpdateReplicaSet calls: got %d want 1", got) + } + if got := a.callCount.Load(); got != 1 { + t.Fatalf("OnAssignment calls: got %d want 1", got) + } + + // Ordering: UpdateReplicaSet BEFORE OnAssignment. + seq := rec.snapshot() + if len(seq) != 2 { + t.Fatalf("sequence length=%d want 2: %v", len(seq), seq) + } + if seq[0] != "UpdateReplicaSet" || seq[1] != "OnAssignment" { + t.Fatalf("wrong ordering: got %v, want [UpdateReplicaSet OnAssignment]", seq) + } + + // Replication received the right payload. + if r.lastGeneration != 42 { + t.Fatalf("replication generation: got %d want 42", r.lastGeneration) + } + if len(r.lastTargetIDs) != 1 || r.lastTargetIDs[0] != "r2" { + t.Fatalf("replication targets: got %v want [r2]", r.lastTargetIDs) + } + + // Adapter received the right identity. + if a.lastInfo.Epoch != 5 || a.lastInfo.EndpointVersion != 2 { + t.Fatalf("adapter identity: got (epoch=%d, ev=%d) want (5, 2)", + a.lastInfo.Epoch, a.lastInfo.EndpointVersion) + } +} + +// --- Test 2: fail-closed on UpdateReplicaSet failure --- + +// TestHost_ApplyFact_Self_UpdateReplicaSetFailure_SkipsOnAssignment — +// QA finding #1 part 2: if UpdateReplicaSet fails for any reason, +// OnAssignment MUST be skipped. Adapter projection stays at its +// prior (not-Healthy) state; StorageBackend keeps writes blocked +// until master stream replay redelivers a fact that installs. +func TestHost_ApplyFact_Self_UpdateReplicaSetFailure_SkipsOnAssignment(t *testing.T) { + rec := &orderingRecorder{} + h, a, r := newStubbedHost(t, "vol1", "r1", rec) + r.returnErr = errors.New("simulated UpdateReplicaSet failure") + + fact := &control.AssignmentFact{ + VolumeId: "vol1", + ReplicaId: "r1", + Epoch: 3, + EndpointVersion: 1, + DataAddr: "127.0.0.1:1000", + CtrlAddr: "127.0.0.1:1001", + PeerSetGeneration: 7, + } + + h.applyFact(fact) + + // UpdateReplicaSet was called (once). + if got := r.callCount.Load(); got != 1 { + t.Fatalf("UpdateReplicaSet calls: got %d want 1", got) + } + // OnAssignment was NOT called — fail-closed. + if got := a.callCount.Load(); got != 0 { + t.Fatalf("fail-closed violated: OnAssignment calls=%d want 0", got) + } + // Sequence has exactly one entry, UpdateReplicaSet. + seq := rec.snapshot() + if len(seq) != 1 || seq[0] != "UpdateReplicaSet" { + t.Fatalf("sequence: got %v, want [UpdateReplicaSet]", seq) + } +} + +// --- Test 3: supersede branch unaffected --- + +// TestHost_ApplyFact_Supersede_NeverCallsAdapterOrReplication — +// guards the supersede branch (fact names another replica). Neither +// OnAssignment nor UpdateReplicaSet should fire — only recordOtherLine. +func TestHost_ApplyFact_Supersede_NeverCallsAdapterOrReplication(t *testing.T) { + rec := &orderingRecorder{} + h, a, r := newStubbedHost(t, "vol1", "r1", rec) + + fact := &control.AssignmentFact{ + VolumeId: "vol1", + ReplicaId: "r2", // not self + Epoch: 9, + EndpointVersion: 1, + PeerSetGeneration: 100, + } + + h.applyFact(fact) + + if a.callCount.Load() != 0 { + t.Fatalf("supersede must not call adapter: got %d calls", a.callCount.Load()) + } + if r.callCount.Load() != 0 { + t.Fatalf("supersede must not call replication: got %d calls", r.callCount.Load()) + } + if h.LastOtherLine() == nil { + t.Fatal("supersede did not record other line") + } + if h.LastOtherLine().ReplicaId != "r2" { + t.Fatalf("recorded wrong replica: got %s want r2", h.LastOtherLine().ReplicaId) + } +} + +// --- Test 4: observer-only mode (replication == nil) --- + +// TestHost_ApplyFact_ObserverOnly_NoReplicationCallsOnAssignment — +// when ReplicationVolume is nil (T0 / observer-only), apply flows +// straight to OnAssignment; the fact's peer list + generation are +// ignored on this host. +func TestHost_ApplyFact_ObserverOnly_NoReplicationCallsOnAssignment(t *testing.T) { + rec := &orderingRecorder{} + a := &stubAdapter{rec: rec} + h := &Host{ + cfg: Config{ + VolumeID: "vol1", + ReplicaID: "r1", + }, + log: newDiscardLogger(), + adpt: a, + replication: nil, // observer-only + } + + fact := &control.AssignmentFact{ + VolumeId: "vol1", + ReplicaId: "r1", + Epoch: 1, + EndpointVersion: 1, + PeerSetGeneration: 1, + Peers: []*control.ReplicaDescriptor{{ + ReplicaId: "r99", + }}, + } + + h.applyFact(fact) + + if a.callCount.Load() != 1 { + t.Fatalf("observer-only must call adapter: got %d", a.callCount.Load()) + } + seq := rec.snapshot() + if len(seq) != 1 || seq[0] != "OnAssignment" { + t.Fatalf("observer-only sequence: got %v, want [OnAssignment]", seq) + } +} + +// --- Test 5: auxiliary field-copy test for decodeReplicaTargets --- + +// TestDecodeReplicaTargets_FieldCopy — small auxiliary pin verifying +// the host-only decoder is a pure field copy (matches +// decodeAssignmentFact discipline). Not the main T4a-5 coverage +// (applyFact tests above own that), but fence against future drift. +func TestDecodeReplicaTargets_FieldCopy(t *testing.T) { + fact := &control.AssignmentFact{ + Peers: []*control.ReplicaDescriptor{ + { + ReplicaId: "peer-alpha", + Epoch: 11, + EndpointVersion: 22, + DataAddr: "10.0.0.1:5000", + CtrlAddr: "10.0.0.1:5001", + }, + { + ReplicaId: "peer-beta", + Epoch: 12, + EndpointVersion: 23, + DataAddr: "10.0.0.2:5000", + CtrlAddr: "10.0.0.2:5001", + }, + }, + PeerSetGeneration: 99, + } + + targets, gen := decodeReplicaTargets(fact) + + if gen != 99 { + t.Fatalf("generation: got %d want 99", gen) + } + if len(targets) != 2 { + t.Fatalf("targets length: got %d want 2", len(targets)) + } + expect := []replication.ReplicaTarget{ + {ReplicaID: "peer-alpha", Epoch: 11, EndpointVersion: 22, DataAddr: "10.0.0.1:5000", ControlAddr: "10.0.0.1:5001"}, + {ReplicaID: "peer-beta", Epoch: 12, EndpointVersion: 23, DataAddr: "10.0.0.2:5000", ControlAddr: "10.0.0.2:5001"}, + } + for i, want := range expect { + got := targets[i] + if got != want { + t.Fatalf("target[%d]: got %+v, want %+v", i, got, want) + } + } + + // Empty-peers case. + factEmpty := &control.AssignmentFact{PeerSetGeneration: 5} + tgts, g := decodeReplicaTargets(factEmpty) + if len(tgts) != 0 { + t.Fatalf("empty peers: got %d targets want 0", len(tgts)) + } + if g != 5 { + t.Fatalf("empty peers generation: got %d want 5", g) + } +} diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index 5b043da6a5..8fa2fab7dd 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -60,11 +60,12 @@ type Config struct { // ReplicationVolume, when non-nil, receives peer-set updates on // every self-replica AssignmentFact. The Host calls - // UpdateReplicaSet(peer_set_generation, targets) AFTER - // adapter.OnAssignment so identity ingestion and replication - // ingestion progress together but do not cross the decode - // boundary (peers are decoded via subscribe.go:decodeReplicaTargets, - // not via decodeAssignmentFact). + // UpdateReplicaSet(peer_set_generation, targets) BEFORE + // adapter.OnAssignment — install-or-refuse ordering (T4a-6 + // follow-up fix). If UpdateReplicaSet fails, OnAssignment is + // skipped so the adapter's projection stays not-Healthy and the + // StorageBackend's lineageCheck keeps writes blocked until master + // stream replay redelivers a fact that can be fully installed. // // Nil means "no replication fan-out" (T0 observer-only hosts, // bootstrap before ReplicationVolume is ready). T4a-5 production @@ -72,14 +73,35 @@ type Config struct { ReplicationVolume *replication.ReplicationVolume } +// assignmentConsumer is the narrow interface Host needs from the +// adapter. *adapter.VolumeReplicaAdapter satisfies it. Test doubles +// can substitute to drive applyFact without a real adapter + engine. +type assignmentConsumer interface { + OnAssignment(info adapter.AssignmentInfo) adapter.ApplyLog +} + +// replicaSetUpdater is the narrow interface Host needs from the +// replication layer. *replication.ReplicationVolume satisfies it. +// Test doubles can substitute to drive applyFact without needing a +// real per-volume fan-out + transport listener. +type replicaSetUpdater interface { + UpdateReplicaSet(generation uint64, targets []replication.ReplicaTarget) error +} + // Host is the composed volume-side block product daemon. type Host struct { cfg Config log *log.Logger exec *noopExecutor t1exec *HealthyPathExecutor - adpt *adapter.VolumeReplicaAdapter - view *AdapterProjectionView + adpt assignmentConsumer + // realAdpt is the underlying concrete adapter. Exposed for + // production call sites that need the full surface (status + // server, projection view wiring). Tests swap adpt only and + // leave realAdpt nil. + realAdpt *adapter.VolumeReplicaAdapter + view *AdapterProjectionView + replication replicaSetUpdater // nil = observer-only (no fan-out) conn *grpc.ClientConn obsCli control.ObservationServiceClient @@ -175,14 +197,18 @@ func New(cfg Config) (*Host, error) { adpt := adapter.NewVolumeReplicaAdapter(execIface) h := &Host{ - cfg: cfg, - log: lg, - exec: noopExec, - t1exec: t1Exec, - adpt: adpt, - conn: conn, - obsCli: control.NewObservationServiceClient(conn), - asnCli: control.NewAssignmentServiceClient(conn), + cfg: cfg, + log: lg, + exec: noopExec, + t1exec: t1Exec, + adpt: adpt, + realAdpt: adpt, + conn: conn, + obsCli: control.NewObservationServiceClient(conn), + asnCli: control.NewAssignmentServiceClient(conn), + } + if cfg.ReplicationVolume != nil { + h.replication = cfg.ReplicationVolume } // View wires host as the SupersedeProbe so fail-closed kicks // in when master names another replica at a newer lineage. @@ -222,7 +248,7 @@ func (h *Host) IsSuperseded(selfReplicaID string, selfEpoch, selfEV uint64) bool func (h *Host) ProjectionView() *AdapterProjectionView { return h.view } // Adapter exposes the underlying VolumeReplicaAdapter for tests. -func (h *Host) Adapter() *adapter.VolumeReplicaAdapter { return h.adpt } +func (h *Host) Adapter() *adapter.VolumeReplicaAdapter { return h.realAdpt } // Executor exposes the noopExecutor for tests that want to // inspect recorded commands. @@ -376,35 +402,68 @@ func (h *Host) streamOnce(ctx context.Context) error { if err != nil { return err } - if fact.ReplicaId != h.cfg.ReplicaID { - // Superseded. The volume currently serving - // (vid, self.ReplicaID) is no longer the current - // authoritative line for this volume. - h.recordOtherLine(fact) - h.log.Printf("blockvolume: volume %s authority is now %s@%d (not this replica %s); recording supersede, not applying to adapter", - h.cfg.VolumeID, fact.ReplicaId, fact.Epoch, h.cfg.ReplicaID) - continue + h.applyFact(fact) + } +} + +// applyFact processes one AssignmentFact from the master's +// subscription stream. Extracted from streamOnce so tests can +// exercise the install-or-refuse seam directly without a real +// gRPC stream. +// +// Install-or-refuse ordering (T4a-6 follow-up fix, QA finding #1): +// +// 1. If the fact names another replica, record supersede and return. +// 2. Otherwise (self-replica fact): +// a. Install replication peer set first (if configured). +// b. On UpdateReplicaSet failure, LOG and RETURN WITHOUT +// calling OnAssignment. The adapter's projection stays at +// its prior (not-Healthy until first successful install) +// state; StorageBackend.lineageCheck keeps writes blocked. +// Master's stream replay redelivers this fact on the next +// cycle; natural eventual convergence. +// c. Only after replication install succeeds (or observer-only +// mode): apply OnAssignment, driving the adapter's +// projection to Healthy. +// +// This preserves the V2 BlockVol.SetReplicaAddrs-then-admit-writes +// atomicity that V3 lost when adapter + ReplicationVolume got split +// across packages. Without install-or-refuse, a window existed where +// OnAssignment could flip the projection Healthy before peers were +// installed, admitting local-only writes with zero fan-out. +func (h *Host) applyFact(fact *control.AssignmentFact) { + if fact.ReplicaId != h.cfg.ReplicaID { + // Superseded. The volume currently serving + // (vid, self.ReplicaID) is no longer the current + // authoritative line for this volume. + h.recordOtherLine(fact) + h.log.Printf("blockvolume: volume %s authority is now %s@%d (not this replica %s); recording supersede, not applying to adapter", + h.cfg.VolumeID, fact.ReplicaId, fact.Epoch, h.cfg.ReplicaID) + return + } + + // Step (2a): install replication peer set first. Decoded via + // the separate host-only decodeReplicaTargets path (not through + // AssignmentInfo), so the TestNoOtherAssignmentInfoConstruction + // AST fence stays green. + if h.replication != nil { + targets, gen := decodeReplicaTargets(fact) + if err := h.replication.UpdateReplicaSet(gen, targets); err != nil { + // Step (2b): fail closed — do NOT apply OnAssignment. + h.log.Printf("blockvolume: volume %s replication UpdateReplicaSet failed (gen=%d, peers=%d): %v — NOT applying to adapter (fail-closed; master will retry via stream replay)", + h.cfg.VolumeID, gen, len(targets), err) + return } - // SOLE permitted decode path. See subscribe.go. - info := decodeAssignmentFact(fact) - h.adpt.OnAssignment(info) - // T4a-5: peer-set routing. Decoded via the separate host-only - // decodeReplicaTargets path (not through AssignmentInfo), so - // the TestNoOtherAssignmentInfoConstruction AST fence stays - // green. If ReplicationVolume is nil (T0/observer-only - // config), the peer set is ignored on this host. - if h.cfg.ReplicationVolume != nil { - targets, gen := decodeReplicaTargets(fact) - if err := h.cfg.ReplicationVolume.UpdateReplicaSet(gen, targets); err != nil { - h.log.Printf("blockvolume: volume %s replication UpdateReplicaSet failed (gen=%d, peers=%d): %v", - h.cfg.VolumeID, gen, len(targets), err) - } - } - if h.cfg.ReadyMarker != nil && info.Epoch > 0 && h.readyOnce.CompareAndSwap(false, true) { - select { - case h.cfg.ReadyMarker <- info: - default: - } + } + + // Step (2c): identity install only after replication is live. + // SOLE permitted decode path. See subscribe.go. + info := decodeAssignmentFact(fact) + h.adpt.OnAssignment(info) + if h.cfg.ReadyMarker != nil && info.Epoch > 0 && h.readyOnce.CompareAndSwap(false, true) { + select { + case h.cfg.ReadyMarker <- info: + default: } } } diff --git a/seaweed-block/core/replication/l2_integration_test.go b/seaweed-block/core/replication/l2_integration_test.go index cdc7ce804f..30a9a26e21 100644 --- a/seaweed-block/core/replication/l2_integration_test.go +++ b/seaweed-block/core/replication/l2_integration_test.go @@ -56,8 +56,13 @@ func smartwalFactory(t *testing.T, dir, label string, blocks uint32, blockSize i return s, cleanup } -// walstoreFactory is the non-sign-bearing matrix row. Failures are -// logged via t.Logf and NOT t.Fatal, matching the T3 matrix rule. +// walstoreFactory is the second matrix row. Both rows are currently +// gating — T4a-6 follow-up (QA finding #4) removed the earlier +// "non-gating" fiction since Go's testing framework has no clean +// demote-subtest-failure API and the previous defer-based harness +// didn't actually demote. Both backends pass today; if walstore +// regresses under BUG-007 the test fails honestly and we invest in +// a real demotion harness then. func walstoreFactory(t *testing.T, dir, label string, blocks uint32, blockSize int) (storage.LogicalStorage, func()) { t.Helper() path := filepath.Join(dir, label+".walstore") @@ -72,34 +77,20 @@ func walstoreFactory(t *testing.T, dir, label string, blocks uint32, blockSize i return s, cleanup } -// runMatrix runs the given scenario against each storage backend and -// reports per-row results. smartwal rows are gating (t.Fatal on -// failure via subtest); walstore rows are reported non-gating -// (t.Logf on failure, no Fatal). +// runMatrix runs the given scenario against each storage backend. +// Both rows are gating in the current harness — see walstoreFactory +// comment for the QA-review history on the earlier non-gating +// fiction. T4a close requires smartwal to pass; walstore is +// expected to pass today (BUG-007 doesn't affect the best-effort +// write path T4a-6 exercises) but any regression will fail the +// test honestly. func runMatrix(t *testing.T, scenario func(t *testing.T, newStorage storageFactory)) { t.Helper() - t.Run("smartwal_gating", func(t *testing.T) { + t.Run("smartwal", func(t *testing.T) { scenario(t, smartwalFactory) }) - t.Run("walstore_nongating", func(t *testing.T) { - // Non-gating: run in a subtest but swallow any Fatal so a - // walstore-only failure doesn't gate the parent test. We use - // t.Run + a recover-once pattern: scenario is free to - // t.Fatalf; we observe via t.Failed() after and demote. - defer func() { - // Note: t.Run returns false if the subtest failed; the - // parent remains green because we inspect + demote below. - }() + t.Run("walstore", func(t *testing.T) { scenario(t, walstoreFactory) - if t.Failed() { - // Force-green the parent while preserving the diagnostic. - // Go testing has no direct "demote failure" API; the best - // we can do is log that this is the documented non-gating - // row. The parent subtest's FAIL status remains for - // operator visibility, but T4a batch gate only cares - // about smartwal. - t.Logf("T4a-6 matrix: walstore row failed (non-gating per BUG-007; T4a close depends on smartwal only)") - } }) }