Merge G9A ACK reintegration policy

This commit is contained in:
pingqiu committed 2026-05-02 18:39:27 -07:00
commit c8cc15595b
14 files changed
+741 -64

No files matched your search

@@ -169,16 +169,17 @@ func startG54Master(t *testing.T, bins l2bins, art string) (*proc, string) {
}
type volOpts struct {
masterAddr string
serverID string
replicaID string
dataAddr string
ctrlAddr string
statusAddr string
iscsiAddr string
iscsiIQN string
durableRoot string
logTag string
masterAddr string
serverID string
replicaID string
dataAddr string
ctrlAddr string
statusAddr string
iscsiAddr string
iscsiIQN string
durableRoot string
logTag string
replicationAck string
}
func startG54Volume(t *testing.T, bins l2bins, art string, o volOpts) *proc {
@@ -210,6 +211,9 @@ func startG54Volume(t *testing.T, bins l2bins, art string, o volOpts) *proc {
"--iscsi-iqn", o.iscsiIQN,
)
}
if o.replicationAck != "" {
cmd.Args = append(cmd.Args, "--replication-ack", o.replicationAck)
}
cmd.Stdout = lf
cmd.Stderr = lf
if err := cmd.Start(); err != nil {
@@ -82,12 +82,18 @@ func (c *g8IscsiClient) close(t *testing.T) {
func (c *g8IscsiClient) write10(t *testing.T, lba uint32, payload []byte) {
t.Helper()
status, _ := c.scsi(t, g8WriteCDB10(lba, 1), payload, 0)
status := c.write10Status(t, lba, payload)
if status != iscsi.StatusGood {
t.Fatalf("iSCSI WRITE(10) status=0x%02x", status)
}
}
func (c *g8IscsiClient) write10Status(t *testing.T, lba uint32, payload []byte) uint8 {
t.Helper()
status, _ := c.scsi(t, g8WriteCDB10(lba, 1), payload, 0)
return status
}
func (c *g8IscsiClient) read10(t *testing.T, lba uint32, blocks uint16, bytesPerBlock int) []byte {
t.Helper()
status, data := c.scsi(t, g8ReadCDB10(lba, blocks), nil, int(blocks)*bytesPerBlock)
@@ -0,0 +1,63 @@
package main
import (
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/replication"
)
func TestG9A_ParseReplicationAckProfile(t *testing.T) {
tests := []struct {
name string
profile string
wantMode replication.DurabilityMode
wantWrite durable.WriteAckPolicy
wantErr bool
}{
{
name: "best effort default",
profile: "best-effort",
wantMode: replication.DurabilityBestEffort,
wantWrite: durable.WriteAckBestEffort,
},
{
name: "sync quorum gates foreground writes",
profile: "sync-quorum",
wantMode: replication.DurabilitySyncQuorum,
wantWrite: durable.WriteAckRequireObserverAck,
},
{
name: "sync all gates foreground writes",
profile: "sync-all",
wantMode: replication.DurabilitySyncAll,
wantWrite: durable.WriteAckRequireObserverAck,
},
{
name: "unknown profile rejected",
profile: "full-sync-ish",
wantErr: true,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
gotMode, gotWrite, err := parseReplicationAckProfile(tt.profile)
if tt.wantErr {
if err == nil {
t.Fatalf("parseReplicationAckProfile(%q): expected error", tt.profile)
}
return
}
if err != nil {
t.Fatalf("parseReplicationAckProfile(%q): %v", tt.profile, err)
}
if gotMode != tt.wantMode {
t.Fatalf("mode=%v want %v", gotMode, tt.wantMode)
}
if gotWrite != tt.wantWrite {
t.Fatalf("writeAck=%v want %v", gotWrite, tt.wantWrite)
}
})
}
}
@@ -0,0 +1,129 @@
package main_test
import (
"bytes"
"path/filepath"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/iscsi"
)
func TestG9A_L2SyncQuorumWriteFailsWhenReplicaDown(t *testing.T) {
if testing.Short() {
t.Skip("L2 subprocess strict ACK test; -short skip")
}
bins := buildG54Binaries(t)
art := t.TempDir()
_, masterAddr := startG8Master(t, bins, art)
iqn := "iqn.2026-05.example.g9a:v1"
r1Data, r1Status, r1Iscsi := pickAddr(t), pickAddr(t), pickAddr(t)
r2Data, r2Status := pickAddr(t), pickAddr(t)
r1Ctrl, r2Ctrl := pickAddr(t), pickAddr(t)
_ = startG54Volume(t, bins, art, volOpts{
masterAddr: masterAddr,
serverID: "s1", replicaID: "r1",
dataAddr: r1Data, ctrlAddr: r1Ctrl,
statusAddr: r1Status,
iscsiAddr: r1Iscsi,
iscsiIQN: iqn,
durableRoot: filepath.Join(art, "g9a-sync-r1-store"),
logTag: "g9a-sync-r1",
replicationAck: "sync-quorum",
})
r2 := startG54Volume(t, bins, art, volOpts{
masterAddr: masterAddr,
serverID: "s2", replicaID: "r2",
dataAddr: r2Data, ctrlAddr: r2Ctrl,
statusAddr: r2Status,
durableRoot: filepath.Join(art, "g9a-sync-r2-store"),
logTag: "g9a-sync-r2",
})
pollStatus(t, r1Status, 10*time.Second, func(b map[string]any) bool {
h, _ := b["Healthy"].(bool)
rid, _ := b["ReplicaID"].(string)
return h && rid == "r1"
})
pollStatus(t, r2Status, 10*time.Second, func(b map[string]any) bool {
_, ok := b["Healthy"]
return ok
})
const durableBlockSize = 4096
payload := bytes.Repeat([]byte{0x9a}, durableBlockSize)
copy(payload, []byte("g9a-sync-quorum-first-write"))
c := dialG8Iscsi(t, r1Iscsi, iqn)
c.write10(t, 9, payload)
r2.stop(t)
copy(payload, []byte("g9a-sync-quorum-write-while-r2-down"))
status := c.write10Status(t, 10, payload)
c.close(t)
if status == iscsi.StatusGood {
t.Fatalf("sync-quorum RF=2 write while secondary down returned GOOD; want foreground ACK failure")
}
}
func TestG9A_L2BestEffortWriteSucceedsWhenReplicaDown(t *testing.T) {
if testing.Short() {
t.Skip("L2 subprocess best-effort ACK test; -short skip")
}
bins := buildG54Binaries(t)
art := t.TempDir()
_, masterAddr := startG8Master(t, bins, art)
iqn := "iqn.2026-05.example.g9a-best-effort:v1"
r1Data, r1Status, r1Iscsi := pickAddr(t), pickAddr(t), pickAddr(t)
r2Data, r2Status := pickAddr(t), pickAddr(t)
r1Ctrl, r2Ctrl := pickAddr(t), pickAddr(t)
_ = startG54Volume(t, bins, art, volOpts{
masterAddr: masterAddr,
serverID: "s1", replicaID: "r1",
dataAddr: r1Data, ctrlAddr: r1Ctrl,
statusAddr: r1Status,
iscsiAddr: r1Iscsi,
iscsiIQN: iqn,
durableRoot: filepath.Join(art, "g9a-best-effort-r1-store"),
logTag: "g9a-best-effort-r1",
})
r2 := startG54Volume(t, bins, art, volOpts{
masterAddr: masterAddr,
serverID: "s2", replicaID: "r2",
dataAddr: r2Data, ctrlAddr: r2Ctrl,
statusAddr: r2Status,
durableRoot: filepath.Join(art, "g9a-best-effort-r2-store"),
logTag: "g9a-best-effort-r2",
})
pollStatus(t, r1Status, 10*time.Second, func(b map[string]any) bool {
h, _ := b["Healthy"].(bool)
rid, _ := b["ReplicaID"].(string)
return h && rid == "r1"
})
pollStatus(t, r2Status, 10*time.Second, func(b map[string]any) bool {
_, ok := b["Healthy"]
return ok
})
const durableBlockSize = 4096
payload := bytes.Repeat([]byte{0xbe}, durableBlockSize)
copy(payload, []byte("g9a-best-effort-first-write"))
c := dialG8Iscsi(t, r1Iscsi, iqn)
c.write10(t, 11, payload)
r2.stop(t)
copy(payload, []byte("g9a-best-effort-write-while-r2-down"))
status := c.write10Status(t, 12, payload)
c.close(t)
if status != iscsi.StatusGood {
t.Fatalf("best-effort write while secondary down status=0x%02x want GOOD", status)
}
}
+41 -2
View File
@@ -68,9 +68,9 @@ type flags struct {
// T2 NVMe/TCP frontend flags. Symmetric with iSCSI flags
// per QA note: same loopback-only safe-default rule, same
// auto-enable of --t1-readiness so the symmetry stays clean.
nvmeListen string
nvmeListen string
nvmeSubsysNQN string
nvmeNS uint
nvmeNS uint
// T3b durable-backend flags. When --durable-root is set, the
// iSCSI and NVMe providers use DurableProvider instead of
@@ -113,6 +113,11 @@ type flags struct {
// after one milestone of dual-lane GREEN observed in CI / hardware
// (architect §11 Resolution 3).
recoveryMode string
// G9A: user-visible replication acknowledgement profile.
// best-effort is the beta default. sync-quorum / sync-all opt into
// foreground write ACK gating through the durable WriteObserver seam.
replicationAck string
}
func parseFlags(args []string) (flags, error) {
@@ -166,6 +171,9 @@ func parseFlags(args []string) (flags, error) {
"core/transport rebuild. \"dual-lane\" = core/recovery PrimaryBridge "+
"with separate listener at data-addr port+1. Default flip is a "+
"separate ops PR after dual-lane GREEN milestone.")
fs.StringVar(&f.replicationAck, "replication-ack", "best-effort",
"G9A replication acknowledgement profile: \"best-effort\" (default), \"sync-quorum\", or \"sync-all\". "+
"sync-* modes fail foreground writes when required replica acknowledgement is unavailable.")
fs.SetOutput(os.Stderr)
if err := fs.Parse(args); err != nil {
return flags{}, err
@@ -173,6 +181,9 @@ func parseFlags(args []string) (flags, error) {
if f.recoveryMode != "legacy" && f.recoveryMode != "dual-lane" {
return flags{}, fmt.Errorf("--recovery-mode=%q invalid; want \"legacy\" or \"dual-lane\"", f.recoveryMode)
}
if _, _, err := parseReplicationAckProfile(f.replicationAck); err != nil {
return flags{}, err
}
missing := []string{}
for name, val := range map[string]string{
"master": f.masterAddr, "server-id": f.serverID,
@@ -223,6 +234,20 @@ func parseFlags(args []string) (flags, error) {
return f, nil
}
func parseReplicationAckProfile(profile string) (replication.DurabilityMode, durable.WriteAckPolicy, error) {
switch profile {
case "best-effort":
return replication.DurabilityBestEffort, durable.WriteAckBestEffort, nil
case "sync-quorum":
return replication.DurabilitySyncQuorum, durable.WriteAckRequireObserverAck, nil
case "sync-all":
return replication.DurabilitySyncAll, durable.WriteAckRequireObserverAck, nil
default:
return replication.DurabilityBestEffort, durable.WriteAckBestEffort,
fmt.Errorf("--replication-ack=%q invalid; want \"best-effort\", \"sync-quorum\", or \"sync-all\"", profile)
}
}
// computeFrontendVolumeSize returns the byte capacity an iSCSI/NVMe
// target should advertise: durableBlocks × blockSize.
//
@@ -472,6 +497,19 @@ func run(f flags) int {
return 1
}
replVolume = replication.NewReplicationVolume(f.volumeID, store)
repMode, writeAck, err := parseReplicationAckProfile(f.replicationAck)
if err != nil {
fmt.Fprintln(os.Stderr, "blockvolume:", err)
_ = durableProv.Close()
if status != nil {
shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second)
_ = status.Close(shutCtx)
shutCancel()
}
_ = h.Close()
return 1
}
replVolume.SetDurabilityMode(repMode)
h.SetReplicationVolume(replVolume)
// G7-redo: when --recovery-mode=dual-lane, inject the dual-lane
@@ -592,6 +630,7 @@ func run(f flags) int {
// primary writes would land locally but never ship to peers.
if sb := durableProv.Backend(f.volumeID); sb != nil {
sb.SetWriteObserver(replVolume)
sb.SetWriteAckPolicy(writeAck)
} else {
fmt.Fprintln(os.Stderr, "blockvolume: write-observer wire: Backend(", f.volumeID, ") returned nil; replication fan-out disabled")
}
@@ -0,0 +1,41 @@
package authority
import "testing"
func TestG9A_ReturnedReplicaCandidateRequiresReadyForPrimaryProgressFact(t *testing.T) {
reader := newFakeBasisReader()
reader.Set("v1", "r2", AuthorityBasis{
Assigned: true, ReplicaID: "r2", Epoch: 2, EndpointVersion: 1,
DataAddr: "d2", CtrlAddr: "c2",
})
ctrl := NewTopologyController(TopologyControllerConfig{}, reader)
r1 := candidate("r1", "s1", "d1", "c1", 1_000)
r1.ReadyForPrimary = false // returned/observed is not reintegrated.
r2 := candidate("r2", "s2", "d2", "c2", 100)
r2.Reachable = false // force failover pressure away from current primary.
r3 := candidate("r3", "s3", "d3", "c3", 10)
snap := ClusterSnapshot{
CollectedRevision: 30,
Servers: []ServerObservation{
{ServerID: "s1", Reachable: true, Eligible: true},
{ServerID: "s2", Reachable: true, Eligible: true},
{ServerID: "s3", Reachable: true, Eligible: true},
},
Volumes: []VolumeTopologySnapshot{
clusterVolume("v1",
AuthorityBasis{Assigned: true, ReplicaID: "r2", Epoch: 2, EndpointVersion: 1, DataAddr: "d2", CtrlAddr: "c2"},
r1, r2, r3,
),
},
}
if err := ctrl.SubmitClusterSnapshot(snap); err != nil {
t.Fatalf("SubmitClusterSnapshot: %v", err)
}
ask := nextAskOrFail(t, ctrl)
if ask.Intent != IntentReassign || ask.ReplicaID != "r3" {
t.Fatalf("returned r1 must not be failover target until progress-ready; got %+v", ask)
}
}
@@ -5,29 +5,29 @@
// or any future impl) and exposes the `frontend.Backend` surface
// iSCSI and NVMe consume. Responsibilities:
//
// 1. byte ↔ LBA translation (G-int.1).
// Frontend layer speaks byte offsets + length; storage layer
// speaks LBA + full-block data. The adapter bridges: partial-
// block writes trigger read-modify-write; full-block writes
// skip the read. Reads copy the slice of the backing block
// covered by the byte range.
// 1. byte ↔ LBA translation (G-int.1).
// Frontend layer speaks byte offsets + length; storage layer
// speaks LBA + full-block data. The adapter bridges: partial-
// block writes trigger read-modify-write; full-block writes
// skip the read. Reads copy the slice of the backing block
// covered by the byte range.
//
// 2. Per-I/O fence check (G-int.2).
// Re-reads `ProjectionView` on every operation; ANY drift
// (identity field mismatch or Healthy=false) → ErrStalePrimary.
// Preserves INV-FRONTEND-002.{EPOCH,EV,REPLICA,HEALTHY} under
// a durable backend.
// 2. Per-I/O fence check (G-int.2).
// Re-reads `ProjectionView` on every operation; ANY drift
// (identity field mismatch or Healthy=false) → ErrStalePrimary.
// Preserves INV-FRONTEND-002.{EPOCH,EV,REPLICA,HEALTHY} under
// a durable backend.
//
// 3. Operational gate (G-int.3, Addendum A).
// Before SetOperational(true, _) is called, every I/O returns
// ErrNotReady with evidence. Starts non-operational — host/
// provider flips to true after recovery succeeds. This is
// local readiness only; NEVER advances epoch / mints authority.
// 3. Operational gate (G-int.3, Addendum A).
// Before SetOperational(true, _) is called, every I/O returns
// ErrNotReady with evidence. Starts non-operational — host/
// provider flips to true after recovery succeeds. This is
// local readiness only; NEVER advances epoch / mints authority.
//
// 4. Sync (G-int.2 sync policy locked as explicit method).
// Dispatches to LogicalStorage.Sync and returns error
// verbatim. iSCSI SYNCHRONIZE CACHE + NVMe Flush wiring lands
// in T3b.
// 4. Sync (G-int.2 sync policy locked as explicit method).
// Dispatches to LogicalStorage.Sync and returns error
// verbatim. iSCSI SYNCHRONIZE CACHE + NVMe Flush wiring lands
// in T3b.
//
// StorageBackend does NOT own the LogicalStorage lifecycle — the
// Provider (T3b) opens and closes storage. Backend.Close marks the
@@ -49,6 +49,27 @@ import (
"github.com/seaweedfs/seaweed-block/core/storage"
)
// WriteAckPolicy controls whether per-write replication observer failures
// affect the foreground Write result.
type WriteAckPolicy int
const (
// WriteAckBestEffort is the MVP default: local durable write success is
// enough for Write to return success. Replication observer failures are
// logged and left to recovery/progress policy.
WriteAckBestEffort WriteAckPolicy = iota
// WriteAckRequireObserverAck is the future full-ack/quorum seam: a Write
// must have an installed observer and the observer must accept the write.
// A replica in recovery/down state should surface through observer error,
// not be silently treated as full-sync success.
WriteAckRequireObserverAck
)
// ErrReplicationAckUnavailable is returned when WriteAckRequireObserverAck
// cannot obtain the configured replication acknowledgement.
var ErrReplicationAckUnavailable = errors.New("durable: replication ack unavailable")
// WriteObserver is the narrow seam StorageBackend uses to notify the
// replication layer of each successfully-applied local write and to
// delegate Sync durability closure. The ReplicationVolume
@@ -60,9 +81,14 @@ import (
// - StorageBackend calls Observe AFTER LogicalStorage.Write
// returns successfully, with the LBA + block data + LSN the
// storage layer just assigned.
// - Observe error does NOT fail the Write (best-effort
// replication matches V2 fire-and-forget ShipAll; per-peer
// degradation is the observer's concern, not the backend's).
// - In the default WriteAckBestEffort policy, Observe error does
// NOT fail the Write (best-effort replication matches V2
// fire-and-forget ShipAll; per-peer degradation is the observer's
// concern, not the backend's).
// - In WriteAckRequireObserverAck, missing observer or Observe
// error fails Write with ErrReplicationAckUnavailable. This is the
// RF=2/full-ack seam: a recovering/down replica must not be
// silently treated as a full-sync peer.
// - StorageBackend calls Observe from within writeBytes; the
// ReplicationVolume's own mutex then serializes fan-out per
// volume (V2 shipMu equivalent; closes
@@ -115,6 +141,7 @@ type StorageBackend struct {
mu sync.Mutex
closed bool
observer WriteObserver // optional; nil = no replication fan-out
writeAck WriteAckPolicy
}
// NewStorageBackend constructs a backend. Starts NON-operational
@@ -219,6 +246,14 @@ func (b *StorageBackend) SetWriteObserver(obs WriteObserver) {
b.mu.Unlock()
}
// SetWriteAckPolicy configures whether observer acknowledgement participates
// in foreground Write success. Default is WriteAckBestEffort.
func (b *StorageBackend) SetWriteAckPolicy(policy WriteAckPolicy) {
b.mu.Lock()
b.writeAck = policy
b.mu.Unlock()
}
// SetOperational flips the readiness gate. evidence is surfaced
// in error strings and diagnostic logs — pass a short reason like
// "recovered LSN=123 epoch=4" or "superblock ahead of assignment".
@@ -310,10 +345,10 @@ func (b *StorageBackend) Write(ctx context.Context, offset int64, p []byte) (int
// gate is the per-I/O precondition stack. Order matters:
//
// 1. closed: tests the lifecycle, cheapest check
// 2. operational: tests local readiness; preserves Add.A Add.1
// 3. lineage: tests that the captured Identity still matches
// the live projection; preserves INV-FRONTEND-002
// 1. closed: tests the lifecycle, cheapest check
// 2. operational: tests local readiness; preserves Add.A Add.1
// 3. lineage: tests that the captured Identity still matches
// the live projection; preserves INV-FRONTEND-002
//
// Returning ANY error short-circuits — no partial I/O.
func (b *StorageBackend) gate() error {
@@ -426,6 +461,14 @@ func (b *StorageBackend) writeBytes(ctx context.Context, offset int64, p []byte)
copy(block[inBlockOff:], buf[:chunkLen])
}
b.mu.Lock()
obs := b.observer
policy := b.writeAck
b.mu.Unlock()
if obs == nil && policy == WriteAckRequireObserverAck {
return total, fmt.Errorf("%w: no write observer installed", ErrReplicationAckUnavailable)
}
lsn, err := b.storage.Write(lba, block)
if err != nil {
return total, fmt.Errorf("durable: write lba=%d: %w", lba, err)
@@ -434,9 +477,6 @@ func (b *StorageBackend) writeBytes(ctx context.Context, offset int64, p []byte)
// b.mu so a concurrent SetWriteObserver doesn't see us reading
// a stale pointer. Error is logged best-effort — peer layer
// degrades; the Write itself has already succeeded locally.
b.mu.Lock()
obs := b.observer
b.mu.Unlock()
// G5-5 instrumentation: log every write hit to the observer
// hook so we can disambiguate "WriteObserver never wired" from
// "wired but fan-out fails downstream". obs==nil at write time
@@ -450,6 +490,9 @@ func (b *StorageBackend) writeBytes(ctx context.Context, offset int64, p []byte)
if werr := obs.Observe(ctx, lba, lsn, block); werr != nil {
log.Printf("durable: replication fan-out failed lba=%d lsn=%d: %v",
lba, lsn, werr)
if policy == WriteAckRequireObserverAck {
return total + chunkLen, fmt.Errorf("%w: %w", ErrReplicationAckUnavailable, werr)
}
}
}
total += chunkLen
@@ -28,6 +28,25 @@ import (
"github.com/seaweedfs/seaweed-block/core/storage/smartwal"
)
type writeObserverFunc struct {
observe func(context.Context, uint32, uint64, []byte) error
sync func(context.Context, uint64) error
}
func (f writeObserverFunc) Observe(ctx context.Context, lba uint32, lsn uint64, data []byte) error {
if f.observe != nil {
return f.observe(ctx, lba, lsn, data)
}
return nil
}
func (f writeObserverFunc) Sync(ctx context.Context, targetLSN uint64) error {
if f.sync != nil {
return f.sync(ctx, targetLSN)
}
return nil
}
// ------- Matrix factory (Addendum A #1) -------
// logicalStorageFactory is the shared factory contract; every
@@ -400,6 +419,70 @@ func TestT3a_StorageBackend_Sync_DispatchesToStorage(t *testing.T) {
}
}
// ------- G9A ACK profile seam -------
func TestG9A_StorageBackend_WriteAckPolicy_BestEffortObserverErrorStillACKs(t *testing.T) {
observerErr := errors.New("replica recovering")
for _, f := range logicalStorageFactories() {
f := f
t.Run(f.name, func(t *testing.T) {
b, _, _ := newTestBackend(t, f, 4, 4096)
b.SetWriteObserver(writeObserverFunc{
observe: func(context.Context, uint32, uint64, []byte) error {
return observerErr
},
})
n, err := b.Write(context.Background(), 0, make([]byte, 4096))
if err != nil {
t.Fatalf("best-effort Write must not fail on observer error, got %v", err)
}
if n != 4096 {
t.Fatalf("Write n=%d want 4096", n)
}
})
}
}
func TestG9A_StorageBackend_WriteAckPolicy_RequireObserverAckFailsWithoutObserver(t *testing.T) {
for _, f := range logicalStorageFactories() {
f := f
t.Run(f.name, func(t *testing.T) {
b, _, _ := newTestBackend(t, f, 4, 4096)
b.SetWriteAckPolicy(durable.WriteAckRequireObserverAck)
n, err := b.Write(context.Background(), 0, make([]byte, 4096))
if !errors.Is(err, durable.ErrReplicationAckUnavailable) {
t.Fatalf("strict Write without observer: want ErrReplicationAckUnavailable, got n=%d err=%v", n, err)
}
})
}
}
func TestG9A_StorageBackend_WriteAckPolicy_RequireObserverAckPropagatesObserverError(t *testing.T) {
observerErr := errors.New("replica recovering")
for _, f := range logicalStorageFactories() {
f := f
t.Run(f.name, func(t *testing.T) {
b, _, _ := newTestBackend(t, f, 4, 4096)
b.SetWriteAckPolicy(durable.WriteAckRequireObserverAck)
b.SetWriteObserver(writeObserverFunc{
observe: func(context.Context, uint32, uint64, []byte) error {
return observerErr
},
})
n, err := b.Write(context.Background(), 0, make([]byte, 4096))
if !errors.Is(err, durable.ErrReplicationAckUnavailable) {
t.Fatalf("strict Write observer error: want ErrReplicationAckUnavailable, got n=%d err=%v", n, err)
}
if !errors.Is(err, observerErr) {
t.Fatalf("strict Write should wrap observer cause, got %v", err)
}
})
}
}
// ------- Close behavior -------
func TestT3a_StorageBackend_Close_ReturnsErrBackendClosed(t *testing.T) {
@@ -77,9 +77,20 @@ func NewAdapterProjectionView(a adapterProjector, volumeID, replicaID string, pr
// Projection satisfies frontend.ProjectionView.
func (v *AdapterProjectionView) Projection() frontend.Projection {
p, _ := v.projectionWithSupersede()
return p
}
// projectionWithSupersede returns the frontend projection plus the
// reason bit that /status needs for G9A vocabulary. The frontend
// still consumes Projection() above; this helper is package-local so
// control-plane diagnostics can explain why Healthy is false without
// changing the frontend contract.
func (v *AdapterProjectionView) projectionWithSupersede() (frontend.Projection, bool) {
p := v.projector.Projection()
healthy := p.Mode == engine.ModeHealthy
if healthy && v.probe != nil && v.probe.IsSuperseded(v.replicaID, p.Epoch, p.EndpointVersion) {
superseded := healthy && v.probe != nil && v.probe.IsSuperseded(v.replicaID, p.Epoch, p.EndpointVersion)
if superseded {
healthy = false
}
return frontend.Projection{
@@ -88,7 +99,7 @@ func (v *AdapterProjectionView) Projection() frontend.Projection {
Epoch: p.Epoch,
EndpointVersion: p.EndpointVersion,
Healthy: healthy,
}
}, superseded
}
// EngineProjection returns the underlying engine.ReplicaProjection
@@ -9,6 +9,7 @@ import (
"sync"
"time"
"github.com/seaweedfs/seaweed-block/core/engine"
"github.com/seaweedfs/seaweed-block/core/frontend"
)
@@ -48,6 +49,28 @@ type StatusServer struct {
recoveryEnabled bool // G5-5: gates /status/recovery; off by default
}
const (
AuthorityRolePrimary = "primary"
AuthorityRoleSuperseded = "superseded"
AuthorityRoleUnknown = "unknown"
ReplicationRoleNone = "none"
ReplicationRoleRecovering = "recovering"
ReplicationRoleNotReady = "not_ready"
ReplicationRoleUnknown = "unknown"
)
// StatusProjection is the append-only /status shape. It embeds the
// original frontend.Projection fields for wire compatibility, then
// adds G9A control-plane vocabulary so operators/tests do not infer
// replica readiness from authority movement.
type StatusProjection struct {
frontend.Projection
FrontendPrimaryReady bool
AuthorityRole string
ReplicationRole string
}
// NewStatusServer wires a server to one volume host's view.
func NewStatusServer(view *AdapterProjectionView) *StatusServer {
return &StatusServer{view: view}
@@ -135,7 +158,7 @@ func (s *StatusServer) handleStatus(w http.ResponseWriter, r *http.Request) {
http.Error(w, "missing volume query param", http.StatusBadRequest)
return
}
p := s.view.Projection()
p := s.statusProjection()
if p.VolumeID != vol {
http.Error(w, fmt.Sprintf("volume %q not served by this host (serves %q)", vol, p.VolumeID), http.StatusNotFound)
return
@@ -144,6 +167,29 @@ func (s *StatusServer) handleStatus(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode(p)
}
func (s *StatusServer) statusProjection() StatusProjection {
p, superseded := s.view.projectionWithSupersede()
ep := s.view.EngineProjection()
authorityRole := AuthorityRoleUnknown
replicationRole := ReplicationRoleUnknown
switch {
case p.Healthy:
authorityRole = AuthorityRolePrimary
replicationRole = ReplicationRoleNone
case superseded:
authorityRole = AuthorityRoleSuperseded
replicationRole = ReplicationRoleNotReady
case ep.Mode == engine.ModeRecovering:
replicationRole = ReplicationRoleRecovering
}
return StatusProjection{
Projection: p,
FrontendPrimaryReady: p.Healthy,
AuthorityRole: authorityRole,
ReplicationRole: replicationRole,
}
}
// handleStatusRecovery returns engine.ReplicaProjection for the
// targeted volume. Loopback-only; same guards as /status. Surfaced
// fields cover the recovery boundaries (R/S/H), recovery decision,
@@ -212,7 +258,7 @@ func isLoopbackRemote(remote string) bool {
return ip != nil && ip.IsLoopback()
}
// Ensure compile-time check that the type returned over the wire
// matches frontend.Projection exactly (clients decode the same
// struct).
var _ frontend.Projection = frontend.Projection{}
// Ensure StatusProjection remains a pure append-only wrapper around
// frontend.Projection; existing clients can still decode /status into
// frontend.Projection because json.Decoder ignores unknown fields.
var _ = StatusProjection{Projection: frontend.Projection{}}
@@ -12,6 +12,7 @@ import (
"time"
"github.com/seaweedfs/seaweed-block/core/engine"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
)
func TestStatusServer_RejectsNonLoopbackBind(t *testing.T) {
@@ -55,6 +56,86 @@ func TestStatusServer_AcceptsLoopbackBindAndServesJSON(t *testing.T) {
}
}
func TestG9A_StatusProjection_ReturnedOldPrimarySupersededNotReady(t *testing.T) {
proj := &mutableProjector{p: engine.ReplicaProjection{
Mode: engine.ModeHealthy, Epoch: 1, EndpointVersion: 1,
}}
h := &Host{cfg: Config{VolumeID: "v1", ReplicaID: "r1"}}
h.view = NewAdapterProjectionView(proj, "v1", "r1", h)
h.recordOtherLine(&control.AssignmentFact{
VolumeId: "v1",
ReplicaId: "r2",
Epoch: 2,
EndpointVersion: 1,
})
s := NewStatusServer(h.view)
addr, err := s.Start("127.0.0.1:0")
if err != nil {
t.Fatalf("start: %v", err)
}
defer func() { _ = s.Close(context.Background()) }()
resp, err := http.Get("http://" + addr + "/status?volume=v1")
if err != nil {
t.Fatalf("get: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
t.Fatalf("status: got %d want 200", resp.StatusCode)
}
var body StatusProjection
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
t.Fatalf("decode: %v", err)
}
if body.Healthy {
t.Fatalf("returned old primary must fail closed: %+v", body)
}
if body.FrontendPrimaryReady {
t.Fatalf("returned old primary must not be frontend-primary-ready: %+v", body)
}
if body.AuthorityRole != AuthorityRoleSuperseded {
t.Fatalf("authority role = %q want %q", body.AuthorityRole, AuthorityRoleSuperseded)
}
if body.ReplicationRole != ReplicationRoleNotReady {
t.Fatalf("replication role = %q want %q", body.ReplicationRole, ReplicationRoleNotReady)
}
}
func TestG9A_StatusProjection_EngineRecoveringMapsReplicationRole(t *testing.T) {
p := stubProjector{p: engine.ReplicaProjection{
Mode: engine.ModeRecovering,
RecoveryDecision: engine.DecisionCatchUp,
SessionKind: engine.SessionCatchUp,
SessionPhase: engine.PhaseRunning,
Epoch: 3,
EndpointVersion: 2,
}}
s := NewStatusServer(NewAdapterProjectionView(p, "v1", "r1", nil))
addr, err := s.Start("127.0.0.1:0")
if err != nil {
t.Fatalf("start: %v", err)
}
defer func() { _ = s.Close(context.Background()) }()
resp, err := http.Get("http://" + addr + "/status?volume=v1")
if err != nil {
t.Fatalf("get: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
t.Fatalf("status: got %d want 200", resp.StatusCode)
}
var body StatusProjection
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
t.Fatalf("decode: %v", err)
}
if body.Healthy || body.FrontendPrimaryReady {
t.Fatalf("recovering replica must not be frontend-primary-ready: %+v", body)
}
if body.ReplicationRole != ReplicationRoleRecovering {
t.Fatalf("replication role = %q want %q", body.ReplicationRole, ReplicationRoleRecovering)
}
}
func TestStatusServer_MissingVolume_Returns400(t *testing.T) {
s := NewStatusServer(NewAdapterProjectionView(stubProjector{}, "v1", "r1", nil))
addr, err := s.Start("127.0.0.1:0")
@@ -0,0 +1,40 @@
package component
import (
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/replication"
)
func TestG9A_BestEffortWriteStillFeedsLaggingReplicaRecovery(t *testing.T) {
c := NewCluster(t, Smartwal).
WithReplicas(1).
WithBlockGeometry(64, 4096).
WithLiveShip().
WithEngineDrivenRecovery().
Start()
c.primary.RepVol.SetDurabilityMode(replication.DurabilityBestEffort)
drivePeerAdmit(t, c)
for i := 0; i < 3; i++ {
writeOneBlock(t, c, uint32(i), byte(0xA0+i))
}
c.WaitForConverge(2 * time.Second)
c.KillReplicaListener(0)
for i := 3; i < 5; i++ {
// Best-effort foreground writes must succeed even while the
// replica listener is down. The recovery/probe layer remains
// responsible for catching the peer up later.
writeOneBlock(t, c, uint32(i), byte(0xD0+i))
}
if c.replicaConverged(c.Replica(0)) {
t.Fatal("replica unexpectedly converged while listener was down; test did not create lag")
}
rebindReplicaListener(t, c, 0)
configureProbeLoopOnCluster(t, c)
c.WaitForConverge(8 * time.Second)
c.AssertReplicaConverged(0)
}
+41 -7
View File
@@ -35,11 +35,11 @@ type LocalWrite struct {
// Lifecycle: borrowed LogicalStorage — Provider owns the engine;
// ReplicationVolume must NEVER call store.Close() (BUG-005 discipline).
type ReplicationVolume struct {
volumeID string
store storage.LogicalStorage // borrowed, NEVER closed by us
newExec executorFactory // test seam; default dials real TCP
volumeID string
store storage.LogicalStorage // borrowed, NEVER closed by us
newExec executorFactory // test seam; default dials real TCP
newDualExec dualLaneExecutorFactory // optional dual-lane override; nil = use newExec
coord *DurabilityCoordinator // used by Sync; stateless
coord *DurabilityCoordinator // used by Sync; stateless
mu sync.Mutex // serializes UpdateReplicaSet + OnLocalWrite entry AND fan-out AND Sync
peers map[string]*ReplicaPeer
@@ -58,9 +58,9 @@ type ReplicationVolume struct {
// during Close (before peer teardown) so an in-flight probe
// callback never lands on a closed volume / closed peer set.
// Read+written under v.mu.
probeLoop *ProbeLoop
probeCfg ProbeLoopConfig // remembered for SetProbeCooldownConfig push-down on UpdateReplicaSet
probeCfgSet bool // true after ConfigureProbeLoop succeeds
probeLoop *ProbeLoop
probeCfg ProbeLoopConfig // remembered for SetProbeCooldownConfig push-down on UpdateReplicaSet
probeCfgSet bool // true after ConfigureProbeLoop succeeds
// G5-5C Batch #7 peer-lifecycle hook. Optional pair of callbacks
// invoked from UpdateReplicaSet on peer add / remove (including
@@ -433,16 +433,50 @@ func (v *ReplicationVolume) OnLocalWrite(ctx context.Context, w LocalWrite) erro
log.Printf("replication: OnLocalWrite volume=%s lba=%d lsn=%d peers=%d",
v.volumeID, w.LBA, w.LSN, len(v.peers))
mode := v.durabilityMode
rf := len(v.peers) + 1
successes := 0
failures := 0
// Fan out under the mutex — LSN-order invariant (Condition A).
// Lineage is informational; each peer uses its own registered
// lineage for authority framing (T4a-3 peer owns its session).
informational := transport.RecoveryLineage{}
for _, peer := range v.peers {
eligible := peer.State() == ReplicaHealthy
if err := peer.ShipEntry(ctx, informational, w.LBA, w.LSN, w.Data); err != nil {
log.Printf("replication: volume %s peer %s ship failed lsn=%d: %v",
v.volumeID, peer.Target().ReplicaID, w.LSN, err)
// Best-effort: continue iterating peers. Peer is already
// marked Degraded inside ShipEntry.
failures++
continue
}
if eligible {
successes++
} else {
failures++
}
}
if err := evaluateWriteAck(mode, rf, successes, failures); err != nil {
return err
}
return nil
}
func evaluateWriteAck(mode DurabilityMode, rf, peerSuccesses, peerFailures int) error {
switch mode {
case DurabilitySyncAll:
if peerFailures > 0 {
return fmt.Errorf("%w: %d of %d write acknowledgements unavailable",
ErrDurabilityBarrierFailed, peerFailures, rf-1)
}
case DurabilitySyncQuorum:
quorum := rf/2 + 1
durableNodes := 1 + peerSuccesses // local primary write already succeeded before Observe.
if durableNodes < quorum {
return fmt.Errorf("%w: %d durable of %d needed for write acknowledgement",
ErrDurabilityQuorumLost, durableNodes, quorum)
}
}
return nil
+64 -7
View File
@@ -75,10 +75,11 @@ func TestReplicationVolume_UpdateReplicaSet_AddPeer(t *testing.T) {
// TestReplicationVolume_UpdateReplicaSet_RemovePeer_ExecutorTornDown —
// Opt-3 three-assertion fence:
// (a) peer.Close called once and only once on removal
// (b) session removed from underlying executor
// (c) re-add at same ReplicaID succeeds and a subsequent OnLocalWrite
// reaches the replica
//
// (a) peer.Close called once and only once on removal
// (b) session removed from underlying executor
// (c) re-add at same ReplicaID succeeds and a subsequent OnLocalWrite
// reaches the replica
func TestReplicationVolume_UpdateReplicaSet_RemovePeer_ExecutorTornDown(t *testing.T) {
addr, replica := replicaHarness(t, "r1")
v := volumeHarness(t, "vol1")
@@ -220,6 +221,61 @@ func TestReplicationVolume_OnLocalWrite_SinglePeer_BestEffort(t *testing.T) {
}
}
func TestG9A_ReplicationVolume_OnLocalWrite_BestEffortRetainsRecoveringPeer(t *testing.T) {
addr, _ := replicaHarness(t, "r1")
v := volumeHarness(t, "vol-g9a-best-effort")
if err := v.UpdateReplicaSet(0, []ReplicaTarget{targetFor("r1", addr, 1, 1)}); err != nil {
t.Fatal(err)
}
v.mu.Lock()
v.peers["r1"].SetState(ReplicaCatchingUp)
v.mu.Unlock()
data := make([]byte, 4096)
data[0] = 0xA9
if err := v.OnLocalWrite(context.Background(), LocalWrite{LBA: 3, Data: data, LSN: 9}); err != nil {
t.Fatalf("best-effort recovering peer should retain/feed without failing Write observer: %v", err)
}
}
func TestG9A_ReplicationVolume_OnLocalWrite_SyncAllFailsRecoveringPeer(t *testing.T) {
addr, _ := replicaHarness(t, "r1")
v := volumeHarness(t, "vol-g9a-sync-all")
v.SetDurabilityMode(DurabilitySyncAll)
if err := v.UpdateReplicaSet(0, []ReplicaTarget{targetFor("r1", addr, 1, 1)}); err != nil {
t.Fatal(err)
}
v.mu.Lock()
v.peers["r1"].SetState(ReplicaCatchingUp)
v.mu.Unlock()
data := make([]byte, 4096)
data[0] = 0xB9
err := v.OnLocalWrite(context.Background(), LocalWrite{LBA: 4, Data: data, LSN: 10})
if !strings.Contains(fmt.Sprint(err), ErrDurabilityBarrierFailed.Error()) {
t.Fatalf("sync_all recovering peer should fail write ack, got %v", err)
}
}
func TestG9A_ReplicationVolume_OnLocalWrite_SyncQuorumRF2FailsRecoveringPeer(t *testing.T) {
addr, _ := replicaHarness(t, "r1")
v := volumeHarness(t, "vol-g9a-sync-quorum")
v.SetDurabilityMode(DurabilitySyncQuorum)
if err := v.UpdateReplicaSet(0, []ReplicaTarget{targetFor("r1", addr, 1, 1)}); err != nil {
t.Fatal(err)
}
v.mu.Lock()
v.peers["r1"].SetState(ReplicaCatchingUp)
v.mu.Unlock()
data := make([]byte, 4096)
data[0] = 0xC9
err := v.OnLocalWrite(context.Background(), LocalWrite{LBA: 5, Data: data, LSN: 11})
if !strings.Contains(fmt.Sprint(err), ErrDurabilityQuorumLost.Error()) {
t.Fatalf("sync_quorum RF=2 recovering peer should fail write ack, got %v", err)
}
}
// --- Test 5 ---
// TestReplicationVolume_OnLocalWrite_PeerErrorDoesNotFailCaller —
@@ -561,9 +617,10 @@ func TestReplicationVolume_UpdateReplicaSet_GenerationZero_DoesNotAdvanceGuard(t
// TestReplicationVolume_UpdateReplicaSet_EmptyPeerSet_AppliesWithTeardown
// — Q3 binding: UpdateReplicaSet(gen, []) MUST go through the normal
// teardown path, NOT a special "clear the map" fast-path. Assertions:
// (a) PeerCount() == 0 after apply
// (b) every formerly-present peer's executor session is invalidated
// (c) next OnLocalWrite succeeds as a zero-fanout no-op
//
// (a) PeerCount() == 0 after apply
// (b) every formerly-present peer's executor session is invalidated
// (c) next OnLocalWrite succeeds as a zero-fanout no-op
func TestReplicationVolume_UpdateReplicaSet_EmptyPeerSet_AppliesWithTeardown(t *testing.T) {
addr1, _ := replicaHarness(t, "r1")
addr2, _ := replicaHarness(t, "r2")