Compare commits

..
Author SHA1 Message Date
pingqiuandClaude Opus 5.5 e6317e3beb seaweed-block: lab helpers read their nodes instead of fixed lab hosts
run-multi-volume-mounted-failover.sh takes a node's address from the
cluster (InternalIP) and reaches it as SW_BLOCK_NODE_SSH_USER, with
SW_BLOCK_NODE_SSH_KEY when set; it no longer maps fixed lab hosts or
treats one named node as local, and a missing user or address fails.
A test drives its node helpers with stub kubectl, ssh and hostname.
Two lab-only helpers and a lab-only scenario that reach fixed lab hosts
leave the tree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 20:05:54 -08:00
pingqiuandClaude Opus 5.5 3404bf5e00 seaweed-block: neutral wording for lines the v1.1.1 sync added
Invariant rows and the CutTime expected-results header drop ruling ids;
the Kubernetes quick start names example nodes node-a/b/c; a state test
targets the renamed fixture node.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 19:59:10 -08:00
pingqiuandClaude Opus 5.5 e58a806489 seaweed-block: drop unreferenced lab notes from the public tree
internal/docs keeps only the notes that public docs, scripts or the test
registry cite, with neutral node names; the rest leave the tree (their
history stays). Gate fixtures use node-a, node-b and node-c, and comments
in two lab helpers name neutral nodes. No behaviour change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 19:59:08 -08:00
pingqiuandClaude Opus 5.5 62bd08e0c0 seaweed-block: neutral names in tests, comments and docs
Test fixtures use node-a, node-b and node-c for lab host names; code
comments drop ruling ids and keep the rule text; docs and comments name
a lab host or the CI runner instead of a machine. No behaviour change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 19:45:21 -08:00
14 changed files with 77 additions and 1600 deletions

No files matched your search

