test: KNOWN-ZERO acceptance test on a fresh volume

TestKnownZeroAcceptance (tags subprocess chunkstore_integration, KZ_RUN=1)
runs the five acceptance steps on a fresh volume (KZ_SIZE, default
1T), each printing one "KZ STEP n PASS|FAIL" line with its counters into
KZ_REPORT:

1. the empty first snapshot stages and uploads nothing and HEAD names no
   segment; the fresh attach certified the chunks known-zero;
2. mkfs (ext4 and xfs) or known blocks, sync, snapshot: the cut's work is
   bounded by the chunks touched;
3. restore and fork of that snapshot on another server node: contents
   equal, the first snapshot of each target without a full scan;
4. reads of snapshot-named blocks before hydration return data, never
   zeros, and each read waits for its own fetch (AbsentChunks, Hydration);
5. the first start of a fresh volume killed before its attach commit: after
   the restart nothing is certified known-zero, the first cut scans every
   chunk once, the data reads back exactly.

KZ_ROLE source|target splits steps 3-4 onto a second host through a handoff
file; SWBLOCK_TEST_LISTEN_HOST (default 127.0.0.1) lets the test harness
bind a host address instead of loopback. KZ_DEVICE=1 uses the kernel
NVMe/TCP device, resolved only by the run's own NQN (kzResolve, with table
tests); a path given by name is never formatted.

Step 5 stops the process at the provider's existing boundary before the
fresh marker is retired, through a binary built with -tags kzhold
(HoldBeforeChunkFreshRetireForTest); a normal build contains none of it,
which TestKZHoldNeverInReleaseBuild checks.

The volume-size test's cluster and volume start move into shared helpers
(headSzStartCluster, headSzStartVolume) used by both tests.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Fable 5.1 committed 2026-11-24 12:09:51 -08:00
1 parent 22766070d6
commit ddb6ff5771
10 files changed
+1161 -55

No files matched your search

