Merge #640's branch at its newest head into ci/process-level-tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-26 01:42:04 -08:00
commit 2d60b4f4ff
6 files changed
+270 -53

No files matched your search

@@ -0,0 +1,54 @@
package main_test
import (
"errors"
"fmt"
"testing"
)
// fillProgress is what a test knows about a running fill: the absent chunk
// count when its reader started, the count now, and the reader's state.
type fillProgress struct {
baseline, absent int
reads int64
readerErr error
finished bool
}
// fillWitness is nil only while a fill is observably running: the reader
// has completed a read without error and has not finished, the absent
// count fell below its value when the reader started, and work remains.
// Remaining work alone does not show a fill is running.
func fillWitness(p fillProgress) error {
switch {
case p.readerErr != nil:
return fmt.Errorf("the reader failed: %w", p.readerErr)
case p.reads == 0:
return errors.New("the reader has completed no read")
case p.finished:
return errors.New("the reader finished: no fill left to interrupt")
case p.absent >= p.baseline:
return fmt.Errorf("no chunk was made local since the reader started (%d absent, %d at its start)", p.absent, p.baseline)
case p.absent == 0:
return errors.New("every chunk is local: no fill left to interrupt")
}
return nil
}
func TestFillWitnessNeedsAnObservedRunningFill(t *testing.T) {
running := fillProgress{baseline: 16, absent: 12, reads: 3}
if err := fillWitness(running); err != nil {
t.Fatalf("a running fill: %v", err)
}
for name, p := range map[string]fillProgress{
"reader never started": {baseline: 16, absent: 16},
"reader failed": {baseline: 16, absent: 12, reads: 3, readerErr: errors.New("read: i/o timeout")},
"reader finished": {baseline: 16, absent: 12, reads: 8, finished: true},
"no progress": {baseline: 16, absent: 16, reads: 3},
"nothing left": {baseline: 16, absent: 0, reads: 16},
} {
if err := fillWitness(p); err == nil {
t.Errorf("%s: %+v accepted as a running fill", name, p)
}
}
}
@@ -197,6 +197,9 @@ type headSzVol struct {
// its spec data and ctrl addresses are host:<port> (ports picked here, not
// probed there), and the test running on that host uses the same ones.
host string
// restoreTarget lists the volume with its placement only, no size_bytes:
// it has no volume record until a restore creates it.
restoreTarget bool
}
// headSzStartCluster starts one weed cluster (the filer's default store, no
@@ -229,7 +232,11 @@ func headSzStartCluster(t *testing.T, prefix string, vols []headSzVol) (*handoff
if v.server != "" {
nodes += fmt.Sprintf(" - server_id: %s\n data_addr: %s\n ctrl_addr: %s\n", server, b.data, b.ctrl)
}
fmt.Fprintf(&spec, " - id: %s\n size_bytes: %d\n replication_factor: 1\n placements:\n - server_id: %s\n replica_id: %s\n", v.id, v.bytes, server, replica)
size := fmt.Sprintf(" size_bytes: %d\n", v.bytes)
if v.restoreTarget {
size = ""
}
fmt.Fprintf(&spec, " - id: %s\n%s replication_factor: 1\n placements:\n - server_id: %s\n replica_id: %s\n", v.id, size, server, replica)
}
specPath := filepath.Join(h.dir, "cluster-spec.yaml")
if err := os.WriteFile(specPath, []byte("nodes:\n"+nodes+"volumes:\n"+spec.String()), 0o644); err != nil {
@@ -75,7 +75,7 @@ func TestKnownZeroAcceptance(t *testing.T) {
var vols []headSzVol
for _, fs := range fss {
vols = append(vols, headSzVol{id: "kz" + fs, bytes: bytes},
headSzVol{id: "kz" + fs + "r", bytes: bytes, server: "t-" + fs + "r", host: targetHost})
headSzVol{id: "kz" + fs + "r", bytes: bytes, server: "t-" + fs + "r", host: targetHost, restoreTarget: true})
}
// step 5: up to kzCrashTries fresh volumes (a try whose stop lands after the
// attach commit has committed that store, so a retry needs a new one)
@@ -285,6 +285,12 @@ func kzTarget(t *testing.T, env *handoffEnv, rep *kzReport, src kzVolume, kind s
t.Helper()
r := kzTargetRecord{Volume: tb.volume, Kind: kind, Source: src.Volume, Snapshot: src.S1Name,
NQN: fmt.Sprintf("nqn.2026-11.io.seaweedfs:kz-%s-%s", run, tb.volume)}
// The target is placement only: before its restore the master has no
// record of it, so the restore creates it.
if out, errOut, code := env.h.run(t, "ops", "chunk", "show", "--master", env.h.masterAddr, "--volume", tb.volume,
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath); code == 0 || !strings.Contains(out+errOut, "resolve --volume") || !strings.Contains(out+errOut, "not found") {
t.Fatalf("restore target %s has a volume record before its restore: exit %d %s %s", tb.volume, code, out, errOut)
}
env.h.command(t, "ops", "chunk", "restore", "--source", src.Volume, "--snapshot", src.S1Name, "--target", tb.volume,
"--master", env.h.masterAddr, "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, "--request-id", "kz-"+kind+"-"+tb.volume)
d, refusal := headSzStartVolume(t, env, tb, bytes, "--nvme-subsysnqn", r.NQN)
@@ -5,6 +5,7 @@ package main_test
import (
"fmt"
"math/rand"
"sync"
"testing"
"time"
)
@@ -95,33 +96,80 @@ func (env *handoffEnv) startTarget(t *testing.T, target, name string) *daemon {
return d
}
// readConcurrently reads one block of each of chunks of target, in order,
// on its own connection: v1 fills a restore target only on access, so this
// is the fill the test kills into. It stops at the first error (the kill)
// or when the returned stop is called, and stop waits for it.
func (env *handoffEnv) readConcurrently(t *testing.T, target string, chunks []uint64) (stop func()) {
// fillReader reads one block of each of its chunks, in order, on its own
// connection: v1 fills a restore target only on access, so this is the fill
// the test kills into. It stops at its first error (the kill, or a failure
// before it, which state reports) or at stop, which waits for it.
type fillReader struct {
mu sync.Mutex
reads int64
err error
finished bool
quit chan struct{}
done chan struct{}
close func()
}
func (env *handoffEnv) readConcurrently(t *testing.T, target string, chunks []uint64) *fillReader {
t.Helper()
c := dialNVMe(t, env.hosts["n-"+target].nvme, plannedHandoffNQN)
done := make(chan struct{})
quit := make(chan struct{})
r := &fillReader{quit: make(chan struct{}), done: make(chan struct{}), close: c.close}
go func() {
defer close(done)
defer close(r.done)
for _, ch := range chunks {
select {
case <-quit:
case <-r.quit:
return
default:
}
_ = c.io.SetDeadline(time.Now().Add(60 * time.Second))
if _, err := c.tryRead(ch*ladderChunkBlocks, 4096); err != nil {
_, err := c.tryRead(ch*ladderChunkBlocks, 4096)
r.mu.Lock()
if err != nil {
r.err = err
} else {
r.reads++
}
r.mu.Unlock()
if err != nil {
return
}
}
r.mu.Lock()
r.finished = true
r.mu.Unlock()
}()
return func() {
close(quit)
c.close()
<-done
return r
}
// progress is the reader's state against baseline absent chunks and absent now.
func (r *fillReader) progress(baseline, absent int) fillProgress {
r.mu.Lock()
defer r.mu.Unlock()
return fillProgress{baseline: baseline, absent: absent, reads: r.reads, readerErr: r.err, finished: r.finished}
}
func (r *fillReader) stop() {
close(r.quit)
r.close()
<-r.done
}
// awaitFill waits until fillWitness accepts the reader's progress on target
// (a fill observably running) and fails the test with the last reason when
// it does not within bound.
func (env *handoffEnv) awaitFill(t *testing.T, target string, r *fillReader, baseline int, bound time.Duration) fillProgress {
t.Helper()
var p fillProgress
var why error
for end := time.Now().Add(bound); ; time.Sleep(20 * time.Millisecond) {
p = r.progress(baseline, kzReadStats(t, env.hosts["n-"+target]).AbsentChunks)
if why = fillWitness(p); why == nil {
return p
}
if p.readerErr != nil || p.finished || time.Now().After(end) {
t.Fatalf("%s: no running fill to kill into within %v: %v (%+v)", target, bound, why, p)
}
}
}
@@ -156,10 +204,13 @@ func TestSnapshotLadderC3KilledHydrating(t *testing.T) {
// (1) killed mid-fill
partly := func(absent int) bool { return absent > 0 && absent < len(chunks) }
stop := env.readConcurrently(t, "v2", chunks)
reader := env.readConcurrently(t, "v2", chunks)
absent := env.awaitAbsent(t, "v2", "a partly filled volume", 120*time.Second, partly)
if p := reader.progress(len(chunks), absent); p.readerErr != nil {
t.Fatalf("the first fill's reader failed before the kill: %v", p.readerErr)
}
target.kill(t)
stop()
reader.stop()
t.Logf("killed with %d of %d chunks absent", absent, len(chunks))
target = env.startTarget(t, "v2", "blockvolume-v2-after-fill-kill")
if after := kzReadStats(t, env.hosts["n-v2"]).AbsentChunks; after >= len(chunks) {
@@ -178,10 +229,12 @@ func TestSnapshotLadderC3KilledHydrating(t *testing.T) {
for c := uint64(1); c < 32; c += 2 {
odd = append(odd, c)
}
stop = env.readConcurrently(t, "v2", odd)
env.awaitAbsent(t, "v2", "a fill still running after the write", 60*time.Second, func(a int) bool { return a > 0 })
baseline := kzReadStats(t, env.hosts["n-v2"]).AbsentChunks
reader = env.readConcurrently(t, "v2", odd)
p := env.awaitFill(t, "v2", reader, baseline, 60*time.Second)
target.kill(t)
stop()
reader.stop()
t.Logf("killed again with a fill running: %d absent (%d when its reader started), %d reads done", p.absent, p.baseline, p.reads)
target = env.startTarget(t, "v2", "blockvolume-v2-after-write-kill")
env.requireBlocksOf(t, "n-v2", w1) // every acknowledged write survived the kill
@@ -651,11 +651,12 @@ func TestSnapshotLadderC2IncrementalRestore(t *testing.T) {
}
// TestSnapshotLadderC3RestoreThenWriteThenSnapshotIt: a restored volume,
// once its status says independent, is written and snapshotted itself, then
// written again; that snapshot holds its first writes and not the later
// ones, and the source's snapshot, also written past, still restores
// unchanged. Every write to the restored volume comes after it is
// independent.
// once every chunk is local, is written and snapshotted itself, then
// written again. Its snapshot still names the source's chunks for the
// chunks it did not write (filling makes bytes local; it does not take the
// source's chunks over), so a restore from it is refused, naming another
// volume's chunks. The restored volume reads its own image, and the
// source's snapshot, also written past, still restores unchanged.
func TestSnapshotLadderC3RestoreThenWriteThenSnapshotIt(t *testing.T) {
env := startLadderEnv(t, "v2", "v3", "v4")
src := ladderImage("c3src", []uint64{0, 3}, 4)
@@ -672,9 +673,12 @@ func TestSnapshotLadderC3RestoreThenWriteThenSnapshotIt(t *testing.T) {
ownLater := ladderImage("c3ownlater", []uint64{0, 11, 25}, 2)
env.writeImage(t, "n-v2", ownLater)
env.restoreInto(t, "v2", "mine", "v3")
env.hydrate(t, "v3")
env.requireImage(t, "n-v3", mergeImages(src, own), ownLater, srcLater)
out, errOut, code := env.h.run(t, "ops", "chunk", "restore", "--master", env.h.masterAddr, "--source", "v2", "--snapshot", "mine", "--target", "v3",
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
if code == 0 || !strings.Contains(out, `"code":"not_admitted"`) || !strings.Contains(out, "names another volume's chunks") {
t.Fatalf("restore from the restored volume's snapshot: exit %d, want not_admitted naming another volume's chunks\n%s\n%s", code, out, errOut)
}
env.requireImage(t, "n-v2", mergeImages(src, own, ownLater), srcLater)
env.restoreInto(t, "v1", "base", "v4") // the source's snapshot is unchanged
env.hydrate(t, "v4")
env.requireImage(t, "n-v4", src, srcLater, own, ownLater)
@@ -2,15 +2,24 @@ package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
)
// The process-level integration tests (cmd/blockvolume, behind build tags)
@@ -18,45 +27,117 @@ import (
// CI, so an invocation the CLI no longer accepts (a removed subcommand, a
// renamed or newly required flag) would pass compile and fail only on a
// lab run. Every literal `ops ...` invocation in them is run through this
// CLI's own argument handling here. Variable values become placeholders and
// addresses point at nothing, so a call that gets past its arguments fails
// on the network or is still waiting at the deadline; only a refusal of the
// arguments themselves fails this test.
// CLI's own argument handling here, each in a child process killed at its
// deadline. Variable values become placeholders; in the child the master
// resolves every name and the filer dial and the restore RPC answer
// errGuardPast, which a command reaches only after all its argument checks.
// Other calls meet addresses nothing listens on. A refusal of the arguments
// fails this test, and so does a call that neither answers nor fails
// within the deadline: waiting is not proof that the arguments passed.
func TestIntegrationTestInvocationsParse(t *testing.T) {
invocations := literalOpsInvocations(t, filepath.Join("..", "blockvolume"))
if len(invocations) == 0 {
t.Fatal("no ops invocations found in the integration tests")
}
// Placeholders reach path flags too: whatever a call writes lands in a
// temporary directory, never in the source tree.
t.Chdir(t.TempDir())
for _, inv := range invocations {
inv := inv
if len(inv.args) < 2 {
t.Fatalf("%s: an ops invocation without a subcommand", inv.where)
}
t.Run(inv.where, func(t *testing.T) {
var stdout, stderr bytes.Buffer
done := make(chan int, 1)
go func() { done <- run(inv.args, &stdout, &stderr) }()
select {
case <-done:
case <-time.After(3 * time.Second):
return // past its arguments: waiting on the network
}
out := stdout.String() + stderr.String()
if strings.Contains(out, "rpc error") || strings.Contains(out, "dial tcp") {
return // past its arguments: the placeholder address refused the call
}
for _, refusal := range []string{`"code":"bad_request"`, "unknown subcommand", "unknown command", "flag provided but not defined"} {
if strings.Contains(out, refusal) {
t.Fatalf("sw-block %s\nrefused its arguments: %s", strings.Join(inv.args, " "), firstLine(out, refusal))
}
if verdict, out := guardInvocation(t, inv.args); verdict != guardPast {
t.Fatalf("sw-block %s\n%s: %s", strings.Join(inv.args, " "), verdict, out)
}
})
}
}
// The guard's own controls: argument lists whose missing flag is checked
// only after the volume names resolve must be refused, and a complete one
// must pass.
func TestIntegrationInvocationGuardReachesLateFlagChecks(t *testing.T) {
for _, c := range []struct {
args []string
want string
}{
{[]string{"ops", "chunk", "snapshots", "--master", "127.0.0.1:1", "--volume", "v1"}, guardRefused},
{[]string{"ops", "chunk", "snapshot-delete", "--master", "127.0.0.1:1", "--volume", "v1", "--name", "s1"}, guardRefused},
{[]string{"ops", "chunk", "restore", "--source", "v1", "--snapshot", "s1", "--target", "v2", "--chunk-filer", "127.0.0.1:1"}, guardRefused},
{[]string{"ops", "chunk", "snapshots", "--master", "127.0.0.1:1", "--volume", "v1", "--chunk-filer", "127.0.0.1:1"}, guardPast},
{[]string{"ops", "chunk", "restore", "--master", "127.0.0.1:1", "--source", "v1", "--snapshot", "s1", "--target", "v2", "--chunk-filer", "127.0.0.1:1"}, guardPast},
} {
if verdict, out := guardInvocation(t, c.args); verdict != c.want {
t.Errorf("sw-block %s: %s, want %s: %s", strings.Join(c.args, " "), verdict, c.want, out)
}
}
}
const (
guardPast = "past its arguments"
guardRefused = "refused its arguments"
guardTimeout = "still running at the deadline"
guardOther = "failed for another reason"
)
// errGuardPast is what the child's filer dial and restore RPC answer.
var errGuardPast = errors.New("invocation guard: past its arguments")
const guardArgsEnv = "SWB_INVOCATION_GUARD_ARGS"
// guardInvocation runs args in a child process of this test binary and
// classifies its output.
func guardInvocation(t *testing.T, args []string) (string, string) {
t.Helper()
enc, err := json.Marshal(args)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestIntegrationInvocationChild$", "-test.count=1")
cmd.Dir = t.TempDir() // whatever a call writes lands here, never in the source tree
cmd.Env = append(os.Environ(), guardArgsEnv+"="+string(enc))
cmd.WaitDelay = time.Second
raw, _ := cmd.CombinedOutput()
out := string(raw)
switch {
case ctx.Err() != nil:
return guardTimeout, out
case strings.Contains(out, errGuardPast.Error()):
return guardPast, firstLine(out, errGuardPast.Error())
}
for _, refusal := range []string{`"code":"bad_request"`, "unknown subcommand", "unknown command", "flag provided but not defined", "invalid value", "is required"} {
if strings.Contains(out, refusal) {
return guardRefused, firstLine(out, refusal)
}
}
if strings.Contains(out, "rpc error") || strings.Contains(out, "dial tcp") || strings.Contains(out, "connection refused") {
return guardPast, "the placeholder address refused the call"
}
return guardOther, out
}
// TestIntegrationInvocationChild is the child process: it runs only with
// guardArgsEnv set.
func TestIntegrationInvocationChild(t *testing.T) {
enc := os.Getenv(guardArgsEnv)
if enc == "" {
t.Skip("the invocation guard's child process")
}
var args []string
if err := json.Unmarshal([]byte(enc), &args); err != nil {
t.Fatal(err)
}
resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) { return layout.VolumeID{1}, nil }
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return nil, nil, errGuardPast }
restoreCreateRPC = func(context.Context, string, *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) {
return nil, errGuardPast
}
var stdout, stderr bytes.Buffer
code := run(args, &stdout, &stderr)
fmt.Printf("exit %d\n%s%s", code, stdout.String(), stderr.String())
}
type opsInvocation struct {
where string
args []string
@@ -167,14 +248,26 @@ func placeholder(prev []string, at int) string {
switch {
case strings.Contains(flag, "timeout") || strings.Contains(flag, "interval") || strings.Contains(flag, "wait"):
return "1s"
case strings.Contains(flag, "lsn") || strings.Contains(flag, "epoch") || strings.Contains(flag, "count") || strings.Contains(flag, "bytes") || strings.Contains(flag, "size"):
case strings.Contains(flag, "lsn") || strings.Contains(flag, "epoch") || strings.Contains(flag, "gen") || strings.Contains(flag, "count") || strings.Contains(flag, "bytes") || strings.Contains(flag, "size"):
return "1"
case strings.Contains(flag, "confirm"):
return volumeOf(prev) + "@1" // a forced move's confirmation names its volume and epoch
case strings.Contains(flag, "master") || strings.Contains(flag, "addr") || strings.Contains(flag, "filer") || strings.Contains(flag, "data") || strings.Contains(flag, "ctrl") || strings.Contains(flag, "endpoint"):
return "127.0.0.1:1"
}
return name
}
// volumeOf is the --volume value among args, or "".
func volumeOf(args []string) string {
for i := 0; i+1 < len(args); i++ {
if args[i] == "--volume" {
return args[i+1]
}
}
return ""
}
func firstLine(out, near string) string {
for _, l := range strings.Split(out, "\n") {
if strings.Contains(l, near) {