@@ -26,13 +26,6 @@ import (
// refuses an interval above half the freshness window (a longer loop gap
// reads as the master's own pause), so the window is 60 s: the dead
// primary's loss then comes at most a window after its last report.
//
// The failover is predicted within gapLoop + gapWindow + gapLoop of the
// kill: the tick that ends creation comes at most a loop after it, the
// loss a window after that tick's silence floor, and the tick that reads
// the loss at most a loop later. The test waits twice that.
const gapLoop, gapWindow = 30 * time.Second, 60 * time.Second
func TestAVolumeThatServedBeforeItsFirstGateTickFailsOver(t *testing.T) {
bins := buildG54Binaries(t)
h := &plannedHandoffHarness{dir: t.TempDir(), t: t}
@@ -55,8 +48,8 @@ func TestAVolumeThatServedBeforeItsFirstGateTickFailsOver(t *testing.T) {
}
master := h.start(t, "blockmaster", bins.master,
"--authority-store", filepath.Join(h.dir, "master", "authority"), "--lifecycle-store", filepath.Join(h.dir, "master", "lifecycle"),
"--cluster-spec", spec, "--expected-slots-per-volume", "3", "--lifecycle-product-loop-interval", gapLoop.String(),
"--freshness-window", gapWindow.String(), "--launcher-replication-ack", "sync-quorum", "--listen", h.masterAddr)
"--cluster-spec", spec, "--expected-slots-per-volume", "3", "--lifecycle-product-loop-interval", "30s",
"--freshness-window", "60s", "--launcher-replication-ack", "sync-quorum", "--listen", h.masterAddr)
master.waitLog(t, 30*time.Second, "blockmaster: lock acquired")
for _, b := range hosts {
lockDir := b.root + ".locks"
@@ -91,8 +84,7 @@ func TestAVolumeThatServedBeforeItsFirstGateTickFailsOver(t *testing.T) {
// 3. The next tick reads the survivors' write: creation ended, and the
// gate fails the volume over.
var p2 *host
predicted := gapLoop + gapWindow + gapLoop
poll(t, 2*predicted, fmt.Sprintf("no survivor became primary at epoch 2 within %v, twice the predicted %v (the volume held as creating, or the gate's replace not acted on: see the master's 'decision=replace' lines)", 2*predicted, predicted), func() bool {
poll(t, 120*time.Second, "no survivor became primary at epoch 2 (the volume held as creating?)", func() bool {
for _, b := range survivors {
if statusIsPrimaryAt(b.status, 2) {
p2 = b
+6 -58
View File
@@ -32,7 +32,6 @@ type TopologyController struct {
unsupported map[string]UnsupportedEvidence
convergenceStuck map[string]*ConvergenceStuckEvidence
bootGrace map[string]*primaryBootGrace // volume/replica -> current incarnation's grace
outcome map[string]string // volume -> what the last intake did with it (LastOutcome); kept like bootGrace
now func() time.Time
}
@@ -45,21 +44,10 @@ func NewTopologyController(config TopologyControllerConfig, reader AuthorityBasi
unsupported: make(map[string]UnsupportedEvidence),
convergenceStuck: make(map[string]*ConvergenceStuckEvidence),
bootGrace: make(map[string]*primaryBootGrace),
outcome: make(map[string]string),
now: time.Now,
}
}
// LastOutcome says what the last snapshot intake that carried the volume
// as supported did with it: the ask it enqueued, or why it enqueued none
// ("" before any). The master logs it beside a promotion gate's replace
// decision, so a decision the controller did not act on says why.
func (c *TopologyController) LastOutcome(volumeID string) string {
c.mu.Lock()
defer c.mu.Unlock()
return c.outcome[volumeID]
}
// SetNowForTest overrides the controller's clock source. Tests
// use this to drive RetryWindow / Stuck transitions deterministically.
// Production code MUST NOT call this.
@@ -137,21 +125,6 @@ func (c *TopologyController) SubmitClusterSnapshot(snap ClusterSnapshot) error {
// desired state live; SubmitObservedState always processes the
// report.
func (c *TopologyController) SubmitObservedState(snap ClusterSnapshot, report SupportabilityReport) error {
return c.submitObservedState(snap, report, nil)
}
// SubmitObservedStateOutcomes is SubmitObservedState that also returns what
// this intake did with each volume it carried (supported, pending or
// unsupported), read while the intake still holds the controller's lock: a
// later intake (the background observation host shares the controller)
// cannot change it. A volume this intake did not carry has no entry.
func (c *TopologyController) SubmitObservedStateOutcomes(snap ClusterSnapshot, report SupportabilityReport) (map[string]string, error) {
out := map[string]string{}
err := c.submitObservedState(snap, report, out)
return out, err
}
func (c *TopologyController) submitObservedState(snap ClusterSnapshot, report SupportabilityReport, outcomes map[string]string) error {
// Validate non-empty supported snapshots the same way
// SubmitClusterSnapshot does. Empty supported + empty report
// is allowed (no-op).
@@ -190,7 +163,6 @@ func (c *TopologyController) submitObservedState(snap ClusterSnapshot, report Su
// stale unsupported record from a prior build is cleared,
// because pending is a transitional state, not a fault.
delete(c.unsupported, vid)
c.outcome[vid] = "no ask: supportability pending"
}
for vid, ev := range report.Unsupported {
c.clearDesiredLocked(vid)
@@ -208,7 +180,6 @@ func (c *TopologyController) submitObservedState(snap ClusterSnapshot, report Su
Basis: AuthorityBasis{},
Reason: joinReasons(ev.Reasons),
}
c.outcome[vid] = "no ask: unsupported: " + joinReasons(ev.Reasons)
}
// Process supported volumes via the existing decision path.
@@ -225,17 +196,6 @@ func (c *TopologyController) submitObservedState(snap ClusterSnapshot, report Su
currentLine, hasLine := c.reader.VolumeAuthorityLine(vol.VolumeID)
c.processSupportedVolumeLocked(vol, snap, serverIndex, currentLine, hasLine, currentLoad, projectedLoad)
}
if outcomes != nil {
for vid := range report.Pending {
outcomes[vid] = c.outcome[vid]
}
for vid := range report.Unsupported {
outcomes[vid] = c.outcome[vid]
}
for _, vol := range volumes {
outcomes[vol.VolumeID] = c.outcome[vol.VolumeID]
}
}
return nil
}
@@ -292,13 +252,11 @@ func (c *TopologyController) processSupportedVolumeLocked(
if vol.Authority.Assigned && !volumeIncludesReplica(vol, vol.Authority.ReplicaID) {
c.recordUnsupportedLocked(vol.VolumeID, snap, vol.Authority, "snapshot authority outside accepted topology: "+vol.Authority.ReplicaID)
c.clearDesiredLocked(vol.VolumeID)
c.outcome[vol.VolumeID] = "no ask: snapshot authority outside accepted topology"
return
}
if hasLine && !volumeIncludesReplica(vol, currentLine.ReplicaID) {
c.recordUnsupportedLocked(vol.VolumeID, snap, currentLine, "publisher authority on replica outside accepted topology: "+currentLine.ReplicaID)
c.clearDesiredLocked(vol.VolumeID)
c.outcome[vol.VolumeID] = "no ask: publisher authority outside accepted topology"
return
}
@@ -311,20 +269,17 @@ func (c *TopologyController) processSupportedVolumeLocked(
// Stale snapshot: do not emit from a stale basis, but keep any
// existing desired (publish-until-observed convergence record).
if !basisMatchesLine(vol.Authority, currentLine, hasLine) {
c.outcome[vol.VolumeID] = fmt.Sprintf("no ask: stale snapshot basis %s@%d, line %s@%d", vol.Authority.ReplicaID, vol.Authority.Epoch, currentLine.ReplicaID, currentLine.Epoch)
return
}
// Stale slot facts: likewise keep any existing desired and emit
// nothing from this snapshot.
if staleFacts {
c.outcome[vol.VolumeID] = "no ask: superseded slot facts"
return
}
ask, reason, emit := c.decideVolume(vol, serverIndex, currentLine, hasLine, currentLoad, projectedLoad)
if !emit {
c.clearDesiredLocked(vol.VolumeID)
c.outcome[vol.VolumeID] = "no ask: " + reason
return
}
// Same-ask dedupe: if the identical ask is already the current
@@ -332,7 +287,6 @@ func (c *TopologyController) processSupportedVolumeLocked(
// identical supported feeds would mint a new Reassign epoch
// each iteration — authority churn.
if prev, ok := c.desired[vol.VolumeID]; ok && sameAsk(prev.Ask, ask) {
c.outcome[vol.VolumeID] = fmt.Sprintf("already desired since %s: %s %s (%s)", prev.DesiredAt.UTC().Format(time.RFC3339Nano), ask.Intent, ask.ReplicaID, prev.Reason)
return
}
@@ -354,7 +308,6 @@ func (c *TopologyController) processSupportedVolumeLocked(
}
c.desired[vol.VolumeID] = desired
c.queue.enqueue(ask)
c.outcome[vol.VolumeID] = fmt.Sprintf("enqueued %s %s (%s)", ask.Intent, ask.ReplicaID, reason)
applyProjectedMove(projectedLoad, vol, currentLine, hasLine, ask)
}
@@ -519,7 +472,7 @@ func (c *TopologyController) decideVolume(
if !hasLine {
cands := placeableCandidates(vol, serverIndex)
if len(cands) == 0 {
return AssignmentAsk{}, "no placeable candidate for the first line", false
return AssignmentAsk{}, "", false
}
best := choosePlacementCandidate(cands, projectedLoad)
return AssignmentAsk{
@@ -534,7 +487,7 @@ func (c *TopologyController) decideVolume(
current, ok := candidateByReplica(vol, currentLine.ReplicaID)
if !ok {
return AssignmentAsk{}, "the line's replica is not in the snapshot", false
return AssignmentAsk{}, "", false
}
if candidateAcceptable(current, serverIndex) {
@@ -547,7 +500,7 @@ func (c *TopologyController) decideVolume(
// current primary is alive, so it is a planned move: the same
// guard as a failback (the target in every acknowledgement set).
if target.PromotionEvidence.Kind != adapter.PrimaryKindPromotion || !target.PlannedMoveAllowed {
return AssignmentAsk{}, "the current primary is acceptable; rebalance target " + target.ReplicaID + " has no planned-move evidence", false
return AssignmentAsk{}, "", false
}
return AssignmentAsk{
VolumeID: vol.VolumeID,
@@ -559,7 +512,7 @@ func (c *TopologyController) decideVolume(
Incarnation: target.Incarnation,
}, "rebalance", true
}
return AssignmentAsk{}, "the current primary is acceptable", false
return AssignmentAsk{}, "", false
}
// A restarted current primary that is placeable but not ready yet
@@ -569,13 +522,9 @@ func (c *TopologyController) decideVolume(
if !superseded && endpointStale(current, currentLine) {
return refreshAsk(vol.VolumeID, current, currentLine), "endpoint refresh (primary boot grace)", true
}
if superseded {
return AssignmentAsk{}, "the current primary holds its boot grace (by its newer recorded fact)", false
}
return AssignmentAsk{}, "the current primary holds its boot grace", false
return AssignmentAsk{}, "", false
}
why := "no acceptable candidate besides the current primary"
other := acceptableCandidatesExcept(vol, serverIndex, current.ReplicaID)
if len(other) > 0 {
best := chooseFailoverCandidate(other, projectedLoad)
@@ -592,7 +541,6 @@ func (c *TopologyController) decideVolume(
Incarnation: best.Incarnation,
}, "failover", true
}
why = "failover target " + best.ReplicaID + " has no promotion evidence"
}
// No promotion-ready peer exists. Keep the current authority endpoint fresh
// when the current replica is still reachable/eligible; this preserves
@@ -600,7 +548,7 @@ func (c *TopologyController) decideVolume(
if candidatePlaceable(current, serverIndex) && endpointStale(current, currentLine) {
return refreshAsk(vol.VolumeID, current, currentLine), "endpoint refresh", true
}
return AssignmentAsk{}, why, false
return AssignmentAsk{}, "", false
}
// endpointStale reports whether the current primary's line needs a new
@@ -1,72 +0,0 @@
package master
import (
"log"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"testing"
"github.com/seaweedfs/seaweed-block/core/authority"
)
// bindingFailingProbe is switchProbe whose fencing round first makes the
// master's workspace binding store fail a write (its file replaced by a
// directory, so the write's rename fails), which latches the store
// uncertain: every later read answers restart-required. It does this once.
type bindingFailingProbe struct {
*switchProbe
once sync.Once
fault func()
}
func (p *bindingFailingProbe) FencePromotionCandidates(volume string, current authority.AuthorityBasis, survivors []PromotionCandidateEvidence) (PromotionProbeResult, error) {
p.once.Do(p.fault)
return p.switchProbe.FencePromotionCandidates(volume, current, survivors)
}
// A binding store that turns uncertain while the gate probes (the probe runs
// without the workspace lock) makes the tick's post-probe binding read fail.
// The tick returns the error and its replace decision is reported as not
// submitted, with the error, instead of vanishing with the tick.
func TestABindingReadFailureAfterTheProbeReportsTheDecisionNotSubmitted(t *testing.T) {
buf := &lockedBuffer{}
dir := t.TempDir()
h := newBootGraceMaster(t, Config{Logger: log.New(buf, "", 0), LifecycleStoreDir: dir})
defer closeTestMaster(t, h)
base, ok := h.promotionProber.(*switchProbe)
if !ok {
t.Fatalf("fixture: the master's prober is %T, want *switchProbe", h.promotionProber)
}
var faultErr error
h.SetPromotionEvidenceProvider(&bindingFailingProbe{switchProbe: base, fault: func() {
file := filepath.Join(dir, "workspace-bindings", "bindings.json")
if err := os.RemoveAll(file); err != nil {
faultErr = err
return
}
if err := os.MkdirAll(file, 0o755); err != nil {
faultErr = err
return
}
if err := h.lifecycle.WorkspaceBindings.Retire("vol-other", "node-x", 1); err == nil {
faultErr = os.ErrInvalid // the write was expected to fail
}
}})
ineligible := restarting
ineligible.eligible = false
ingestRF3Incarnations(t, h, ineligible, readySlot("r2-a"), readySlot("r3-a"))
_, err := h.RunLifecycleProductTick()
if faultErr != nil {
t.Fatalf("fixture: the binding store did not fail its write: %v", faultErr)
}
if err == nil || !strings.Contains(err.Error(), "restart required") {
t.Fatalf("tick error %v, want the binding store's restart-required error", err)
}
pattern := `promotion gate volume=vol-rf3 decision=replace\(fenced_at=2\) not submitted: the workspace bindings could not be read after the probe: .*restart required`
if !regexp.MustCompile(pattern).MatchString(buf.String()) {
t.Fatalf("no log line matching %q:\n%s", pattern, buf.String())
}
}
@@ -1,150 +0,0 @@
package master
import (
"log"
"regexp"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/adapter"
"github.com/seaweedfs/seaweed-block/core/authority"
)
// A replace decision of the promotion gate is followed, on the master's
// log, by what became of it: the ask the controller enqueued, why it
// enqueued none, or that it was not submitted. A replace the controller
// does not act on is otherwise silent until the volume fails to fail over.
func TestAReplaceDecisionLogsWhatTheControllerDidWithIt(t *testing.T) {
// The gate's replace of the lost r1, fed to a controller bound to r1@1.
replaced := func(t *testing.T) (*Host, *lockedBuffer, *authority.TopologyController, authority.ClusterSnapshot) {
t.Helper()
ctrl, pub, stop := lossCluster(t, authority.TopologyControllerConfig{})
stop() // the enqueued ask stays queued: the outcome is the controller's alone
h, buf := lossMaster(t, &fenceProbe{plain: lossPlain, fenced: lossFenced})
h.ctrl = ctrl
snap := lossTicks(h)
snap.Volumes[0].Authority, _ = pub.VolumeAuthorityLine("vol-rf3")
return h, buf, ctrl, snap
}
submit := func(t *testing.T, h *Host, ctrl *authority.TopologyController, snap authority.ClusterSnapshot) {
t.Helper()
outcomes, err := ctrl.SubmitObservedStateOutcomes(snap, authority.SupportabilityReport{})
if err != nil {
t.Fatal(err)
}
h.reportReplaces("", nil, outcomes)
}
want := func(t *testing.T, buf *lockedBuffer, pattern string) {
t.Helper()
if !regexp.MustCompile(pattern).MatchString(buf.String()) {
t.Fatalf("no log line matching %q:\n%s", pattern, buf.String())
}
}
t.Run("enqueued", func(t *testing.T) {
h, buf, ctrl, snap := replaced(t)
submit(t, h, ctrl, snap)
want(t, buf, `promotion gate volume=vol-rf3 decision=replace\(fenced_at=2\) controller: enqueued Reassign r[23] \(failover\)`)
})
t.Run("the same decision again: already desired", func(t *testing.T) {
h, buf, ctrl, snap := replaced(t)
submit(t, h, ctrl, snap)
h.noteGateReplace("vol-rf3", "replace(fenced_at=2)") // the next tick decides the same
submit(t, h, ctrl, snap)
want(t, buf, `decision=replace\(fenced_at=2\) controller: already desired since \S+: Reassign r[23] \(failover\)`)
})
t.Run("not acted on: says why", func(t *testing.T) {
h, buf, ctrl, snap := replaced(t)
for i := range snap.Volumes[0].Slots {
snap.Volumes[0].Slots[i].PromotionEvidence = adapter.PrimaryEvidence{}
}
submit(t, h, ctrl, snap)
want(t, buf, `decision=replace\(fenced_at=2\) controller: no ask: failover target r[23] has no promotion evidence`)
})
t.Run("not submitted", func(t *testing.T) {
h, buf, _, _ := replaced(t)
h.reportReplaces("not submitted: the placements changed during the probe", nil, nil)
want(t, buf, `decision=replace\(fenced_at=2\) not submitted: the placements changed during the probe`)
})
t.Run("an intake after the submission does not change its report", func(t *testing.T) {
// The background observation host shares the controller: its intake
// may land between the tick's submit and the report.
h, buf, ctrl, snap := replaced(t)
outcomes, err := ctrl.SubmitObservedStateOutcomes(snap, authority.SupportabilityReport{})
if err != nil {
t.Fatal(err)
}
stale := snap
stale.Volumes = append([]authority.VolumeTopologySnapshot(nil), snap.Volumes...)
stale.Volumes[0].Authority.Epoch++ // a basis the publisher does not hold
if err := ctrl.SubmitClusterSnapshot(stale); err != nil {
t.Fatal(err)
}
if o := ctrl.LastOutcome("vol-rf3"); !strings.HasPrefix(o, "no ask: stale snapshot basis") {
t.Fatalf("fixture: the intervening intake did not record its own outcome: %q", o)
}
h.reportReplaces("", nil, outcomes)
want(t, buf, `decision=replace\(fenced_at=2\) controller: enqueued Reassign r[23] \(failover\)`)
if strings.Contains(buf.String(), "decision=replace(fenced_at=2) controller: no ask: stale") {
t.Fatalf("the report took the later intake's outcome:\n%s", buf.String())
}
})
t.Run("a submission that did not carry the volume", func(t *testing.T) {
h, buf, _, _ := replaced(t)
h.reportReplaces("", nil, map[string]string{})
want(t, buf, `decision=replace\(fenced_at=2\) controller: no outcome \(the submission did not carry the volume\)`)
})
t.Run("one report per decision", func(t *testing.T) {
h, buf, ctrl, snap := replaced(t)
submit(t, h, ctrl, snap)
h.reportReplaces("", nil, nil) // nothing decided since: nothing to report
if n := strings.Count(buf.String(), "decision=replace(fenced_at=2) controller:"); n != 1 {
t.Fatalf("%d reports of one decision:\n%s", n, buf.String())
}
})
}
// The same through the production tick on the supported gate: an
// established volume whose primary turns ineligible is replaced by a fencing
// round; the gate's replace is reported with the controller's enqueued
// failover, and the publication is logged. The publication line comes from
// the publisher's observer after the line is visible, so it is waited for
// (bounded); the two lines are not ordered against each other.
func TestAProductTickReplaceLogsTheControllerOutcomeAndThePublication(t *testing.T) {
buf := &lockedBuffer{}
h := newBootGraceMaster(t, Config{Logger: log.New(buf, "", 0)})
defer closeTestMaster(t, h)
ineligible := restarting
ineligible.eligible = false
supportedCreatingTick(t, h, ineligible)
expectFailoverToR2(t, h, "fenced survivors")
for _, pattern := range []string{
`promotion gate volume=vol-rf3 decision=replace\(fenced_at=2\) controller: enqueued Reassign r2 \(failover\)`,
`blockmaster: volume=vol-rf3 authority reassigned to replica r2 epoch=2 endpoint_version=1 \(Reassign\)`,
} {
waitLogLine(t, buf, pattern, 5*time.Second)
}
}
// waitLogLine waits up to limit for a line of buf matching pattern.
func waitLogLine(t *testing.T, buf *lockedBuffer, pattern string, limit time.Duration) {
t.Helper()
re := regexp.MustCompile(pattern)
for end := time.Now().Add(limit); !re.MatchString(buf.String()); time.Sleep(10 * time.Millisecond) {
if time.Now().After(end) {
t.Fatalf("no log line matching %q within %v:\n%s", pattern, limit, buf.String())
}
}
}
// Every publication is on the master's log, with or without an event log.
func TestAPublicationIsLogged(t *testing.T) {
h, buf := lossMaster(t, &fenceProbe{})
h.recordAuthorityPublishedEvent(authority.PublishEvent{
Info: adapter.AssignmentInfo{VolumeID: "vol-rf3", ReplicaID: "r2", Epoch: 2, EndpointVersion: 1},
Ask: authority.AssignmentAsk{VolumeID: "vol-rf3", ReplicaID: "r2", Intent: authority.IntentReassign},
})
if !strings.Contains(buf.String(), "blockmaster: volume=vol-rf3 authority reassigned to replica r2 epoch=2 endpoint_version=1 (Reassign)") {
t.Fatalf("publication not logged:\n%s", buf.String())
}
}
-1
View File
@@ -149,7 +149,6 @@ type Host struct {
log *log.Logger
gateNoteMu sync.Mutex // guards gateNoteLast
gateNoteLast map[string]string // per kind, the last skip or drop a product-loop tick logged (noteGate)
gateReplaces []gateReplace // this tick's replace decisions, reported after the submit (reportReplaces)
primaryLossMu sync.Mutex // guards primaryLoss
primaryLoss primaryLosses // per volume, the recorded loss of the current primary (primary_loss.go)
boot *bootstrap.DurableAuthorityBootstrap
+2 -64
View File
@@ -263,7 +263,6 @@ func (h *Host) submitPlacementSnapshots(placements []lifecycle.PlacementIntent)
receipts := h.obs.Store().Snapshot()
build := authority.BuildSnapshot(receipts, topology, h.Publisher())
h.notePrimaryLosses(receipts, &build.Snapshot)
h.takeGateReplaces() // only this tick's decisions are reported
probeCount, blockedCount, directAsks := h.applyPromotionEvidenceGate(&build.Snapshot)
supported := supportedSnapshotVolumes(build.Snapshot)
unsupportedProbeCount, unsupportedBlockedCount, unsupportedDirectAsks := h.applyUnsupportedPromotionEvidenceGate(placements, build.Report, supported)
@@ -276,16 +275,13 @@ func (h *Host) submitPlacementSnapshots(placements []lifecycle.PlacementIntent)
defer h.workspaceMu.Unlock()
if !reflect.DeepEqual(captured, h.lifecycle.Placements.ListPlacements()) {
h.noteGate(gateNoteTick, "decisions not submitted: the placements changed during the probe")
h.reportReplaces("not submitted: the placements changed during the probe", nil, nil)
return false, probeCount, blockedCount, nil, nil
}
for _, p := range placements {
if _, bound, err := h.lifecycle.WorkspaceBindings.Get(p.VolumeID); err != nil {
h.reportReplaces("not submitted: the workspace bindings could not be read after the probe: "+err.Error(), nil, nil)
return false, probeCount, blockedCount, nil, err
} else if bound {
h.noteGate(gateNoteTick, "decisions not submitted: volume "+p.VolumeID+" got a workspace binding during the probe")
h.reportReplaces("not submitted: volume "+p.VolumeID+" got a workspace binding during the probe", nil, nil)
return false, probeCount, blockedCount, nil, nil
}
}
@@ -293,58 +289,12 @@ func (h *Host) submitPlacementSnapshots(placements []lifecycle.PlacementIntent)
for _, slot := range v.Slots {
if err := h.lifecycle.WorkspaceBindings.CheckAvailable(lifecycle.WorkspaceBinding{VolumeID: v.VolumeID, DataAddr: slot.DataAddr, CtrlAddr: slot.CtrlAddr}); err != nil {
h.noteGate(gateNoteTick, fmt.Sprintf("decisions not submitted: volume %s replica %s endpoints are bound elsewhere: %v", v.VolumeID, slot.ReplicaID, err))
h.reportReplaces(fmt.Sprintf("not submitted: volume %s replica %s endpoints are bound elsewhere", v.VolumeID, slot.ReplicaID), nil, nil)
return false, probeCount, blockedCount, nil, nil
}
}
}
h.noteGate(gateNoteTick, "")
// The outcomes are this submission's own, read under the controller's
// lock: the background observation host may submit right after it.
outcomes, err := h.ctrl.SubmitObservedStateOutcomes(build.Snapshot, build.Report)
h.reportReplaces("", err, outcomes)
return true, probeCount, blockedCount, directAsks, err
}
// gateReplace is one replace decision of a tick's promotion gate.
type gateReplace struct{ volumeID, decision string }
func (h *Host) noteGateReplace(volumeID, decision string) {
h.gateNoteMu.Lock()
h.gateReplaces = append(h.gateReplaces, gateReplace{volumeID, decision})
h.gateNoteMu.Unlock()
}
func (h *Host) takeGateReplaces() []gateReplace {
h.gateNoteMu.Lock()
defer h.gateNoteMu.Unlock()
out := h.gateReplaces
h.gateReplaces = nil
return out
}
// reportReplaces logs what became of each replace decision of this tick:
// not submitted (notSubmitted says why), a failed submit, or what the
// controller did with the volume (an enqueued ask, or why none). A decision
// the controller does not act on is otherwise silent until the volume is
// seen not to fail over.
func (h *Host) reportReplaces(notSubmitted string, submitErr error, outcomes map[string]string) {
for _, d := range h.takeGateReplaces() {
outcome := ""
switch {
case notSubmitted != "":
outcome = notSubmitted
case submitErr != nil:
outcome = "submit failed: " + submitErr.Error()
default:
if o, ok := outcomes[d.volumeID]; ok {
outcome = "controller: " + o
} else {
outcome = "controller: no outcome (the submission did not carry the volume)"
}
}
h.log.Printf("blockmaster: promotion gate volume=%s decision=%s %s", d.volumeID, d.decision, outcome)
}
return true, probeCount, blockedCount, directAsks, h.ctrl.SubmitObservedState(build.Snapshot, build.Report)
}
func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int, int, []authority.AssignmentAsk) {
@@ -426,7 +376,6 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
// decision names, on the gate's line, the branch this tick took, so a
// volume that keeps a lost primary says why.
decision := ""
replaceDecided := false // the gate decided to replace the primary (reported after the submit)
switch {
case !replaceWanted:
decision = "keep_current(" + gateAcceptance(vol.Slots[currentIdx], serverIndex, h.placementEligible(vol.Slots[currentIdx].ServerID)) + ")"
@@ -453,7 +402,6 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
} else if (len(allowed) > 0 || emptyVolumeSurvivors(result, ok)) && replacing {
result, allowed = h.fencedDecision(vol.VolumeID, vol.Authority, result, len(candidates))
fencedReplace = len(allowed) > 0
replaceDecided = true
decision = fmt.Sprintf("replace(fenced_at=%d)", vol.Authority.Epoch+1)
if len(allowed) == 0 {
decision = "replace(fencing_round_published_nothing)"
@@ -469,12 +417,8 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int,
}
}
if decision == "" && replacing {
replaceDecided = true
decision = "replace(no_candidate_to_fence)"
}
if replaceDecided {
h.noteGateReplace(vol.VolumeID, decision)
}
if ok {
h.log.Printf("blockmaster: promotion gate volume=%s current=%s current_known=%t current_ready=%t ack_profile=%s required_lsn=%d candidates=%v allowed=%v primary_lost=%t decision=%s",
vol.VolumeID, vol.Authority.ReplicaID, result.CurrentKnown, result.Current.Ready, result.AckProfile, result.SyncAckLSN, result.Candidates, allowed, lost, decision)
@@ -1013,19 +957,13 @@ func (h *Host) recordVolumeBlockedEvent(volumeID, reason string) {
}
func (h *Host) recordAuthorityPublishedEvent(event authority.PublishEvent) {
if h == nil {
if h == nil || h.events == nil {
return
}
message := fmt.Sprintf("authority published replica %s epoch=%d endpoint_version=%d", event.Info.ReplicaID, event.Info.Epoch, event.Info.EndpointVersion)
if event.Ask.Intent == authority.IntentReassign {
message = fmt.Sprintf("authority reassigned to replica %s epoch=%d endpoint_version=%d", event.Info.ReplicaID, event.Info.Epoch, event.Info.EndpointVersion)
}
if h.log != nil {
h.log.Printf("blockmaster: volume=%s %s (%s)", event.Info.VolumeID, message, event.Ask.Intent)
}
if h.events == nil {
return
}
h.events.append(ops.ClusterEvent{
VolumeID: event.Info.VolumeID,
ReplicaID: event.Info.ReplicaID,
-1
View File
@@ -1323,7 +1323,6 @@ Notes:
| `INV-PROMOTE-FRONTIER-UNKNOWN-001` | With an unknown frontier under `sync_quorum` or `sync_all`, the gate allows the highest-durable ready candidate only if at least N_peers-K+1 of the N_peers peers are probed ready this tick and have a fresh heartbeat (K as in `waitForSyncAcks`); else none. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas`, `unknownFrontierSurvivorsNeeded`, `freshPromotionPeers`; `core/replication/async_ack.go` `waitForSyncAcks` | `TestMountedFailover_ProductLoopRF3UnknownRequiredLSNFallsBackToHighestDurableLSN` (`core/host/master/product_loop_test.go`); `TestProductLoop_MissingRequiredFrontierRefusesRF3Promotion` (`core/host/master/promotion_missing_frontier_regression_test.go`); `TestUnknownFrontierSurvivorsNeeded`, `TestFreshPromotionPeers_UsesObservationFreshness`, `TestProductLoop_UnknownFrontierSurvivorReadyLastTickMissingNowRefused` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE |
| `INV-PROMOTE-FRONTIER-BEST-EFFORT-001` | The automatic path never replaces a lost primary of a `best_effort` volume (a write may be on the primary alone, as for the operator's move): both gates hold it before any fencing round and show `best_effort_no_automatic_failover`. | M3 Supporting → promotion candidate (both gates) | `core/host/master/product_loop.go` `automaticFailoverHold` (supported gate before `fencedDecision`; unsupported gate before its candidates); `promotionAllowedReplicas` | `TestTheAutomaticPathHoldsABestEffortVolume` (`core/host/master/best_effort_hold_test.go`); `TestMountedFailover_ProductLoopRF3BestEffortIsHeldDespiteAHighestDurableSurvivor`, `TestMountedFailover_ProductLoopRF3RejectsBestEffortProbeForHA` (`core/host/master/product_loop_test.go`); `TestPromotionAllowedReplicas_RequiredFrontierCoverage` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE |
| `INV-PROMOTE-ACK-PROFILE-MATCH-001` | The automatic path holds a lost primary's volume, before any fencing round and showing `ack_profile_mismatch`, when a probe answer names no ack profile or another than blockmaster's `--launcher-replication-ack`; blockmaster refuses to start with an unknown one. | M3 Supporting → promotion candidate (both gates) | `core/host/master/probe_round.go` `profileMismatch`; `core/host/master/product_loop.go` `automaticFailoverHold` (plain round), `fencedDecision` (fencing round); `core/host/volume/probe_round.go` `probeAnswer`; `cmd/blockvolume/main.go` `hostConfig`; `cmd/blockmaster/main.go` `parseFlags` | `TestTheAutomaticPathHoldsOnAnAckProfileMismatch`, `TestProbeRound_ReportsAnAckProfileMismatch`, `TestTheFencingRoundsAckProfileIsCheckedToo` (`core/host/master/ack_profile_mismatch_test.go`); `TestProbeAnswerNamesTheVolumesAckProfile` (`core/host/volume/probe_ack_profile_test.go`); `TestHostConfigAnswersTheVolumesOwnAckProfile` (`cmd/blockvolume/probe_ack_profile_test.go`); `TestBlockmasterRefusesAnUnknownLauncherReplicationAck` (`cmd/blockmaster/launcher_replication_ack_flag_test.go`) | — | ACTIVE |
| `INV-PROMOTE-DECISION-REPORTED-001` | Every replace decision of the supported promotion gate is reported on the master's log once, after its tick: with the controller's outcome for that volume from the same submission (read under the controller's lock, so a later intake cannot change it), as not submitted and why (placements changed, a binding appeared, endpoints bound elsewhere, or the workspace bindings could not be read after the probe), or as a failed submit; every publication is logged. Diagnostics only: no decision changes. | M3 Supporting → promotion candidate (supported gate → controller → publisher) | `core/host/master/product_loop.go` `submitPlacementSnapshots`, `noteGateReplace`, `reportReplaces`, `recordAuthorityPublishedEvent`; `core/authority/controller.go` `SubmitObservedStateOutcomes`, `LastOutcome` | `TestAReplaceDecisionLogsWhatTheControllerDidWithIt` (cases: enqueued, already desired, no ask with why, not submitted, an intake after the submission does not change its report, a submission that did not carry the volume, one report per decision), `TestAProductTickReplaceLogsTheControllerOutcomeAndThePublication`, `TestABindingReadFailureAfterTheProbeReportsTheDecisionNotSubmitted`, `TestAPublicationIsLogged` (`core/host/master/gate_controller_outcome_test.go`, `core/host/master/gate_binding_read_failure_test.go`) | — (diagnostics; no published specification models the log) | ACTIVE |
| `INV-PRIMARY-ACK-PROFILE-001` | A primary of a replicated line serves only when its own `--replication-ack` is the profile its assignment names (blockmaster's); otherwise its frontend is not Healthy and status names both profiles. So a lost primary, which does not answer, acknowledged under the master's profile. | M1 Primary → Serving (replicated line) | `core/host/master/services.go` `assignmentFact` (`ack_profile`); `core/host/volume/workspace_startup.go` `noteAckProfile`; `core/host/volume/projection_bridge.go` `projectionWithSupersede`; `core/host/volume/status_server.go` | `TestPrimaryOfAReplicatedLineServesOnlyUnderTheMastersAckProfile` (`core/host/volume/ack_profile_refusal_test.go`); `TestAssignmentNamesTheMastersAckProfile` (`core/host/master/ack_profile_mismatch_test.go`) | — | ACTIVE |
| `INV-CSI-CONSUMES-AUTHORITY-001` | CSI never imports authority code or builds assignment facts; it takes the publish target from blockmaster and refreshes it before a stage, and blockmaster mints the IDs of the events CSI reports. | M2 (read side) | `core/csi/master_backend.go` `LookupPublishTarget`; `core/csi/node.go` `refreshPublishContext`; `core/host/master/observation_service.go` `ReportClusterEvent` | `TestG15a_CSI_DoesNotImportAuthorityOrConstructAssignmentFacts` (`core/csi/boundary_guard_test.go`); `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestObservationService_ReportClusterEventAppearsInVolumeTimeline` (`core/host/master/observation_service_test.go`) | — | ACTIVE |
| `INV-K8S-NONLOOPBACK-001` | Generated multi-node Helm values enable external iSCSI, external status and loopback rejection; with rejection enabled CSI never publishes a loopback target and fails closed when only loopback targets exist. | M2 (read side) | `cmd/sw-block/main.go` `runOpsGenerateHelmValues`; `core/csi/master_backend.go` `rejectFrontendAddr` | `TestOpsGenerateHelmValuesMultiNodeExternalISCSI` (`cmd/sw-block/main_test.go`); `TestNodeLoss_ControlStatusLookup_RejectsLoopbackPublishTargetsWhenEnabled`, `TestNodeLoss_ControlStatusLookup_FailClosedWhenOnlyLoopbackTargets` (`core/csi/master_backend_test.go`) | — | ACTIVE |
-32
View File
@@ -14,38 +14,6 @@ v1.1.1 is a fix release of the v1.1 line. None of its changes alters a stored fo
- The `sw-block` commands that `mini` prints assume it is on `PATH`: in the extracted directory, run
`export PATH="$PWD:$PATH"`. Its `weed shell` hint needs the full path of the `weed` binary given to `--weed`.
## Known issue: restarting blockmaster with many declared volumes
- **What happens:** when blockmaster restarts, it rewrites every declared volume's node and placement records to disk, one by one, before it answers again. With a few hundred declared volumes this can take longer than a running volume's lease. Running volumes then stop (`lease_expired`, exit 75), and the guest sees I/O errors on those volumes while they are stopped.
- In our test with 999 declared volumes, blockmaster answered again after about 45 s; the 8 running volumes stopped 12–20 s after the restart.
- With 33 declared volumes, nothing stopped.
- No acknowledged data is lost.
- **Recovery:** a stopped volume comes back only if it is supervised. The shipped systemd unit restarts a volume that exits 75; in our test the volumes were serving again within a minute. Otherwise, start the volume again yourself.
- **Where it starts:** we estimate around 150 declared volumes; it depends on the disk under blockmaster's state directory.
- **What to do:** restart blockmaster in a maintenance window if a cluster declares more than about 150 volumes. A fix is planned for v1.1.2; in our test with it, 999 volumes restarted in under 6 s including the stop, and no volume stopped.
## Known issue: blockmaster needs its filer to start
- blockmaster checks that its SeaweedFS filer answers before it starts. If the filer is unreachable, blockmaster stops with an error after about 60 s instead of starting.
- While blockmaster cannot start, running volumes stop when their leases run out.
- Start or fix the filer first, then start blockmaster.
## Known issue: `sw-block ops chunk detach --plain` waits for a scheduled periodic cut
- A scheduled periodic cut is not interrupted by `sw-block ops chunk detach --plain`. A detach issued while such a cut is capturing waits until the cut finishes, so on a volume with a long cut the detach takes correspondingly longer.
- No data is lost. A fix is planned for a later v1.1.x release.
## Known issue: a walstore volume unit can reach its systemd start limit while blockmaster is unreachable
- Affects volumes on the walstore engine run by `sw-blockvolume.service`, `sw-blockvolume@.service` or `sw-blockvolume-ublk.service` (`StartLimitBurst=10` in 600 s, `RestartSec=5s`). Chunk-store volumes wait for blockmaster in process and are not affected.
- A walstore volume that starts while blockmaster is unreachable exits with 75 after about 10 s and is restarted by systemd. After about 10 attempts (about 150 s) the unit stays failed, even once blockmaster is back.
- No data is lost. Recover with `systemctl reset-failed <unit>`, then `systemctl start <unit>`. A fix is planned for v1.1.2.
## Known issue: startup retirement reads can delay blockmaster
- At startup blockmaster checks volumes that are reserved for deletion and hold no workspace lease, one at a time, before it serves. Each check reads the filer, so a slow filer delays the start: in our test, 100 such volumes with a 100 ms filer delay added about 20 s. Volumes in normal use are skipped without a read.
- No data is lost. A fix is planned for v1.1.2.
## Upgrade notes
- **Order: the CLI first, then blockmaster, then each holder**, as in
@@ -1,675 +0,0 @@
#!/usr/bin/env bash
# iterate-m01-replicated-write.sh — G5-5 lab hardware first-light orchestration
#
# Per v3-phase-15-g5-5-mini-plan.md v0.3 §2 acceptance criteria:
# #1 verify_cluster_ready — blockmaster + 2x blockvolume, role-appropriate ready
# #2 verify_byte_equal — kernel iSCSI write → m01verify storage-aware compare
# #3 verify_network_catchup — iptables disconnect + /status/recovery R/H polling
# #4 verify_restart_catchup — SIGTERM replica + restart same --durable-root
# #5 verify_race_stress — TestG54_BinaryWiring x10 -race
# #6 verify_full_suite — go test ./... clean
#
# Two-node cluster:
# node-a (its address) — primary blockvolume + iSCSI target + blockmaster
# node-b (its address) — replica blockvolume
#
# Run from local workstation (Windows / Git Bash); SSH drives both nodes.
# Exit 0 on all-green; non-zero + diagnostic artifacts on any failure.
set -euo pipefail
# --- Config (env-overridable) ---
M01_HOST="${M01_HOST:-testdev@192.168.1.181}"
M02_HOST="${M02_HOST:-testdev@192.168.1.184}"
# Routable IPs for cross-host advertise (--data-addr / --ctrl-addr).
# Extracted from M01_HOST/M02_HOST. Used as the BIND addr too in
# Tier 2: binding to a specific local-interface IP works on Linux,
# AND ensures the daemon ADVERTISES a routable IP to master via
# heartbeat (peer.DataAddr in AssignmentFact). Binding 0.0.0.0
# would advertise "0.0.0.0:port" and break primary→replica dial
# (0.0.0.0 is not a routable destination). QA round 54 finding.
M01_IP="${M01_HOST##*@}"
M02_IP="${M02_HOST##*@}"
SSH_KEY="${SSH_KEY:-/c/work/dev_server/testdev_key}"
SRC_DIR="${SRC_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
REMOTE_BUILD_DIR="${REMOTE_BUILD_DIR:-/tmp/g5_sb_build}"
REMOTE_RUN_DIR="${REMOTE_RUN_DIR:-/tmp/g5_sb_run}"
DURABLE_IMPL="${DURABLE_IMPL:-walstore}"
DURABLE_BLOCKS="${DURABLE_BLOCKS:-256}" # 1 MiB at 4 KiB blocks (small for fast tests)
DURABLE_BLOCKSIZE="${DURABLE_BLOCKSIZE:-4096}"
ARTIFACT_DIR="${ARTIFACT_DIR:-${SRC_DIR%/*}/seaweedfs/sw-block/design/g5-artifacts}"
# Network ports (node-a primary side)
M01_MASTER_PORT=9180
M01_PRIMARY_CTRL_PORT=9210
M01_PRIMARY_DATA_PORT=9220
M01_PRIMARY_STATUS_PORT=9290
M01_ISCSI_PORT=3260
# Network ports (node-b replica side)
M02_REPLICA_CTRL_PORT=9211
M02_REPLICA_DATA_PORT=9221
M02_REPLICA_STATUS_PORT=9291
# iSCSI target identity (primary serves a single LUN)
ISCSI_IQN="iqn.2026-04.io.seaweed.block:v1"
# Catch-up deadline (s) for #3 + #4
CATCHUP_DEADLINE=30
# Two SSH option sets — DIFFERENT requirements for two patterns:
#
# 1. SSH_OPTS — for `ssh host "CMD"` (command-as-argument).
# Includes `-n` to close ssh's stdin so the connection doesn't
# wait on terminal input. Used by collect_diagnostics, status
# polls, simple one-shot commands.
#
# 2. SSH_OPTS_LAUNCH — for `ssh host bash -s <<EOF ... EOF`
# (script-via-stdin pattern, used by launch_m01/launch_m02).
# MUST NOT include `-n` because `-n` redirects ssh stdin from
# /dev/null, which means `bash -s` reads EOF immediately and
# exits before running the heredoc body — the daemon never
# starts. QA round 53 isolated this: dbg.sh on node-a confirmed
# `bash -s` works without `-n` and silently does nothing with
# `-n`. The PTY-hang protection comes from `-T` alone, which
# both option sets keep.
#
# Both sets keep `-T` (no PTY allocation) and `BatchMode=yes`
# (refuse to prompt for password/key passphrase).
SSH_OPTS_BASE="-T -i ${SSH_KEY} -o ConnectTimeout=10 -o StrictHostKeyChecking=no -o BatchMode=yes"
SSH_OPTS="${SSH_OPTS_BASE} -n"
SSH_OPTS_LAUNCH="${SSH_OPTS_BASE}"
SSH_M01="ssh ${SSH_OPTS} ${M01_HOST}"
SSH_M02="ssh ${SSH_OPTS} ${M02_HOST}"
# SSH_LAUNCH wraps the *_HOST ssh command with a hard timeout for
# the launch-and-detach pattern (start_master / start_primary /
# start_replica). Even with -T -n + setsid + nohup + disown + exit 0,
# Windows OpenSSH occasionally fails to release the connection. The
# 15s wall-clock cap means we move on regardless — the remote process
# is already detached, so the only risk is a stale ssh client process
# on the local box, which is harmless.
#
# Falls back to a no-op wrapper if `timeout` isn't installed (Git
# Bash without GNU coreutils — install via `pacman -S coreutils` or
# upgrade Git for Windows).
if command -v timeout >/dev/null 2>&1; then
LAUNCH_TIMEOUT_PREFIX="timeout --preserve-status 15"
else
LAUNCH_TIMEOUT_PREFIX=""
fi
# --- Helpers ---
log() { printf '\033[1;36m[g5-5]\033[0m %s\n' "$*" >&2; }
die() { printf '\033[1;31m[g5-5 FAIL]\033[0m %s\n' "$*" >&2; collect_diagnostics fail; exit 1; }
# launch_m01 / launch_m02 — accept a script body on stdin and execute
# it via `bash -s` either locally (LOCAL_MODE=1) or remote ssh
# (LOCAL_MODE=0). Used by start_master / start_primary / start_replica
# to launch background daemons safely.
#
# Architect option (A) round 53: `bash -s <<EOF ... EOF` avoids the
# `\<newline>` line-continuation hazard that plagued the prior
# double-quoted-ssh-arg form. With `bash -s`, the heredoc body is
# piped to remote bash's stdin and executed line-by-line with literal
# newlines preserved — `&` and `disown` stay on separate lines no
# matter what the local shell does to the script source.
#
# Hard-capped at 15s by LAUNCH_TIMEOUT_PREFIX (if `timeout` available).
# If launch ssh hangs, we move on; remote process is already detached.
launch_m01() {
if [ "${LOCAL_MODE}" = "1" ]; then
${LAUNCH_TIMEOUT_PREFIX} bash -s
else
# SSH_OPTS_LAUNCH (no -n) — bash -s reads from stdin; -n
# would redirect stdin from /dev/null and bash would EOF.
${LAUNCH_TIMEOUT_PREFIX} ssh ${SSH_OPTS_LAUNCH} ${M01_HOST} bash -s
fi
}
launch_m02() {
if [ "${LOCAL_MODE}" = "1" ]; then
${LAUNCH_TIMEOUT_PREFIX} bash -s
else
${LAUNCH_TIMEOUT_PREFIX} ssh ${SSH_OPTS_LAUNCH} ${M02_HOST} bash -s
fi
}
mkdir -p "${ARTIFACT_DIR}"
# Two-tier test mode (set BEFORE first SSH-or-bash command):
# Tier 1 (LOCAL_MODE=1): single Linux host (e.g. WSL Ubuntu)
# - both "node-a" + "node-b" processes on localhost
# - no SSH overhead, no cross-node sync
# - iSCSI tests skip if iscsiadm not installed
# - use for fast iteration during dev
# Tier 2 (default, LOCAL_MODE=0): node-a (its address) + node-b (its address)
# - real network + real iSCSI/NVMe kernel + real cross-host wire
# - use for deployment-realism close evidence
LOCAL_MODE="${LOCAL_MODE:-0}"
if [ "${LOCAL_MODE}" = "1" ]; then
log "LOCAL_MODE=1 → Tier 1: both processes on localhost (no SSH)"
SSH_M01="bash -c"
SSH_M02="bash -c"
M02_MASTER_TARGET="127.0.0.1"
# Tier 1: bind+advertise on loopback (single host).
M01_PRIMARY_BIND_IP="127.0.0.1"
M02_REPLICA_BIND_IP="127.0.0.1"
else
log "Tier 2: m01 cross-node (override with LOCAL_MODE=1 for fast local iteration)"
M02_MASTER_TARGET="${M01_IP}"
# Tier 2 (architect round 54): bind+advertise on each host's
# routable IP. The daemon advertises the literal --data-addr /
# --ctrl-addr to master heartbeat, master mints AssignmentFact.peers
# with the same string, primary dials it. 0.0.0.0 advertise breaks
# cross-host (primary tries to dial 0.0.0.0:port → unroutable).
M01_PRIMARY_BIND_IP="${M01_IP}"
M02_REPLICA_BIND_IP="${M02_IP}"
fi
HAS_ISCSI=0
if [ "${LOCAL_MODE}" = "1" ]; then
if command -v iscsiadm >/dev/null 2>&1; then HAS_ISCSI=1; fi
else
HAS_ISCSI=1 # assume node-a/node-b have iscsiadm; verified at first iSCSI test
fi
[ "${HAS_ISCSI}" = "0" ] && log " (iscsiadm not present locally → criteria #2/#3/#4 will skip with explicit message)"
collect_diagnostics() {
local label="$1"
log "collecting diagnostics [${label}]..."
$SSH_M01 "cat ${REMOTE_RUN_DIR}/logs/master.log 2>/dev/null" > "${ARTIFACT_DIR}/master-${label}.log" || true
$SSH_M01 "cat ${REMOTE_RUN_DIR}/logs/primary.log 2>/dev/null" > "${ARTIFACT_DIR}/primary-${label}.log" || true
$SSH_M02 "cat ${REMOTE_RUN_DIR}/logs/replica.log 2>/dev/null" > "${ARTIFACT_DIR}/replica-${label}.log" || true
}
# poll_status — fetch /status/recovery from a given node + status port,
# extract a JSON field via a tiny python one-liner. Returns the field
# value on stdout or empty on failure.
poll_status_field() {
local ssh_cmd="$1" status_port="$2" field="$3"
$ssh_cmd "curl -s --max-time 2 'http://127.0.0.1:${status_port}/status/recovery?volume=v1' | python3 -c 'import json,sys; d=json.load(sys.stdin); print(d.get(\"${field}\",\"\"))' 2>/dev/null" || true
}
# wait_until — polls a check command until it returns 0 or deadline.
wait_until() {
local desc="$1" deadline_s="$2" check_cmd="$3"
local end=$(( $(date +%s) + deadline_s ))
while [ "$(date +%s)" -lt "${end}" ]; do
if eval "${check_cmd}" >/dev/null 2>&1; then
return 0
fi
sleep 1
done
log "wait_until(${desc}) TIMEOUT after ${deadline_s}s"
return 1
}
# wait_until_byte_equal — poll-cycles m01verify against the replica's
# walstore until the LBA's bytes match the expected pattern, or the
# deadline expires. Each cycle: stop replica daemon (so OpenReadOnly
# is honest about the no-concurrent-writer assumption), invoke
# m01verify, restart replica. The "replica running" gap between
# cycles is what gives the catch-up ship traffic time to land.
#
# Caller must ensure the replica daemon is RUNNING at entry (we kill
# + restart). Caller is also responsible for the post-call replica
# state (we leave it RUNNING on both success and timeout, so the
# next test step can use the cluster).
#
# Usage: wait_until_byte_equal <lba> <hex-byte-pattern> <deadline_s> <desc>
# Pattern is a single hex byte (e.g. "ab"), per m01verify --expected-pattern.
wait_until_byte_equal() {
local lba="$1" pattern="$2" deadline_s="$3" desc="$4"
local end=$(( $(date +%s) + deadline_s ))
local last_out=""
while [ "$(date +%s)" -lt "${end}" ]; do
# Stop replica so m01verify's OpenReadOnly assumption holds.
$SSH_M02 "sudo killall -TERM g5-blockvolume 2>/dev/null; sleep 1" >/dev/null 2>&1 || true
local out
out=$($SSH_M02 "/tmp/g5-m01verify --walstore ${REMOTE_RUN_DIR}/replica-store/v1.bin --lba-start ${lba} --lba-count 1 --block-size 4096 --expected-pattern ${pattern} 2>&1" || true)
last_out="${out}"
# Restart replica so ship traffic can resume + cluster stays up.
start_replica >/dev/null 2>&1 || true
if echo "${out}" | grep -q '^OK '; then
log " byte-equal ${desc} lba=${lba} pattern=${pattern} ✓ ($(($(date +%s) - (end - deadline_s)))s)"
return 0
fi
sleep 3 # let new ships arrive between attempts
done
log "wait_until_byte_equal(${desc}) TIMEOUT lba=${lba} pattern=${pattern} after ${deadline_s}s; last=${last_out}"
return 1
}
# iscsi_write_pattern — drive a kernel iSCSI write at the given LBA
# with N blocks of the supplied 0xHH hex pattern. Login + write +
# logout under set -euo pipefail with explicit failure modes.
# Usage: iscsi_write_pattern <lba> <count> <hex-pattern>
# Total bytes written = count * 4096.
iscsi_write_pattern() {
local lba="$1" count="$2" pattern="$3"
local bytes=$(( count * 4096 ))
$SSH_M01 'set -euo pipefail
sudo iscsiadm -m discovery -t st -p 127.0.0.1:'"${M01_ISCSI_PORT}"' >/dev/null
sudo iscsiadm -m node -T '"${ISCSI_IQN}"' -p 127.0.0.1:'"${M01_ISCSI_PORT}"' --login >/dev/null
sleep 2
DEV=$(ls -t /dev/disk/by-path/*'"${ISCSI_IQN}"'*-lun-0 2>/dev/null | head -1)
[ -n "$DEV" ] || { echo "ERROR: iSCSI device not visible after login"; exit 2; }
python3 -c "import sys; sys.stdout.buffer.write(b\"\x'"${pattern}"'\" * '"${bytes}"')" | sudo dd of="$DEV" bs=4096 count='"${count}"' seek='"${lba}"' conv=fsync,nocreat
sync
sudo iscsiadm -m node -T '"${ISCSI_IQN}"' -p 127.0.0.1:'"${M01_ISCSI_PORT}"' --logout >/dev/null
echo "WROTE-LBA-'"${lba}"'-COUNT-'"${count}"'-PATTERN-'"${pattern}"'"
'
}
# --- Phase 1: sync + build ---
sync_and_build() {
if [ "${LOCAL_MODE}" = "1" ]; then
if [ -n "${PREBUILT_BIN_DIR:-}" ] && [ -x "${PREBUILT_BIN_DIR}/g5-blockmaster" ]; then
log "phase 1: use pre-built binaries from PREBUILT_BIN_DIR=${PREBUILT_BIN_DIR}"
cp "${PREBUILT_BIN_DIR}/g5-blockmaster" /tmp/g5-blockmaster
cp "${PREBUILT_BIN_DIR}/g5-blockvolume" /tmp/g5-blockvolume
cp "${PREBUILT_BIN_DIR}/g5-m01verify" /tmp/g5-m01verify
chmod +x /tmp/g5-blockmaster /tmp/g5-blockvolume /tmp/g5-m01verify
return
fi
log "phase 1: build binaries locally (LOCAL_MODE — no sync, no scp)"
log " hint: cross-compile on Windows + set PREBUILT_BIN_DIR if WSL Go is too old (project needs go 1.21+)"
cd "${SRC_DIR}" && \
go build -o /tmp/g5-blockmaster ./cmd/blockmaster/ && \
go build -o /tmp/g5-blockvolume ./cmd/blockvolume/ && \
go build -tags m01verify -o /tmp/g5-m01verify ./cmd/m01verify/ \
|| die "local build failed (try PREBUILT_BIN_DIR=/path/to/cross-compiled-bins)"
return
fi
# Tier 2 PREBUILT_BIN_DIR fast-path (architect option (a) round 53):
# If the operator has pre-built the 3 binaries (e.g. on a Windows
# workstation cross-compiled GOOS=linux, or fetched from a CI
# artifact), skip the source-tar + remote-build cycle entirely.
# Just scp the binaries to node-a:/tmp/ and onward to node-b.
if [ -n "${PREBUILT_BIN_DIR:-}" ]; then
log "phase 1: use pre-built binaries from PREBUILT_BIN_DIR=${PREBUILT_BIN_DIR}"
for bin in g5-blockmaster g5-blockvolume g5-m01verify; do
[ -x "${PREBUILT_BIN_DIR}/${bin}" ] || \
die "PREBUILT_BIN_DIR set but ${PREBUILT_BIN_DIR}/${bin} is missing or not executable"
done
scp -i "${SSH_KEY}" -o StrictHostKeyChecking=no \
"${PREBUILT_BIN_DIR}/g5-blockmaster" \
"${PREBUILT_BIN_DIR}/g5-blockvolume" \
"${PREBUILT_BIN_DIR}/g5-m01verify" \
"${M01_HOST}:/tmp/" >/dev/null \
|| die "scp pre-built binaries → m01 failed"
log " scp blockvolume + m01verify to M02..."
$SSH_M01 "scp -o StrictHostKeyChecking=no /tmp/g5-blockvolume /tmp/g5-m01verify ${M02_HOST}:/tmp/" >/dev/null \
|| die "scp m01→M02 failed"
return
fi
log "phase 1: sync source + build binaries on m01"
# Safety guard (architect option (a) round 53 binding): refuse to tar
# if SRC_DIR is empty / "/" / missing repo markers. Catches the case
# where the script was copied away from the repo (e.g. SMB-driven
# `bash /tmp/iterate.sh`) and SRC_DIR resolves to / — without this
# guard, the next line would tar the entire root filesystem.
case "${SRC_DIR}" in
""|"/")
die "SRC_DIR refuses to be empty or '/' (would tar root filesystem); set PREBUILT_BIN_DIR or run from a real seaweed_block checkout"
;;
esac
[ -f "${SRC_DIR}/go.mod" ] && [ -d "${SRC_DIR}/cmd/blockvolume" ] || \
die "SRC_DIR=${SRC_DIR} doesn't look like a seaweed_block checkout (missing go.mod or cmd/blockvolume/); set PREBUILT_BIN_DIR or fix SRC_DIR"
cd "${SRC_DIR}"
tar --exclude='.git' --exclude='*.exe' --exclude='*.test' -czf /tmp/g5-src.tgz .
scp -i "${SSH_KEY}" -o StrictHostKeyChecking=no /tmp/g5-src.tgz "${M01_HOST}:/tmp/" >/dev/null
$SSH_M01 "rm -rf ${REMOTE_BUILD_DIR} && mkdir -p ${REMOTE_BUILD_DIR} && cd ${REMOTE_BUILD_DIR} && tar xzf /tmp/g5-src.tgz"
$SSH_M01 "
cd ${REMOTE_BUILD_DIR} && \
go build -o /tmp/g5-blockmaster ./cmd/blockmaster/ && \
go build -o /tmp/g5-blockvolume ./cmd/blockvolume/ && \
go build -tags m01verify -o /tmp/g5-m01verify ./cmd/m01verify/
" || die "build failed on m01"
log " scp blockvolume + m01verify to M02..."
$SSH_M01 "scp -o StrictHostKeyChecking=no /tmp/g5-blockvolume /tmp/g5-m01verify ${M02_HOST}:/tmp/" >/dev/null \
|| die "scp m01→M02 failed"
}
# --- Phase 2: cluster lifecycle ---
write_topology() {
$SSH_M01 "cat > ${REMOTE_RUN_DIR}/topology.yaml <<EOF
volumes:
- volume_id: v1
slots:
- replica_id: r1
server_id: m01-primary
- replica_id: r2
server_id: m02-replica
EOF"
}
start_master() {
log " start blockmaster on m01..."
# Architect option (A) round 53: pipe command via `bash -s`
# heredoc instead of double-quoted ssh argument. Single-line
# `setsid nohup ... &` (no `\<newline>` continuations) avoids
# the local-shell line-collapse hazard that joined `&` into the
# following `disown` statement, making remote bash wait on the
# bg job and hang the SSH session.
launch_m01 <<EOF
setsid nohup /tmp/g5-blockmaster --authority-store ${REMOTE_RUN_DIR}/master-store --listen 0.0.0.0:${M01_MASTER_PORT} --topology ${REMOTE_RUN_DIR}/topology.yaml --expected-slots-per-volume 2 --t0-print-ready > ${REMOTE_RUN_DIR}/logs/master.log 2>&1 </dev/null &
disown \$! 2>/dev/null || true
sleep 1
exit 0
EOF
}
start_primary() {
log " start primary blockvolume on m01..."
launch_m01 <<EOF
setsid nohup /tmp/g5-blockvolume --master 127.0.0.1:${M01_MASTER_PORT} --server-id m01-primary --volume-id v1 --replica-id r1 --ctrl-addr ${M01_PRIMARY_BIND_IP}:${M01_PRIMARY_CTRL_PORT} --data-addr ${M01_PRIMARY_BIND_IP}:${M01_PRIMARY_DATA_PORT} --status-addr 127.0.0.1:${M01_PRIMARY_STATUS_PORT} --status-recovery --durable-root ${REMOTE_RUN_DIR}/primary-store --durable-impl ${DURABLE_IMPL} --durable-blocks ${DURABLE_BLOCKS} --durable-blocksize ${DURABLE_BLOCKSIZE} --iscsi-listen 127.0.0.1:${M01_ISCSI_PORT} --iscsi-iqn ${ISCSI_IQN} --t1-readiness --degraded-probe-interval=5s > ${REMOTE_RUN_DIR}/logs/primary.log 2>&1 </dev/null &
disown \$! 2>/dev/null || true
sleep 1
exit 0
EOF
}
start_replica() {
log " start replica blockvolume on M02..."
launch_m02 <<EOF
mkdir -p ${REMOTE_RUN_DIR}/{logs,replica-store}
setsid nohup /tmp/g5-blockvolume --master ${M02_MASTER_TARGET}:${M01_MASTER_PORT} --server-id m02-replica --volume-id v1 --replica-id r2 --ctrl-addr ${M02_REPLICA_BIND_IP}:${M02_REPLICA_CTRL_PORT} --data-addr ${M02_REPLICA_BIND_IP}:${M02_REPLICA_DATA_PORT} --status-addr 127.0.0.1:${M02_REPLICA_STATUS_PORT} --status-recovery --durable-root ${REMOTE_RUN_DIR}/replica-store --durable-impl ${DURABLE_IMPL} --durable-blocks ${DURABLE_BLOCKS} --durable-blocksize ${DURABLE_BLOCKSIZE} --t1-readiness > ${REMOTE_RUN_DIR}/logs/replica.log 2>&1 </dev/null &
disown \$! 2>/dev/null || true
sleep 1
exit 0
EOF
}
start_cluster() {
log "phase 2: start cluster"
# Pre-flight: drop any stale iptables rules from prior aborted runs.
# Both possible patterns (old INPUT-on-node-b and new OUTPUT-on-node-a) are
# cleared so repeated test runs don't poison each other. Use `|| true`
# so missing rules don't fail set -e.
$SSH_M01 "sudo iptables -D OUTPUT -d ${M02_IP} -p tcp --dport ${M02_REPLICA_DATA_PORT} -j DROP 2>/dev/null || true"
$SSH_M02 "sudo iptables -D INPUT -p tcp --dport ${M02_REPLICA_DATA_PORT} -j DROP 2>/dev/null || true"
$SSH_M01 "sudo pkill -9 -f '[g]5-blockvolume' 2>/dev/null || true; sudo pkill -9 -f '[g]5-blockmaster' 2>/dev/null || true; rm -rf ${REMOTE_RUN_DIR} && mkdir -p ${REMOTE_RUN_DIR}/{logs,master-store,primary-store}"
$SSH_M02 "sudo pkill -9 -f '[g]5-blockvolume' 2>/dev/null || true; rm -rf ${REMOTE_RUN_DIR} && mkdir -p ${REMOTE_RUN_DIR}/{logs,replica-store}"
write_topology
start_master
start_primary
start_replica
}
stop_cluster() {
log "stop cluster"
$SSH_M01 "sudo pkill -9 -f '[g]5-blockvolume' 2>/dev/null || true; sudo pkill -9 -f '[g]5-blockmaster' 2>/dev/null || true" || true
$SSH_M02 "sudo pkill -9 -f '[g]5-blockvolume' 2>/dev/null || true" || true
}
# --- Phase 3: verify steps (per mini-plan v0.3 §2) ---
# §2 #1 — cluster reaches role-appropriate ready state
verify_cluster_ready() {
log "verify_cluster_ready: primary should reach Healthy=true; replica Healthy=false"
wait_until "primary Healthy=true" 15 \
"[ \"\$($SSH_M01 \"curl -s --max-time 2 'http://127.0.0.1:${M01_PRIMARY_STATUS_PORT}/status?volume=v1' | grep -o '\\\"Healthy\\\":true'\")\" = '\"Healthy\":true' ]" \
|| die "primary did not reach Healthy=true within 15s"
# Replica must respond to /status with Healthy=false (NOT Healthy=true; role split).
local rh
rh=$($SSH_M02 "curl -s --max-time 2 'http://127.0.0.1:${M02_REPLICA_STATUS_PORT}/status?volume=v1' | grep -o '\"Healthy\":[a-z]*'")
[ "${rh}" = '"Healthy":false' ] || die "replica reported ${rh}; expected Healthy=false (architect role-split binding)"
log " ✓ cluster ready"
}
# §2 #2 — kernel iSCSI write + m01verify storage-aware compare
# Architect findings round 52: remote SSH bash blocks use
# `set -euo pipefail`; DEV must be non-empty; primary.H must advance
# after the write (catches silent-write-failure masking).
verify_byte_equal() {
if [ "${HAS_ISCSI}" = "0" ]; then
log "verify_byte_equal: SKIP (no iscsiadm; install open-iscsi for Tier 1 iSCSI coverage, OR use Tier 2 m01)"
return 0
fi
log "verify_byte_equal: iSCSI write 1 LBA + m01verify SHA-256"
$SSH_M01 "command -v iscsiadm >/dev/null" || die "iscsiadm not installed on m01 (apt install open-iscsi)"
local prim_h_before prim_h_after
prim_h_before=$(poll_status_field "$SSH_M01" "${M01_PRIMARY_STATUS_PORT}" H)
[ -n "${prim_h_before}" ] || die "could not read primary.H before write"
# Discover + login + write + assert + logout — all under set -euo pipefail
$SSH_M01 'set -euo pipefail
sudo iscsiadm -m discovery -t st -p 127.0.0.1:'"${M01_ISCSI_PORT}"' >/dev/null
sudo iscsiadm -m node -T '"${ISCSI_IQN}"' -p 127.0.0.1:'"${M01_ISCSI_PORT}"' --login >/dev/null
sleep 2
DEV=$(ls -t /dev/disk/by-path/*'"${ISCSI_IQN}"'*-lun-0 2>/dev/null | head -1)
[ -n "$DEV" ] || { echo "ERROR: iSCSI device not visible after login"; exit 2; }
echo "DEV=$DEV"
# Fill 1 block with 0xab and write to LBA 0.
# NOTE: do NOT use `tr "\0" "\xab"` — tr does not interpret \xHH
# escapes; it would substitute with the literal char "x" (0x78).
# Use python3 binary write for byte-exact 0xab.
python3 -c "import sys; sys.stdout.buffer.write(b\"\xab\" * 4096)" | sudo dd of="$DEV" bs=4096 count=1 conv=fsync,nocreat
sync
sudo iscsiadm -m node -T '"${ISCSI_IQN}"' -p 127.0.0.1:'"${M01_ISCSI_PORT}"' --logout >/dev/null
echo "WROTE-LBA-0-PATTERN-AB"
' || die "iscsi write failed"
# NOTE (round-12): H-advance preflight removed. 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); after a local write
# at LSN=1 the next-allocated LSN becomes 2 but Recovery.H stays
# 1 until a probe re-reads boundaries. Using H-advance here is a
# false-positive trap. The actual proof of write+ship is the
# m01verify byte-equal compare below; failures upstream of that
# surface via the primary's log (set -euo pipefail in the dd
# block + non-zero exit on iscsi failure).
prim_h_after=$(poll_status_field "$SSH_M01" "${M01_PRIMARY_STATUS_PORT}" H)
log " primary.H pre/post: ${prim_h_before} → ${prim_h_after} (informational)"
sleep 1 # let replication fan-out complete
# Logout iscsi (release the device handle so we can stop replica cleanly later)
$SSH_M01 "sudo iscsiadm -m node -T ${ISCSI_IQN} -p 127.0.0.1:${M01_ISCSI_PORT} --logout >/dev/null" || true
# Stop replica daemon so m01verify can OpenReadOnly
$SSH_M02 "sudo pkill -TERM -f '[g]5-blockvolume.*server-id m02-replica' && sleep 2"
# m01verify reads replica's walstore
local out
out=$($SSH_M02 "/tmp/g5-m01verify --walstore ${REMOTE_RUN_DIR}/replica-store/v1.bin --lba-start 0 --lba-count 1 --block-size 4096 --expected-pattern ab 2>&1")
log " m01verify output: ${out}"
echo "${out}" | grep -q '^OK ' || die "byte-equal verify failed: ${out}"
# Restart replica for subsequent steps
start_replica
sleep 3
log " ✓ byte-equal"
}
# §2 #3 — network disconnect catch-up
#
# Pattern (architect round 13 ratification per QA's planning input):
# direct byte-equal as the pass condition, replacing the H/R polling
# proxy. /status/recovery snapshots stay as supporting diagnostic
# only.
#
# 1. baseline write LBA[0]=0xab; byte-equal verify (already done in
# verify_byte_equal — primary now contains LBA0=0xab)
# 2. iptables OUTPUT DROP on node-a toward node-b:M02_REPLICA_DATA_PORT
# (architect ruling: node-a OUTPUT drop preferred over node-b INPUT
# drop; least-broad rule that proves the scenario)
# 3. primary write LBA[1]=0xcd (new pattern, BestEffort: primary
# WAL accepts; ship to r2 fails until heal)
# 4. heal: iptables -D
# 5. wait_until_byte_equal LBA[1]=0xcd CATCHUP_DEADLINE
# 6. (informational) snapshot /status/recovery for diagnostic
#
# trap ensures iptables -D runs even on script abort so a failed run
# does not poison the box.
verify_network_catchup() {
if [ "${HAS_ISCSI}" = "0" ]; then
log "verify_network_catchup: SKIP (needs iscsiadm to drive write; use Tier 2 m01)"
return 0
fi
log "verify_network_catchup: m01 OUTPUT drop to ${M02_IP}:${M02_REPLICA_DATA_PORT} + write + heal + byte-equal"
# Cleanup trap: best-effort iptables -D, runs on any function exit
# path (success, die, set -e abort upstream).
local cleanup_done=0
_verify_network_catchup_cleanup() {
[ "${cleanup_done}" = "1" ] && return
cleanup_done=1
$SSH_M01 "sudo iptables -D OUTPUT -d ${M02_IP} -p tcp --dport ${M02_REPLICA_DATA_PORT} -j DROP" >/dev/null 2>&1 || true
}
trap _verify_network_catchup_cleanup RETURN
# Step 2: iptables OUTPUT drop on node-a.
$SSH_M01 "sudo iptables -A OUTPUT -d ${M02_IP} -p tcp --dport ${M02_REPLICA_DATA_PORT} -j DROP" \
|| die "iptables -A failed"
log " network partitioned (m01 OUTPUT → ${M02_IP}:${M02_REPLICA_DATA_PORT} DROP)"
# Step 3: primary write LBA[1]=0xcd (different pattern from #2's
# LBA[0]=0xab so we can't false-positive on stale data).
iscsi_write_pattern 1 1 cd >/dev/null || die "iscsi write LBA[1]=0xcd during disconnect failed"
log " primary wrote LBA[1]=0xcd (replica still partitioned)"
# Step 4: heal.
_verify_network_catchup_cleanup
log " network healed (iptables -D applied)"
# Step 5: poll until byte-equal at replica.
wait_until_byte_equal 1 cd "${CATCHUP_DEADLINE}" "verify_network_catchup-LBA1" \
|| die "replica did not converge LBA[1]=0xcd within ${CATCHUP_DEADLINE}s after heal"
# Step 6: diagnostic snapshot (not pass/fail oracle).
local prim_h rep_r decision
prim_h=$(poll_status_field "$SSH_M01" "${M01_PRIMARY_STATUS_PORT}" H)
rep_r=$(poll_status_field "$SSH_M02" "${M02_REPLICA_STATUS_PORT}" R)
decision=$(poll_status_field "$SSH_M02" "${M02_REPLICA_STATUS_PORT}" RecoveryDecision)
log " diagnostic /status/recovery: primary.H=${prim_h} replica.R=${rep_r} replica.RecoveryDecision=${decision:-<empty>}"
log " ✓ network catch-up byte-equal converged"
trap - RETURN
}
# §2 #4 — replica process stop/restart catch-up
#
# Pattern (architect round 13 ratification):
# 1. baseline: replica running, byte-equal at LBA[0]=0xab from #2
# 2. kill replica: pkill -TERM g5-blockvolume on node-b
# 3. primary write LBA[2]=0xef while replica is down (BestEffort:
# primary's WAL accepts the write; ship attempts to r2 fail
# since r2 is offline)
# 4. restart replica with same --durable-root
# 5. wait_until_byte_equal LBA[2]=0xef CATCHUP_DEADLINE
#
# Run #4 NAIVELY first (architect ruling 2 round 13). If catch-up
# does not converge — primary's WAL did not retain writes during the
# disconnect — that is a real recovery-path finding to surface, NOT
# a test flaw. Do not change durability mode; do not paper over.
#
# Note: m01verify must read replica's walstore only while the
# replica daemon is stopped or quiesced (architect caution round 13).
# wait_until_byte_equal handles this internally (kill→verify→restart
# per cycle).
verify_restart_catchup() {
if [ "${HAS_ISCSI}" = "0" ]; then
log "verify_restart_catchup: SKIP (needs iscsiadm to drive write; use Tier 2 m01)"
return 0
fi
log "verify_restart_catchup: kill replica + write while down + restart + byte-equal"
# Step 2: stop replica daemon. TERM first for graceful shutdown,
# then KILL fallback after a brief grace window. Wait for the
# replica's status port to actually release before continuing —
# prior runs hit "address already in use" on restart because TERM
# alone left a lingering process holding the bind.
$SSH_M02 "sudo killall -TERM g5-blockvolume 2>/dev/null; sleep 1; sudo killall -KILL g5-blockvolume 2>/dev/null; for i in 1 2 3 4 5 6 7 8 9 10; do ss -ltn 2>/dev/null | grep -q ':${M02_REPLICA_STATUS_PORT}\b' || break; sleep 1; done" >/dev/null 2>&1 || true
log " replica stopped"
# Step 3: primary write LBA[2]=0xef while replica is down.
iscsi_write_pattern 2 1 ef >/dev/null || die "iscsi write LBA[2]=0xef during replica-down failed"
log " primary wrote LBA[2]=0xef (replica down)"
# Step 4: restart replica.
start_replica >/dev/null 2>&1 || true
log " replica restarted"
# Step 5: wait_until_byte_equal at LBA[2]=0xef.
wait_until_byte_equal 2 ef "${CATCHUP_DEADLINE}" "verify_restart_catchup-LBA2" \
|| die "replica did not converge LBA[2]=0xef within ${CATCHUP_DEADLINE}s after restart (CHECK: primary WAL retention during replica-down — real recovery-path finding if writes were dropped)"
# Diagnostic snapshot (not pass/fail oracle).
local prim_h rep_r decision
prim_h=$(poll_status_field "$SSH_M01" "${M01_PRIMARY_STATUS_PORT}" H)
rep_r=$(poll_status_field "$SSH_M02" "${M02_REPLICA_STATUS_PORT}" R)
decision=$(poll_status_field "$SSH_M02" "${M02_REPLICA_STATUS_PORT}" RecoveryDecision)
log " diagnostic /status/recovery: primary.H=${prim_h} replica.R=${rep_r} replica.RecoveryDecision=${decision:-<empty>}"
log " ✓ restart catch-up byte-equal converged"
}
# §2 #5 — race ×10 stress on G5-4 integration test
verify_race_stress() {
if [ "${LOCAL_MODE}" = "1" ]; then
# WSL Ubuntu 22 ships Go 1.18; project needs 1.21+. Skip in LOCAL_MODE
# unless WSL has been upgraded.
local go_minor; go_minor=$(go version 2>/dev/null | grep -oP 'go1\.\K[0-9]+' || echo 0)
if [ "${go_minor}" -lt 21 ]; then
log "verify_race_stress: SKIP (LOCAL_MODE Go ${go_minor} < 1.21; use Tier 2 m01 for -race)"
return 0
fi
log "verify_race_stress: TestG54_BinaryWiring x10 -race in SRC_DIR=${SRC_DIR}"
( cd "${SRC_DIR}" && CGO_ENABLED=1 go test -race -count=10 -run TestG54_BinaryWiring ./cmd/blockvolume/ ) > "${ARTIFACT_DIR}/race-stress.log" 2>&1 \
|| die "race stress failed; see ${ARTIFACT_DIR}/race-stress.log"
log " ✓ race ×10"
return
fi
log "verify_race_stress: TestG54_BinaryWiring x10 -race on m01"
$SSH_M01 "command -v gcc >/dev/null" || die "gcc not installed on m01 (needed for CGO -race)"
$SSH_M01 "cd ${REMOTE_BUILD_DIR} && CGO_ENABLED=1 go test -race -count=10 -run TestG54_BinaryWiring ./cmd/blockvolume/ 2>&1" > "${ARTIFACT_DIR}/race-stress.log" \
|| die "race stress failed; see ${ARTIFACT_DIR}/race-stress.log"
log " ✓ race ×10"
}
# §2 #6 — full V3 suite green from node-a
verify_full_suite() {
if [ "${LOCAL_MODE}" = "1" ]; then
local go_minor; go_minor=$(go version 2>/dev/null | grep -oP 'go1\.\K[0-9]+' || echo 0)
if [ "${go_minor}" -lt 21 ]; then
log "verify_full_suite: SKIP (LOCAL_MODE Go ${go_minor} < 1.21; use Tier 2 m01 for full suite)"
return 0
fi
log "verify_full_suite: go test ./... in SRC_DIR=${SRC_DIR}"
( cd "${SRC_DIR}" && go test ./... -count=1 -timeout 600s ) > "${ARTIFACT_DIR}/full-suite.log" 2>&1 \
|| die "full suite failed; see ${ARTIFACT_DIR}/full-suite.log"
log " ✓ full suite green"
return
fi
log "verify_full_suite: go test ./... clean from m01"
$SSH_M01 "cd ${REMOTE_BUILD_DIR} && go test ./... -count=1 -timeout 600s 2>&1" > "${ARTIFACT_DIR}/full-suite.log" \
|| die "full suite has failures; see ${ARTIFACT_DIR}/full-suite.log"
log " ✓ full suite green"
}
# --- Main ---
main() {
log "=== G5-5 m01 hardware first-light ==="
log "primary: ${M01_HOST} ; replica: ${M02_HOST}"
log "substrate: ${DURABLE_IMPL} ; ${DURABLE_BLOCKS} blocks × ${DURABLE_BLOCKSIZE} B"
log "artifacts: ${ARTIFACT_DIR}"
sync_and_build
start_cluster
sleep 3
verify_cluster_ready
verify_byte_equal
verify_network_catchup
verify_restart_catchup
verify_race_stress
verify_full_suite
stop_cluster
log "=== G5-5 ALL VERIFY STEPS PASS ==="
}
main "$@"
-1
View File
@@ -32,7 +32,6 @@ This directory contains developer and QA helper scripts.
| `run-g15b-k8s-static.sh` | Historical static PV Kubernetes harness. |
| `run-g15d-k8s-dynamic.sh` | Historical dynamic PVC harness used by compatibility scenarios. |
| `iterate-m01-nvme.sh` | Lab iteration helper for NVMe work. |
| `iterate-m01-replicated-write.sh` | Lab iteration helper for replicated write tests. |
| `genproto.sh` | Protocol/code generation helper. |
## Design Rules
@@ -0,0 +1,51 @@
#!/usr/bin/env bash
# Tests node_ip_for_name and run_on_node from run-multi-volume-mounted-failover.sh with stub kubectl, ssh and
# hostname: local nodes run locally, remote nodes use the cluster's InternalIP and the configured ssh user/key,
# and a missing user or address fails instead of falling back to a fixed host.
# Usage: bash scripts/run-multi-volume-mounted-failover-nodes-test.sh [script]
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
script=${1:-$here/run-multi-volume-mounted-failover.sh}
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
mkdir -p "$work/bin"
cat >"$work/bin/kubectl" <<'EOF'
#!/usr/bin/env bash
# get node <name> -o jsonpath=...: worker-1 has an InternalIP, others none.
[ "$1 $2" = "get node" ] || exit 2
[ "$3" = worker-1 ] && printf '192.0.2.10'
exit 0
EOF
cat >"$work/bin/ssh" <<'EOF'
#!/usr/bin/env bash
printf '%s\n' "$*" >"$SSH_LOG"
cat >/dev/null
EOF
cat >"$work/bin/hostname" <<'EOF'
#!/usr/bin/env bash
echo ctl
EOF
chmod +x "$work/bin/"*
# Only the two helpers, not the script body.
awk '/^node_ip_for_name\(\) \{/,/^}/' "$script" >"$work/helpers.sh"
awk '/^run_on_node\(\) \{/,/^}/' "$script" >>"$work/helpers.sh"
fail() { echo "FAIL: $*" >&2; exit 1; }
run() { PATH="$work/bin:$PATH" SSH_LOG="$work/ssh.log" bash -c 'source "$1"; shift; "$@"' _ "$work/helpers.sh" "$@"; }
[ "$(echo 'echo local-ok' | run run_on_node '')" = local-ok ] || fail "empty node did not run locally"
[ "$(echo 'echo local-ok' | run run_on_node ctl)" = local-ok ] || fail "this host did not run locally"
rm -f "$work/ssh.log"
echo 'true' | SW_BLOCK_NODE_SSH_USER=tester SW_BLOCK_NODE_SSH_KEY=/keys/id run run_on_node worker-1 || fail "remote node with user and key failed"
[ "$(cat "$work/ssh.log")" = "-i /keys/id -o StrictHostKeyChecking=no tester@192.0.2.10 bash -s" ] || fail "ssh args with key: $(cat "$work/ssh.log")"
rm -f "$work/ssh.log"
echo 'true' | SW_BLOCK_NODE_SSH_USER=tester run run_on_node worker-1 || fail "remote node without key failed"
[ "$(cat "$work/ssh.log")" = "-o StrictHostKeyChecking=no tester@192.0.2.10 bash -s" ] || fail "ssh args without key: $(cat "$work/ssh.log")"
if echo 'true' | run run_on_node worker-1 2>/dev/null; then fail "remote node without SW_BLOCK_NODE_SSH_USER ran"; fi
if echo 'true' | SW_BLOCK_NODE_SSH_USER=tester run run_on_node worker-2 2>/dev/null; then fail "node without InternalIP ran"; fi
echo "run-multi-volume-mounted-failover-nodes-test: ok"
@@ -36,26 +36,32 @@ safe_capture() {
"$@" >"$out" 2>&1 || true
}
# A node's InternalIP, read from the cluster.
node_ip_for_name() {
case "$1" in
m01) echo "192.168.1.181" ;;
m02|"") echo "192.168.1.184" ;;
tp01) echo "192.168.1.188" ;;
*) return 1 ;;
esac
local ip
ip="$(kubectl get node "$1" -o jsonpath='{.status.addresses[?(@.type=="InternalIP")].address}' 2>/dev/null)" || return 1
[[ -n "$ip" ]] || return 1
echo "$ip"
}
# Runs stdin on a node: locally for this host, otherwise over ssh as
# SW_BLOCK_NODE_SSH_USER, with SW_BLOCK_NODE_SSH_KEY when it is set.
run_on_node() {
local node="${1:-}"
local local_node
local_node="$(hostname -s 2>/dev/null || hostname)"
if [[ -z "$node" || "$node" == "$local_node" || "$node" == "m02" ]]; then
if [[ -z "$node" || "$node" == "$local_node" ]]; then
bash -s
return
fi
local ip
ip="$(node_ip_for_name "$node")"
ssh -i /opt/work/testdev_key -o StrictHostKeyChecking=no "testdev@${ip}" bash -s
ip="$(node_ip_for_name "$node")" || { echo "no InternalIP for node $node" >&2; return 1; }
local user="${SW_BLOCK_NODE_SSH_USER:?set SW_BLOCK_NODE_SSH_USER to reach node $node over ssh}"
local key_args=()
if [[ -n "${SW_BLOCK_NODE_SSH_KEY:-}" ]]; then
key_args=(-i "$SW_BLOCK_NODE_SSH_KEY")
fi
ssh "${key_args[@]}" -o StrictHostKeyChecking=no "${user}@${ip}" bash -s
}
sw_block_cmd() {
@@ -1,279 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT="${1:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
M01_HOST="${SW_BLOCK_PHASE174_M01_HOST:-testdev@192.168.1.181}"
M02_HOST="${SW_BLOCK_PHASE174_M02_HOST:-testdev@192.168.1.184}"
TP01_HOST="${SW_BLOCK_PHASE174_TP01_HOST:-testdev@192.168.1.188}"
M01_DATA_IP="${SW_BLOCK_PHASE174_M01_DATA_IP:-192.168.1.181}"
TP01_DATA_IP="${SW_BLOCK_PHASE174_TP01_DATA_IP:-192.168.1.188}"
SSH_KEY="${SW_BLOCK_PHASE174_SSH_KEY:-/c/work/dev_server/testdev_key}"
PUBLISH_ROOT="${SW_BLOCK_PHASE174_PUBLISH_ROOT:-/mnt/smb/work/share/g15d-k8s}"
RUN_ID="${SW_BLOCK_PHASE174_RUN_ID:-$(date -u +%Y%m%dT%H%M%SZ)-phase174-d2-rf3-distinct}"
ARTIFACT_DIR="${SW_BLOCK_ARTIFACT_DIR:-/tmp/${RUN_ID}}"
LOCAL_BINARY="/tmp/${RUN_ID}-replication.test"
PREBUILT_BINARY="${SW_BLOCK_PHASE174_PREBUILT_BINARY:-}"
REMOTE_ROOT="/tmp/${RUN_ID}"
REMOTE_BINARY="${REMOTE_ROOT}/replication.test"
M02_STORE_ROOT="/data/nvme/block/${RUN_ID}-stores"
RESULTS="${ARTIFACT_DIR}/phase174-distinct-node-rf3-results.jsonl"
SUMMARY="${ARTIFACT_DIR}/phase174-distinct-node-rf3-summary.txt"
M01_ADDR="${M01_DATA_IP}:17411"
TP01_ADDR="${TP01_DATA_IP}:17412"
RUNS=5
WRITERS=(1 4 8)
GATE_COMPLETE=false
SSH=(ssh -T -i "${SSH_KEY}" -o ConnectTimeout=10 -o StrictHostKeyChecking=no -o BatchMode=yes)
SCP=(scp -q -i "${SSH_KEY}" -o ConnectTimeout=10 -o StrictHostKeyChecking=no -o BatchMode=yes)
remote() {
local host="$1"
shift
"${SSH[@]}" "${host}" "$@"
}
write_summary() {
echo "$*" | tee -a "${SUMMARY}" >/dev/null
}
cleanup() {
local exit_status=$?
if [[ "${GATE_COMPLETE}" != "true" ]]; then
mkdir -p "${ARTIFACT_DIR}/remote"
for spec in "${M01_HOST}:m01" "${TP01_HOST}:tp01"; do
local host="${spec%:*}" node="${spec##*:}"
remote "${host}" "for pidfile in '${REMOTE_ROOT}'/w*-'${node}'/pid; do
test -f \"\${pidfile}\" || continue
touch \"\$(dirname \"\${pidfile}\")/stop\"
done
for pidfile in '${REMOTE_ROOT}'/w*-'${node}'/pid; do
test -f \"\${pidfile}\" || continue
pid=\$(cat \"\${pidfile}\")
for _ in \$(seq 1 50); do kill -0 \"\${pid}\" 2>/dev/null || break; sleep 0.1; done
if kill -0 \"\${pid}\" 2>/dev/null && tr '\\0' ' ' <\"/proc/\${pid}/cmdline\" | grep -Fq '${REMOTE_BINARY}'; then
kill \"\${pid}\"
fi
done" >/dev/null 2>&1 || true
for writers in "${WRITERS[@]}"; do
local dir="${REMOTE_ROOT}/w${writers}-${node}"
"${SCP[@]}" "${host}:${dir}/replica.log" "${ARTIFACT_DIR}/remote/w${writers}-${node}-failure.log" >/dev/null 2>&1 || true
"${SCP[@]}" "${host}:${dir}/result.json" "${ARTIFACT_DIR}/remote/w${writers}-${node}-failure-result.json" >/dev/null 2>&1 || true
done
done
write_summary "phase174_distinct_node_rf3_status=failed"
write_summary "failure_artifact=${PUBLISH_ROOT}/${RUN_ID}.tar.gz"
tar -C "$(dirname "${ARTIFACT_DIR}")" -czf "${ARTIFACT_DIR}.tar.gz" "$(basename "${ARTIFACT_DIR}")" >/dev/null 2>&1 || true
sha256sum "${ARTIFACT_DIR}.tar.gz" >"${ARTIFACT_DIR}.tar.gz.sha256" 2>/dev/null || true
"${SCP[@]}" "${ARTIFACT_DIR}.tar.gz" "${M02_HOST}:${PUBLISH_ROOT}/${RUN_ID}.tar.gz" >/dev/null 2>&1 || true
fi
rm -f "${LOCAL_BINARY}"
for host in "${M01_HOST}" "${TP01_HOST}"; do
remote "${host}" "test '${REMOTE_ROOT}' = '/tmp/${RUN_ID}'; rm -rf -- '${REMOTE_ROOT}'" >/dev/null 2>&1 || true
done
remote "${M02_HOST}" "test '${REMOTE_ROOT}' = '/tmp/${RUN_ID}'; test '${M02_STORE_ROOT}' = '/data/nvme/block/${RUN_ID}-stores'; rm -rf -- '${REMOTE_ROOT}' '${M02_STORE_ROOT}'" >/dev/null 2>&1 || true
return "${exit_status}"
}
trap cleanup EXIT
wait_remote_file() {
local host="$1" path="$2" label="$3"
for _ in $(seq 1 150); do
if remote "${host}" "test -s '${path}'"; then
return 0
fi
sleep 0.2
done
echo "timed out waiting for ${label}: ${host}:${path}" >&2
return 1
}
start_replica() {
local host="$1" address="$2" writers="$3" node="$4"
local dir="${REMOTE_ROOT}/w${writers}-${node}"
remote "${host}" "set -e; mkdir -p '${dir}'; setsid nohup env \
SW_BLOCK_PHASE174_REPLICA_STORE='${dir}/replica.store' \
SW_BLOCK_PHASE174_REPLICA_LISTEN='${address}' \
SW_BLOCK_PHASE174_REPLICA_READY_FILE='${dir}/ready' \
SW_BLOCK_PHASE174_REPLICA_STOP_FILE='${dir}/stop' \
SW_BLOCK_PHASE174_REPLICA_RESULT_FILE='${dir}/result.json' \
SW_BLOCK_PHASE174_REPLICA_FINAL_SET=1 \
SW_BLOCK_PHASE174_REPLICA_FINAL_RUN=${RUNS} \
'${REMOTE_BINARY}' -test.run '^TestPhase174RemoteReplicaProcess$' -test.v -test.timeout=20m \
>'${dir}/replica.log' 2>&1 </dev/null & echo \$! >'${dir}/pid'"
wait_remote_file "${host}" "${dir}/ready" "${node} replica readiness"
}
stop_replica() {
local host="$1" writers="$2" node="$3"
local dir="${REMOTE_ROOT}/w${writers}-${node}"
remote "${host}" "touch '${dir}/stop'"
wait_remote_file "${host}" "${dir}/result.json" "${node} replica result"
"${SCP[@]}" "${host}:${dir}/result.json" "${ARTIFACT_DIR}/remote/w${writers}-${node}-result.json"
"${SCP[@]}" "${host}:${dir}/replica.log" "${ARTIFACT_DIR}/remote/w${writers}-${node}.log"
}
mkdir -p "${ARTIFACT_DIR}/environment" "${ARTIFACT_DIR}/logs" "${ARTIFACT_DIR}/remote"
: >"${SUMMARY}"
: >"${RESULTS}"
required_commands=(ssh scp python3 tar)
if [[ -z "${PREBUILT_BINARY}" ]]; then
required_commands+=(go)
fi
for command in "${required_commands[@]}"; do
command -v "${command}" >/dev/null 2>&1 || {
echo "missing required command: ${command}" >&2
exit 2
}
done
write_summary "phase174_distinct_node_rf3_status=running"
write_summary "contract=phase174-distinct-node-rf3-v1"
write_summary "source_commit=$(git -C "${ROOT}" rev-parse HEAD)"
write_summary "foreground_ack_profile=sync_quorum_rf3"
write_summary "post_measurement_drain=probe_catchup_then_sync_all"
write_summary "transport=tcp"
write_summary "network_class=management_lan"
write_summary "primary_node=m02"
write_summary "replica_nodes=m01,tp01"
write_summary "primary_management_ip=192.168.1.184"
write_summary "replica_addresses=${M01_ADDR},${TP01_ADDR}"
write_summary "tp01_roce_capable=false"
write_summary "cross_ack_profile_throughput_ratio_allowed=false"
for spec in "m01:${M01_HOST}" "m02:${M02_HOST}" "tp01:${TP01_HOST}"; do
name="${spec%%:*}"
host="${spec#*:}"
remote "${host}" 'hostname; uname -a; uptime; lsblk -o NAME,TYPE,SIZE,ROTA,MODEL,FSTYPE,MOUNTPOINTS; ip -brief address' \
>"${ARTIFACT_DIR}/environment/${name}.txt"
done
remote "${M02_HOST}" "test \"\$(findmnt -n -T /data/nvme/block -o SOURCE)\" = /dev/nvme0n1p1"
remote "${M01_HOST}" "findmnt -n -T /tmp -o SOURCE,FSTYPE" >"${ARTIFACT_DIR}/environment/m01-store.txt"
remote "${TP01_HOST}" "findmnt -n -T /tmp -o SOURCE,FSTYPE" >"${ARTIFACT_DIR}/environment/tp01-store.txt"
remote "${M01_HOST}" "! ss -ltnH | grep -q ':17411 '"
remote "${TP01_HOST}" "! ss -ltnH | grep -q ':17412 '"
cd "${ROOT}"
if [[ -n "${PREBUILT_BINARY}" ]]; then
cp "${PREBUILT_BINARY}" "${LOCAL_BINARY}"
else
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go test -tags swblock_testtools -c \
-o "${LOCAL_BINARY}" ./core/replication
fi
for host in "${M01_HOST}" "${M02_HOST}" "${TP01_HOST}"; do
remote "${host}" "test '${REMOTE_ROOT}' = '/tmp/${RUN_ID}'; rm -rf -- '${REMOTE_ROOT}'; mkdir -p '${REMOTE_ROOT}'"
"${SCP[@]}" "${LOCAL_BINARY}" "${host}:${REMOTE_BINARY}"
remote "${host}" "chmod 0755 '${REMOTE_BINARY}'"
done
remote "${M02_HOST}" "test '${M02_STORE_ROOT}' = '/data/nvme/block/${RUN_ID}-stores'; rm -rf -- '${M02_STORE_ROOT}'; mkdir -p '${M02_STORE_ROOT}'"
for writers in "${WRITERS[@]}"; do
start_replica "${M01_HOST}" "${M01_ADDR}" "${writers}" m01
start_replica "${TP01_HOST}" "${TP01_ADDR}" "${writers}" tp01
for run in $(seq 0 "${RUNS}"); do
log="${ARTIFACT_DIR}/logs/w${writers}-run${run}.log"
remote "${M02_HOST}" "env \
SW_BLOCK_PHASE174_STORE_DIR='${M02_STORE_ROOT}/w${writers}' \
SW_BLOCK_PHASE174_LAYER=rf3_tcp \
SW_BLOCK_PHASE174_WRITERS=${writers} \
SW_BLOCK_PHASE174_SET=1 \
SW_BLOCK_PHASE174_RUN=${run} \
SW_BLOCK_PHASE174_REMOTE_REPLICAS='${M01_ADDR},${TP01_ADDR}' \
GOMAXPROCS=4 taskset -c 0,2,4,6 \
'${REMOTE_BINARY}' -test.run '^TestPhase174FixedWorkPipeline$' -test.v -test.count=1 -test.timeout=10m" \
>"${log}" 2>&1
if [[ "${run}" != "0" ]]; then
sed -n 's/^phase174_fixed_work_result=//p' "${log}" >>"${RESULTS}"
fi
done
stop_replica "${M01_HOST}" "${writers}" m01
stop_replica "${TP01_HOST}" "${writers}" tp01
done
python3 - "${RESULTS}" "${ARTIFACT_DIR}/remote" "${SUMMARY}" "${RUNS}" <<'PY'
import glob
import json
import statistics
import sys
results_path, remote_dir, summary_path, runs_text = sys.argv[1:]
runs = int(runs_text)
rows = [json.loads(line) for line in open(results_path, encoding="utf-8") if line.strip()]
if len(rows) != 3 * runs:
raise SystemExit(f"primary rows={len(rows)} want {3 * runs}")
queue_saturation_rows = 0
replica_probe_count = 0
replica_catchup_count = 0
replica_rebuild_count = 0
max_replica_lag_lsn = 0
for row in rows:
if row["contract"] != "phase174-fixed-work-v1" or row["ack_profile"] != "sync_quorum_rf3":
raise SystemExit(f"bad primary contract: {row}")
if row["replica_count"] != 2 or not row["remote_replica_evidence_required"]:
raise SystemExit(f"bad external replica contract: {row}")
if not row["post_measurement_sync_all"] or row["post_measurement_sync_all_ns"] <= 0:
raise SystemExit(f"missing post-measurement drain: {row}")
if not row["post_measurement_recovery"] or row.get("replica_probe_count") != 2:
raise SystemExit(f"missing post-measurement recovery evidence: {row}")
if row["api_operations"] != 16384 or row["logical_bytes"] != 67108864:
raise SystemExit(f"bad fixed work: {row}")
if row["primary_wal_write_ops"] != 16384 or row["replication_write_ops"] != 16384:
raise SystemExit(f"write counter mismatch: {row}")
if not row["close_recover_complete"] or row["primary_stable_lsn"] != row["primary_head_lsn"]:
raise SystemExit(f"primary recovery mismatch: {row}")
if row.get("peer_queue_saturated", 0) > 0:
queue_saturation_rows += 1
replica_probe_count += row["replica_probe_count"]
replica_catchup_count += row.get("replica_catchup_count", 0)
replica_rebuild_count += row.get("replica_rebuild_count", 0)
max_replica_lag_lsn = max(max_replica_lag_lsn, row.get("max_replica_lag_lsn", 0))
remote_paths = sorted(glob.glob(f"{remote_dir}/w*-*-result.json"))
if len(remote_paths) != 6:
raise SystemExit(f"remote results={len(remote_paths)} want 6")
for path in remote_paths:
row = json.load(open(path, encoding="utf-8"))
if row["status"] != "ok" or row["stable_lsn"] != row["head_lsn"]:
raise SystemExit(f"bad remote recovery {path}: {row}")
if row["head_lsn"] != row["expected_head_lsn"] or row["correctness_samples"] < 5:
raise SystemExit(f"bad remote frontier/data {path}: {row}")
with open(summary_path, "a", encoding="utf-8") as out:
for writers in (1, 4, 8):
rates = [row["mib_per_second"] for row in rows if int(row["writers"]) == writers]
out.write(f"writers_{writers}_median_mibps={statistics.median(rates):.3f}\n")
out.write(f"writers_{writers}_max_min_ratio={max(rates) / min(rates):.3f}\n")
out.write(f"primary_result_count={len(rows)}\n")
out.write(f"remote_recovered_replica_count={len(remote_paths)}\n")
out.write(f"peer_queue_saturation_row_count={queue_saturation_rows}\n")
out.write(f"replica_probe_count={replica_probe_count}\n")
out.write(f"replica_catchup_count={replica_catchup_count}\n")
out.write(f"replica_rebuild_count={replica_rebuild_count}\n")
out.write(f"max_replica_lag_lsn={max_replica_lag_lsn}\n")
out.write("remote_replica_frontiers_and_bytes_equal=true\n")
out.write("foreground_sync_quorum_preserved=true\n")
out.write("post_measurement_recovery_verified=true\n")
out.write("post_measurement_sync_all_verified=true\n")
out.write("rf3_distinct_node_healthy=true\n")
out.write("architecture_candidate_selected=false\n")
out.write("product_mutation_present=false\n")
out.write("phase174_distinct_node_rf3_status=ok\n")
PY
GATE_COMPLETE=true
cleanup
trap - EXIT
for host in "${M01_HOST}" "${M02_HOST}" "${TP01_HOST}"; do
remote "${host}" "test ! -e '${REMOTE_ROOT}'"
done
remote "${M02_HOST}" "test ! -e '${M02_STORE_ROOT}'"
write_summary "remote_process_and_store_residue_count=0"
write_summary "published_artifact=${PUBLISH_ROOT}/${RUN_ID}.tar.gz"
tar -C "$(dirname "${ARTIFACT_DIR}")" -czf "${ARTIFACT_DIR}.tar.gz" "$(basename "${ARTIFACT_DIR}")"
"${SCP[@]}" "${ARTIFACT_DIR}.tar.gz" "${M02_HOST}:${PUBLISH_ROOT}/${RUN_ID}.tar.gz"
sha256sum "${ARTIFACT_DIR}.tar.gz" | tee "${ARTIFACT_DIR}.tar.gz.sha256"
cat "${SUMMARY}"
@@ -1,247 +0,0 @@
# Phase 27 D8: multi-volume RF=3 mounted failover with app pods spread across nodes.
#
# Pass = three RF=3 PVCs are mounted by long-running writer pods distributed
# across node-a/node-b/node-c, each target volume's current primary is stopped in turn,
# the same writer pod UID verifies old data and writes new data through
# dm-multipath, and cleanup is clean.
name: helm-multi-volume-rf3-app-spread-failover-chain
timeout: 52m
env:
product_root: "/tmp/seaweed_block"
ssh_key: "C:\\work\\dev_server\\testdev_key"
helm_release: "sw-block"
helm_namespace: "kube-system"
sw_block_image: "sw-block:phase27-d8"
sw_block_csi_image: "sw-block-csi:phase27-d8"
volume_count: "3"
replication_factor: "3"
app_nodes: "m01,m02,tp01"
topology:
nodes:
m02:
host: 192.168.1.184
user: testdev
key: "{{ ssh_key }}"
phases:
- name: pre_clean
actions:
- action: pre_run_cleanup
node: m02
kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target"
nvme_disconnect: "true"
iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs"
- action: exec
node: m02
timeout: 6m
cmd: |
set -e
helm uninstall {{ helm_release }} --namespace {{ helm_namespace }} --wait --timeout 240s >/dev/null 2>&1 || true
kubectl -n default delete pod -l sw-block-test=multi-volume-mounted-failover --ignore-not-found=true --wait=true --timeout=180s
for i in 1 2 3; do
kubectl -n default delete pod sw-block-multi-mounted-writer-$i --ignore-not-found=true --wait=true --timeout=180s
kubectl -n default delete pvc sw-block-multi-mounted-pvc-$i --ignore-not-found=true --wait=true --timeout=180s
done
kubectl delete storageclass sw-block-multi-mounted sw-block-dynamic --ignore-not-found=true --wait=true --timeout=180s
kubectl delete clusterrole/sw-block-csi clusterrolebinding/sw-block-csi --ignore-not-found=true
for ip in 192.168.1.181 192.168.1.184 192.168.1.188; do
if [ "$ip" = "192.168.1.184" ]; then runner="bash -lc"; else runner="ssh -i /opt/work/testdev_key -o StrictHostKeyChecking=no testdev@$ip"; fi
$runner 'sudo -n iscsiadm -m node 2>/dev/null | awk '"'"'/io.seaweedfs/ {print $1, $2}'"'"' | while read portal target; do sudo -n iscsiadm -m node -T "$target" -p "$portal" --logout >/dev/null 2>&1 || true; sudo -n iscsiadm -m node -T "$target" -p "$portal" -o delete >/dev/null 2>&1 || true; done; sudo -n multipath -F >/dev/null 2>&1 || true'
done
rm -rf /mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover
mkdir -p /mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/bin /mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/values /mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/install /mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/recovery /mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/cleanup
env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml"
- action: exec
node: m02
timeout: 5m
cmd: "cd {{ product_root }} && bash scripts/verify-helm-cleanup.sh"
env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml"
env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/preclean/verify"
env.SW_BLOCK_HELM_RELEASE: "{{ helm_release }}"
env.SW_BLOCK_HELM_NAMESPACE: "{{ helm_namespace }}"
env.SW_BLOCK_CLEANUP_MULTIPATH_FLUSH: "1"
- action: assert_no_active_iscsi_sessions
node: m02
- name: preflight
actions:
- action: exec
node: m02
cmd: "kubectl get nodes -o wide | tee /mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/preflight-nodes.txt && kubectl get nodes --no-headers | awk '$2==\"Ready\"{c++} END{if(c<3){exit 1}}'"
env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml"
- action: grep_log
node: m02
path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/preflight-nodes.txt"
pattern: "Ready"
save_as: ready_node_count
- action: assert_greater
actual: "{{ ready_node_count }}"
threshold: "2"
- name: host_multipath_prereq
actions:
- action: exec
node: m02
cmd: |
set -e
B=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover
: > "$B/multipath-prereq.txt"
for spec in m01:192.168.1.181 m02:192.168.1.184 tp01:192.168.1.188; do
name="${spec%%:*}"
ip="${spec#*:}"
if [ "$ip" = "192.168.1.184" ]; then runner="bash -lc"; else runner="ssh -i /opt/work/testdev_key -o StrictHostKeyChecking=no testdev@$ip"; fi
$runner 'set -e; command -v iscsiadm >/dev/null; command -v multipath >/dev/null; command -v sg_rtpg >/dev/null; sudo modprobe iscsi_tcp; sudo modprobe dm_multipath; sudo modprobe scsi_dh_alua; test -d /sys/module/iscsi_tcp; test -d /sys/module/dm_multipath; test -d /sys/module/scsi_dh_alua; sudo multipath -t >/tmp/sw-block-multipath-prereq.config.txt 2>&1'
echo "node=${name} multipath_prereq=pass" >> "$B/multipath-prereq.txt"
done
echo multipath_prereq=pass >> "$B/multipath-prereq.txt"
- action: grep_log
node: m02
path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/multipath-prereq.txt"
pattern: "multipath_prereq=pass"
save_as: multipath_prereq_count
- action: assert_greater
actual: "{{ multipath_prereq_count }}"
threshold: "0"
- name: build_and_generate_values
actions:
- action: exec
node: m02
timeout: 8m
cmd: "cd {{ product_root }} && SW_BLOCK_IMAGE={{ sw_block_image }} SW_BLOCK_CSI_IMAGE={{ sw_block_csi_image }} SW_BLOCK_IMPORT_K3S=1 SW_BLOCK_IMPORT_K3S_NODES='192.168.1.181,192.168.1.188' SW_BLOCK_IMPORT_K3S_SSH_USER=testdev SW_BLOCK_IMPORT_K3S_SSH_KEY=/opt/work/testdev_key SW_BLOCK_ARTIFACT_DIR=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/build bash scripts/build-alpha-images.sh {{ product_root }}"
env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml"
- action: exec
node: m02
timeout: 6m
cmd: "cd {{ product_root }} && go build -o /mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/bin/sw-block ./cmd/sw-block && /mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/bin/sw-block ops generate-helm-values --kubeconfig /etc/rancher/k3s/k3s.yaml --out /mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/values/values.day1.yaml --image {{ sw_block_image }} --csi-image {{ sw_block_csi_image }} --replication-factor {{ replication_factor }} --ack-profile sync-quorum --stage2-multipath > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/values/generate.stdout.txt && python3 - <<'PY'\nfrom pathlib import Path\np=Path('/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/values/values.day1.yaml')\ns=p.read_text()\ns=s.replace('launcherReplicationAckFlag: false','launcherReplicationAckFlag: true')\np.write_text(s)\nPY"
env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml"
- action: grep_log
node: m02
path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/values/generate.stdout.txt"
pattern: "helm_values_status=ok"
save_as: generator_ok_count
- action: assert_greater
actual: "{{ generator_ok_count }}"
threshold: "0"
- name: helm_install_stack
actions:
- action: exec
node: m02
timeout: 10m
cmd: |
set -e
B=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover
cd {{ product_root }}
helm lint charts/seaweed-block -f "$B/values/values.day1.yaml" > "$B/install/helm-lint.txt"
helm install {{ helm_release }} charts/seaweed-block --namespace {{ helm_namespace }} --create-namespace -f "$B/values/values.day1.yaml" --wait --timeout 10m > "$B/install/helm-install.txt"
kubectl -n {{ helm_namespace }} rollout status deploy/sw-blockmaster --timeout=180s > "$B/install/rollout-blockmaster.txt"
kubectl -n {{ helm_namespace }} rollout status deploy/sw-block-csi-controller --timeout=180s > "$B/install/rollout-csi-controller.txt"
kubectl -n {{ helm_namespace }} rollout status ds/sw-block-csi-node --timeout=180s > "$B/install/rollout-csi-node.txt"
helm get values {{ helm_release }} --namespace {{ helm_namespace }} --all > "$B/install/helm-values.applied.yaml"
helm get manifest {{ helm_release }} --namespace {{ helm_namespace }} > "$B/install/helm-manifest.yaml"
kubectl -n {{ helm_namespace }} get pods,deploy,ds,svc -o wide > "$B/install/kube-system.after-install.txt"
env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml"
- action: grep_log
node: m02
path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/install/helm-install.txt"
pattern: "STATUS: deployed"
save_as: helm_deployed_count
- action: assert_greater
actual: "{{ helm_deployed_count }}"
threshold: "0"
- action: grep_log
node: m02
path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/install/helm-manifest.yaml"
pattern: "sw-block:phase27-d8"
save_as: helm_manifest_phase_image_count
- action: assert_greater
actual: "{{ helm_manifest_phase_image_count }}"
threshold: "0"
- name: app_spread_mounted_failover
actions:
- action: exec
node: m02
timeout: 34m
cmd: "cd {{ product_root }} && bash scripts/run-multi-volume-mounted-failover.sh {{ product_root }}"
env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml"
env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/recovery"
env.SW_BLOCK_MULTI_VOLUME_COUNT: "{{ volume_count }}"
env.SW_BLOCK_MULTI_VOLUME_RF: "{{ replication_factor }}"
env.SW_BLOCK_MULTI_VOLUME_APP_NODE: "{{ app_nodes }}"
env.SW_BLOCK_CLI: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/bin/sw-block"
- action: grep_log
node: m02
path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/recovery/multi-volume-mounted-failover-summary.txt"
pattern: "^multi_volume_mounted_failover_status=ok$"
save_as: mounted_failover_ok_count
- action: assert_greater
actual: "{{ mounted_failover_ok_count }}"
threshold: "0"
- name: app_spread_asserts
actions:
- action: grep_log
node: m02
path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/recovery/multi-volume-mounted-failover-summary.txt"
pattern: "^app_node_distribution_count=3$"
save_as: app_spread_count
- action: assert_greater
actual: "{{ app_spread_count }}"
threshold: "0"
- action: grep_log
node: m02
path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/recovery/multi-volume-mounted-failover-summary.txt"
pattern: "^recovered_volume_count=3$"
save_as: recovered_count_ok
- action: assert_greater
actual: "{{ recovered_count_ok }}"
threshold: "0"
- action: exec
node: m02
timeout: 2m
cmd: "B=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/recovery/failover; grep -q '^writer_node=m01$' \"$B/volume-1/summary.txt\"; grep -q '^writer_node=m02$' \"$B/volume-2/summary.txt\"; grep -q '^writer_node=tp01$' \"$B/volume-3/summary.txt\"; for i in 1 2 3; do S=$B/volume-$i/summary.txt; grep -q '^failover_status=promoted$' \"$S\"; grep -q '^target_recovered=true$' \"$S\"; grep -q '^pod_recreate_used=false$' \"$S\"; grep -q '^rtpg_transition_verified=true$' \"$S\"; grep -q '^old_primary_stale_io_success_count=0$' \"$S\"; done"
env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml"
- name: helm_uninstall_cleanup
always: true
actions:
- action: exec
node: m02
timeout: 3m
cmd: |
helm status {{ helm_release }} --namespace {{ helm_namespace }} >/dev/null 2>&1 && helm uninstall {{ helm_release }} --namespace {{ helm_namespace }} --wait --timeout 180s > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/cleanup/helm-uninstall.txt || true
kubectl -n default delete pod -l sw-block-test=multi-volume-mounted-failover --ignore-not-found=true --force --grace-period=0 --wait=false
for i in 1 2 3; do kubectl -n default delete pvc sw-block-multi-mounted-pvc-$i --ignore-not-found=true --wait=false; done
kubectl delete storageclass sw-block-multi-mounted sw-block-dynamic --ignore-not-found=true --wait=false
kubectl -n default delete deploy -l app=sw-blockvolume --ignore-not-found=true --wait=false
for ip in 192.168.1.181 192.168.1.184 192.168.1.188; do
if [ "$ip" = "192.168.1.184" ]; then runner="bash -lc"; else runner="ssh -i /opt/work/testdev_key -o StrictHostKeyChecking=no testdev@$ip"; fi
$runner 'sudo -n iscsiadm -m node 2>/dev/null | awk '"'"'/io.seaweedfs/ {print $1, $2}'"'"' | while read portal target; do sudo -n iscsiadm -m node -T "$target" -p "$portal" --logout >/dev/null 2>&1 || true; sudo -n iscsiadm -m node -T "$target" -p "$portal" -o delete >/dev/null 2>&1 || true; done; sudo -n multipath -F >/dev/null 2>&1 || true'
done
env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml"
env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/cleanup/verify"
env.SW_BLOCK_HELM_RELEASE: "{{ helm_release }}"
env.SW_BLOCK_NAMESPACE: "{{ helm_namespace }}"
- action: exec
node: m02
timeout: 3m
cmd: "cd {{ product_root }} && SW_BLOCK_ARTIFACT_DIR=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/cleanup/verify SW_BLOCK_HELM_RELEASE={{ helm_release }} SW_BLOCK_HELM_NAMESPACE={{ helm_namespace }} SW_BLOCK_CLEANUP_MULTIPATH_FLUSH=1 bash scripts/verify-helm-cleanup.sh {{ product_root }}"
env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml"
- action: assert_no_active_iscsi_sessions
node: m02
- action: assert_no_processes
node: m02
pattern: "(blockmaster|blockvolume|blockcsi|iscsi-target)"
- action: grep_log
node: m02
path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-helm-multi-volume-rf3-app-spread-failover/cleanup/verify/cleanup-summary.txt"
pattern: "^cleanup_status=ok$"
save_as: helm_cleanup_ok_count
- action: assert_greater
actual: "{{ helm_cleanup_ok_count }}"
threshold: "0"