@@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"io"
"math/rand"
"net/http"
"net/url"
"os"
@@ -159,14 +160,11 @@ func TestHeadSizeAgainstVolumeSize(t *testing.T) {
}
cfg.attempts = n
}
h := newPlannedHandoffHarness(t)
clusterDir := filepath.Join(h.dir, "weed")
if err := os.MkdirAll(clusterDir, 0o700); err != nil {
t.Fatal(err)
var vols []headSzVol
for _, s := range sizes {
vols = append(vols, headSzVol{id: "h" + strings.ToLower(strings.TrimSpace(s)), bytes: headSzParse(t, s)})
}
headSzAmbientFilerToml(t, clusterDir)
env := &handoffEnv{h: h, cluster: startWorkspaceWeedWith(t, clusterDir, w4WeedOpts{VolumeSizeLimitMB: 1024, VolumeMax: 64}),
chunkPath: fmt.Sprintf("/headsz-%d", time.Now().UnixNano()), hosts: map[string]bvHost{}}
env, clusterDir := headSzStartCluster(t, "headsz", vols)
rep := &headSzReport{StartedAt: time.Now().UTC(), ChunkPath: env.chunkPath,
FilerStore: "leveldb2 (weed filer default store), -defaultStoreDir=" + filepath.Join(clusterDir, "f") + ", no filer.toml"}
defer func() {
@@ -178,36 +176,126 @@ func TestHeadSizeAgainstVolumeSize(t *testing.T) {
}
}()
// one cluster spec with every size's volume; one replica each on s1
var vols strings.Builder
for i, s := range sizes {
b := headSzParse(t, s)
id := "h" + strings.ToLower(strings.TrimSpace(s))
env.hosts[id] = bvHost{id: id, server: "s1", replica: fmt.Sprintf("r%d", i+1), volume: id, root: filepath.Join(h.dir, "vol-"+id),
data: handoffAddress(t), ctrl: handoffAddress(t), status: handoffAddress(t), nvme: handoffAddress(t)}
fmt.Fprintf(&vols, " - id: %s\n size_bytes: %d\n replication_factor: 1\n placements:\n - server_id: s1\n replica_id: r%d\n", id, b, i+1)
}
spec := filepath.Join(h.dir, "cluster-spec.yaml")
if err := os.WriteFile(spec, []byte(fmt.Sprintf("nodes:\n - server_id: s1\n data_addr: %s\n ctrl_addr: %s\nvolumes:\n%s", h.dataAddr, h.ctrlAddr, vols.String())), 0o644); err != nil {
t.Fatal(err)
}
mstate := filepath.Join(h.dir, "master")
master := h.start(t, "blockmaster", h.master, "--authority-store", filepath.Join(mstate, "authority"), "--lifecycle-store", filepath.Join(mstate, "lifecycle"),
"--cluster-spec", spec, "--expected-slots-per-volume", "1", "--listen", h.masterAddr,
"--workspace-rpc", "--workspace-head-base-url", "http://"+env.cluster.filerHTTP+env.chunkPath)
master.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=")
for _, s := range sizes {
rep.Sizes = append(rep.Sizes, headSzOne(t, env, cfg, s, changeCuts))
}
}
// headSzVol is one volume of the test cluster spec. server "" places it on
// s1 (replica rN); any other server gets its own node in the spec and the
// volume's one replica r1 on it (a restore or fork target, as
// startHandoffEnvWith places its targets).
type headSzVol struct {
id string
bytes uint64
server string
// host, when set, is another machine that runs this volume's blockvolume:
// 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
}
// headSzStartCluster starts one weed cluster (the filer's default store, no
// filer.toml) and a blockmaster whose spec holds vols. It returns the env,
// with one bvHost per volume, and the cluster dir. The chunk path is
// /<prefix>-<unix ns>.
func headSzStartCluster(t *testing.T, prefix string, vols []headSzVol) (*handoffEnv, string) {
t.Helper()
h := newPlannedHandoffHarness(t)
clusterDir := filepath.Join(h.dir, "weed")
if err := os.MkdirAll(clusterDir, 0o700); err != nil {
t.Fatal(err)
}
headSzAmbientFilerToml(t, clusterDir)
env := &handoffEnv{h: h, cluster: startWorkspaceWeedWith(t, clusterDir, w4WeedOpts{VolumeSizeLimitMB: 1024, VolumeMax: 64}),
chunkPath: fmt.Sprintf("/%s-%d", prefix, time.Now().UnixNano()), hosts: map[string]bvHost{}}
var spec strings.Builder
nodes := fmt.Sprintf(" - server_id: s1\n data_addr: %s\n ctrl_addr: %s\n", h.dataAddr, h.ctrlAddr)
for i, v := range vols {
server, replica := "s1", fmt.Sprintf("r%d", i+1)
if v.server != "" {
server, replica = v.server, "r1"
}
b := bvHost{id: v.id, server: server, replica: replica, volume: v.id, root: filepath.Join(h.dir, "vol-"+v.id),
data: handoffAddress(t), ctrl: handoffAddress(t), status: handoffAddress(t), nvme: handoffAddress(t)}
if v.host != "" {
b.data, b.ctrl = headSzRemoteAddr(t, v.host), headSzRemoteAddr(t, v.host)
}
env.hosts[v.id] = b
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)
}
specPath := filepath.Join(h.dir, "cluster-spec.yaml")
if err := os.WriteFile(specPath, []byte("nodes:\n"+nodes+"volumes:\n"+spec.String()), 0o644); err != nil {
t.Fatal(err)
}
mstate := filepath.Join(h.dir, "master")
master := h.start(t, "blockmaster", h.master, "--authority-store", filepath.Join(mstate, "authority"), "--lifecycle-store", filepath.Join(mstate, "lifecycle"),
"--cluster-spec", specPath, "--expected-slots-per-volume", "1", "--listen", h.masterAddr,
"--workspace-rpc", "--workspace-head-base-url", "http://"+env.cluster.filerHTTP+env.chunkPath)
master.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=")
return env, clusterDir
}
// headSzRemoteAddr picks host:<port> for a process on another machine from
// the same port range handoffAddress uses, never handing out a port twice.
func headSzRemoteAddr(t *testing.T, host string) string {
t.Helper()
handoffPorts.Lock()
defer handoffPorts.Unlock()
if handoffPorts.used == nil {
handoffPorts.used = map[int]bool{}
}
for i := 0; i < 500; i++ {
p := 10000 + rand.Intn(10000)
if !handoffPorts.used[p] {
handoffPorts.used[p] = true
return fmt.Sprintf("%s:%d", host, p)
}
}
t.Fatal("no port left for " + host)
return ""
}
// headSzConfig: HEADSZ_SNAPSHOT_TIMEOUT is the snapshot command's --timeout
// (the server caps it at its own operation deadline); HEADSZ_ATTEMPTS is how
// many times one cut is tried before it is recorded as not completed.
// many times one cut is tried before it is recorded as not completed. name
// is the snapshot name prefix ("headsz" when empty): cut N is "<name>-N".
type headSzConfig struct {
snapshotTimeout string
attempts int
name string
}
// headSzStartVolume starts b's blockvolume for a volume of bytes (no capture
// interval, no snapshot schedule: cuts happen only when the test asks), waits
// until it adopted the volume as PRIMARY and its frontend is ready, and
// returns it. When the volume refuses for headroom it returns nil and the
// refusal line; any other early exit or timeout fails the test. The caller
// stops the daemon.
func headSzStartVolume(t *testing.T, env *handoffEnv, b bvHost, bytes uint64, extra ...string) (*daemon, string) {
t.Helper()
env.volExtra = append([]string{"--durable-blocks", strconv.FormatUint(bytes/4096, 10), "--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"}, extra...)
d := env.h.start(t, "blockvolume-"+b.id, env.h.volume, env.volArgsFor(b)...)
primary := fmt.Sprintf("blockvolume: volume %s adopted as PRIMARY at %s@", b.volume, b.replica)
end := time.Now().Add(120 * time.Second)
for !d.has(primary) {
select {
case <-d.done:
if l := d.line("bytes free"); l != "" {
return nil, strings.TrimSpace(l)
}
t.Fatalf("blockvolume %s exited before it adopted its volume: %v", b.id, d.err)
case <-time.After(200 * time.Millisecond):
}
if time.Now().After(end) {
t.Fatalf("blockvolume %s did not adopt its volume in 120 s", b.id)
}
}
poll(t, 60*time.Second, b.id+" never reported its frontend ready", func() bool { return volumeFrontendReady(b.status, b.volume) })
return d, ""
}
// headSzOne measures one size; its blockvolume is stopped at the end.
@@ -217,26 +305,12 @@ func headSzOne(t *testing.T, env *handoffEnv, cfg headSzConfig, size string, cha
id := "h" + strings.ToLower(strings.TrimSpace(size))
b := env.hosts[id]
row := headSzSize{Size: strings.TrimSpace(size), Bytes: bytes, Segments: int((bytes + headSegmentBytes - 1) / headSegmentBytes)}
env.volExtra = []string{"--durable-blocks", strconv.FormatUint(bytes/4096, 10), "--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"}
d := env.h.start(t, "blockvolume-"+id, env.h.volume, env.volArgsFor(b)...)
primary := fmt.Sprintf("blockvolume: volume %s adopted as PRIMARY at %s@", b.volume, b.replica)
end := time.Now().Add(120 * time.Second)
for !d.has(primary) {
select {
case <-d.done:
if l := d.line("bytes free"); l != "" {
row.Result, row.Refusal = "refused_headroom", strings.TrimSpace(l)
return row
}
t.Fatalf("blockvolume %s exited before it adopted its volume: %v", id, d.err)
case <-time.After(200 * time.Millisecond):
}
if time.Now().After(end) {
t.Fatalf("blockvolume %s did not adopt its volume in 120 s", id)
}
d, refusal := headSzStartVolume(t, env, b, bytes)
if d == nil {
row.Result, row.Refusal = "refused_headroom", refusal
return row
}
defer d.term(t, 60*time.Second)
poll(t, 60*time.Second, id+" never reported its frontend ready", func() bool { return volumeFrontendReady(b.status, b.volume) })
c := dialNVMe(t, b.nvme, plannedHandoffNQN)
write := func(lba uint64, tag string) {
@@ -281,11 +355,15 @@ func headSzOne(t *testing.T, env *handoffEnv, cfg headSzConfig, size string, cha
func headSzCutOnce(t *testing.T, env *handoffEnv, cfg headSzConfig, b bvHost, cut, changed int) headSzCut {
t.Helper()
r := headSzCut{Cut: cut, ChangedBlocks: changed}
name := cfg.name
if name == "" {
name = "headsz"
}
start := time.Now()
for a := 1; a <= cfg.attempts; a++ {
as := time.Now()
out, code := headSzRun(t, env, cfg.snapshotTimeout, "ops", "chunk", "snapshot", "--volume", b.volume, "--status-addr", b.status, "--timeout", cfg.snapshotTimeout,
"--name", fmt.Sprintf("headsz-%d", cut), "--request-id", fmt.Sprintf("headsz-%s-%d", b.volume, cut))
"--name", fmt.Sprintf("%s-%d", name, cut), "--request-id", fmt.Sprintf("%s-%s-%d", name, b.volume, cut))
at := headSzAttempt{Attempt: a, ExitCode: code, WallMs: ms(time.Since(as)), KeysAfter: headSzCountDir(t, env, env.chunkPath+"/"+b.volume+"/keys")}
if code != 0 {
var e struct{ Code, Message string }
@@ -0,0 +1,24 @@
//go:build kzhold
package main
import (
"log"
"os"
"path/filepath"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
)
// applyBuildTagHold: in a kzhold build (test-only, never released) with
// SWBLOCK_KZHOLD_DIR set, the provider holds before the fresh marker is
// retired: it writes <dir>/reached and waits for <dir>/release.
func applyBuildTagHold(dp *durable.DurableProvider) {
dir := os.Getenv("SWBLOCK_KZHOLD_DIR")
if dir == "" {
return
}
log.Printf("blockvolume: TEST-ONLY build (kzhold): holding before the fresh-marker retire; reached=%s release=%s",
filepath.Join(dir, "reached"), filepath.Join(dir, "release"))
dp.HoldBeforeChunkFreshRetireForTest(filepath.Join(dir, "reached"), filepath.Join(dir, "release"))
}
@@ -0,0 +1,8 @@
//go:build !kzhold
package main
import "github.com/seaweedfs/seaweed-block/core/frontend/durable"
// applyBuildTagHold does nothing in a normal build.
func applyBuildTagHold(*durable.DurableProvider) {}
@@ -0,0 +1,733 @@
//go:build subprocess && chunkstore_integration
package main_test
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"testing"
"time"
)
// TestKnownZeroAcceptance is the KNOWN-ZERO acceptance test (V1-SPEC r2.116),
// gated by KZ_RUN=1. Source role (this file, steps 1-2):
//
// (1) a fresh volume of KZ_SIZE (default 1T) and an empty first snapshot S0:
// it finishes in seconds, stages and uploads nothing, and HEAD names no
// segment; the fresh attach certified chunks known-zero.
// (2) mkfs (KZ_FS: ext4 and xfs, one volume each) on the kernel NVMe/TCP
// device, small files with known sha256, sync, snapshot S1: the chunks
// mkfs dirtied, staged chunks, uploaded bytes and HEAD size, bounded by
// the touched chunks.
//
// Device steps run only with KZ_DEVICE=1 (root through sudo -n, nvme-cli,
// mkfs). Every device path comes from kzResolve on this run's own NQN; a path
// given by name is never formatted. Without KZ_DEVICE the test writes known
// blocks through the user-space NVMe client instead (a smoke of the counters,
// not the acceptance run). Each step prints one "KZ STEP n PASS|FAIL <why>"
// line and its counters into KZ_REPORT.
func TestKnownZeroAcceptance(t *testing.T) {
if os.Getenv("KZ_RUN") != "1" {
t.Skip("KZ_RUN=1 not set")
}
size := os.Getenv("KZ_SIZE")
if size == "" {
size = "1T"
}
bytes := headSzParse(t, size)
fss := strings.Split(os.Getenv("KZ_FS"), ",")
if os.Getenv("KZ_FS") == "" {
fss = []string{"ext4", "xfs"}
}
device := os.Getenv("KZ_DEVICE") == "1"
run := os.Getenv("KZ_RUN_ID")
if run == "" {
run = fmt.Sprintf("local-%d", time.Now().Unix())
}
// KZ_ROLE: "" = every step in this process (the smoke); "source" = steps
// 1, 2 and 5 here, the restore and fork targets on KZ_TARGET_HOST (r2.116:
// "on the second host"), handed over through KZ_HANDOFF; "target" = steps
// 3 and 4 on this host against the source's cluster named in KZ_HANDOFF.
role := os.Getenv("KZ_ROLE")
rep := &kzReport{Run: run, Size: size, Bytes: bytes, Device: device, Role: role, StartedAt: time.Now().UTC()}
defer rep.write(t)
if role == "target" {
kzTargetRole(t, rep, bytes, device, run)
return
}
targetHost := ""
if role == "source" {
if targetHost = os.Getenv("KZ_TARGET_HOST"); targetHost == "" || os.Getenv("KZ_HANDOFF") == "" {
t.Fatal("KZ_ROLE=source needs KZ_TARGET_HOST and KZ_HANDOFF")
}
} else if role != "" {
t.Fatalf("KZ_ROLE %q: want source, target or unset", role)
}
// per file system: the source and two targets of its S1, each target on
// its own server node (on KZ_TARGET_HOST in the source role)
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 + "f", bytes: bytes, server: "t-" + fs + "f", host: targetHost})
}
// 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)
for i := 1; i <= kzCrashTries; i++ {
vols = append(vols, headSzVol{id: fmt.Sprintf("kzc%d", i), bytes: bytes})
}
env, _ := headSzStartCluster(t, "kz", vols)
rep.ChunkPath = env.chunkPath
ho := kzHandoff{Run: run, Bytes: bytes, FilerGRPC: env.cluster.filerGRPC, FilerHTTP: env.cluster.filerHTTP,
Master: env.h.masterAddr, ChunkPath: env.chunkPath}
for _, fs := range fss {
v := kzSource(t, env, rep, env.hosts["kz"+fs], fs, bytes, device, run)
rep.Volumes = append(rep.Volumes, v)
if !v.S1.Completed {
continue
}
for _, kind := range []string{"restore", "fork"} {
tb := env.hosts["kz"+fs+kind[:1]]
if role == "source" {
ho.Targets = append(ho.Targets, kzHandoffTarget{Kind: kind, Volume: tb.volume, Server: tb.server, Data: tb.data, Ctrl: tb.ctrl,
Source: v.Volume, S1: v.S1Name, Dirty1: v.Dirty1, Files: v.Files, Blocks: kzHexBlocks(v.Blocks)})
continue
}
rep.Targets = append(rep.Targets, kzTarget(t, env, rep, v, kind, tb, bytes, device, run))
}
}
if role == "source" {
kzWriteHandoff(t, ho)
kzWaitTargetDone(t)
}
rep.Crash = kzCrashFirstStart(t, env, rep, bytes, run)
}
// kzHandoff is what the source role hands to the target role (KZ_HANDOFF):
// the cluster to use and, per target, the S1 to restore or fork and what the
// source wrote into it.
type kzHandoff struct {
Run string `json:"run"`
Bytes uint64 `json:"bytes"`
FilerGRPC string `json:"filer_grpc"`
FilerHTTP string `json:"filer_http"`
Master string `json:"master"`
ChunkPath string `json:"chunk_path"`
Targets []kzHandoffTarget `json:"targets"`
}
type kzHandoffTarget struct {
Kind string `json:"kind"`
Volume string `json:"volume"`
Server string `json:"server"`
Data string `json:"data_addr"`
Ctrl string `json:"ctrl_addr"`
Source string `json:"source"`
S1 string `json:"s1"`
Dirty1 int `json:"dirty1"`
Files map[string]string `json:"files_sha256"`
Blocks map[string]string `json:"blocks_hex"`
}
func kzHexBlocks(b map[uint64][]byte) map[string]string {
out := map[string]string{}
for lba, d := range b {
out[fmt.Sprint(lba)] = hex.EncodeToString(d)
}
return out
}
func kzWriteHandoff(t *testing.T, ho kzHandoff) {
t.Helper()
b, _ := json.MarshalIndent(ho, "", " ")
p := os.Getenv("KZ_HANDOFF")
if err := os.WriteFile(p+".tmp", append(b, '\n'), 0o644); err != nil {
t.Fatal(err)
}
if err := os.Rename(p+".tmp", p); err != nil {
t.Fatal(err)
}
t.Logf("KZ HANDOFF written: %s (%d targets)", p, len(ho.Targets))
}
// kzWaitTargetDone waits for KZ_TARGET_DONE (the window script creates it
// after the target role ended), at most KZ_TARGET_WAIT (default 90m). The
// source's cluster must stay up while the targets run.
func kzWaitTargetDone(t *testing.T) {
t.Helper()
done := os.Getenv("KZ_TARGET_DONE")
if done == "" {
t.Fatal("KZ_ROLE=source needs KZ_TARGET_DONE")
}
wait := 90 * time.Minute
if v := os.Getenv("KZ_TARGET_WAIT"); v != "" {
d, err := time.ParseDuration(v)
if err != nil {
t.Fatalf("KZ_TARGET_WAIT=%q: %v", v, err)
}
wait = d
}
poll(t, wait, "the target role never finished ("+done+" absent)", func() bool {
_, err := os.Stat(done)
return err == nil
})
}
// kzTargetRole runs steps 3 and 4 on this host: no weed cluster or
// blockmaster of its own; every blockvolume uses the source's filer and
// blockmaster from KZ_HANDOFF, with the data and ctrl addresses the source's
// cluster spec names for it.
func kzTargetRole(t *testing.T, rep *kzReport, bytes uint64, device bool, run string) {
t.Helper()
b, err := os.ReadFile(os.Getenv("KZ_HANDOFF"))
if err != nil {
t.Fatalf("KZ_HANDOFF: %v", err)
}
var ho kzHandoff
if err := json.Unmarshal(b, &ho); err != nil {
t.Fatalf("KZ_HANDOFF: %v", err)
}
if ho.Run != run || ho.Bytes != bytes || len(ho.Targets) == 0 {
t.Fatalf("KZ_HANDOFF run %q bytes %d targets %d; this run %q bytes %d", ho.Run, ho.Bytes, len(ho.Targets), run, bytes)
}
h := newPlannedHandoffHarness(t)
h.masterAddr = ho.Master
env := &handoffEnv{h: h, cluster: &w4WeedCluster{filerGRPC: ho.FilerGRPC, filerHTTP: ho.FilerHTTP}, chunkPath: ho.ChunkPath, hosts: map[string]bvHost{}}
rep.ChunkPath = ho.ChunkPath
for _, ht := range ho.Targets {
tb := bvHost{id: ht.Volume, server: ht.Server, replica: "r1", volume: ht.Volume, root: filepath.Join(h.dir, "vol-"+ht.Volume),
data: ht.Data, ctrl: ht.Ctrl, status: handoffAddress(t), nvme: handoffAddress(t)}
env.hosts[ht.Volume] = tb
src := kzVolume{Volume: ht.Source, S1Name: ht.S1, Dirty1: ht.Dirty1, Files: ht.Files, Blocks: map[uint64][]byte{}}
for k, v := range ht.Blocks {
var lba uint64
if _, err := fmt.Sscan(k, &lba); err != nil {
t.Fatalf("KZ_HANDOFF block %q: %v", k, err)
}
d, err := hex.DecodeString(v)
if err != nil {
t.Fatalf("KZ_HANDOFF block %q: %v", k, err)
}
src.Blocks[lba] = d
}
rep.Targets = append(rep.Targets, kzTarget(t, env, rep, src, ht.Kind, tb, bytes, device, run))
}
}
type kzTargetRecord struct {
Volume string `json:"volume"`
Kind string `json:"kind"`
Source string `json:"source"`
Snapshot string `json:"snapshot"`
NQN string `json:"nqn"`
Identity string `json:"device_identity,omitempty"`
Before kzStats `json:"stats_before_reads"`
After kzStats `json:"stats_after_reads"`
ReadsEqual int `json:"reads_equal"`
ReadsZero int `json:"reads_zero"`
Reads int `json:"reads"`
FilesEqual int `json:"files_equal"`
FirstCut kzCutRecord `json:"first_snapshot"`
}
// kzTarget restores or forks the source's S1 into tb, then runs step 4 (read
// the S1-named blocks BEFORE hydration: data, never zeros; the read itself
// waits for its chunk) and step 3 (all contents equal the source; the target's
// first snapshot completes without a full scan).
func kzTarget(t *testing.T, env *handoffEnv, rep *kzReport, src kzVolume, kind string, tb bvHost, bytes uint64, device bool, run string) kzTargetRecord {
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)}
env.h.command(t, "ops", "chunk", kind, "--source", src.Volume, "--snapshot", src.S1Name, "--target", tb.volume,
"--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)
if d == nil {
rep.step(t, 3, tb.volume, false, kind+" target refused: "+refusal)
return r
}
defer d.term(t, 60*time.Second)
// (4) wrong-zero guard, before any hydration (a restore is driven only after)
r.Before = kzReadStats(t, tb)
c := dialNVMe(t, tb.nvme, r.NQN)
zero := make([]byte, 4096)
for lba, want := range src.Blocks {
_ = c.io.SetDeadline(time.Now().Add(60 * time.Second))
got := c.read(t, lba, 4096)
r.Reads++
switch {
case string(got) == string(want):
r.ReadsEqual++
case string(got) == string(zero):
r.ReadsZero++
}
}
c.close()
r.After = kzReadStats(t, tb)
waited := r.After.Hydration.WaitCalls - r.Before.Hydration.WaitCalls
ok4 := r.Reads > 0 && r.ReadsEqual == r.Reads && r.ReadsZero == 0 && r.Before.AbsentChunks > 0 && waited > 0
rep.step(t, 4, tb.volume, ok4, fmt.Sprintf("%s reads=%d equal=%d zero=%d absent_before=%d absent_after=%d read_waits=%d fetches=%d",
kind, r.Reads, r.ReadsEqual, r.ReadsZero, r.Before.AbsentChunks, r.After.AbsentChunks, waited,
r.After.Hydration.Fetches-r.Before.Hydration.Fetches))
// (3) contents equal + first snapshot without a full scan
if kind == "restore" {
env.h.command(t, "ops", "chunk", "restore", "--volume", tb.volume, "--status-addr", tb.status)
}
if device {
r.Identity, r.FilesEqual = kzDeviceVerify(t, tb, r.NQN, src, run)
} else {
c := dialNVMe(t, tb.nvme, r.NQN)
for lba, want := range src.Blocks {
_ = c.io.SetDeadline(time.Now().Add(60 * time.Second))
if string(c.read(t, lba, 4096)) == string(want) {
r.FilesEqual++
}
}
c.close()
}
total := int((bytes + kzChunkBytes - 1) / kzChunkBytes)
r.FirstCut = kzCut(t, env, headSzConfig{snapshotTimeout: "120s", attempts: 3, name: "kz-" + tb.volume + "-s"}, tb, 0, total)
want := len(src.Files)
cand := kzLC(r.FirstCut.Stats).CandidateChunks
ok3 := r.FilesEqual == want && want > 0 && r.FirstCut.Completed && cand <= src.Dirty1
rep.step(t, 3, tb.volume, ok3, fmt.Sprintf("%s files_equal=%d/%d first_snapshot completed=%v candidates=%d (source dirtied %d) of %d chunks wall_ms=%.0f",
kind, r.FilesEqual, want, r.FirstCut.Completed, cand, src.Dirty1, total, r.FirstCut.WallMs))
return r
}
// kzDeviceVerify connects the target through the kernel, resolves it by
// NQN, mounts it read-only under the run's scratch, compares every source
// file's sha256, unmounts and disconnects.
func kzDeviceVerify(t *testing.T, tb bvHost, nqn string, src kzVolume, run string) (string, int) {
t.Helper()
host, port := kzSplit(t, tb.nvme)
kzSudo(t, "nvme", "connect", "-t", "tcp", "-n", nqn, "-a", host, "-s", port)
defer kzSudo(t, "nvme", "disconnect", "-n", nqn)
var dev kzDevice
poll(t, 30*time.Second, "kernel device for "+nqn+" never appeared", func() bool {
out, err := exec.Command("sudo", "-n", "nvme", "list-subsys", "-o", "json").Output()
if err != nil {
return false
}
d, err := kzResolve(out, nqn, "")
dev = d
return err == nil
})
t.Log(dev.Identity())
mnt := filepath.Join(os.TempDir(), "kz-"+run, tb.volume)
if err := os.MkdirAll(mnt, 0o755); err != nil {
t.Fatal(err)
}
kzSudo(t, "mount", "-o", "ro", dev.Path, mnt)
defer kzSudo(t, "umount", mnt)
equal := 0
for name, want := range src.Files {
out := kzSudo(t, "sha256sum", filepath.Join(mnt, name))
if f := strings.Fields(out); len(f) > 0 && f[0] == want {
equal++
}
}
return dev.Identity(), equal
}
// kzReport is the JSON evidence (KZ_REPORT); Lines are the step verdicts.
type kzReport struct {
Run string `json:"run"`
Size string `json:"size"`
Bytes uint64 `json:"bytes"`
Device bool `json:"device"`
Role string `json:"role,omitempty"`
ChunkPath string `json:"chunk_path"`
StartedAt time.Time `json:"started_at"`
Volumes []kzVolume `json:"volumes"`
Targets []kzTargetRecord `json:"targets"`
Crash kzCrashRecord `json:"crash"`
HoldBin string `json:"hold_bin,omitempty"`
Lines []string `json:"lines"`
}
const kzCrashTries = 3
type kzCrashTry struct {
Volume string `json:"volume"`
Markers []string `json:"markers_at_stop"`
Before bool `json:"stopped_before_commit"`
}
type kzCrashRecord struct {
Tries []kzCrashTry `json:"tries"`
Volume string `json:"volume,omitempty"`
FreshLine string `json:"fresh_line_after_restart,omitempty"`
S0 kzCutRecord `json:"s0_after_restart"`
Dirty1 int `json:"dirty_chunks_before_s1"`
S1 kzCutRecord `json:"s1_after_restart"`
Equal int `json:"blocks_equal"`
Blocks int `json:"blocks"`
}
// kzHoldBin is KZ_HOLD_BIN: the kzhold-tagged blockvolume (go build -tags kzhold
// ./cmd/blockvolume), test-only and never released; its sha256 goes into the
// report so the evidence names exactly which binary held.
func kzHoldBin(t *testing.T, rep *kzReport) string {
t.Helper()
p := os.Getenv("KZ_HOLD_BIN")
if p == "" {
t.Fatal("step 5 needs KZ_HOLD_BIN (a blockvolume built with -tags kzhold)")
}
b, err := os.ReadFile(p)
if err != nil {
t.Fatalf("KZ_HOLD_BIN: %v", err)
}
sum := sha256.Sum256(b)
rep.HoldBin = p + " sha256:" + hex.EncodeToString(sum[:])
return p
}
// kzCrashFirstStart is step 5 (V1-SPEC r2.116):
// the first start of a fresh volume runs the kzhold test binary, which holds
// at the boundary before the fresh marker is retired; the test requires the
// .chunkfresh marker present there, then SIGKILLs it. More than one try fails
// the step. Then restart that volume and
// repeat steps 1-2: nothing certified known-zero (KnownZeroChunks 0, no
// fresh-attach line), the first cut scans every chunk once, the next cut only
// the touched ones, and the written blocks read back exactly.
func kzCrashFirstStart(t *testing.T, env *handoffEnv, rep *kzReport, bytes uint64, run string) kzCrashRecord {
t.Helper()
var r kzCrashRecord
total := int((bytes + kzChunkBytes - 1) / kzChunkBytes)
var b bvHost
for i := 1; i <= kzCrashTries; i++ {
b = env.hosts[fmt.Sprintf("kzc%d", i)]
nqn := fmt.Sprintf("nqn.2026-11.io.seaweedfs:kz-%s-%s", run, b.volume)
env.volExtra = []string{"--durable-blocks", fmt.Sprint(bytes / 4096), "--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off", "--nvme-subsysnqn", nqn}
// Deterministic, with no hook in a release binary: the
// first start runs KZ_HOLD_BIN, a blockvolume built with the kzhold tag
// (test-only, never released), which holds at the provider's existing
// boundary after presence and before the fresh marker is retired (the
// attach commit) and writes <dir>/reached there. The release stays
// absent: the process is killed while held.
holdDir := filepath.Join(env.h.dir, "kzhold-"+b.id)
if err := os.MkdirAll(holdDir, 0o755); err != nil {
t.Fatal(err)
}
reached := filepath.Join(holdDir, "reached")
os.Setenv("SWBLOCK_KZHOLD_DIR", holdDir)
d := env.h.start(t, "blockvolume-"+b.id+"-first", kzHoldBin(t, rep), env.volArgsFor(b)...)
os.Unsetenv("SWBLOCK_KZHOLD_DIR")
end := time.Now().Add(120 * time.Second)
for {
if _, err := os.Stat(reached); err == nil {
break
}
select {
case <-d.done:
t.Fatalf("%s exited before the hold was reached: %v", b.id, d.err)
case <-time.After(20 * time.Millisecond):
}
if time.Now().After(end) {
t.Fatalf("%s never reached the hold (%s)", b.id, reached)
}
}
if !d.has("TEST-ONLY build (kzhold)") {
t.Fatalf("%s: the first start is not the kzhold build", b.id)
}
if err := d.proc.Signal(syscall.SIGSTOP); err != nil {
t.Fatalf("SIGSTOP %s: %v", b.id, err)
}
markers, _ := filepath.Glob(filepath.Join(b.root, "*.chunkfresh"))
more, _ := filepath.Glob(b.root + "*.chunkfresh")
markers = append(markers, more...)
d.kill(t)
try := kzCrashTry{Volume: b.volume, Markers: markers, Before: len(markers) > 0}
r.Tries = append(r.Tries, try)
if try.Before {
break
}
}
last := r.Tries[len(r.Tries)-1]
if !last.Before {
rep.step(t, 5, "kzc", false, fmt.Sprintf("no try stopped before the attach commit in %d tries (marker always gone)", len(r.Tries)))
return r
}
r.Volume = b.volume
nqn := fmt.Sprintf("nqn.2026-11.io.seaweedfs:kz-%s-%s", run, b.volume)
d, refusal := headSzStartVolume(t, env, b, bytes, "--nvme-subsysnqn", nqn)
if d == nil {
rep.step(t, 5, b.volume, false, "restart refused: "+refusal)
return r
}
defer d.term(t, 60*time.Second)
r.FreshLine = strings.TrimSpace(d.line("known-zero"))
cfg := headSzConfig{snapshotTimeout: "120s", attempts: 3, name: "kz-" + b.volume + "-s"}
r.S0 = kzCut(t, env, cfg, b, 0, total)
_, blocks := kzUserSpaceFiles(t, b, nqn, bytes)
r.Dirty1 = kzReadStats(t, b).DirtyChunks
r.S1 = kzCut(t, env, cfg, b, 1, total)
c := dialNVMe(t, b.nvme, nqn)
for lba, want := range blocks {
_ = c.io.SetDeadline(time.Now().Add(60 * time.Second))
r.Blocks++
if string(c.read(t, lba, 4096)) == string(want) {
r.Equal++
}
}
c.close()
s0, s1 := kzLC(r.S0.Stats), kzLC(r.S1.Stats)
// the stop is deterministic (filer paused), so an acceptance run must catch the marker on the FIRST try
ok := len(r.Tries) == 1 && r.S0.Completed && r.S1.Completed && r.S0.Stats.KnownZeroChunks == 0 && r.FreshLine == "" &&
s0.CandidateChunks == total && s1.CandidateChunks <= r.Dirty1 && r.Equal == r.Blocks && r.Blocks > 0
rep.step(t, 5, b.volume, ok, fmt.Sprintf("tries=%d marker_at_stop=%v known_zero=%d fresh_line=%t s0_candidates=%d/%d s0_uploaded=%d s1_candidates=%d (dirtied %d) blocks_equal=%d/%d",
len(r.Tries), last.Markers, r.S0.Stats.KnownZeroChunks, r.FreshLine != "", s0.CandidateChunks, total, s0.UploadedChunks, s1.CandidateChunks, r.Dirty1, r.Equal, r.Blocks))
return r
}
func (r *kzReport) step(t *testing.T, n int, vol string, pass bool, why string) {
t.Helper()
v := "FAIL"
if pass {
v = "PASS"
}
l := fmt.Sprintf("KZ STEP %d %s %s %s", n, v, vol, why)
r.Lines = append(r.Lines, l)
t.Log(l)
if !pass {
t.Error(l)
}
}
func (r *kzReport) write(t *testing.T) {
if p := os.Getenv("KZ_REPORT"); p != "" {
b, _ := json.MarshalIndent(r, "", " ")
if err := os.WriteFile(p, append(b, '\n'), 0o644); err != nil {
t.Errorf("KZ_REPORT: %v", err)
}
}
}
type kzVolume struct {
Volume string `json:"volume"`
FS string `json:"fs"`
NQN string `json:"nqn"`
Identity string `json:"device_identity,omitempty"`
Fresh string `json:"fresh_attach_line"`
S0 kzCutRecord `json:"s0"`
Dirty1 int `json:"dirty_chunks_before_s1"`
Discard string `json:"discard,omitempty"`
S1 kzCutRecord `json:"s1"`
Files map[string]string `json:"files_sha256,omitempty"`
S1Name string `json:"s1_name"`
Blocks map[uint64][]byte `json:"-"`
}
type kzCutRecord struct {
Cut headSzCut `json:"cut"`
Stats kzStats `json:"stats_after"`
Total int `json:"total_chunks"`
WallMs float64 `json:"wall_ms"`
Completed bool `json:"completed"`
}
// kzStats is the part of the chunk layer's durable status the test reads.
type kzStats struct {
DirtyChunks int
StagedChunks uint64
KnownZeroChunks uint64
AbsentChunks int
Hydration struct{ WaitCalls, Fetches, Completed, FetchErrors uint64 }
LastCut *struct {
CandidateChunks, StagedChunks, UploadedChunks, ZeroedChunks, UnchangedChunks int
UploadedBytes int64
}
}
func kzReadStats(t *testing.T, b bvHost) kzStats {
t.Helper()
var c struct{ Stats kzStats }
raw := headSzChunkStatus(t, b)
if raw == nil {
t.Fatalf("%s: durable status has no chunk section", b.volume)
}
if err := json.Unmarshal(raw, &c); err != nil {
t.Fatalf("%s: chunk status: %v", b.volume, err)
}
return c.Stats
}
const kzChunkBytes = 4 << 20
func kzSource(t *testing.T, env *handoffEnv, rep *kzReport, b bvHost, fs string, bytes uint64, device bool, run string) kzVolume {
t.Helper()
total := int((bytes + kzChunkBytes - 1) / kzChunkBytes)
v := kzVolume{Volume: b.volume, FS: fs, NQN: fmt.Sprintf("nqn.2026-11.io.seaweedfs:kz-%s-%s", run, b.volume)}
d, refusal := headSzStartVolume(t, env, b, bytes, "--nvme-subsysnqn", v.NQN)
if d == nil {
rep.step(t, 1, b.volume, false, "volume refused: "+refusal)
return v
}
defer d.term(t, 60*time.Second)
v.Fresh = strings.TrimSpace(d.line("known-zero"))
// (1) empty S0
cfg := headSzConfig{snapshotTimeout: "120s", attempts: 3, name: "kz-" + b.volume + "-s"}
v.S0 = kzCut(t, env, cfg, b, 0, total)
st := v.S0.Stats
ok1 := v.S0.Completed && st.LastCut != nil && st.LastCut.StagedChunks == 0 && st.LastCut.UploadedChunks == 0 &&
v.S0.Cut.HeadSegments == 0 && st.KnownZeroChunks > 0 && v.Fresh != ""
rep.step(t, 1, b.volume, ok1, fmt.Sprintf("s0 completed=%v wall_ms=%.0f staged=%d uploaded_chunks=%d head_segments=%d head_bytes=%d known_zero=%d/%d fresh_line=%t",
v.S0.Completed, v.S0.WallMs, kzLC(st).StagedChunks, kzLC(st).UploadedChunks, v.S0.Cut.HeadSegments, v.S0.Cut.HeadBytes, st.KnownZeroChunks, total, v.Fresh != ""))
// (2) mkfs + files + S1
if device {
v.Identity, v.Discard, v.Files = kzDeviceFiles(t, b, v.NQN, fs, run)
} else {
v.Files, v.Blocks = kzUserSpaceFiles(t, b, v.NQN, bytes)
}
v.Dirty1 = kzReadStats(t, b).DirtyChunks
v.S1 = kzCut(t, env, cfg, b, 1, total)
v.S1Name = cfg.name + "-1"
st = v.S1.Stats
touched := v.Dirty1
ok2 := v.S1.Completed && st.LastCut != nil && touched > 0 && st.LastCut.CandidateChunks <= touched &&
st.LastCut.StagedChunks <= touched && st.LastCut.UploadedBytes <= int64(touched)*kzChunkBytes && len(v.Files) > 0
rep.step(t, 2, b.volume, ok2, fmt.Sprintf("s1 completed=%v wall_ms=%.0f dirtied=%d candidates=%d staged=%d uploaded_bytes=%d head_bytes=%d files=%d discard=%q",
v.S1.Completed, v.S1.WallMs, touched, kzLC(st).CandidateChunks, kzLC(st).StagedChunks, kzLC(st).UploadedBytes, v.S1.Cut.HeadBytes, len(v.Files), v.Discard))
return v
}
// kzLC returns the last cut or a zero value, for printing only.
func kzLC(s kzStats) struct {
CandidateChunks, StagedChunks, UploadedChunks, ZeroedChunks, UnchangedChunks int
UploadedBytes int64
} {
if s.LastCut == nil {
return struct {
CandidateChunks, StagedChunks, UploadedChunks, ZeroedChunks, UnchangedChunks int
UploadedBytes int64
}{}
}
return *s.LastCut
}
func kzCut(t *testing.T, env *handoffEnv, cfg headSzConfig, b bvHost, n, total int) kzCutRecord {
t.Helper()
start := time.Now()
c := headSzCutOnce(t, env, cfg, b, n, 0)
return kzCutRecord{Cut: c, Stats: kzReadStats(t, b), Total: total, WallMs: ms(time.Since(start)), Completed: c.Completed}
}
// kzUserSpaceFiles writes three known 4 KiB blocks (the first, middle and last
// block of the volume, so three different chunks) through the user-space
// client and flushes (smoke only: no file system).
func kzUserSpaceFiles(t *testing.T, b bvHost, nqn string, bytes uint64) (map[string]string, map[uint64][]byte) {
t.Helper()
c := dialNVMe(t, b.nvme, nqn)
out, blocks := map[string]string{}, map[uint64][]byte{}
last := bytes/4096 - 1
for i, lba := range []uint64{0, last / 2, last} {
blk := f1Block(b.id, 0, "kz", lba)
_ = c.io.SetDeadline(time.Now().Add(60 * time.Second))
c.write(t, lba, blk)
blocks[lba] = blk
sum := sha256.Sum256(blk)
out[fmt.Sprintf("block-%d", i)] = hex.EncodeToString(sum[:])
}
_ = c.io.SetDeadline(time.Now().Add(60 * time.Second))
c.flush(t)
return out, blocks
}
// kzDeviceFiles connects this run's NQN through the kernel, resolves the
// device by NQN, formats it, writes files with known sha256, syncs, unmounts
// and disconnects. It returns the identity line, whether mkfs sent a discard
// and the files' sha256.
func kzDeviceFiles(t *testing.T, b bvHost, nqn, fs, run string) (string, string, map[string]string) {
t.Helper()
host, port := kzSplit(t, b.nvme)
kzSudo(t, "nvme", "connect", "-t", "tcp", "-n", nqn, "-a", host, "-s", port)
defer kzSudo(t, "nvme", "disconnect", "-n", nqn)
var dev kzDevice
poll(t, 30*time.Second, "kernel device for "+nqn+" never appeared", func() bool {
out, err := exec.Command("sudo", "-n", "nvme", "list-subsys", "-o", "json").Output()
if err != nil {
return false
}
d, err := kzResolve(out, nqn, "")
dev = d
return err == nil
})
t.Log(dev.Identity())
mkfs := map[string][]string{"ext4": {"mkfs.ext4", "-F", "-v"}, "xfs": {"mkfs.xfs", "-f"}}[fs]
if mkfs == nil {
t.Fatalf("KZ_FS %q: want ext4 or xfs", fs)
}
out := kzSudo(t, append(mkfs, dev.Path)...)
discard := "no"
if strings.Contains(strings.ToLower(out), "discard") {
discard = "yes: " + kzFirstLine(out, "iscard")
}
mnt := filepath.Join(os.TempDir(), "kz-"+run, b.volume)
if err := os.MkdirAll(mnt, 0o755); err != nil {
t.Fatal(err)
}
kzSudo(t, "mount", dev.Path, mnt)
files := map[string]string{}
func() {
defer kzSudo(t, "umount", mnt)
for i := 0; i < 4; i++ {
name := fmt.Sprintf("kz-%d.bin", i)
data := make([]byte, (i+1)*64*1024)
for j := range data {
data[j] = byte(i*31 + j%251)
}
kzSudoWrite(t, filepath.Join(mnt, name), data)
sum := sha256.Sum256(data)
files[name] = hex.EncodeToString(sum[:])
}
kzSudo(t, "sync")
}()
return dev.Identity(), discard, files
}
func kzSudo(t *testing.T, args ...string) string {
t.Helper()
out, err := exec.Command("sudo", append([]string{"-n"}, args...)...).CombinedOutput()
if err != nil {
t.Fatalf("sudo %s: %v: %s", strings.Join(args, " "), err, strings.TrimSpace(string(out)))
}
return string(out)
}
func kzSudoWrite(t *testing.T, path string, data []byte) {
t.Helper()
c := exec.Command("sudo", "-n", "tee", path)
c.Stdin = strings.NewReader(string(data))
if out, err := c.CombinedOutput(); err != nil && len(out) == 0 {
t.Fatalf("sudo tee %s: %v", path, err)
}
}
func kzSplit(t *testing.T, addr string) (string, string) {
t.Helper()
i := strings.LastIndex(addr, ":")
if i < 0 {
t.Fatalf("address %q has no port", addr)
}
return addr[:i], addr[i+1:]
}
func kzFirstLine(s, sub string) string {
for _, l := range strings.Split(s, "\n") {
if strings.Contains(l, sub) {
return strings.TrimSpace(l)
}
}
return ""
}
@@ -0,0 +1,178 @@
package main_test
import (
"encoding/json"
"fmt"
"sort"
"strings"
"testing"
)
// kzDevice is the only way the KNOWN-ZERO acceptance test gets a block
// device path. It reads `nvme list-subsys -o json` and returns /dev/<ns> only
// when exactly one subsystem has subsystem NQN == nqn (string equality, never a
// prefix), it has exactly one controller with transport tcp (and serial ==
// serial when serial is not empty), and exactly one namespace. mkfs and mount
// take its result; a path given by name alone is never formatted.
type kzDevice struct {
Path, Ctrl, NQN, Serial string
}
// Identity is the evidence line recorded before any mkfs.
func (d kzDevice) Identity() string {
s := d.Serial
if s == "" {
s = "-"
}
return fmt.Sprintf("DEVICE-IDENTITY nqn=%s serial=%s ctrl=%s transport=tcp namespace=%s match=exact", d.NQN, s, d.Ctrl, d.Path)
}
type kzNS struct {
NameSpace string `json:"NameSpace"`
}
type kzPath struct {
Name string `json:"Name"`
Transport string `json:"Transport"`
Serial string `json:"Serial"`
Namespaces []kzNS `json:"Namespaces"`
}
type kzSubsys struct {
NQN string `json:"NQN"`
Serial string `json:"Serial"`
Paths []kzPath `json:"Paths"`
Controllers []kzPath `json:"Controllers"`
Namespaces []kzNS `json:"Namespaces"`
}
type kzRoot struct {
Subsystems []kzSubsys `json:"Subsystems"`
}
// kzResolve parses one `nvme list-subsys -o json` document (nvme-cli 2.x
// prints a list of host roots, older versions one object).
func kzResolve(doc []byte, nqn, serial string) (kzDevice, error) {
if !strings.HasPrefix(nqn, "nqn.") {
return kzDevice{}, fmt.Errorf("refused: %q is not an NQN (a device path is never accepted)", nqn)
}
var roots []kzRoot
if err := json.Unmarshal(doc, &roots); err != nil {
var one kzRoot
if err2 := json.Unmarshal(doc, &one); err2 != nil {
return kzDevice{}, fmt.Errorf("refused: unreadable list-subsys: %v", err)
}
roots = []kzRoot{one}
}
var hits []kzSubsys
for _, r := range roots {
for _, s := range r.Subsystems {
if s.NQN == nqn {
hits = append(hits, s)
}
}
}
if len(hits) != 1 {
return kzDevice{}, fmt.Errorf("refused: %d subsystems with NQN == %s (want exactly 1)", len(hits), nqn)
}
s := hits[0]
paths := s.Paths
if len(paths) == 0 {
paths = s.Controllers
}
if len(paths) != 1 {
return kzDevice{}, fmt.Errorf("refused: subsystem %s has %d controllers (want exactly 1)", nqn, len(paths))
}
p := paths[0]
if p.Transport != "tcp" {
return kzDevice{}, fmt.Errorf("refused: controller %s transport %q (want tcp)", p.Name, p.Transport)
}
got := p.Serial
if got == "" {
got = s.Serial
}
if serial != "" && got != serial {
return kzDevice{}, fmt.Errorf("refused: controller %s serial %q != %q", p.Name, got, serial)
}
set := map[string]bool{}
for _, n := range append(append([]kzNS{}, s.Namespaces...), p.Namespaces...) {
if n.NameSpace != "" {
set[n.NameSpace] = true
}
}
if len(set) != 1 {
ns := make([]string, 0, len(set))
for n := range set {
ns = append(ns, n)
}
sort.Strings(ns)
return kzDevice{}, fmt.Errorf("refused: subsystem %s has %d namespaces %v (want exactly 1)", nqn, len(set), ns)
}
var dev string
for n := range set {
dev = "/dev/" + n
}
return kzDevice{Path: dev, Ctrl: p.Name, NQN: nqn, Serial: serial}, nil
}
func kzSubJSON(nqn, ctrl, transport, serial string, ns ...string) string {
var b strings.Builder
for i, n := range ns {
if i > 0 {
b.WriteString(",")
}
fmt.Fprintf(&b, `{"NameSpace":%q}`, n)
}
return fmt.Sprintf(`{"NQN":%q,"Serial":%q,"Paths":[{"Name":%q,"Transport":%q,"Serial":%q,"Namespaces":[%s]}]}`, nqn, serial, ctrl, transport, serial, b.String())
}
func kzDocJSON(subs ...string) []byte {
return []byte(`[{"HostNQN":"nqn.host","Subsystems":[` + strings.Join(subs, ",") + `]}]`)
}
// TestKnownZeroDeviceResolver: each refusal is the only check that can refuse
// its case (a real local disk, a longer or shorter NQN, duplicates, two
// namespaces, a wrong serial, a path instead of an NQN).
func TestKnownZeroDeviceResolver(t *testing.T) {
const ours = "nqn.2026-11.io.seaweedfs:kz-r1-v1"
real := kzSubJSON("nqn.2014.08.org.nvmexpress:uuid:real-disk", "nvme0", "pcie", "S1", "nvme0n1")
cases := []struct {
name, nqn, serial string
doc []byte
want, refusal string
}{
{"exact-single-match", ours, "", kzDocJSON(real, kzSubJSON(ours, "nvme1", "tcp", "SWB1", "nvme1n1")), "/dev/nvme1n1", ""},
{"serial-match", ours, "SWB1", kzDocJSON(real, kzSubJSON(ours, "nvme1", "tcp", "SWB1", "nvme1n1")), "/dev/nvme1n1", ""},
{"single-object-shape", ours, "", []byte(`{"Subsystems":[` + kzSubJSON(ours, "nvme1", "tcp", "SWB1", "nvme1n1") + `]}`), "/dev/nvme1n1", ""},
{"absent", ours, "", kzDocJSON(real), "", "0 subsystems"},
{"duplicate", ours, "", kzDocJSON(kzSubJSON(ours, "nvme1", "tcp", "A", "nvme1n1"), kzSubJSON(ours, "nvme2", "tcp", "B", "nvme2n1")), "", "2 subsystems"},
{"longer-nqn-not-ours", ours, "", kzDocJSON(kzSubJSON(ours+"-other", "nvme1", "tcp", "A", "nvme1n1")), "", "0 subsystems"},
{"shorter-nqn-not-ours", ours, "", kzDocJSON(kzSubJSON("nqn.2026-11.io.seaweedfs:kz-r1", "nvme1", "tcp", "A", "nvme1n1")), "", "0 subsystems"},
{"pcie-real-disk", ours, "", kzDocJSON(kzSubJSON(ours, "nvme0", "pcie", "A", "nvme0n1")), "", `transport "pcie"`},
{"two-namespaces", ours, "", kzDocJSON(kzSubJSON(ours, "nvme1", "tcp", "A", "nvme1n1", "nvme1n2")), "", "2 namespaces"},
{"wrong-serial", ours, "SWB9", kzDocJSON(kzSubJSON(ours, "nvme1", "tcp", "SWB1", "nvme1n1")), "", `serial "SWB1" != "SWB9"`},
{"literal-path", "/dev/nvme1n1", "", kzDocJSON(kzSubJSON(ours, "nvme1", "tcp", "A", "nvme1n1")), "", "is not an NQN"},
{"unreadable", ours, "", []byte("not json"), "", "unreadable"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
d, err := kzResolve(c.doc, c.nqn, c.serial)
if c.refusal != "" {
if err == nil || !strings.Contains(err.Error(), c.refusal) {
t.Fatalf("want refusal containing %q, got path %q err %v", c.refusal, d.Path, err)
}
return
}
if err != nil || d.Path != c.want {
t.Fatalf("want %s, got %q err %v", c.want, d.Path, err)
}
})
}
d, err := kzResolve(kzDocJSON(kzSubJSON(ours, "nvme1", "tcp", "SWB1", "nvme1n1")), ours, "SWB1")
if err != nil {
t.Fatal(err)
}
if got, want := d.Identity(), "DEVICE-IDENTITY nqn="+ours+" serial=SWB1 ctrl=nvme1 transport=tcp namespace=/dev/nvme1n1 match=exact"; got != want {
t.Fatalf("identity line\n got %s\nwant %s", got, want)
}
}
@@ -0,0 +1,41 @@
package main_test
import (
"os/exec"
"path/filepath"
"strings"
"testing"
)
// TestKZHoldNeverInReleaseBuild: the kzhold hold (a test-only stop before the
// fresh marker is retired) exists only in a binary built with -tags kzhold.
// A normal build of blockvolume must contain no symbol of it; the kzhold build
// must (the positive control: a check that finds nothing in either build would
// prove nothing).
func TestKZHoldNeverInReleaseBuild(t *testing.T) {
if testing.Short() {
t.Skip("builds blockvolume twice")
}
dir := t.TempDir()
syms := func(name string, tags ...string) string {
t.Helper()
out := filepath.Join(dir, name)
args := append([]string{"build"}, tags...)
args = append(args, "-o", out, "github.com/seaweedfs/seaweed-block/cmd/blockvolume")
if b, err := exec.Command("go", args...).CombinedOutput(); err != nil {
t.Fatalf("go %s: %v\n%s", strings.Join(args, " "), err, b)
}
b, err := exec.Command("go", "tool", "nm", out).CombinedOutput()
if err != nil {
t.Fatalf("go tool nm %s: %v\n%s", out, err, b)
}
return string(b)
}
const hold = "HoldBeforeChunkFreshRetireForTest"
if s := syms("release"); strings.Contains(s, hold) || strings.Contains(strings.ToLower(s), "kzhold") {
t.Fatalf("a normal build of blockvolume contains the test-only kzhold hold")
}
if s := syms("kzhold", "-tags", "kzhold"); !strings.Contains(s, hold) {
t.Fatalf("the kzhold build lacks %s: this check would pass blindly", hold)
}
}
+3
View File
@@ -754,6 +754,9 @@ func runVolume(f flags, exits *processExit) int {
err := geometryErr
if err == nil {
dp, err = durable.NewDurableProvider(cfg, h.ProjectionView())
if err == nil {
applyBuildTagHold(dp) // a no-op except in a kzhold (test-only) build
}
}
if chunkErr != nil {
err = chunkErr
@@ -403,14 +403,14 @@ func handoffAddress(t *testing.T) string {
if handoffPorts.used[p] {
continue
}
addr := fmt.Sprintf("127.0.0.1:%d", p)
addr := fmt.Sprintf("%s:%d", testListenHost(), p)
if ln, err := net.Listen("tcp", addr); err == nil {
ln.Close()
handoffPorts.used[p] = true
return addr
}
}
t.Fatal("no free loopback port below the ephemeral range")
t.Fatal("no free port below the ephemeral range on " + testListenHost())
return ""
}
@@ -24,6 +24,17 @@ type w4WeedCluster struct {
procs map[string]*w4WeedProc
}
// testListenHost is the address the test harness binds and advertises for
// its weed cluster, blockmaster and blockvolume ports: 127.0.0.1 unless
// SWBLOCK_TEST_LISTEN_HOST names another (a lab run whose processes span two
// hosts). Unset, every test behaves exactly as before.
func testListenHost() string {
if h := os.Getenv("SWBLOCK_TEST_LISTEN_HOST"); h != "" {
return h
}
return "127.0.0.1"
}
func w4FreePortPair(t *testing.T, used map[int]bool) int {
t.Helper()
for i := 0; i < 200; i++ {
@@ -33,7 +44,7 @@ func w4FreePortPair(t *testing.T, used map[int]bool) int {
}
ok := true
for _, q := range []int{p, p + 10000} {
l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", q))
l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", testListenHost(), q))
if err != nil {
ok = false
break
@@ -92,9 +103,9 @@ func startWorkspaceWeedWith(t *testing.T, dir string, o w4WeedOpts) *w4WeedClust
used := map[int]bool{}
mp, vp, fp := w4FreePortPair(t, used), w4FreePortPair(t, used), w4FreePortPair(t, used)
c := &w4WeedCluster{
master: fmt.Sprintf("127.0.0.1:%d", mp),
filerHTTP: fmt.Sprintf("127.0.0.1:%d", fp),
filerGRPC: fmt.Sprintf("127.0.0.1:%d", fp+10000),
master: fmt.Sprintf("%s:%d", testListenHost(), mp),
filerHTTP: fmt.Sprintf("%s:%d", testListenHost(), fp),
filerGRPC: fmt.Sprintf("%s:%d", testListenHost(), fp+10000),
dir: dir,
weed: weed,
}
@@ -121,10 +132,10 @@ func startWorkspaceWeedWith(t *testing.T, dir string, o w4WeedOpts) *w4WeedClust
t.Fatal(err)
}
}
run("master", "master", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", mp), "-mdir="+filepath.Join(dir, "m"), fmt.Sprintf("-volumeSizeLimitMB=%d", o.VolumeSizeLimitMB), "-defaultReplication=000")
run("master", "master", "-ip="+testListenHost(), fmt.Sprintf("-port=%d", mp), "-mdir="+filepath.Join(dir, "m"), fmt.Sprintf("-volumeSizeLimitMB=%d", o.VolumeSizeLimitMB), "-defaultReplication=000")
w4WaitTCP(t, c.master, 20*time.Second)
run("volume", "volume", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", vp), "-dir="+filepath.Join(dir, "v"), "-master="+c.master, fmt.Sprintf("-max=%d", o.VolumeMax))
run("filer", "filer", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", fp), "-master="+c.master, "-defaultStoreDir="+filepath.Join(dir, "f"))
run("volume", "volume", "-ip="+testListenHost(), fmt.Sprintf("-port=%d", vp), "-dir="+filepath.Join(dir, "v"), "-master="+c.master, fmt.Sprintf("-max=%d", o.VolumeMax))
run("filer", "filer", "-ip="+testListenHost(), fmt.Sprintf("-port=%d", fp), "-master="+c.master, "-defaultStoreDir="+filepath.Join(dir, "f"))
w4WaitTCP(t, c.filerGRPC, 30*time.Second)
// Wait until an assign succeeds (volume registered, volumes growable).
@@ -0,0 +1,30 @@
//go:build kzhold
package durable
import (
"fmt"
"os"
"time"
)
// HoldBeforeChunkFreshRetireForTest exists only in a binary built with the
// kzhold tag, which is never released. At the attach's boundary after
// presence and before the fresh marker is retired (the attach commit), the
// provider writes reached and then waits until release exists (at most ten
// minutes), so a test can stop the process at that exact point.
func (p *DurableProvider) HoldBeforeChunkFreshRetireForTest(reached, release string) {
p.testBeforeChunkFreshRetire = func() error {
if err := os.WriteFile(reached, []byte(time.Now().UTC().Format(time.RFC3339Nano)+"\n"), 0o644); err != nil {
return fmt.Errorf("kzhold: write %s: %w", reached, err)
}
end := time.Now().Add(10 * time.Minute)
for time.Now().Before(end) {
if _, err := os.Stat(release); err == nil {
return nil
}
time.Sleep(20 * time.Millisecond)
}
return fmt.Errorf("kzhold: %s never appeared", release)
}
}