Compare commits

..
Author SHA1 Message Date
Chris LuandClaude Opus 5.5 c624372936 seaweed-block: scope the manual's lifecycle exit policy to the stores it covers
Only the node, placement and volume stores have the fail-stop handler.
State that deletion-reservation and workspace-binding write failures
return the error without exiting, and that an uncertain binding store
needs a restart.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 09:17:44 -08:00
Chris LuandClaude Opus 5.5 fc4c4ae546 seaweed-block: add the lifecycle machine's transition table
Every other Part A machine lists its transitions with guard, enforcing
code and Part B rows; the lifecycle record I/O machine had only its
diagram. Also name DeletePlacement and DeleteVolume beside RemoveNode in
the open gap: none of them syncs the directory after removing a record.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 09:17:43 -08:00
Chris LuandClaude Opus 5.5 41eab1edb6 seaweed-block: assert the one-second fail-stop bound
The blocked-logger control checked only exit status 1 inside a four-second
child timeout, so a longer exit timer still passed. The child now reports
when it triggers the failure, and the parent requires exit within the
one-second deadline plus one second of scheduler tolerance.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 09:16:13 -08:00
Chris LuandClaude Opus 5.5 83545dc103 seaweed-block: check both views after a removal retry
present() returned record && snapshot, so a removal that cleared only one
view passed the final check. Report both and require both absent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 09:15:38 -08:00
Chris LuandClaude Opus 5.5 16e8cce859 seaweed-block: assert the imported values before the reopen check
The import step control compared the store's snapshot with a reopen, so
an import that synced and renamed but committed the old values passed.
Check the changed and unchanged values before and after reopen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 09:15:37 -08:00
Chris LuandClaude Opus 5.5 a2b8926092 seaweed-block: use the import syncfs only on filesystems that report its errors
The batch path was chosen from the kernel release alone. On overlayfs,
syncfs checks the overlay superblock's writeback errors, not the upper
file's, and on FUSE it does not send FSYNC to the daemon, so an import
could publish records whose data never became durable. Select syncfs
only when the records directory is on ext4, xfs, btrfs or tmpfs, and keep
per-file fsync elsewhere. The startup line now reports the path for the
lifecycle store, after it exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 09:15:13 -08:00
Chris LuandClaude Opus 5.5 5491d95f40 seaweed-block: keep a node's SeenAt when its declaration changes
registrationLocked kept SeenAt only for an unchanged declaration. A
restart that changed a node's declared pools or address stamped the
current time, so a silent node passed the stale-observation check. A
declaration without an observation time now keeps the stored one; a new
node still gets the current time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 09:13:55 -08:00
Chris LuandClaude Opus 5.5 55f0ea1439 seaweed-block: poison a lifecycle store only on a persistence error
A node registration whose SeenAt cannot be encoded failed before any file
I/O, but RegisterNode latched the marshal error and every later mutation
returned ErrLifecycleRecoveryRequired until reopen. Latch only a
RecordPersistenceError, as the volume store already did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 09:13:22 -08:00
Chris LuandClaude Opus 5.5 30710c46a6 seaweed-block: name the import path in the freshness row and registry guard
Startup now replays nodes through ImportNodes, not RegisterNode; list it
where the freshness invariant and the registry-writer guard name the
writers. Drop a doubled blank line in the operations manual.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 07:36:13 -08:00
Chris LuandClaude Opus 5.5 f6588ff84c seaweed-block: name the rejected entry in a startup import error
The batch import returned the bare validation error, so a bad cluster-spec
node or placement seed stopped startup without saying which entry. The
per-entry RegisterNode/ApplyPlan loop named it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 07:35:55 -08:00
pingqiu 5f4e92da5c seaweed-block: preserve unchanged imports and batch durable publication 2026-12-05 07:05:00 -08:00
46 changed files with 2619 additions and 1054 deletions

No files matched your search

@@ -0,0 +1,91 @@
package main
import (
"context"
"fmt"
"os"
"path/filepath"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/host/master"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
)
// Re-importing the same declarative spec must preserve the durable records,
// including the registration observation time. This checks replacement, not
// just equal JSON: an identical rewrite still pays the durability barriers.
func TestUnchangedSpecRestartKeepsAll999ImportRecords(t *testing.T) {
const count = 999
authorityDir, lifecycleDir := t.TempDir(), t.TempDir()
open := func() *master.Host {
t.Helper()
h, err := master.New(master.Config{Listen: "127.0.0.1:0", AuthorityStoreDir: authorityDir, LifecycleStoreDir: lifecycleDir})
if err != nil {
t.Fatal(err)
}
return h
}
closeHost := func(h *master.Host) {
t.Helper()
h.Start()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := h.Close(ctx); err != nil {
t.Fatal(err)
}
}
nodes := make([]lifecycle.NodeRegistration, count)
intents := make([]lifecycle.PlacementIntent, count)
for i := range nodes {
id := fmt.Sprintf("n%04d", i)
nodes[i] = lifecycle.NodeRegistration{ServerID: id, Addr: "127.0.0.1:19001"}
intents[i] = lifecycle.PlacementIntent{VolumeID: fmt.Sprintf("v%04d", i), DesiredRF: 1, Slots: []lifecycle.PlacementSlotIntent{{ServerID: id, ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}
}
importSpec := func(h *master.Host) {
t.Helper()
if err := importLifecycleNodeInventory(h, nodes); err != nil {
t.Fatal(err)
}
if err := importLifecyclePlacementIntents(h, intents); err != nil {
t.Fatal(err)
}
}
h := open()
importSpec(h)
closeHost(h)
before := make(map[string]os.FileInfo, 2*count)
for _, kind := range []string{"nodes", "placements"} {
entries, err := os.ReadDir(filepath.Join(lifecycleDir, kind))
if err != nil {
t.Fatal(err)
}
if len(entries) != count {
t.Fatalf("%s records=%d, want %d", kind, len(entries), count)
}
for _, entry := range entries {
path := filepath.Join(lifecycleDir, kind, entry.Name())
info, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
before[path] = info
}
}
h = open()
importSpec(h)
closeHost(h)
rewritten := map[string]int{}
for path, info := range before {
after, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
if !os.SameFile(info, after) || !info.ModTime().Equal(after.ModTime()) {
rewritten[filepath.Base(filepath.Dir(path))]++
}
}
if rewritten["nodes"] != 0 || rewritten["placements"] != 0 {
t.Fatalf("unchanged restart replaced records: nodes=%d placements=%d; want zero", rewritten["nodes"], rewritten["placements"])
}
}
+9 -7
View File
@@ -274,6 +274,7 @@ func run(f flags) int {
fmt.Fprintln(os.Stderr, "blockmaster: dynamic lifecycle topology enabled by cluster-spec node inventory; assignments will be derived from verified placement intents")
}
cfg := master.Config{
FailStopLifecycleWrites: true,
EphemeralLauncherState: (f.launcherManifestDir != "" || f.launcherKubernetesApply) && f.launcherStateHostPath == "",
AuthorityStoreDir: f.authorityStore,
LifecycleStoreDir: f.lifecycleStore,
@@ -339,6 +340,7 @@ func run(f flags) int {
fmt.Fprintln(os.Stderr, "blockmaster:", err)
return 1
}
fmt.Fprintf(os.Stderr, "blockmaster: lifecycle import durability: %s\n", lifecycle.ImportDurabilityMode(f.lifecycleStore))
// Every promotion decides on the probe round's answers: each candidate
// answers a fresh round over its authenticated node stream.
h.SetPromotionEvidenceProvider(h.NewRoundPromotionEvidenceProvider(f.launcherReplicationAck, nil))
@@ -478,10 +480,8 @@ func importLifecycleNodeInventory(h *master.Host, nodes []lifecycle.NodeRegistra
if stores == nil {
return fmt.Errorf("lifecycle node import requires --lifecycle-store")
}
for _, node := range nodes {
if _, err := stores.Nodes.RegisterNode(node); err != nil {
return fmt.Errorf("register lifecycle node %s: %w", node.ServerID, err)
}
if err := stores.Nodes.ImportNodes(nodes); err != nil {
return fmt.Errorf("import lifecycle nodes: %w", err)
}
return nil
}
@@ -510,6 +510,7 @@ func importLifecyclePlacementIntents(h *master.Host, intents []lifecycle.Placeme
if stores == nil {
return fmt.Errorf("lifecycle placement import requires --lifecycle-store")
}
plans := make([]lifecycle.PlacementPlan, 0, len(intents))
for _, intent := range intents {
if stores.Deletions.Reserved(intent.VolumeID) {
continue // never placed again (see importLifecycleVolumes)
@@ -528,9 +529,10 @@ func importLifecyclePlacementIntents(h *master.Host, intents []lifecycle.Placeme
Source: slot.Source,
})
}
if _, err := stores.Placements.ApplyPlan(plan); err != nil {
return fmt.Errorf("apply lifecycle placement seed %s: %w", intent.VolumeID, err)
}
plans = append(plans, plan)
}
if err := stores.Placements.ImportPlans(plans); err != nil {
return fmt.Errorf("import lifecycle placement seeds: %w", err)
}
return nil
}
@@ -19,7 +19,7 @@ import (
// only a host that holds no volume: a retired id is then unregistered, so a
// holder RPC under it is refused (refuseWorkspaceHolderHost) and the checks
// only get stricter. This guard fails when any other non-test caller of
// RegisterNode or RemoveNode appears anywhere.
// RegisterNode, ImportNodes or RemoveNode appears anywhere.
func TestNodeRegistryIsWrittenOnlyAtStartup(t *testing.T) {
root, err := filepath.Abs(filepath.Join("..", ".."))
if err != nil {
@@ -56,7 +56,7 @@ func TestNodeRegistryIsWrittenOnlyAtStartup(t *testing.T) {
if !ok {
return true
}
if sel, ok := call.Fun.(*ast.SelectorExpr); ok && (sel.Sel.Name == "RegisterNode" || sel.Sel.Name == "RemoveNode") {
if sel, ok := call.Fun.(*ast.SelectorExpr); ok && (sel.Sel.Name == "RegisterNode" || sel.Sel.Name == "ImportNodes" || sel.Sel.Name == "RemoveNode") {
sites = append(sites, filepath.ToSlash(rel)+":"+fn.Name.Name+"."+sel.Sel.Name)
}
return true
@@ -68,7 +68,7 @@ func TestNodeRegistryIsWrittenOnlyAtStartup(t *testing.T) {
t.Fatal(err)
}
sort.Strings(sites)
want := []string{"cmd/blockmaster/main.go:importLifecycleNodeInventory.RegisterNode", "core/host/master/format_gate.go:RetireHost.RemoveNode"}
want := []string{"cmd/blockmaster/main.go:importLifecycleNodeInventory.ImportNodes", "core/host/master/format_gate.go:RetireHost.RemoveNode"}
if strings.Join(sites, ",") != strings.Join(want, ",") {
t.Fatalf("node registry writers = %v, want only %v: an adder after start, or another remover, breaks the identity checks' assumption", sites, want)
}
@@ -0,0 +1,112 @@
//go:build linux
package main
import (
"context"
"encoding/json"
"errors"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/host/master"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
)
func TestMasterImportPersistenceFailureExitsAndRecovers(t *testing.T) {
root := t.TempDir()
nodeDir := filepath.Join(root, "lifecycle", "nodes")
store, err := lifecycle.OpenNodeInventoryStore(nodeDir)
if err != nil {
t.Fatal(err)
}
old := lifecycle.NodeRegistration{ServerID: "kept", Addr: "127.0.0.1:19001"}
old, err = store.RegisterNode(old)
if err != nil {
t.Fatal(err)
}
// A real rename failure, even as root; the preceding committed record
// stays untouched. Directories are not parsed as JSON records on reload.
block := filepath.Join(nodeDir, "new.json")
if err := os.Mkdir(block, 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(block, "blocker"), []byte("fixture"), 0600); err != nil {
t.Fatal(err)
}
spec := filepath.Join(root, "spec.yaml")
if err := os.WriteFile(spec, []byte("nodes:\n - server_id: new\n addr: 127.0.0.1:19002\n"), 0600); err != nil {
t.Fatal(err)
}
args := []string{"--listen", "127.0.0.1:0", "--authority-store", filepath.Join(root, "authority"), "--lifecycle-store", filepath.Join(root, "lifecycle"), "--cluster-spec", spec}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestGuardHelperProcess$", "-test.timeout=8s")
cmd.Env = append(os.Environ(), guardHelperEnv+"="+strings.Join(args, guardHelperSep))
out, runErr := cmd.CombinedOutput()
var exit *exec.ExitError
if ctx.Err() != nil || !errors.As(runErr, &exit) || exit.ExitCode() != 1 {
t.Fatalf("master did not fail-stop with exit1: %v context=%v\n%s", runErr, ctx.Err(), out)
}
text := string(out)
if strings.Count(text, "exiting so the supervisor restarts from durable state") != 1 || !strings.Contains(text, "ERROR") || !strings.Contains(text, "new.json") || !strings.Contains(text, nodeDir) {
t.Fatalf("missing single persistence ERROR: %s", text)
}
oldRaw, err := json.Marshal(old)
if err != nil {
t.Fatal(err)
}
recovery := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestMasterImportPersistenceRecoveryChild$", "-test.timeout=8s")
recovery.Env = append(os.Environ(), "MASTER_RECOVERY_ROOT="+root, "MASTER_RECOVERY_OLD="+string(oldRaw))
if out, err := recovery.CombinedOutput(); err != nil {
t.Fatalf("bounded recovery: %v context=%v\n%s", err, ctx.Err(), out)
}
}
func TestMasterImportPersistenceRecoveryChild(t *testing.T) {
root := os.Getenv("MASTER_RECOVERY_ROOT")
if root == "" {
t.Skip("bounded recovery subprocess")
}
nodeDir := filepath.Join(root, "lifecycle", "nodes")
var old lifecycle.NodeRegistration
if err := json.Unmarshal([]byte(os.Getenv("MASTER_RECOVERY_OLD")), &old); err != nil {
t.Fatal(err)
}
// A new master must load the complete committed record, not a speculative
// new registration or partial JSON from the failed write.
h, err := master.New(master.Config{Listen: "127.0.0.1:0", AuthorityStoreDir: filepath.Join(root, "authority"), LifecycleStoreDir: filepath.Join(root, "lifecycle")})
if err != nil {
t.Fatal(err)
}
h.Start()
t.Cleanup(func() {
closeCtx, stop := context.WithTimeout(context.Background(), 5*time.Second)
defer stop()
if err := h.Close(closeCtx); err != nil {
t.Error(err)
}
})
if got, ok := h.Lifecycle().Nodes.GetNodeSnapshot("kept"); !ok || got.ServerID != old.ServerID || got.Addr != old.Addr || !got.SeenAt.Equal(old.SeenAt) {
t.Fatalf("committed record lost on restart: %+v %v", got, ok)
}
if _, ok := h.Lifecycle().Nodes.GetNodeSnapshot("new"); ok {
t.Fatal("failed record appeared on restart")
}
entries, err := os.ReadDir(nodeDir)
if err != nil {
t.Fatal(err)
}
for _, entry := range entries {
if !entry.IsDir() && strings.HasSuffix(entry.Name(), ".json") {
raw, err := os.ReadFile(filepath.Join(nodeDir, entry.Name()))
if err != nil || !json.Valid(raw) {
t.Fatalf("partial record %s: %v", entry.Name(), err)
}
}
}
}
@@ -0,0 +1,111 @@
//go:build linux && subprocess && chunkstore_integration
package main_test
import (
"context"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc"
)
// A master restart must not replace live holders while rebuilding its
// heartbeat view. Registration time is deliberately older than the window;
// only the new process's received heartbeats make its node evidence fresh.
func TestMasterImportRestartKeepsLiveHoldersAcrossFreshnessWindow(t *testing.T) {
const window = 6 * time.Second
env := startHandoffEnvVolumes(t, 1, []string{"v2"}, "--freshness-window", window.String(), "--lifecycle-product-loop-interval", "100ms")
env.volExtra = append(env.volExtra, "--heartbeat-interval", "250ms")
for id, volume := range map[string]string{"s1": "v1", "n-v2": "v2"} {
host := env.hosts[id]
host.volume, host.replica = volume, "r1"
env.hosts[id] = host
}
first, second := f1Up(t, env, "s1"), f1Up(t, env, "n-v2")
epochs := map[string]uint64{}
for volume, holder := range map[string]*daemon{"v1": first, "v2": second} {
epoch, err := adoptedEpochOf(volume, holder.line("blockvolume: volume "+volume+" adopted as PRIMARY at r1@"))
if err != nil {
t.Fatal(err)
}
epochs[volume] = epoch
}
// Both durable registrations now age beyond freshness while holders keep
// reporting; a restart must not renew these durable observation times.
time.Sleep(window + 100*time.Millisecond)
env.masterProcess.term(t, 10*time.Second)
started := time.Now()
env.masterProcess = env.h.start(t, "blockmaster-import-restarted", env.h.master, env.masterArgs...)
conn, err := grpc.NewClient(env.h.masterAddr, env.masterDialOption(t, "admin"))
if err != nil {
t.Fatal(err)
}
defer conn.Close()
client := control.NewClusterEvidenceServiceClient(conn)
fresh := map[string]bool{}
verified := map[string]bool{}
observed := map[string]bool{}
samples := 0
for time.Since(started) < window {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
status, err := client.GetClusterStatus(ctx, &control.GetClusterStatusRequest{})
cancel()
if err == nil {
samples++
for _, node := range status.Nodes {
if at := node.GetLastHeartbeatAt(); at != nil && at.AsTime().After(started) {
fresh[node.GetNodeName()] = true
}
}
for _, volume := range status.Volumes {
if epoch, ok := epochs[volume.VolumeId]; ok && volume.Epoch != 0 {
observed[volume.VolumeId] = true
if volume.Epoch != epoch {
t.Fatalf("%s changed epoch after restart: %d -> %d", volume.VolumeId, epoch, volume.Epoch)
}
}
}
for _, event := range status.Events {
if event.EventType == "placement_verified" {
verified[event.VolumeId] = true
}
}
}
for _, bad := range []string{"primary lost:", "decision=replace("} {
if env.masterProcess.has(bad) {
t.Fatalf("live-holder restart made a loss/replacement decision: %s", bad)
}
}
for id, d := range map[string]*daemon{"s1": first, "n-v2": second} {
select {
case <-d.done:
t.Fatalf("live holder %s exited during master restart: %v", id, d.err)
default:
}
}
time.Sleep(100 * time.Millisecond)
}
if samples == 0 {
t.Fatal("no successful status sample in the freshness window")
}
for _, id := range []string{"s1", "n-v2"} {
if !fresh[id] {
t.Fatalf("live node %s never became fresh after restart", id)
}
}
for id := range epochs {
if !observed[id] {
t.Fatalf("volume %s never showed its authoritative epoch again", id)
}
if !verified[id] {
t.Fatalf("placement %s did not verify again within one window", id)
}
}
for _, id := range []string{"s1", "n-v2"} {
block := pattern("restart-live-io!")
env.writeBlock(t, id, 0, block)
}
t.Logf("master restart: %d status samples, both nodes fresh, both placements verified, no loss/replacement or holder exit within %s", samples, window)
}
@@ -31,9 +31,6 @@ type BCatalog struct {
base string
cleanMu sync.Mutex
cursors map[VolumeRef]*cleanCursor
// chunkGuard: the startup probe saw the filer refuse a mismatched
// IF_CHUNKS_EQUAL update; every store it opens sends the condition.
chunkGuard bool
}
// NewBCatalog returns the catalog of the volumes under base.
@@ -52,25 +49,9 @@ func (c *BCatalog) Store(v VolumeRef) (*LayoutStore, error) {
}
counts, _ := c.headWrites.LoadOrStore(v.Dir(), s.headWrites)
s.headWrites = counts.(*headWriteCounters)
s.chunkGuard = c.chunkGuard
return s, nil
}
// Metadata change protections, as /status and the startup log name them.
const (
MetadataGuardChunks = "filer_chunk_condition" // IF_CHUNKS_EQUAL enforced; the page re-read stays as well
MetadataGuardReread = "page_reread_only" // the filer ignores the condition; the re-read is the only check
)
// MetadataGuard names the protection this catalog's metadata changes run
// under, decided once by the startup probe.
func (c *BCatalog) MetadataGuard() string {
if c.chunkGuard {
return MetadataGuardChunks
}
return MetadataGuardReread
}
func (c *BCatalog) open(v VolumeRef) (*LayoutStore, *layout.Reader, error) {
s, err := c.Store(v)
if err != nil {
@@ -362,10 +343,6 @@ type Usage struct {
Dependents int `json:"dependents"`
OwnChunks int `json:"own_chunks"`
ForeignChunks int `json:"foreign_chunks"`
// MetadataGuard names the protection of the volume's metadata changes:
// filer_chunk_condition (the filer enforces the chunk condition) or
// page_reread_only (it does not; delete intent pages are re-read).
MetadataGuard string `json:"metadata_guard"`
}
// Usage reads the volume's usage from its HEAD and current root.
@@ -381,7 +358,7 @@ func (c *BCatalog) Usage(ctx context.Context, v VolumeRef) (Usage, error) {
if !found {
return Usage{}, layout.ErrHeadAbsent
}
u := Usage{Snapshots: len(h.Snapshots), MetadataGuard: c.MetadataGuard()}
u := Usage{Snapshots: len(h.Snapshots)}
for _, sn := range h.Snapshots {
u.Dependents += len(sn.Dependents)
}
@@ -64,9 +64,6 @@ type fakeFiler struct {
// (lookups overlap) and bounded by ctx, as a remote filer's.
slowLookup func(p string) time.Duration
deferredCreates []deferredCreate
// ignoreChunkCondition makes UpdateEntryIfChunks ignore its condition,
// as a filer that predates IF_CHUNKS_EQUAL drops the unknown field.
ignoreChunkCondition bool
}
func newFakeFiler() *fakeFiler { return &fakeFiler{entries: map[string]*filerpb.Entry{}} }
@@ -140,19 +137,6 @@ func (f *fakeFiler) CreateEntry(ctx context.Context, dir string, e *filerpb.Entr
}
func (f *fakeFiler) UpdateEntry(_ context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
return f.updateEntry(dir, e, expected, nil)
}
// UpdateEntryIfChunks evaluates IF_CHUNKS_EQUAL as the filer does (stored
// chunk fids equal fids as a multiset), unless ignoreChunkCondition.
func (f *fakeFiler) UpdateEntryIfChunks(_ context.Context, dir string, e *filerpb.Entry, expected map[string][]byte, fids []string) error {
if fids == nil {
fids = []string{}
}
return f.updateEntry(dir, e, expected, fids)
}
func (f *fakeFiler) updateEntry(dir string, e *filerpb.Entry, expected map[string][]byte, fids []string) error {
f.mu.Lock()
defer f.mu.Unlock()
p := path.Join(dir, e.Name)
@@ -171,9 +155,6 @@ func (f *fakeFiler) updateEntry(dir string, e *filerpb.Entry, expected map[strin
return fmt.Errorf("%w: extended %q changed", ErrPrecondition, k)
}
}
if fids != nil && !f.ignoreChunkCondition && !fidsEqual(entryFids(cur), fids) {
return fmt.Errorf("%w: chunks of %s changed", ErrPrecondition, p)
}
f.entries[p] = proto.Clone(e).(*filerpb.Entry)
f.written = append(f.written, proto.Clone(e).(*filerpb.Entry))
f.updates++
@@ -97,52 +97,6 @@ func (FilerError) EnumDescriptor() ([]byte, []int) {
return file_filer_subset_proto_rawDescGZIP(), []int{0}
}
type WriteCondition_Kind int32
const (
WriteCondition_NONE WriteCondition_Kind = 0
WriteCondition_IF_CHUNKS_EQUAL WriteCondition_Kind = 9 // fail unless the stored chunk fid multiset equals fids (absent entry = no chunks)
)
// Enum value maps for WriteCondition_Kind.
var (
WriteCondition_Kind_name = map[int32]string{
0: "NONE",
9: "IF_CHUNKS_EQUAL",
}
WriteCondition_Kind_value = map[string]int32{
"NONE": 0,
"IF_CHUNKS_EQUAL": 9,
}
)
func (x WriteCondition_Kind) Enum() *WriteCondition_Kind {
p := new(WriteCondition_Kind)
*p = x
return p
}
func (x WriteCondition_Kind) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (WriteCondition_Kind) Descriptor() protoreflect.EnumDescriptor {
return file_filer_subset_proto_enumTypes[1].Descriptor()
}
func (WriteCondition_Kind) Type() protoreflect.EnumType {
return &file_filer_subset_proto_enumTypes[1]
}
func (x WriteCondition_Kind) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use WriteCondition_Kind.Descriptor instead.
func (WriteCondition_Kind) EnumDescriptor() ([]byte, []int) {
return file_filer_subset_proto_rawDescGZIP(), []int{9, 0}
}
type LookupDirectoryEntryRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Directory string `protobuf:"bytes,1,opt,name=directory,proto3" json:"directory,omitempty"`
@@ -757,54 +711,6 @@ func (x *CreateEntryResponse) GetErrorCode() FilerError {
return FilerError_OK
}
// WriteCondition is copied from weed/pb/filer.proto (this repository): the
// IF_CHUNKS_EQUAL clause only. A filer that predates it drops field 6 of
// UpdateEntryRequest as unknown and applies the write unguarded, so the
// chunkstore decides at startup, by a probe, whether it is enforced.
type WriteCondition struct {
state protoimpl.MessageState `protogen:"open.v1"`
Clauses []*WriteCondition_Clause `protobuf:"bytes,1,rep,name=clauses,proto3" json:"clauses,omitempty"` // all must hold (logical AND)
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *WriteCondition) Reset() {
*x = WriteCondition{}
mi := &file_filer_subset_proto_msgTypes[9]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *WriteCondition) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*WriteCondition) ProtoMessage() {}
func (x *WriteCondition) ProtoReflect() protoreflect.Message {
mi := &file_filer_subset_proto_msgTypes[9]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use WriteCondition.ProtoReflect.Descriptor instead.
func (*WriteCondition) Descriptor() ([]byte, []int) {
return file_filer_subset_proto_rawDescGZIP(), []int{9}
}
func (x *WriteCondition) GetClauses() []*WriteCondition_Clause {
if x != nil {
return x.Clauses
}
return nil
}
type UpdateEntryRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Directory string `protobuf:"bytes,1,opt,name=directory,proto3" json:"directory,omitempty"`
@@ -812,14 +718,13 @@ type UpdateEntryRequest struct {
IsFromOtherCluster bool `protobuf:"varint,3,opt,name=is_from_other_cluster,json=isFromOtherCluster,proto3" json:"is_from_other_cluster,omitempty"`
Signatures []int32 `protobuf:"varint,4,rep,packed,name=signatures,proto3" json:"signatures,omitempty"`
ExpectedExtended map[string][]byte `protobuf:"bytes,5,rep,name=expected_extended,json=expectedExtended,proto3" json:"expected_extended,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
Condition *WriteCondition `protobuf:"bytes,6,opt,name=condition,proto3" json:"condition,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *UpdateEntryRequest) Reset() {
*x = UpdateEntryRequest{}
mi := &file_filer_subset_proto_msgTypes[10]
mi := &file_filer_subset_proto_msgTypes[9]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -831,7 +736,7 @@ func (x *UpdateEntryRequest) String() string {
func (*UpdateEntryRequest) ProtoMessage() {}
func (x *UpdateEntryRequest) ProtoReflect() protoreflect.Message {
mi := &file_filer_subset_proto_msgTypes[10]
mi := &file_filer_subset_proto_msgTypes[9]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -844,7 +749,7 @@ func (x *UpdateEntryRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use UpdateEntryRequest.ProtoReflect.Descriptor instead.
func (*UpdateEntryRequest) Descriptor() ([]byte, []int) {
return file_filer_subset_proto_rawDescGZIP(), []int{10}
return file_filer_subset_proto_rawDescGZIP(), []int{9}
}
func (x *UpdateEntryRequest) GetDirectory() string {
@@ -882,13 +787,6 @@ func (x *UpdateEntryRequest) GetExpectedExtended() map[string][]byte {
return nil
}
func (x *UpdateEntryRequest) GetCondition() *WriteCondition {
if x != nil {
return x.Condition
}
return nil
}
type UpdateEntryResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
@@ -897,7 +795,7 @@ type UpdateEntryResponse struct {
func (x *UpdateEntryResponse) Reset() {
*x = UpdateEntryResponse{}
mi := &file_filer_subset_proto_msgTypes[11]
mi := &file_filer_subset_proto_msgTypes[10]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -909,7 +807,7 @@ func (x *UpdateEntryResponse) String() string {
func (*UpdateEntryResponse) ProtoMessage() {}
func (x *UpdateEntryResponse) ProtoReflect() protoreflect.Message {
mi := &file_filer_subset_proto_msgTypes[11]
mi := &file_filer_subset_proto_msgTypes[10]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -922,7 +820,7 @@ func (x *UpdateEntryResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use UpdateEntryResponse.ProtoReflect.Descriptor instead.
func (*UpdateEntryResponse) Descriptor() ([]byte, []int) {
return file_filer_subset_proto_rawDescGZIP(), []int{11}
return file_filer_subset_proto_rawDescGZIP(), []int{10}
}
type DeleteEntryRequest struct {
@@ -938,7 +836,7 @@ type DeleteEntryRequest struct {
func (x *DeleteEntryRequest) Reset() {
*x = DeleteEntryRequest{}
mi := &file_filer_subset_proto_msgTypes[12]
mi := &file_filer_subset_proto_msgTypes[11]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -950,7 +848,7 @@ func (x *DeleteEntryRequest) String() string {
func (*DeleteEntryRequest) ProtoMessage() {}
func (x *DeleteEntryRequest) ProtoReflect() protoreflect.Message {
mi := &file_filer_subset_proto_msgTypes[12]
mi := &file_filer_subset_proto_msgTypes[11]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -963,7 +861,7 @@ func (x *DeleteEntryRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use DeleteEntryRequest.ProtoReflect.Descriptor instead.
func (*DeleteEntryRequest) Descriptor() ([]byte, []int) {
return file_filer_subset_proto_rawDescGZIP(), []int{12}
return file_filer_subset_proto_rawDescGZIP(), []int{11}
}
func (x *DeleteEntryRequest) GetDirectory() string {
@@ -1010,7 +908,7 @@ type DeleteEntryResponse struct {
func (x *DeleteEntryResponse) Reset() {
*x = DeleteEntryResponse{}
mi := &file_filer_subset_proto_msgTypes[13]
mi := &file_filer_subset_proto_msgTypes[12]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1022,7 +920,7 @@ func (x *DeleteEntryResponse) String() string {
func (*DeleteEntryResponse) ProtoMessage() {}
func (x *DeleteEntryResponse) ProtoReflect() protoreflect.Message {
mi := &file_filer_subset_proto_msgTypes[13]
mi := &file_filer_subset_proto_msgTypes[12]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1035,7 +933,7 @@ func (x *DeleteEntryResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use DeleteEntryResponse.ProtoReflect.Descriptor instead.
func (*DeleteEntryResponse) Descriptor() ([]byte, []int) {
return file_filer_subset_proto_rawDescGZIP(), []int{13}
return file_filer_subset_proto_rawDescGZIP(), []int{12}
}
func (x *DeleteEntryResponse) GetError() string {
@@ -1063,7 +961,7 @@ type AssignVolumeRequest struct {
func (x *AssignVolumeRequest) Reset() {
*x = AssignVolumeRequest{}
mi := &file_filer_subset_proto_msgTypes[14]
mi := &file_filer_subset_proto_msgTypes[13]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1075,7 +973,7 @@ func (x *AssignVolumeRequest) String() string {
func (*AssignVolumeRequest) ProtoMessage() {}
func (x *AssignVolumeRequest) ProtoReflect() protoreflect.Message {
mi := &file_filer_subset_proto_msgTypes[14]
mi := &file_filer_subset_proto_msgTypes[13]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1088,7 +986,7 @@ func (x *AssignVolumeRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use AssignVolumeRequest.ProtoReflect.Descriptor instead.
func (*AssignVolumeRequest) Descriptor() ([]byte, []int) {
return file_filer_subset_proto_rawDescGZIP(), []int{14}
return file_filer_subset_proto_rawDescGZIP(), []int{13}
}
func (x *AssignVolumeRequest) GetCount() int32 {
@@ -1179,7 +1077,7 @@ type AssignVolumeResponse struct {
func (x *AssignVolumeResponse) Reset() {
*x = AssignVolumeResponse{}
mi := &file_filer_subset_proto_msgTypes[15]
mi := &file_filer_subset_proto_msgTypes[14]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1191,7 +1089,7 @@ func (x *AssignVolumeResponse) String() string {
func (*AssignVolumeResponse) ProtoMessage() {}
func (x *AssignVolumeResponse) ProtoReflect() protoreflect.Message {
mi := &file_filer_subset_proto_msgTypes[15]
mi := &file_filer_subset_proto_msgTypes[14]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1204,7 +1102,7 @@ func (x *AssignVolumeResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use AssignVolumeResponse.ProtoReflect.Descriptor instead.
func (*AssignVolumeResponse) Descriptor() ([]byte, []int) {
return file_filer_subset_proto_rawDescGZIP(), []int{15}
return file_filer_subset_proto_rawDescGZIP(), []int{14}
}
func (x *AssignVolumeResponse) GetFileId() string {
@@ -1286,7 +1184,7 @@ type LookupVolumeRequest struct {
func (x *LookupVolumeRequest) Reset() {
*x = LookupVolumeRequest{}
mi := &file_filer_subset_proto_msgTypes[16]
mi := &file_filer_subset_proto_msgTypes[15]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1298,7 +1196,7 @@ func (x *LookupVolumeRequest) String() string {
func (*LookupVolumeRequest) ProtoMessage() {}
func (x *LookupVolumeRequest) ProtoReflect() protoreflect.Message {
mi := &file_filer_subset_proto_msgTypes[16]
mi := &file_filer_subset_proto_msgTypes[15]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1311,7 +1209,7 @@ func (x *LookupVolumeRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use LookupVolumeRequest.ProtoReflect.Descriptor instead.
func (*LookupVolumeRequest) Descriptor() ([]byte, []int) {
return file_filer_subset_proto_rawDescGZIP(), []int{16}
return file_filer_subset_proto_rawDescGZIP(), []int{15}
}
func (x *LookupVolumeRequest) GetVolumeIds() []string {
@@ -1330,7 +1228,7 @@ type Locations struct {
func (x *Locations) Reset() {
*x = Locations{}
mi := &file_filer_subset_proto_msgTypes[17]
mi := &file_filer_subset_proto_msgTypes[16]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1342,7 +1240,7 @@ func (x *Locations) String() string {
func (*Locations) ProtoMessage() {}
func (x *Locations) ProtoReflect() protoreflect.Message {
mi := &file_filer_subset_proto_msgTypes[17]
mi := &file_filer_subset_proto_msgTypes[16]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1355,7 +1253,7 @@ func (x *Locations) ProtoReflect() protoreflect.Message {
// Deprecated: Use Locations.ProtoReflect.Descriptor instead.
func (*Locations) Descriptor() ([]byte, []int) {
return file_filer_subset_proto_rawDescGZIP(), []int{17}
return file_filer_subset_proto_rawDescGZIP(), []int{16}
}
func (x *Locations) GetLocations() []*Location {
@@ -1378,7 +1276,7 @@ type Location struct {
func (x *Location) Reset() {
*x = Location{}
mi := &file_filer_subset_proto_msgTypes[18]
mi := &file_filer_subset_proto_msgTypes[17]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1390,7 +1288,7 @@ func (x *Location) String() string {
func (*Location) ProtoMessage() {}
func (x *Location) ProtoReflect() protoreflect.Message {
mi := &file_filer_subset_proto_msgTypes[18]
mi := &file_filer_subset_proto_msgTypes[17]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1403,7 +1301,7 @@ func (x *Location) ProtoReflect() protoreflect.Message {
// Deprecated: Use Location.ProtoReflect.Descriptor instead.
func (*Location) Descriptor() ([]byte, []int) {
return file_filer_subset_proto_rawDescGZIP(), []int{18}
return file_filer_subset_proto_rawDescGZIP(), []int{17}
}
func (x *Location) GetUrl() string {
@@ -1450,7 +1348,7 @@ type LookupVolumeResponse struct {
func (x *LookupVolumeResponse) Reset() {
*x = LookupVolumeResponse{}
mi := &file_filer_subset_proto_msgTypes[19]
mi := &file_filer_subset_proto_msgTypes[18]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1462,7 +1360,7 @@ func (x *LookupVolumeResponse) String() string {
func (*LookupVolumeResponse) ProtoMessage() {}
func (x *LookupVolumeResponse) ProtoReflect() protoreflect.Message {
mi := &file_filer_subset_proto_msgTypes[19]
mi := &file_filer_subset_proto_msgTypes[18]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1475,7 +1373,7 @@ func (x *LookupVolumeResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use LookupVolumeResponse.ProtoReflect.Descriptor instead.
func (*LookupVolumeResponse) Descriptor() ([]byte, []int) {
return file_filer_subset_proto_rawDescGZIP(), []int{19}
return file_filer_subset_proto_rawDescGZIP(), []int{18}
}
func (x *LookupVolumeResponse) GetLocationsMap() map[string]*Locations {
@@ -1493,7 +1391,7 @@ type GetFilerConfigurationRequest struct {
func (x *GetFilerConfigurationRequest) Reset() {
*x = GetFilerConfigurationRequest{}
mi := &file_filer_subset_proto_msgTypes[20]
mi := &file_filer_subset_proto_msgTypes[19]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1505,7 +1403,7 @@ func (x *GetFilerConfigurationRequest) String() string {
func (*GetFilerConfigurationRequest) ProtoMessage() {}
func (x *GetFilerConfigurationRequest) ProtoReflect() protoreflect.Message {
mi := &file_filer_subset_proto_msgTypes[20]
mi := &file_filer_subset_proto_msgTypes[19]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1518,7 +1416,7 @@ func (x *GetFilerConfigurationRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use GetFilerConfigurationRequest.ProtoReflect.Descriptor instead.
func (*GetFilerConfigurationRequest) Descriptor() ([]byte, []int) {
return file_filer_subset_proto_rawDescGZIP(), []int{20}
return file_filer_subset_proto_rawDescGZIP(), []int{19}
}
// Only the fields the single-filer startup check reads.
@@ -1532,7 +1430,7 @@ type GetFilerConfigurationResponse struct {
func (x *GetFilerConfigurationResponse) Reset() {
*x = GetFilerConfigurationResponse{}
mi := &file_filer_subset_proto_msgTypes[21]
mi := &file_filer_subset_proto_msgTypes[20]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1544,7 +1442,7 @@ func (x *GetFilerConfigurationResponse) String() string {
func (*GetFilerConfigurationResponse) ProtoMessage() {}
func (x *GetFilerConfigurationResponse) ProtoReflect() protoreflect.Message {
mi := &file_filer_subset_proto_msgTypes[21]
mi := &file_filer_subset_proto_msgTypes[20]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1557,7 +1455,7 @@ func (x *GetFilerConfigurationResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use GetFilerConfigurationResponse.ProtoReflect.Descriptor instead.
func (*GetFilerConfigurationResponse) Descriptor() ([]byte, []int) {
return file_filer_subset_proto_rawDescGZIP(), []int{21}
return file_filer_subset_proto_rawDescGZIP(), []int{20}
}
func (x *GetFilerConfigurationResponse) GetMasters() []string {
@@ -1574,58 +1472,6 @@ func (x *GetFilerConfigurationResponse) GetFilerGroup() string {
return ""
}
type WriteCondition_Clause struct {
state protoimpl.MessageState `protogen:"open.v1"`
Kind WriteCondition_Kind `protobuf:"varint,1,opt,name=kind,proto3,enum=filer_pb.WriteCondition_Kind" json:"kind,omitempty"`
Fids []string `protobuf:"bytes,9,rep,name=fids,proto3" json:"fids,omitempty"` // chunk fid strings for IF_CHUNKS_EQUAL
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *WriteCondition_Clause) Reset() {
*x = WriteCondition_Clause{}
mi := &file_filer_subset_proto_msgTypes[23]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *WriteCondition_Clause) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*WriteCondition_Clause) ProtoMessage() {}
func (x *WriteCondition_Clause) ProtoReflect() protoreflect.Message {
mi := &file_filer_subset_proto_msgTypes[23]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use WriteCondition_Clause.ProtoReflect.Descriptor instead.
func (*WriteCondition_Clause) Descriptor() ([]byte, []int) {
return file_filer_subset_proto_rawDescGZIP(), []int{9, 0}
}
func (x *WriteCondition_Clause) GetKind() WriteCondition_Kind {
if x != nil {
return x.Kind
}
return WriteCondition_NONE
}
func (x *WriteCondition_Clause) GetFids() []string {
if x != nil {
return x.Fids
}
return nil
}
var File_filer_subset_proto protoreflect.FileDescriptor
const file_filer_subset_proto_rawDesc = "" +
@@ -1684,15 +1530,7 @@ const file_filer_subset_proto_rawDesc = "" +
"\x13CreateEntryResponse\x12\x14\n" +
"\x05error\x18\x01 \x01(\tR\x05error\x123\n" +
"\n" +
"error_code\x18\x03 \x01(\x0e2\x14.filer_pb.FilerErrorR\terrorCode\"\xc3\x01\n" +
"\x0eWriteCondition\x129\n" +
"\aclauses\x18\x01 \x03(\v2\x1f.filer_pb.WriteCondition.ClauseR\aclauses\x1aO\n" +
"\x06Clause\x121\n" +
"\x04kind\x18\x01 \x01(\x0e2\x1d.filer_pb.WriteCondition.KindR\x04kind\x12\x12\n" +
"\x04fids\x18\t \x03(\tR\x04fids\"%\n" +
"\x04Kind\x12\b\n" +
"\x04NONE\x10\x00\x12\x13\n" +
"\x0fIF_CHUNKS_EQUAL\x10\t\"\x8a\x03\n" +
"error_code\x18\x03 \x01(\x0e2\x14.filer_pb.FilerErrorR\terrorCode\"\xd2\x02\n" +
"\x12UpdateEntryRequest\x12\x1c\n" +
"\tdirectory\x18\x01 \x01(\tR\tdirectory\x12%\n" +
"\x05entry\x18\x02 \x01(\v2\x0f.filer_pb.EntryR\x05entry\x121\n" +
@@ -1700,8 +1538,7 @@ const file_filer_subset_proto_rawDesc = "" +
"\n" +
"signatures\x18\x04 \x03(\x05R\n" +
"signatures\x12_\n" +
"\x11expected_extended\x18\x05 \x03(\v22.filer_pb.UpdateEntryRequest.ExpectedExtendedEntryR\x10expectedExtended\x126\n" +
"\tcondition\x18\x06 \x01(\v2\x18.filer_pb.WriteConditionR\tcondition\x1aC\n" +
"\x11expected_extended\x18\x05 \x03(\v22.filer_pb.UpdateEntryRequest.ExpectedExtendedEntryR\x10expectedExtended\x1aC\n" +
"\x15ExpectedExtendedEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
"\x05value\x18\x02 \x01(\fR\x05value:\x028\x01\"\x15\n" +
@@ -1802,80 +1639,74 @@ func file_filer_subset_proto_rawDescGZIP() []byte {
return file_filer_subset_proto_rawDescData
}
var file_filer_subset_proto_enumTypes = make([]protoimpl.EnumInfo, 2)
var file_filer_subset_proto_msgTypes = make([]protoimpl.MessageInfo, 27)
var file_filer_subset_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
var file_filer_subset_proto_msgTypes = make([]protoimpl.MessageInfo, 25)
var file_filer_subset_proto_goTypes = []any{
(FilerError)(0), // 0: filer_pb.FilerError
(WriteCondition_Kind)(0), // 1: filer_pb.WriteCondition.Kind
(*LookupDirectoryEntryRequest)(nil), // 2: filer_pb.LookupDirectoryEntryRequest
(*LookupDirectoryEntryResponse)(nil), // 3: filer_pb.LookupDirectoryEntryResponse
(*ListEntriesRequest)(nil), // 4: filer_pb.ListEntriesRequest
(*ListEntriesResponse)(nil), // 5: filer_pb.ListEntriesResponse
(*Entry)(nil), // 6: filer_pb.Entry
(*FileChunk)(nil), // 7: filer_pb.FileChunk
(*FuseAttributes)(nil), // 8: filer_pb.FuseAttributes
(*CreateEntryRequest)(nil), // 9: filer_pb.CreateEntryRequest
(*CreateEntryResponse)(nil), // 10: filer_pb.CreateEntryResponse
(*WriteCondition)(nil), // 11: filer_pb.WriteCondition
(*UpdateEntryRequest)(nil), // 12: filer_pb.UpdateEntryRequest
(*UpdateEntryResponse)(nil), // 13: filer_pb.UpdateEntryResponse
(*DeleteEntryRequest)(nil), // 14: filer_pb.DeleteEntryRequest
(*DeleteEntryResponse)(nil), // 15: filer_pb.DeleteEntryResponse
(*AssignVolumeRequest)(nil), // 16: filer_pb.AssignVolumeRequest
(*AssignVolumeResponse)(nil), // 17: filer_pb.AssignVolumeResponse
(*LookupVolumeRequest)(nil), // 18: filer_pb.LookupVolumeRequest
(*Locations)(nil), // 19: filer_pb.Locations
(*Location)(nil), // 20: filer_pb.Location
(*LookupVolumeResponse)(nil), // 21: filer_pb.LookupVolumeResponse
(*GetFilerConfigurationRequest)(nil), // 22: filer_pb.GetFilerConfigurationRequest
(*GetFilerConfigurationResponse)(nil), // 23: filer_pb.GetFilerConfigurationResponse
nil, // 24: filer_pb.Entry.ExtendedEntry
(*WriteCondition_Clause)(nil), // 25: filer_pb.WriteCondition.Clause
nil, // 26: filer_pb.UpdateEntryRequest.ExpectedExtendedEntry
nil, // 27: filer_pb.DeleteEntryRequest.ExpectedExtendedEntry
nil, // 28: filer_pb.LookupVolumeResponse.LocationsMapEntry
(*LookupDirectoryEntryRequest)(nil), // 1: filer_pb.LookupDirectoryEntryRequest
(*LookupDirectoryEntryResponse)(nil), // 2: filer_pb.LookupDirectoryEntryResponse
(*ListEntriesRequest)(nil), // 3: filer_pb.ListEntriesRequest
(*ListEntriesResponse)(nil), // 4: filer_pb.ListEntriesResponse
(*Entry)(nil), // 5: filer_pb.Entry
(*FileChunk)(nil), // 6: filer_pb.FileChunk
(*FuseAttributes)(nil), // 7: filer_pb.FuseAttributes
(*CreateEntryRequest)(nil), // 8: filer_pb.CreateEntryRequest
(*CreateEntryResponse)(nil), // 9: filer_pb.CreateEntryResponse
(*UpdateEntryRequest)(nil), // 10: filer_pb.UpdateEntryRequest
(*UpdateEntryResponse)(nil), // 11: filer_pb.UpdateEntryResponse
(*DeleteEntryRequest)(nil), // 12: filer_pb.DeleteEntryRequest
(*DeleteEntryResponse)(nil), // 13: filer_pb.DeleteEntryResponse
(*AssignVolumeRequest)(nil), // 14: filer_pb.AssignVolumeRequest
(*AssignVolumeResponse)(nil), // 15: filer_pb.AssignVolumeResponse
(*LookupVolumeRequest)(nil), // 16: filer_pb.LookupVolumeRequest
(*Locations)(nil), // 17: filer_pb.Locations
(*Location)(nil), // 18: filer_pb.Location
(*LookupVolumeResponse)(nil), // 19: filer_pb.LookupVolumeResponse
(*GetFilerConfigurationRequest)(nil), // 20: filer_pb.GetFilerConfigurationRequest
(*GetFilerConfigurationResponse)(nil), // 21: filer_pb.GetFilerConfigurationResponse
nil, // 22: filer_pb.Entry.ExtendedEntry
nil, // 23: filer_pb.UpdateEntryRequest.ExpectedExtendedEntry
nil, // 24: filer_pb.DeleteEntryRequest.ExpectedExtendedEntry
nil, // 25: filer_pb.LookupVolumeResponse.LocationsMapEntry
}
var file_filer_subset_proto_depIdxs = []int32{
6, // 0: filer_pb.LookupDirectoryEntryResponse.entry:type_name -> filer_pb.Entry
6, // 1: filer_pb.ListEntriesResponse.entry:type_name -> filer_pb.Entry
7, // 2: filer_pb.Entry.chunks:type_name -> filer_pb.FileChunk
8, // 3: filer_pb.Entry.attributes:type_name -> filer_pb.FuseAttributes
24, // 4: filer_pb.Entry.extended:type_name -> filer_pb.Entry.ExtendedEntry
6, // 5: filer_pb.CreateEntryRequest.entry:type_name -> filer_pb.Entry
5, // 0: filer_pb.LookupDirectoryEntryResponse.entry:type_name -> filer_pb.Entry
5, // 1: filer_pb.ListEntriesResponse.entry:type_name -> filer_pb.Entry
6, // 2: filer_pb.Entry.chunks:type_name -> filer_pb.FileChunk
7, // 3: filer_pb.Entry.attributes:type_name -> filer_pb.FuseAttributes
22, // 4: filer_pb.Entry.extended:type_name -> filer_pb.Entry.ExtendedEntry
5, // 5: filer_pb.CreateEntryRequest.entry:type_name -> filer_pb.Entry
0, // 6: filer_pb.CreateEntryResponse.error_code:type_name -> filer_pb.FilerError
25, // 7: filer_pb.WriteCondition.clauses:type_name -> filer_pb.WriteCondition.Clause
6, // 8: filer_pb.UpdateEntryRequest.entry:type_name -> filer_pb.Entry
26, // 9: filer_pb.UpdateEntryRequest.expected_extended:type_name -> filer_pb.UpdateEntryRequest.ExpectedExtendedEntry
11, // 10: filer_pb.UpdateEntryRequest.condition:type_name -> filer_pb.WriteCondition
27, // 11: filer_pb.DeleteEntryRequest.expected_extended:type_name -> filer_pb.DeleteEntryRequest.ExpectedExtendedEntry
20, // 12: filer_pb.AssignVolumeResponse.location:type_name -> filer_pb.Location
20, // 13: filer_pb.AssignVolumeResponse.replicas:type_name -> filer_pb.Location
0, // 14: filer_pb.AssignVolumeResponse.error_code:type_name -> filer_pb.FilerError
20, // 15: filer_pb.Locations.locations:type_name -> filer_pb.Location
28, // 16: filer_pb.LookupVolumeResponse.locations_map:type_name -> filer_pb.LookupVolumeResponse.LocationsMapEntry
1, // 17: filer_pb.WriteCondition.Clause.kind:type_name -> filer_pb.WriteCondition.Kind
19, // 18: filer_pb.LookupVolumeResponse.LocationsMapEntry.value:type_name -> filer_pb.Locations
2, // 19: filer_pb.SeaweedFiler.LookupDirectoryEntry:input_type -> filer_pb.LookupDirectoryEntryRequest
4, // 20: filer_pb.SeaweedFiler.ListEntries:input_type -> filer_pb.ListEntriesRequest
9, // 21: filer_pb.SeaweedFiler.CreateEntry:input_type -> filer_pb.CreateEntryRequest
12, // 22: filer_pb.SeaweedFiler.UpdateEntry:input_type -> filer_pb.UpdateEntryRequest
14, // 23: filer_pb.SeaweedFiler.DeleteEntry:input_type -> filer_pb.DeleteEntryRequest
16, // 24: filer_pb.SeaweedFiler.AssignVolume:input_type -> filer_pb.AssignVolumeRequest
18, // 25: filer_pb.SeaweedFiler.LookupVolume:input_type -> filer_pb.LookupVolumeRequest
22, // 26: filer_pb.SeaweedFiler.GetFilerConfiguration:input_type -> filer_pb.GetFilerConfigurationRequest
3, // 27: filer_pb.SeaweedFiler.LookupDirectoryEntry:output_type -> filer_pb.LookupDirectoryEntryResponse
5, // 28: filer_pb.SeaweedFiler.ListEntries:output_type -> filer_pb.ListEntriesResponse
10, // 29: filer_pb.SeaweedFiler.CreateEntry:output_type -> filer_pb.CreateEntryResponse
13, // 30: filer_pb.SeaweedFiler.UpdateEntry:output_type -> filer_pb.UpdateEntryResponse
15, // 31: filer_pb.SeaweedFiler.DeleteEntry:output_type -> filer_pb.DeleteEntryResponse
17, // 32: filer_pb.SeaweedFiler.AssignVolume:output_type -> filer_pb.AssignVolumeResponse
21, // 33: filer_pb.SeaweedFiler.LookupVolume:output_type -> filer_pb.LookupVolumeResponse
23, // 34: filer_pb.SeaweedFiler.GetFilerConfiguration:output_type -> filer_pb.GetFilerConfigurationResponse
27, // [27:35] is the sub-list for method output_type
19, // [19:27] is the sub-list for method input_type
19, // [19:19] is the sub-list for extension type_name
19, // [19:19] is the sub-list for extension extendee
0, // [0:19] is the sub-list for field type_name
5, // 7: filer_pb.UpdateEntryRequest.entry:type_name -> filer_pb.Entry
23, // 8: filer_pb.UpdateEntryRequest.expected_extended:type_name -> filer_pb.UpdateEntryRequest.ExpectedExtendedEntry
24, // 9: filer_pb.DeleteEntryRequest.expected_extended:type_name -> filer_pb.DeleteEntryRequest.ExpectedExtendedEntry
18, // 10: filer_pb.AssignVolumeResponse.location:type_name -> filer_pb.Location
18, // 11: filer_pb.AssignVolumeResponse.replicas:type_name -> filer_pb.Location
0, // 12: filer_pb.AssignVolumeResponse.error_code:type_name -> filer_pb.FilerError
18, // 13: filer_pb.Locations.locations:type_name -> filer_pb.Location
25, // 14: filer_pb.LookupVolumeResponse.locations_map:type_name -> filer_pb.LookupVolumeResponse.LocationsMapEntry
17, // 15: filer_pb.LookupVolumeResponse.LocationsMapEntry.value:type_name -> filer_pb.Locations
1, // 16: filer_pb.SeaweedFiler.LookupDirectoryEntry:input_type -> filer_pb.LookupDirectoryEntryRequest
3, // 17: filer_pb.SeaweedFiler.ListEntries:input_type -> filer_pb.ListEntriesRequest
8, // 18: filer_pb.SeaweedFiler.CreateEntry:input_type -> filer_pb.CreateEntryRequest
10, // 19: filer_pb.SeaweedFiler.UpdateEntry:input_type -> filer_pb.UpdateEntryRequest
12, // 20: filer_pb.SeaweedFiler.DeleteEntry:input_type -> filer_pb.DeleteEntryRequest
14, // 21: filer_pb.SeaweedFiler.AssignVolume:input_type -> filer_pb.AssignVolumeRequest
16, // 22: filer_pb.SeaweedFiler.LookupVolume:input_type -> filer_pb.LookupVolumeRequest
20, // 23: filer_pb.SeaweedFiler.GetFilerConfiguration:input_type -> filer_pb.GetFilerConfigurationRequest
2, // 24: filer_pb.SeaweedFiler.LookupDirectoryEntry:output_type -> filer_pb.LookupDirectoryEntryResponse
4, // 25: filer_pb.SeaweedFiler.ListEntries:output_type -> filer_pb.ListEntriesResponse
9, // 26: filer_pb.SeaweedFiler.CreateEntry:output_type -> filer_pb.CreateEntryResponse
11, // 27: filer_pb.SeaweedFiler.UpdateEntry:output_type -> filer_pb.UpdateEntryResponse
13, // 28: filer_pb.SeaweedFiler.DeleteEntry:output_type -> filer_pb.DeleteEntryResponse
15, // 29: filer_pb.SeaweedFiler.AssignVolume:output_type -> filer_pb.AssignVolumeResponse
19, // 30: filer_pb.SeaweedFiler.LookupVolume:output_type -> filer_pb.LookupVolumeResponse
21, // 31: filer_pb.SeaweedFiler.GetFilerConfiguration:output_type -> filer_pb.GetFilerConfigurationResponse
24, // [24:32] is the sub-list for method output_type
16, // [16:24] is the sub-list for method input_type
16, // [16:16] is the sub-list for extension type_name
16, // [16:16] is the sub-list for extension extendee
0, // [0:16] is the sub-list for field type_name
}
func init() { file_filer_subset_proto_init() }
@@ -1888,8 +1719,8 @@ func file_filer_subset_proto_init() {
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_filer_subset_proto_rawDesc), len(file_filer_subset_proto_rawDesc)),
NumEnums: 2,
NumMessages: 27,
NumEnums: 1,
NumMessages: 25,
NumExtensions: 0,
NumServices: 1,
},
@@ -102,29 +102,12 @@ message CreateEntryResponse {
FilerError error_code = 3;
}
// WriteCondition is copied from weed/pb/filer.proto (this repository): the
// IF_CHUNKS_EQUAL clause only. A filer that predates it drops field 6 of
// UpdateEntryRequest as unknown and applies the write unguarded, so the
// chunkstore decides at startup, by a probe, whether it is enforced.
message WriteCondition {
enum Kind {
NONE = 0;
IF_CHUNKS_EQUAL = 9; // fail unless the stored chunk fid multiset equals fids (absent entry = no chunks)
}
message Clause {
Kind kind = 1;
repeated string fids = 9; // chunk fid strings for IF_CHUNKS_EQUAL
}
repeated Clause clauses = 1; // all must hold (logical AND)
}
message UpdateEntryRequest {
string directory = 1;
Entry entry = 2;
bool is_from_other_cluster = 3;
repeated int32 signatures = 4;
map<string, bytes> expected_extended = 5;
WriteCondition condition = 6;
}
message UpdateEntryResponse {
@@ -45,7 +45,6 @@ var headReaders = map[string]string{
"core/frontend/chunkstore/layout_verify.go verifyHead -> LookupEntry": "absent or unknown generation makes verify incomplete and suppresses MISSING/ORPHAN (TestVerifyLayoutRequiresStableHeadForMissingAndOrphans)",
"core/frontend/chunkstore/layout_verify.go verifyHead -> DecodeLayoutHeadEntry": "invalid inline envelope supplies no generation and cannot confirm findings (TestVerifyLayoutRequiresStableHeadForMissingAndOrphans)",
"core/frontend/chunkstore/startup_head_probe.go checkConditionalHead -> ReadHead": "absent/unreadable/changed disposable HEAD refuses startup; no volume HEAD is read (TestCatalogStartupRequiresWrongGenerationHeadRefusal)",
"core/frontend/chunkstore/startup_head_probe.go probeChunkCondition -> LookupEntry": "absent/unreadable disposable HEAD leaves the chunk guard off (page re-read only); no volume HEAD is read (TestCatalogStartupRequiresWrongGenerationHeadRefusal)",
"cmd/blockvolume/chunk_maintenance.go newChunkMaintenance -> ReadHead": "diagnostic absent HEAD reports headGen0 and headGenError; it neither authorizes nor changes cleaning (TestMaintenanceStatusRealPassAndTimeout/head-absent)",
"core/frontend/chunkstore/layout_remote.go ProbeSnapshots -> ReadHead": "absent or failed reads do not infer snapshot deletion; open local activity skips the read (TestMaintenanceNoticesSnapshotDeleteWithoutNotification, TestLayoutSnapshotProbeSkipsOpenActivityWithoutReadingHEAD)",
"core/frontend/durable/provider_seal_replay.go readLayoutSeal -> ReadHead": "absent, unreadable and foreign layout proof refuse without cached success (TestLayoutPlainDetachReplayAfterRestartNeedsNoLegacyFactory)",
@@ -172,18 +172,6 @@ func RunDeleteSnapshotWithIntent(ctx context.Context, st ListChainStore, base ui
if !found || meta.Volume != h.VolumeID || meta.Session != deleteIntentWriter(base, ref) || meta.Mark != "" {
return ErrPrecondition
}
// Read the page again now that this run owns its tag. A stalled
// update from another run of the same delete can land between
// the read above and the adoption, putting a deleted page's data
// reference on this entry; once this run's tag is on it, no such
// update passes. An intent published over a page whose data is
// gone could never be consumed. The filer frees chunks from a
// deletion queue, so this sees only data already freed.
again := c
again.Ref = ref
if _, err := readListPage(ctx, st, h.VolumeID, again); err != nil {
return fmt.Errorf("%w: delete intent page changed during adoption: %w", ErrPrecondition, err)
}
return nil
}); err != nil {
return Head{}, false, err
@@ -1,171 +0,0 @@
package layout
import (
"context"
"errors"
"fmt"
"testing"
)
// staleUpdateBeforeAdoption is the store as the second run of a snapshot
// delete sees it when the first run's stalled page update lands between the
// second run's read of one page (rel) and its adoption: the page then
// carries the first run's writer tag, and its data is whatever the update
// left. This is a consequence-level projection of that update: it edits the
// tag and decides what a later read of the page returns (mode). The backend
// mechanism itself, a tag-conditional whole-entry update writing a deleted
// object's chunk reference over a re-created one, is exercised on the real
// store in package chunkstore: refused with the filer's chunk condition
// (TestAStaleMetadataChangeDoesNotOverwriteARecreatedObject), and landing
// without it (TestWithoutTheChunkGuardAStaleMetadataChangeOverwritesARecreatedObject).
type staleUpdateBeforeAdoption struct {
*chainStore
rel string
staleTag string
mode string // "freed": the read fails; "wrong": it returns other bytes; "deadline": the caller's deadline ends the read; "valid": the bytes are intact
wrong []byte
landed bool
}
func (s *staleUpdateBeforeAdoption) Stat(ctx context.Context, rel string) (ObjectMeta, bool, error) {
if rel == s.rel && !s.landed {
s.landed = true
if o, ok := s.objs[s.full(rel)]; ok {
o.meta.Session = s.staleTag
}
}
return s.chainStore.Stat(ctx, rel)
}
func (s *staleUpdateBeforeAdoption) ReadListPage(ctx context.Context, ref ListRef) ([]byte, bool, error) {
if rel, _ := ref.Path(); s.landed && rel == s.rel {
switch s.mode {
case "freed":
return nil, false, errors.New("the page's data was freed")
case "wrong":
return append([]byte(nil), s.wrong...), true, nil
case "deadline":
return nil, false, fmt.Errorf("lookup: %w", context.DeadlineExceeded)
}
}
return s.chainStore.ReadListPage(ctx, ref)
}
// rerunFixture stages a snapshot delete's intent at the first base, lets a
// cleaning pass delete the unlinked pages, and stages them again at the new
// base: the second run. With twoPages the intent has two pages and the
// stale update hits the later one, the second page the chain visits.
func rerunFixture(t *testing.T, twoPages bool) (s *chainStore, c ListCursor, hit ListRef, other []byte, firstBase, secondBase uint64) {
t.Helper()
ctx := context.Background()
s, c, p := deleteIntentFixture(t)
firstBase = s.h.Gen
pages := []ListPage{p}
if twoPages {
tail := p
tail.Entries = p.Entries[1:]
tailRef, err := tail.Ref()
if err != nil {
t.Fatal(err)
}
head := p
head.Entries = p.Entries[:1]
head.Pages = 2
head.Next = &tailRef
headRef, err := head.Ref()
if err != nil {
t.Fatal(err)
}
pages = []ListPage{tail, head}
c.Ref = headRef
}
stage := func(base uint64) {
for _, pg := range pages {
if _, err := StageSnapshotDeletePage(ctx, s, base, pg); err != nil {
t.Fatal(err)
}
}
}
stage(firstBase)
s.h.Gen = firstBase + 2 // a cleaning pass
for _, pg := range pages {
ref, _ := pg.Ref()
rel, _ := ref.Path()
delete(s.objs, s.full(rel))
}
secondBase = s.h.Gen
stage(secondBase)
hit, _ = pages[0].Ref() // the only page, or the tail: the later page visited
for _, pg := range pages {
if ref, _ := pg.Ref(); ref != hit {
other, _, _ = s.ReadListPage(ctx, ref)
}
}
if other == nil {
other = []byte(`{"pages":1,"entries":["not this page"]}`)
}
return s, c, hit, other, firstBase, secondBase
}
// The second run of a snapshot delete must not publish an intent whose page
// lost its data, or holds other bytes, after a stalled update from the first
// run landed between the second run's read of the page and its adoption.
// The refusal comes after the adoption (the page carries this run's tag), is
// a precondition, and writes nothing to HEAD: the snapshot stays. The same
// schedule with the page's bytes intact publishes.
func TestASnapshotDeleteIsNotPublishedOverAPageWhoseDataWasFreed(t *testing.T) {
for _, tc := range []struct {
name string
mode string
twoPages bool
publish bool
cause error
}{
{"freed, one page", "freed", false, false, nil},
{"other bytes, one page", "wrong", false, false, nil},
{"freed, the later of two pages", "freed", true, false, nil},
{"other bytes, the later of two pages", "wrong", true, false, nil},
{"the caller's deadline ends the re-read", "deadline", false, false, context.DeadlineExceeded},
{"intact bytes after the stale tag, one page", "valid", false, true, nil},
{"intact bytes after the stale tag, two pages", "valid", true, true, nil},
} {
t.Run(tc.name, func(t *testing.T) {
ctx := context.Background()
s, c, hit, other, firstBase, secondBase := rerunFixture(t, tc.twoPages)
rel, err := hit.Path()
if err != nil {
t.Fatal(err)
}
st := &staleUpdateBeforeAdoption{chainStore: s, rel: rel, staleTag: deleteIntentWriter(firstBase, hit), mode: tc.mode, wrong: other}
updates := s.updates
_, publishErr := RunDeleteSnapshotWithIntent(ctx, st, secondBase, c)
if !st.landed {
t.Fatal("fixture: the stale update never landed (the adoption did not Stat the page)")
}
if tc.publish {
if publishErr != nil || s.h.List == nil {
t.Fatalf("an intact page after the stale tag did not publish: %v, list %+v", publishErr, s.h.List)
}
if _, kept := s.h.Snapshots["daily"]; kept {
t.Fatal("published, but the snapshot is still named")
}
return
}
if !errors.Is(publishErr, ErrPrecondition) {
t.Fatalf("publishing over a page whose data changed answered %v, want ErrPrecondition", publishErr)
}
if tc.cause != nil && !errors.Is(publishErr, tc.cause) {
t.Fatalf("the refusal dropped the re-read's cause: %v, want it to keep %v", publishErr, tc.cause)
}
if s.h.List != nil || s.updates != updates {
t.Fatalf("the refusal wrote HEAD: list %+v, %d update(s)", s.h.List, s.updates-updates)
}
if snap, kept := s.h.Snapshots["daily"]; !kept || snap.Gen != 4 {
t.Fatalf("the refusal did not keep the snapshot: %+v (kept %v)", snap, kept)
}
if meta, found, _ := s.Stat(ctx, rel); !found || meta.Session != deleteIntentWriter(secondBase, hit) {
t.Fatalf("the refusal came before the adoption: the page's tag is %+v, want this run's %q", meta, deleteIntentWriter(secondBase, hit))
}
})
}
}
@@ -1,218 +0,0 @@
package chunkstore
import (
"bytes"
"context"
"errors"
"sync"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
)
// betweenLookupAndUpdate runs before, once, ahead of the first update: what
// other writers do while a stale one is between its lookup and its
// conditional update. It forwards the chunk condition, so a store over it can
// run with the guard on.
type betweenLookupAndUpdate struct {
Filer
once sync.Once
before func()
}
func (f *betweenLookupAndUpdate) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
f.once.Do(f.before)
return f.Filer.UpdateEntry(ctx, dir, e, expected)
}
func (f *betweenLookupAndUpdate) UpdateEntryIfChunks(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte, fids []string) error {
f.once.Do(f.before)
return f.Filer.(ChunkConditionFiler).UpdateEntryIfChunks(ctx, dir, e, expected, fids)
}
// recreatedObject is one object that a stale writer looked up, then (while
// the writer was between its lookup and its update) a cleaner marked and
// deleted, and another executor of the same operation created again with the
// same producer tag and a new chunk.
type recreatedObject struct {
f *fakeFiler
others, stale *LayoutStore
rel string
meta layout.ObjectMeta
first, second string
fid func() (string, bool)
}
func newRecreatedObject(t *testing.T, guard bool) *recreatedObject {
t.Helper()
ctx := context.Background()
f, b := newFakeFiler(), newFakeBlobs()
var id layout.VolumeID
for i := range id {
id[i] = 0x30 + byte(i)
}
others, err := NewLayoutStore(f, b, "/vol", id)
if err != nil {
t.Fatal(err)
}
hooked := &betweenLookupAndUpdate{Filer: f}
stale, err := NewLayoutStore(hooked, b, "/vol", id)
if err != nil {
t.Fatal(err)
}
stale.SetChunkGuard(guard)
data := bytes.Repeat([]byte{0x5a}, 4096)
o := &recreatedObject{f: f, others: others, stale: stale, rel: layout.NameChunk(1, data).Path()}
dir, name, err := others.object(o.rel)
if err != nil {
t.Fatal(err)
}
o.fid = func() (string, bool) {
e, err := f.LookupEntry(ctx, dir, name)
if errors.Is(err, ErrNotFound) {
return "", false
}
if err != nil || len(e.Chunks) != 1 {
t.Fatalf("lookup %s: %+v %v", o.rel, e, err)
}
return e.Chunks[0].FileId, true
}
if err := others.Create(ctx, o.rel, data, "producer-1"); err != nil {
t.Fatal(err)
}
o.first, _ = o.fid()
meta, found, err := others.Stat(ctx, o.rel)
if err != nil || !found {
t.Fatalf("stat: %v %v", found, err)
}
o.meta = meta
hooked.before = func() {
if err := others.Mark(ctx, o.rel, meta, "clean-1"); err != nil {
t.Errorf("mark: %v", err)
}
if err := others.DeleteMarked(ctx, o.rel, "clean-1"); err != nil {
t.Errorf("delete: %v", err)
}
if err := others.Create(ctx, o.rel, data, "producer-1"); err != nil {
t.Errorf("re-create: %v", err)
}
o.second, _ = o.fid()
}
return o
}
func (o *recreatedObject) checkRecreated(t *testing.T) {
t.Helper()
if o.second == "" || o.second == o.first {
t.Fatalf("fixture: the object was not re-created with a new chunk (first %s, second %s)", o.first, o.second)
}
}
// A stale metadata change (a delete-intent page's adoption by an executor
// that paused between its lookup and its update) must not write the entry it
// looked up over an object deleted and created again with the same tags in
// between: the update would put the deleted object's chunk on the new entry,
// and the filer would free the new entry's chunk. With the filer's chunk
// condition the write is refused, since a re-created object has a new chunk.
func TestAStaleMetadataChangeDoesNotOverwriteARecreatedObject(t *testing.T) {
o := newRecreatedObject(t, true)
err := o.stale.Reuse(context.Background(), o.rel, o.meta, "writer-1")
o.checkRecreated(t)
if !errors.Is(err, layout.ErrPrecondition) {
t.Fatalf("the stale update over a re-created object answered %v, want ErrPrecondition", err)
}
if got, _ := o.fid(); got != o.second {
t.Fatalf("the stale update wrote chunk %s over the re-created object's %s", got, o.second)
}
}
// With the guard on, a metadata change of an object nobody touched since its
// lookup still lands: adoption retags it, and a cleaner marks and deletes it.
func TestWithTheChunkGuardAnUnchangedObjectIsStillAdoptedMarkedAndDeleted(t *testing.T) {
ctx := context.Background()
f, b := newFakeFiler(), newFakeBlobs()
var id layout.VolumeID
for i := range id {
id[i] = 0x40 + byte(i)
}
st, err := NewLayoutStore(f, b, "/vol", id)
if err != nil {
t.Fatal(err)
}
st.SetChunkGuard(true)
data := bytes.Repeat([]byte{0x3c}, 4096)
rel := layout.NameChunk(1, data).Path()
if err := st.Create(ctx, rel, data, "producer-1"); err != nil {
t.Fatal(err)
}
meta, _, err := st.Stat(ctx, rel)
if err != nil {
t.Fatal(err)
}
if err := st.Reuse(ctx, rel, meta, "writer-1"); err != nil {
t.Fatalf("guarded adoption of an unchanged object: %v", err)
}
if meta, _, err = st.Stat(ctx, rel); err != nil || meta.Session != "writer-1" {
t.Fatalf("after adoption: %+v %v", meta, err)
}
if err := st.Mark(ctx, rel, meta, "clean-1"); err != nil {
t.Fatalf("guarded mark of an unchanged object: %v", err)
}
if err := st.DeleteMarked(ctx, rel, "clean-1"); err != nil {
t.Fatalf("delete: %v", err)
}
if _, found, err := st.Stat(ctx, rel); err != nil || found {
t.Fatalf("the marked object was not deleted: found %v %v", found, err)
}
}
// A cleaner that looked up an object to mark it, then paused, must not
// delete the object created again in between: its mark is refused, so its
// delete (which expects that mark) is refused too.
func TestAStaleCleanerMarkDoesNotDeleteARecreatedObject(t *testing.T) {
o := newRecreatedObject(t, true)
ctx := context.Background()
markErr := o.stale.Mark(ctx, o.rel, o.meta, "clean-2")
o.checkRecreated(t)
if !errors.Is(markErr, layout.ErrPrecondition) {
t.Fatalf("the stale mark over a re-created object answered %v, want ErrPrecondition", markErr)
}
if err := o.stale.DeleteMarked(ctx, o.rel, "clean-2"); !errors.Is(err, layout.ErrPrecondition) {
t.Fatalf("deleting under the refused mark answered %v, want ErrPrecondition", err)
}
if got, found := o.fid(); !found || got != o.second {
t.Fatalf("the re-created object is gone or changed: chunk %q found %v, want %s", got, found, o.second)
}
}
// Without the chunk condition (a filer that does not enforce it) both stale
// writes land: the store behavior the delete intent page re-read exists for,
// kept visible here.
func TestWithoutTheChunkGuardAStaleMetadataChangeOverwritesARecreatedObject(t *testing.T) {
t.Run("adoption", func(t *testing.T) {
o := newRecreatedObject(t, false)
err := o.stale.Reuse(context.Background(), o.rel, o.meta, "writer-1")
o.checkRecreated(t)
if err != nil {
t.Fatalf("the unguarded stale update was refused (%v)", err)
}
if got, _ := o.fid(); got != o.first {
t.Fatalf("the unguarded stale update left chunk %s, want the deleted object's %s", got, o.first)
}
})
t.Run("cleaner", func(t *testing.T) {
o := newRecreatedObject(t, false)
ctx := context.Background()
if err := o.stale.Mark(ctx, o.rel, o.meta, "clean-2"); err != nil {
t.Fatalf("the unguarded stale mark was refused (%v)", err)
}
o.checkRecreated(t)
if err := o.stale.DeleteMarked(ctx, o.rel, "clean-2"); err != nil {
t.Fatalf("delete: %v", err)
}
if _, found := o.fid(); found {
t.Fatal("the unguarded stale mark did not lead to the re-created object's deletion")
}
})
}
@@ -36,9 +36,6 @@ type LayoutStore struct {
b Blobs
root string
id layout.VolumeID
// chunkGuard: the filer enforces IF_CHUNKS_EQUAL (the startup probe said
// so), and metadata changes send the looked-up entry's chunk fids with it.
chunkGuard bool
}
func NewLayoutStore(f Filer, b Blobs, root string, id layout.VolumeID) (*LayoutStore, error) {
@@ -365,28 +362,9 @@ func (s *LayoutStore) changeMeta(ctx context.Context, rel string, expect layout.
e.Extended[layoutMark] = []byte(mark)
// Preserve the original FileChunks: an UpdateEntry dropping them
// would tell the filer to delete the object's immutable data.
//
// The update writes the whole looked-up entry back, chunks included, and
// its tags alone do not tell this object from one deleted and created
// again with the same tags since the lookup: written over that one, the
// update would put the deleted object's chunks on it and the filer would
// free the new chunks. A re-created object always has new chunks, so the
// filer's chunk condition refuses that write. Without it (a filer that
// does not enforce the condition), delete intent publication re-reads
// each adopted page instead (layout.RunDeleteSnapshotWithIntent).
if cf, ok := s.f.(ChunkConditionFiler); ok && s.chunkGuard {
return layoutError(cf.UpdateEntryIfChunks(ctx, dir, e, objectExpected(expect), entryFids(e)))
}
return layoutError(s.f.UpdateEntry(ctx, dir, e, objectExpected(expect)))
}
// SetChunkGuard turns the filer chunk condition on or off for this store's
// metadata changes; BCatalog sets it from its startup probe.
func (s *LayoutStore) SetChunkGuard(on bool) { s.chunkGuard = on }
// ChunkGuard reports whether metadata changes send the chunk condition.
func (s *LayoutStore) ChunkGuard() bool { return s.chunkGuard }
func (s *LayoutStore) Reuse(ctx context.Context, rel string, expect layout.ObjectMeta, session string) error {
if session == "" {
return errors.New("chunkstore: reuse needs a session")
@@ -63,23 +63,6 @@ func (m *MemFiler) UpdateEntry(_ context.Context, dir string, e *filerpb.Entry,
return nil
}
// UpdateEntryIfChunks is UpdateEntry that also requires the stored chunk
// fids to equal fids as a multiset, as the filer's IF_CHUNKS_EQUAL does.
func (m *MemFiler) UpdateEntryIfChunks(_ context.Context, dir string, e *filerpb.Entry, expected map[string][]byte, fids []string) error {
m.mu.Lock()
defer m.mu.Unlock()
p := path.Join(dir, e.GetName())
cur, ok := m.e[p]
if !ok {
return ErrNotFound
}
if !extendedMatch(cur, expected) || !fidsEqual(entryFids(cur), fids) {
return ErrPrecondition
}
m.e[p] = proto.Clone(e).(*filerpb.Entry)
return nil
}
func (m *MemFiler) ListEntries(_ context.Context, dir, prefix, startAfter string, limit uint32) ([]*filerpb.Entry, error) {
m.mu.Lock()
defer m.mu.Unlock()
@@ -35,49 +35,6 @@ type Filer interface {
DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error
}
// ChunkConditionFiler is a Filer that can also send the filer's
// IF_CHUNKS_EQUAL write condition: UpdateEntryIfChunks applies e only if every
// expected extended key still holds its value AND the stored entry's chunk
// fids still equal fids as a multiset; otherwise ErrPrecondition. A filer
// that predates the condition drops it and applies the write unguarded, which
// only a probe can tell (BCatalog.checkConditionalHead); a wrapper that does
// not forward this method is treated the same way.
type ChunkConditionFiler interface {
UpdateEntryIfChunks(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte, fids []string) error
}
// chunksEqual is the filer write condition that the stored chunk fids equal
// fids as a multiset (no fids: the entry has no chunks).
func chunksEqual(fids []string) *filerpb.WriteCondition {
return &filerpb.WriteCondition{Clauses: []*filerpb.WriteCondition_Clause{{Kind: filerpb.WriteCondition_IF_CHUNKS_EQUAL, Fids: fids}}}
}
// entryFids is the multiset of e's chunk fids, in its order.
func entryFids(e *filerpb.Entry) []string {
fids := make([]string, 0, len(e.GetChunks()))
for _, c := range e.GetChunks() {
fids = append(fids, c.GetFileId())
}
return fids
}
// fidsEqual compares two fid lists as multisets, as the filer does.
func fidsEqual(a, b []string) bool {
if len(a) != len(b) {
return false
}
n := make(map[string]int, len(a))
for _, f := range a {
n[f]++
}
for _, f := range b {
if n[f]--; n[f] < 0 {
return false
}
}
return true
}
// Blobs stores immutable chunk payloads as SeaweedFS needles.
type Blobs interface {
// Put stores data as a new needle and returns its fid. A fid is never
@@ -1,63 +0,0 @@
package chunkstore
import (
"context"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
)
// hidesChunkCondition is a Filer wrapper that does not forward
// UpdateEntryIfChunks: to the probe it is a filer without the condition.
type hidesChunkCondition struct{ Filer }
// The startup probe decides the metadata change guard from the filer's
// answer alone: a filer that refuses a mismatched IF_CHUNKS_EQUAL update turns
// the guard on for every store the catalog opens; a filer that drops the
// condition (or a client that cannot send it) leaves the page re-read as the
// only check. No version string is read.
func TestTheStartupProbeTurnsTheChunkGuardOnOnlyForAFilerThatEnforcesIt(t *testing.T) {
for _, tc := range []struct {
name string
filer func() Filer
guard string
storeG bool
}{
{"a filer that enforces the condition", func() Filer { return newFakeFiler() }, MetadataGuardChunks, true},
{"a filer that drops the condition", func() Filer { f := newFakeFiler(); f.ignoreChunkCondition = true; return f }, MetadataGuardReread, false},
{"a client wrapper that cannot send it", func() Filer { return hidesChunkCondition{newFakeFiler()} }, MetadataGuardReread, false},
} {
t.Run(tc.name, func(t *testing.T) {
cat, err := NewBCatalog(tc.filer(), newFakeBlobs(), "/blocks")
if err != nil {
t.Fatal(err)
}
if err := cat.checkConditionalHead(context.Background()); err != nil {
t.Fatalf("the conditional HEAD probe failed: %v", err)
}
if got := cat.MetadataGuard(); got != tc.guard {
t.Fatalf("metadata guard %q, want %q", got, tc.guard)
}
id, err := layout.NewVolumeID()
if err != nil {
t.Fatal(err)
}
v := VolumeRef{Name: "v1", ID: id}
st, err := cat.Store(v)
if err != nil {
t.Fatal(err)
}
if st.ChunkGuard() != tc.storeG {
t.Fatalf("a store opened by the catalog has chunk guard %v, want %v", st.ChunkGuard(), tc.storeG)
}
// /status/chunk answers the catalog's usage: it names the guard.
ctx := context.Background()
if _, err := cat.CreateVolume(ctx, v, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil {
t.Fatal(err)
}
if u, err := cat.Usage(ctx, v); err != nil || u.MetadataGuard != tc.guard {
t.Fatalf("usage names guard %q (%v), want %q", u.MetadataGuard, err, tc.guard)
}
})
}
}
@@ -152,34 +152,5 @@ func (c *BCatalog) checkConditionalHead(ctx context.Context) error {
if err != nil || !bytes.Equal(before, after) {
return fmt.Errorf("%w: wrong-generation update changed %s", ErrConditionalHead, root)
}
c.chunkGuard = probeChunkCondition(ctx, c.f, root)
log.Printf("chunkstore: metadata change guard: %s", c.MetadataGuard())
return nil
}
// probeChunkCondition asks the filer to rewrite the disposable probe HEAD
// only if it holds a chunk it does not have. A filer that enforces
// IF_CHUNKS_EQUAL refuses; one that predates it drops the unknown field and
// applies the write (the same entry, in a directory nothing else reads).
// Only a definite refusal turns the guard on; anything else leaves the
// page re-read as the only check. No version string is consulted.
func probeChunkCondition(ctx context.Context, f Filer, root string) bool {
cf, ok := f.(ChunkConditionFiler)
if !ok {
return false
}
e, err := f.LookupEntry(ctx, root, layout.HeadName)
if err != nil {
log.Printf("chunkstore: WARNING chunk condition probe: read %s: %v", root, err)
return false
}
absent := append(entryFids(e), "0,"+strings.TrimPrefix(path.Base(root), startupProbePrefix))
err = cf.UpdateEntryIfChunks(ctx, root, e, nil, absent)
if errors.Is(err, ErrPrecondition) {
return true
}
if err != nil {
log.Printf("chunkstore: WARNING chunk condition probe: update %s: %v", root, err)
}
return false
}
@@ -23,12 +23,8 @@ type conditionalProbeServer struct {
configFiler
store *fakeFiler
mode string
updates int // updates without a write condition: the wrong-generation exchange
// chunkProbes counts updates carrying a write condition: the chunk
// condition probe. Only mode conditional-chunk-filer enforces it; the
// other modes drop it, as a filer that predates it does.
chunkProbes int
creates []*filerpb.CreateEntryRequest
updates int
creates []*filerpb.CreateEntryRequest
}
func (f *conditionalProbeServer) CreateEntry(ctx context.Context, r *filerpb.CreateEntryRequest) (*filerpb.CreateEntryResponse, error) {
@@ -42,29 +38,9 @@ func (f *conditionalProbeServer) CreateEntry(ctx context.Context, r *filerpb.Cre
}
func (f *conditionalProbeServer) UpdateEntry(ctx context.Context, r *filerpb.UpdateEntryRequest) (*filerpb.UpdateEntryResponse, error) {
f.mu.Lock()
if r.GetCondition() != nil {
f.chunkProbes++
} else {
f.updates++
}
f.updates++
mode := f.mode
f.mu.Unlock()
if mode == "conditional-chunk-filer" && r.GetCondition() != nil {
var fids []string
for _, c := range r.GetCondition().GetClauses() {
if c.GetKind() != filerpb.WriteCondition_IF_CHUNKS_EQUAL {
return nil, status.Error(codes.InvalidArgument, "unexpected clause")
}
fids = append(fids, c.GetFids()...)
}
if err := f.store.UpdateEntryIfChunks(ctx, r.Directory, r.Entry, r.ExpectedExtended, fids); err != nil {
if errors.Is(err, ErrPrecondition) {
return nil, status.Error(codes.FailedPrecondition, err.Error())
}
return nil, status.Error(codes.Internal, err.Error())
}
return &filerpb.UpdateEntryResponse{}, nil
}
if mode == "not-found" {
return nil, status.Error(codes.NotFound, "update target absent")
}
@@ -119,7 +95,7 @@ func (f *conditionalProbeServer) DeleteEntry(ctx context.Context, r *filerpb.Del
return &filerpb.DeleteEntryResponse{}, nil
}
func TestCatalogStartupRequiresWrongGenerationHeadRefusal(t *testing.T) {
for _, mode := range []string{"ignores-conditions", "mutates-then-refuses", "transport-error", "not-found", "conditional-filer", "conditional-chunk-filer", "cleanup-head-error", "cleanup-dir-error"} {
for _, mode := range []string{"ignores-conditions", "mutates-then-refuses", "transport-error", "not-found", "conditional-filer", "cleanup-head-error", "cleanup-dir-error"} {
t.Run(mode, func(t *testing.T) {
var logs bytes.Buffer
previous := log.Writer()
@@ -144,8 +120,7 @@ func TestCatalogStartupRequiresWrongGenerationHeadRefusal(t *testing.T) {
if client != nil {
defer client.Close()
}
admitted := mode == "conditional-filer" || mode == "conditional-chunk-filer" || strings.HasPrefix(mode, "cleanup-")
if !admitted {
if mode != "conditional-filer" && !strings.HasPrefix(mode, "cleanup-") {
if !errors.Is(err, ErrConditionalHead) || cat != nil || !strings.Contains(err.Error(), "conditional HEAD") {
t.Fatalf("broken conditional startup: cat=%v err=%v", cat, err)
}
@@ -156,27 +131,9 @@ func TestCatalogStartupRequiresWrongGenerationHeadRefusal(t *testing.T) {
t.Fatalf("cleanup warning missing: %s", logs.String())
}
f.mu.Lock()
updates, chunkProbes := f.updates, f.chunkProbes
updates := f.updates
creates := append([]*filerpb.CreateEntryRequest(nil), f.creates...)
f.mu.Unlock()
// An admitted startup sends one chunk condition probe, over the
// real client, and keeps the guard on only if the filer refused it.
wantProbes, wantGuard := 0, ""
if admitted {
wantProbes, wantGuard = 1, MetadataGuardReread
if mode == "conditional-chunk-filer" {
wantGuard = MetadataGuardChunks
}
}
if chunkProbes != wantProbes {
t.Fatalf("chunk condition probes=%d want %d", chunkProbes, wantProbes)
}
if admitted && cat.MetadataGuard() != wantGuard {
t.Fatalf("metadata guard %q want %q", cat.MetadataGuard(), wantGuard)
}
if admitted && !strings.Contains(logs.String(), "metadata change guard: "+wantGuard) {
t.Fatalf("the startup log does not name the guard %q: %s", wantGuard, logs.String())
}
// This mint is a disposable HEAD label, not an alternate volume
// creator. No VOLUME, lifecycle identity or real volume root is used.
if len(creates) != 1 {
+1 -12
View File
@@ -160,19 +160,8 @@ func (c *SWFS) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, oE
// FailedPrecondition. Any other error is ambiguous (the write may or may not
// have applied) and is returned unwrapped from the sentinels.
func (c *SWFS) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
return c.updateEntry(ctx, dir, e, expected, nil)
}
// UpdateEntryIfChunks implements ChunkConditionFiler: UpdateEntry that also
// sends the filer's IF_CHUNKS_EQUAL condition with fids. A failed condition
// comes back as gRPC FailedPrecondition, like a failed expected_extended.
func (c *SWFS) UpdateEntryIfChunks(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte, fids []string) error {
return c.updateEntry(ctx, dir, e, expected, chunksEqual(fids))
}
func (c *SWFS) updateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte, cond *filerpb.WriteCondition) error {
return maintenanceError(ctx, func(ctx context.Context) error {
_, err := c.fc.UpdateEntry(ctx, &filerpb.UpdateEntryRequest{Directory: dir, Entry: e, ExpectedExtended: expected, Condition: cond})
_, err := c.fc.UpdateEntry(ctx, &filerpb.UpdateEntryRequest{Directory: dir, Entry: e, ExpectedExtended: expected})
if err == nil {
return nil
}
+18
View File
@@ -121,6 +121,11 @@ type Config struct {
// GET /status/workspace-lease on this loopback address.
StatusListen string
// FailStopLifecycleWrites exits the process on uncertain lifecycle-store
// persistence. The supervised blockmaster executable enables it; embedders
// that leave it off must reopen a failed store before attempting mutations.
FailStopLifecycleWrites bool
// Logger is used for structured startup and error logging. If
// nil, the default log package logger is used.
Logger *log.Logger
@@ -275,6 +280,10 @@ func New(cfg Config) (*Host, error) {
if lg == nil {
lg = log.Default()
}
var persistenceFailure lifecycle.PersistenceFailureHandler
if cfg.FailStopLifecycleWrites {
persistenceFailure = lifecycleFailStop(lg)
}
holder := &publisherHolder{}
ctrlCfg := cfg.ControllerConfig
@@ -323,9 +332,18 @@ func New(cfg Config) (*Host, error) {
// the master's state it reads.
lifecycleStores, err := openLifecycleStores(cfg.LifecycleStoreDir)
if err != nil {
var failure *lifecycle.RecordPersistenceError
if persistenceFailure != nil && errors.As(err, &failure) {
persistenceFailure(failure)
}
_ = boot.Close()
return nil, fmt.Errorf("master.New: lifecycle stores: %w", err)
}
if lifecycleStores != nil && persistenceFailure != nil {
lifecycleStores.Nodes.SetPersistenceFailureHandler(persistenceFailure)
lifecycleStores.Placements.SetPersistenceFailureHandler(persistenceFailure)
lifecycleStores.Volumes.SetPersistenceFailureHandler(persistenceFailure)
}
// A new cluster starts at the current level: with no prior
// state in any master store (no authority record reloaded or skipped, no
// attestation file, no volume, node, placement or deletion in the
@@ -0,0 +1,25 @@
package master
import (
"log"
"os"
"sync"
"time"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
)
func lifecycleFailStop(logger *log.Logger) lifecycle.PersistenceFailureHandler {
var once sync.Once
return func(failure *lifecycle.RecordPersistenceError) {
once.Do(func() {
// Arm termination before touching the logger: its writer or output
// mutex may be blocked. ERROR delivery is best effort in that case.
time.AfterFunc(time.Second, func() { os.Exit(1) })
logger.Printf("ERROR lifecycle persistence failure store=%q record=%q error=%q; exiting so the supervisor restarts from durable state", failure.Store, failure.Record, failure.Err)
// A graceful close can wait on the writer that discovered the error.
// The supervisor restarts; Open establishes the recovery barriers.
os.Exit(1)
})
}
}
@@ -0,0 +1,273 @@
//go:build linux
package master
import (
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"syscall"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
)
func TestLifecyclePersistenceFailureStopsTheProcess(t *testing.T) {
for _, kind := range []string{"nodes", "placements", "volumes", "concurrent"} {
t.Run(kind, func(t *testing.T) {
root := t.TempDir()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestLifecyclePersistenceExitChild$", "-test.timeout=8s")
cmd.Env = append(os.Environ(), "LIFECYCLE_EXIT_ROOT="+root, "LIFECYCLE_EXIT_KIND="+kind)
out, err := cmd.CombinedOutput()
var exit *exec.ExitError
if ctx.Err() != nil || !errors.As(err, &exit) || exit.ExitCode() != 1 {
t.Fatalf("master failed to exit1: %v context=%v\n%s", err, ctx.Err(), out)
}
text := string(out)
record := "new.json"
if kind == "volumes" {
record = "kept.json"
}
if strings.Count(text, "exiting so the supervisor restarts from durable state") != 1 || !strings.Contains(text, "ERROR") || !strings.Contains(text, record) || !strings.Contains(text, filepath.Join(root, "lifecycle")) {
t.Fatalf("missing single record/store/error line: %s", text)
}
recovery := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestLifecyclePersistenceRecoveryChild$", "-test.timeout=8s")
recovery.Env = append(os.Environ(), "LIFECYCLE_RECOVERY_ROOT="+root, "LIFECYCLE_EXIT_KIND="+kind)
if out, err := recovery.CombinedOutput(); err != nil {
t.Fatalf("bounded recovery: %v context=%v\n%s", err, ctx.Err(), out)
}
})
}
}
func TestLifecyclePersistenceRecoveryChild(t *testing.T) {
root := os.Getenv("LIFECYCLE_RECOVERY_ROOT")
if root == "" {
t.Skip("bounded recovery subprocess")
}
kind := os.Getenv("LIFECYCLE_EXIT_KIND")
h, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: filepath.Join(root, "authority"), LifecycleStoreDir: filepath.Join(root, "lifecycle"), FailStopLifecycleWrites: true})
if err != nil {
t.Fatal("restart", err)
}
h.Start()
t.Cleanup(func() {
c, stop := context.WithTimeout(context.Background(), 5*time.Second)
defer stop()
if err := h.Close(c); err != nil {
t.Error(err)
}
})
kinds := []string{kind}
if kind == "concurrent" {
kinds = []string{"nodes", "placements"}
}
for _, part := range kinds {
raw, err := os.ReadFile(filepath.Join(root, "lifecycle", part, "kept.json"))
if err != nil {
t.Fatal(err)
}
want, err := os.ReadFile(filepath.Join(root, part+"-sha256"))
if err != nil || fmt.Sprintf("%x", sha256.Sum256(raw)) != string(want) {
t.Fatalf("restart changed committed %s: %v", part, err)
}
var kept, failed bool
switch part {
case "nodes":
_, kept = h.Lifecycle().Nodes.GetNodeSnapshot("kept")
_, failed = h.Lifecycle().Nodes.GetNodeSnapshot("new")
case "placements":
_, kept = h.Lifecycle().Placements.GetPlacementSnapshot("kept")
_, failed = h.Lifecycle().Placements.GetPlacementSnapshot("new")
case "volumes":
_, kept = h.Lifecycle().Volumes.GetVolumeSnapshot("kept")
_, failed = h.Lifecycle().Volumes.GetVolumeSnapshot("new")
}
if !kept || failed {
t.Fatalf("restart published wrong %s records", part)
}
entries, err := os.ReadDir(filepath.Join(root, "lifecycle", part))
if err != nil {
t.Fatal(err)
}
for _, entry := range entries {
if !entry.IsDir() && strings.HasSuffix(entry.Name(), ".json") {
raw, err := os.ReadFile(filepath.Join(root, "lifecycle", part, entry.Name()))
if err != nil || !json.Valid(raw) {
t.Fatalf("partial record %s: %v", entry.Name(), err)
}
}
}
}
}
type blockedLifecycleLog struct {
entered chan struct{}
once sync.Once
}
func (w *blockedLifecycleLog) Write(p []byte) (int, error) {
w.once.Do(func() { close(w.entered) })
select {}
}
func TestLifecycleFailStopExitsWithBlockedLogger(t *testing.T) {
for _, mode := range []string{"writer", "held-lock"} {
t.Run(mode, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestLifecycleBlockedLoggerChild$", "-test.timeout=4s")
cmd.Env = append(os.Environ(), "LIFECYCLE_BLOCKED_LOG="+mode)
out, err := cmd.CombinedOutput()
exited := time.Now()
var exit *exec.ExitError
if ctx.Err() != nil || !errors.As(err, &exit) || exit.ExitCode() != 1 {
t.Fatalf("blocked logger prevented own exit1: %v context=%v\n%s", err, ctx.Err(), out)
}
var triggered int64
for _, line := range strings.Split(string(out), "\n") {
if v, ok := strings.CutPrefix(line, "lifecycle-failure-triggered="); ok {
triggered, _ = strconv.ParseInt(v, 10, 64)
}
}
if triggered == 0 {
t.Fatalf("child did not report its failure trigger:\n%s", out)
}
// One-second deadline plus one second of scheduler tolerance; the
// subprocess watchdog above is separate and longer.
if elapsed := exited.Sub(time.Unix(0, triggered)); elapsed > 2*time.Second {
t.Fatalf("exit took %s after the failure, want within the one-second deadline", elapsed)
}
})
}
}
func TestLifecycleBlockedLoggerChild(t *testing.T) {
mode := os.Getenv("LIFECYCLE_BLOCKED_LOG")
if mode == "" {
t.Skip("bounded blocked-sink child")
}
w := &blockedLifecycleLog{entered: make(chan struct{})}
logger := log.New(w, "", 0)
if mode == "held-lock" {
go logger.Print("earlier message")
<-w.entered
}
fail := lifecycleFailStop(logger)
fmt.Printf("lifecycle-failure-triggered=%d\n", time.Now().UnixNano())
go fail(&lifecycle.RecordPersistenceError{Store: "nodes", Record: "v.json", Err: errors.New("fixture")})
fail(&lifecycle.RecordPersistenceError{Store: "placements", Record: "v.json", Err: errors.New("fixture")})
os.Exit(91)
}
func TestLifecyclePersistenceExitChild(t *testing.T) {
root := os.Getenv("LIFECYCLE_EXIT_ROOT")
if root == "" {
t.Skip("bounded fail-stop subprocess")
}
h, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: filepath.Join(root, "authority"), LifecycleStoreDir: filepath.Join(root, "lifecycle"), FailStopLifecycleWrites: true})
if err != nil {
t.Fatal(err)
}
h.Start()
put := func(kind, id string) error {
switch kind {
case "nodes":
_, err := h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: id, Addr: "127.0.0.1:19001"})
return err
case "placements":
_, err := h.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: id, DesiredRF: 1, Candidates: []lifecycle.PlacementCandidate{{ServerID: "node", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}})
return err
default:
_, err := h.Lifecycle().Volumes.CreateVolume(lifecycle.VolumeSpec{VolumeID: id, SizeBytes: 1 << 20, ReplicationFactor: 1})
return err
}
}
kinds := []string{os.Getenv("LIFECYCLE_EXIT_KIND")}
if kinds[0] == "concurrent" {
kinds = []string{"nodes", "placements"}
}
for _, kind := range kinds {
if err := put(kind, "kept"); err != nil {
t.Fatal(err)
}
raw, err := os.ReadFile(filepath.Join(root, "lifecycle", kind, "kept.json"))
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, kind+"-sha256"), []byte(fmt.Sprintf("%x", sha256.Sum256(raw))), 0600); err != nil {
t.Fatal(err)
}
if kind == "volumes" {
continue
}
block := filepath.Join(root, "lifecycle", kind, "new.json")
if err := os.Mkdir(block, 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(block, "blocker"), []byte("fixture"), 0600); err != nil {
t.Fatal(err)
}
}
var descriptors []*os.File
if kinds[0] == "volumes" {
// Attach has no pre-write record lookup on disk. Exhaust only this child's
// descriptor budget so CreateTemp fails while its committed file stays intact.
var limit syscall.Rlimit
if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {
t.Fatal(err)
}
if limit.Cur > 128 {
limit.Cur = 128
}
if err := syscall.Setrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {
t.Fatal(err)
}
for {
file, err := os.Open(os.DevNull)
if errors.Is(err, syscall.EMFILE) {
break
}
if err != nil {
t.Fatal(err)
}
descriptors = append(descriptors, file)
}
}
start := make(chan struct{})
done := make(chan error, len(kinds))
for _, kind := range kinds {
go func(kind string) {
<-start
if kind == "volumes" {
_, err := h.Lifecycle().Volumes.AttachVolume("kept", "node")
done <- err
return
}
done <- put(kind, "new")
}(kind)
}
close(start)
for range kinds {
if err := <-done; err != nil {
fmt.Fprintln(os.Stderr, "persistence error returned instead of exiting:", err)
os.Exit(91)
}
}
runtime.KeepAlive(descriptors)
fmt.Fprintln(os.Stderr, "failed persistence did not stop master")
os.Exit(92)
}
@@ -16,7 +16,7 @@ import (
// GET /status/chunk?volume= answers the served volume's space accounting
// and retention policy; the usual chunk-route guards apply.
func TestStatusServer_StatusChunkUsage(t *testing.T) {
fake := &fakeChunkControl{usage: chunkstore.Usage{Snapshots: 1, Dependents: 2, OwnChunks: 3, ForeignChunks: 4, MetadataGuard: chunkstore.MetadataGuardChunks}}
fake := &fakeChunkControl{usage: chunkstore.Usage{Snapshots: 1, Dependents: 2, OwnChunks: 3, ForeignChunks: 4}}
s := chunkServer(t, fake, true)
w := serveStatusChunk(t, s, http.MethodGet, "/status/chunk?volume=v1")
if w.Code != http.StatusOK {
@@ -0,0 +1,41 @@
package lifecycle
import (
"errors"
"strings"
"testing"
)
func TestImportRejectionNamesTheEntry(t *testing.T) {
nodes, err := OpenNodeInventoryStore(t.TempDir())
if err != nil {
t.Fatal(err)
}
err = nodes.ImportNodes([]NodeRegistration{{ServerID: "good", Addr: "127.0.0.1:19001"}, {ServerID: "no-addr"}})
if !errors.Is(err, ErrInvalidNodeRegistration) || !strings.Contains(err.Error(), "no-addr") {
t.Fatalf("node import error = %v, want ErrInvalidNodeRegistration naming no-addr", err)
}
if _, ok := nodes.GetNodeSnapshot("good"); ok {
t.Fatal("rejected node step published an entry")
}
if err := nodes.ImportNodes([]NodeRegistration{{ServerID: "good", Addr: "127.0.0.1:19001"}}); err != nil {
t.Fatalf("validation rejection blocked the next import: %v", err)
}
placements, err := OpenPlacementIntentStore(t.TempDir())
if err != nil {
t.Fatal(err)
}
valid := PlacementPlan{VolumeID: "good", DesiredRF: 1, Candidates: []PlacementCandidate{{ServerID: "node", ReplicaID: "r1", Source: PlacementSourceExistingReplica}}}
short := PlacementPlan{VolumeID: "short", DesiredRF: 2, Candidates: valid.Candidates}
err = placements.ImportPlans([]PlacementPlan{valid, short})
if !errors.Is(err, ErrInsufficientPlacementCandidates) || !strings.Contains(err.Error(), "short") {
t.Fatalf("placement import error = %v, want ErrInsufficientPlacementCandidates naming short", err)
}
if _, ok := placements.GetPlacementSnapshot("good"); ok {
t.Fatal("rejected placement step published an entry")
}
if err := placements.ImportPlans([]PlacementPlan{valid}); err != nil {
t.Fatalf("validation rejection blocked the next import: %v", err)
}
}
@@ -0,0 +1,239 @@
//go:build linux
package lifecycle
import (
"context"
"errors"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
)
func TestRecordEqualityRequiresRecoveredDirectoryAndConsistentDisk(t *testing.T) {
for _, kind := range []string{"nodes", "placements"} {
for _, mode := range []string{"reopen-barrier", "single-directory", "batch-directory", "batch-second-file"} {
t.Run(kind+"/"+mode, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestRecordEqualityRecoveryChild$", "-test.timeout=8s")
cmd.Env = append(os.Environ(), "RECORD_RECOVERY_KIND="+kind, "RECORD_RECOVERY_MODE="+mode)
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("recovery control: %v context=%v\n%s", err, ctx.Err(), out)
}
})
}
}
}
func TestRecordEqualityRecoveryChild(t *testing.T) {
kind := os.Getenv("RECORD_RECOVERY_KIND")
if kind == "" {
t.Skip("isolated recovery hooks")
}
mode := os.Getenv("RECORD_RECOVERY_MODE")
dir := t.TempDir()
fault := errors.New("injected recovery barrier failure")
var cause error = fault
if mode == "syncfs-second-rename" {
cause = os.ErrNotExist
}
useSyncfs := strings.HasPrefix(mode, "syncfs-")
var apply func(bool) error
var view func() any
var reopen func() error
var otherMutations func() []error
var setPolicy func(PersistenceFailureHandler)
var latched func() bool
if kind == "nodes" {
var store *NodeInventoryStore
reopen = func() error { var err error; store, err = OpenNodeInventoryStore(dir); return err }
apply = func(changed bool) error {
nodes := []NodeRegistration{{ServerID: "a", Addr: "127.0.0.1:19001", SeenAt: time.Unix(1, 0).UTC()}, {ServerID: "b", Addr: "127.0.0.1:19001", SeenAt: time.Unix(1, 0).UTC()}}
if changed {
for i := range nodes {
nodes[i].Addr = "127.0.0.1:19002"
}
}
if mode == "single-directory" {
_, err := store.RegisterNode(nodes[0])
return err
}
return store.ImportNodes(nodes)
}
view = func() any { return store.ListNodes() }
setPolicy = func(handler PersistenceFailureHandler) { store.SetPersistenceFailureHandler(handler) }
latched = func() bool { return store.writeErr != nil }
otherMutations = func() []error {
_, e := store.RegisterNode(NodeRegistration{ServerID: "c", Addr: "127.0.0.1:19001"})
return []error{e, store.ImportNodes(nil), store.RemoveNode("a")}
}
} else {
var store *PlacementIntentStore
reopen = func() error { var err error; store, err = OpenPlacementIntentStore(dir); return err }
apply = func(changed bool) error {
plans := make([]PlacementPlan, 2)
for i, id := range []string{"a", "b"} {
plans[i] = PlacementPlan{VolumeID: id, DesiredRF: 1, Candidates: []PlacementCandidate{{ServerID: "node", ReplicaID: "r1", Source: PlacementSourceExistingReplica}}}
if changed {
plans[i].Candidates[0].ReplicaID = "r2"
}
}
if mode == "single-directory" {
_, err := store.ApplyPlan(plans[0])
return err
}
return store.ImportPlans(plans)
}
view = func() any { return store.ListPlacements() }
setPolicy = func(handler PersistenceFailureHandler) { store.SetPersistenceFailureHandler(handler) }
latched = func() bool { return store.writeErr != nil }
otherMutations = func() []error {
_, e := store.ApplyPlan(PlacementPlan{VolumeID: "c", DesiredRF: 1, Candidates: []PlacementCandidate{{ServerID: "node", ReplicaID: "r1", Source: PlacementSourceExistingReplica}}})
return []error{e, store.ImportPlans(nil), store.DeletePlacement("a")}
}
}
if err := reopen(); err != nil {
t.Fatal(err)
}
if err := apply(false); err != nil {
t.Fatal(err)
}
old := view()
callbacks := 0
setPolicy(func(failure *RecordPersistenceError) {
callbacks++
record := "<import-step>"
if mode == "single-directory" {
record = "a.json"
}
if mode == "batch-second-file" || mode == "syncfs-second-rename" {
record = "b.json"
}
if !latched() || failure.Store != dir || failure.Record != record || !errors.Is(failure, cause) {
t.Fatalf("incorrect failure-policy context: %+v", failure)
}
})
if mode == "reopen-barrier" {
called := 0
durableRecordHooksForTest.Store(&durableRecordHooks{dirSync: func(path string) error {
called++
if path != dir {
t.Fatal("recovery synced wrong directory")
}
return fault
}})
defer durableRecordHooksForTest.Store(nil)
if err := reopen(); !errors.Is(err, fault) {
t.Fatalf("loaded records published without a successful recovery barrier: %v calls=%d", err, called)
}
if called != 1 {
t.Fatalf("recovery directory barriers=%d want1", called)
}
durableRecordHooksForTest.Store(nil)
if err := reopen(); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(view(), old) {
t.Fatal("recovery barrier changed record contents")
}
return
}
files, filesystemSyncs, renames, directorySyncs, ioCalls := 0, 0, 0, 0, 0
durableRecordHooksForTest.Store(&durableRecordHooks{batchSyncfs: &useSyncfs,
crash: func(point string) {
ioCalls++
if point == "before-rename" {
renames++
if mode == "syncfs-second-rename" && renames == 2 {
temps, err := filepath.Glob(filepath.Join(dir, "b.json.*.tmp"))
if err != nil || len(temps) != 1 {
t.Fatalf("second rename has no unique staged file: %v %v", temps, err)
}
if err := os.Remove(temps[0]); err != nil {
t.Fatal(err)
}
}
}
},
fileSync: func(f *os.File) error {
ioCalls++
files++
if useSyncfs {
t.Fatal("batch syncfs control fell back to per-file fsync")
}
if mode == "batch-second-file" && files == 2 {
return fault
}
return f.Sync()
},
fsSync: func(fd *os.File) error {
ioCalls++
filesystemSyncs++
if mode == "syncfs-failure" {
return fault
}
return syncRecordFilesystem(fd)
},
dirSync: func(string) error { ioCalls++; directorySyncs++; return fault },
})
defer durableRecordHooksForTest.Store(nil)
if err := apply(true); !errors.Is(err, cause) {
t.Fatalf("fixture did not expose the failed persistence: %v", err)
}
if callbacks != 1 {
t.Fatalf("failure callbacks=%d want1", callbacks)
}
if !reflect.DeepEqual(view(), old) {
t.Fatal("failed write published its records")
}
if useSyncfs {
wantRenames, wantDirs := 0, 0
if mode == "syncfs-second-rename" {
wantRenames = 2
}
if mode == "syncfs-directory" {
wantRenames = 2
wantDirs = 1
}
if filesystemSyncs != 1 || renames != wantRenames || directorySyncs != wantDirs || files != 0 {
t.Fatalf("failure boundary: syncfs=%d renames=%d dir=%d files=%d", filesystemSyncs, renames, directorySyncs, files)
}
}
beforeRefusals := ioCalls
for _, err := range otherMutations() {
if !errors.Is(err, ErrLifecycleRecoveryRequired) {
t.Fatalf("mutation after uncertainty: %v", err)
}
}
if callbacks != 1 {
t.Fatalf("refused mutation called policy again: %d", callbacks)
}
retryErr := apply(false)
if !errors.Is(retryErr, ErrLifecycleRecoveryRequired) {
t.Fatalf("old-value retry must require recovery: %v", retryErr)
}
if callbacks != 1 || ioCalls != beforeRefusals {
t.Fatalf("poisoned mutation retried I/O/policy: io=%d/%d callbacks=%d", ioCalls, beforeRefusals, callbacks)
}
durableRecordHooksForTest.Store(nil)
if err := reopen(); err != nil {
t.Fatal(err)
}
if useSyncfs && !reflect.DeepEqual(view(), syncfsFailureReopenedView(old, mode)) {
t.Fatalf("reopen did not expose complete records at the injected boundary: got=%+v want=%+v", view(), syncfsFailureReopenedView(old, mode))
}
if err := apply(false); err != nil {
t.Fatalf("recovered store cannot restore the old value: %v", err)
}
if err := reopen(); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(view(), old) {
t.Fatal("successful post-recovery write did not match disk")
}
}
@@ -0,0 +1,210 @@
//go:build linux
package lifecycle
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"reflect"
"testing"
"time"
)
func TestImportStepSyncsChangedFilesThenOneDirectory(t *testing.T) {
for _, kind := range []string{"nodes", "placements"} {
for _, failure := range []string{"none", "file", "second-file", "directory"} {
t.Run(kind+"/"+failure, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestImportStepSyncChild$", "-test.timeout=8s")
cmd.Env = append(os.Environ(), "IMPORT_STEP_KIND="+kind, "IMPORT_STEP_FAILURE="+failure)
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("import control: %v context=%v\n%s", err, ctx.Err(), out)
}
})
}
}
}
func TestImportStepSyncChild(t *testing.T) {
kind := os.Getenv("IMPORT_STEP_KIND")
if kind == "" {
t.Skip("isolated filesystem hooks")
}
failure := os.Getenv("IMPORT_STEP_FAILURE")
dir := t.TempDir()
var apply func(bool) error
var snapshot func() any
var reopen func() any
var values func() []string
var wantValues []string
if kind == "nodes" {
store, err := OpenNodeInventoryStore(dir)
if err != nil {
t.Fatal(err)
}
nodes := []NodeRegistration{{ServerID: "a", Addr: "127.0.0.1:19001"}, {ServerID: "b", Addr: "127.0.0.1:19001"}, {ServerID: "unchanged", Addr: "127.0.0.1:19001"}}
apply = func(change bool) error {
next := append([]NodeRegistration(nil), nodes...)
if change {
next[0].Addr = "127.0.0.1:19002"
next[1].Addr = "127.0.0.1:19002"
}
return store.ImportNodes(next)
}
snapshot = func() any {
var got []NodeRegistration
for _, node := range nodes {
r, _ := store.GetNodeSnapshot(node.ServerID)
got = append(got, r)
}
return got
}
values = func() []string {
var got []string
for _, node := range nodes {
r, _ := store.GetNodeSnapshot(node.ServerID)
got = append(got, r.Addr)
}
return got
}
wantValues = []string{"127.0.0.1:19002", "127.0.0.1:19002", "127.0.0.1:19001"}
reopen = func() any {
s, err := OpenNodeInventoryStore(dir)
if err != nil {
t.Fatal(err)
}
store = s
return s.ListNodes()
}
} else {
store, err := OpenPlacementIntentStore(dir)
if err != nil {
t.Fatal(err)
}
plans := make([]PlacementPlan, 3)
for i, id := range []string{"a", "b", "unchanged"} {
plans[i] = PlacementPlan{VolumeID: id, DesiredRF: 1, Candidates: []PlacementCandidate{{ServerID: "node", ReplicaID: "r1", Source: PlacementSourceExistingReplica}}}
}
apply = func(change bool) error {
next := make([]PlacementPlan, len(plans))
copy(next, plans)
for i := range next {
next[i].Candidates = append([]PlacementCandidate(nil), plans[i].Candidates...)
}
if change {
next[0].Candidates[0].ReplicaID = "r2"
next[1].Candidates[0].ReplicaID = "r2"
}
return store.ImportPlans(next)
}
snapshot = func() any {
var got []PlacementIntent
for _, p := range plans {
r, _ := store.GetPlacementSnapshot(p.VolumeID)
got = append(got, r)
}
return got
}
values = func() []string {
var got []string
for _, p := range plans {
r, _ := store.GetPlacementSnapshot(p.VolumeID)
if len(r.Slots) != 1 {
return nil
}
got = append(got, r.Slots[0].ReplicaID)
}
return got
}
wantValues = []string{"r2", "r2", "r1"}
reopen = func() any {
s, err := OpenPlacementIntentStore(dir)
if err != nil {
t.Fatal(err)
}
store = s
return s.ListPlacements()
}
}
if err := apply(false); err != nil {
t.Fatal(err)
}
old := snapshot()
var events []string
fault := errors.New("injected import sync failure")
// Qualify the portable per-file fallback independently of the syncfs path.
useSyncfs := false
durableRecordHooksForTest.Store(&durableRecordHooks{
batchSyncfs: &useSyncfs,
fileSync: func(file *os.File) error {
events = append(events, "file")
if failure == "file" || failure == "second-file" && len(events) == 2 {
return fault
}
return file.Sync()
},
dirSync: func(path string) error {
events = append(events, "directory")
if !reflect.DeepEqual(snapshot(), old) {
t.Fatal("step published before its directory barrier")
}
if path != dir {
t.Fatal("wrong import directory barrier")
}
if failure == "directory" {
return fault
}
return syncBindingParent(path)
},
})
defer durableRecordHooksForTest.Store(nil)
err := apply(true)
want := []string{"file", "file", "directory"}
if failure == "file" {
want = []string{"file"}
} else if failure == "second-file" {
want = []string{"file", "file"}
}
if !reflect.DeepEqual(events, want) {
t.Fatalf("events %v want %v", events, want)
}
if failure != "none" {
if !errors.Is(err, fault) {
t.Fatalf("sync failure hidden: %v", err)
}
if !reflect.DeepEqual(snapshot(), old) {
t.Fatal("failed step changed the published snapshot")
}
// A failed step requires recovery before any further mutations.
durableRecordHooksForTest.Store(nil)
if err := apply(true); !errors.Is(err, ErrLifecycleRecoveryRequired) {
t.Fatalf("mutation after failed persistence: %v", err)
}
reopen()
if err := apply(true); err != nil {
t.Fatal(err)
}
} else if err != nil {
t.Fatal(err)
}
if got := values(); !reflect.DeepEqual(got, wantValues) {
t.Fatalf("completed import published %v want %v", got, wantValues)
}
completed := snapshot()
durableRecordHooksForTest.Store(nil)
if !reflect.DeepEqual(reopen(), completed) {
t.Fatal("completed import did not survive reopen")
}
if got := values(); !reflect.DeepEqual(got, wantValues) {
t.Fatalf("reopened store holds %v want %v", got, wantValues)
}
events = nil
durableRecordHooksForTest.Store(&durableRecordHooks{fileSync: func(*os.File) error { return fmt.Errorf("unchanged file synced") }, dirSync: func(string) error { return fmt.Errorf("unchanged directory synced") }})
if err := apply(true); err != nil {
t.Fatalf("unchanged step did I/O: %v", err)
}
}
@@ -0,0 +1,379 @@
//go:build linux
package lifecycle
import (
"context"
"encoding/json"
"errors"
"os"
"os/exec"
"path/filepath"
"reflect"
"testing"
"time"
"golang.org/x/sys/unix"
)
func TestImportBatchStagesAllFilesBeforeAnyRename(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestImportBatchStageChild$", "-test.timeout=8s")
cmd.Env = append(os.Environ(), "IMPORT_BATCH_STAGE_CHILD=1")
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("batch stage control: %v context=%v\n%s", err, ctx.Err(), out)
}
}
func TestImportBatchStageChild(t *testing.T) {
if os.Getenv("IMPORT_BATCH_STAGE_CHILD") == "" {
t.Skip("isolated filesystem hooks")
}
dir := t.TempDir()
s, err := OpenNodeInventoryStore(dir)
if err != nil {
t.Fatal(err)
}
checked := false
useSyncfs := true
durableRecordHooksForTest.Store(&durableRecordHooks{batchSyncfs: &useSyncfs, crash: func(point string) {
if point != "before-rename" || checked {
return
}
checked = true
temps, err := filepath.Glob(filepath.Join(dir, "*.tmp"))
if err != nil {
t.Fatal(err)
}
if len(temps) != 2 {
t.Fatalf("first rename has %d staged files, want 2", len(temps))
}
}})
defer durableRecordHooksForTest.Store(nil)
if err := s.ImportNodes([]NodeRegistration{{ServerID: "a", Addr: "127.0.0.1:19001"}, {ServerID: "b", Addr: "127.0.0.1:19002"}}); err != nil {
t.Fatal(err)
}
if !checked {
t.Fatal("rename boundary not observed")
}
}
func TestImportSyncfsFailureAndOrdering(t *testing.T) {
for _, kind := range []string{"nodes", "placements"} {
for _, mode := range []string{"success", "failure", "old-kernel"} {
t.Run(kind+"/"+mode, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestImportSyncfsChild$", "-test.timeout=8s")
cmd.Env = append(os.Environ(), "IMPORT_SYNCFS_KIND="+kind, "IMPORT_SYNCFS_MODE="+mode)
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("syncfs control: %v context=%v\n%s", err, ctx.Err(), out)
}
})
}
}
}
func TestImportSyncfsChild(t *testing.T) {
kind := os.Getenv("IMPORT_SYNCFS_KIND")
if kind == "" {
t.Skip("isolated filesystem hooks")
}
mode := os.Getenv("IMPORT_SYNCFS_MODE")
dir := t.TempDir()
var apply func() error
var reopen func()
var snapshot func() int
if kind == "nodes" {
var s *NodeInventoryStore
reopen = func() {
var err error
s, err = OpenNodeInventoryStore(dir)
if err != nil {
t.Fatal(err)
}
}
apply = func() error {
return s.ImportNodes([]NodeRegistration{{ServerID: "a", Addr: "127.0.0.1:19001"}, {ServerID: "b", Addr: "127.0.0.1:19002"}})
}
snapshot = func() int {
n := 0
for _, id := range []string{"a", "b"} {
if _, ok := s.GetNodeSnapshot(id); ok {
n++
}
}
return n
}
} else {
var s *PlacementIntentStore
reopen = func() {
var err error
s, err = OpenPlacementIntentStore(dir)
if err != nil {
t.Fatal(err)
}
}
apply = func() error {
return s.ImportPlans([]PlacementPlan{{VolumeID: "a", DesiredRF: 1, Candidates: []PlacementCandidate{{ServerID: "node", ReplicaID: "r1", Source: PlacementSourceExistingReplica}}}, {VolumeID: "b", DesiredRF: 1, Candidates: []PlacementCandidate{{ServerID: "node", ReplicaID: "r1", Source: PlacementSourceExistingReplica}}}})
}
snapshot = func() int {
n := 0
for _, id := range []string{"a", "b"} {
if _, ok := s.GetPlacementSnapshot(id); ok {
n++
}
}
return n
}
}
reopen()
useSyncfs := mode != "old-kernel"
fault := errors.New("injected filesystem writeback failure")
var events []string
var failedTemps []string
install := func(fail bool) {
durableRecordHooksForTest.Store(&durableRecordHooks{
batchSyncfs: &useSyncfs,
crash: func(point string) {
if point == "batch-open" {
temps, _ := filepath.Glob(filepath.Join(dir, "*.tmp"))
if len(temps) != 0 {
t.Fatal("syncfs fd opened after temp writes")
}
events = append(events, "open")
}
if point == "before-rename" {
if useSyncfs && !reflect.DeepEqual(events, []string{"open", "syncfs"}) && !reflect.DeepEqual(events, []string{"open", "syncfs", "rename"}) {
t.Fatalf("rename before syncfs completed: %v", events)
}
events = append(events, "rename")
}
},
fileSync: func(f *os.File) error {
if useSyncfs {
t.Fatal("syncfs path used per-file fsync")
}
events = append(events, "file")
return f.Sync()
},
fsSync: func(fd *os.File) error {
if fd.Name() != dir {
t.Fatal("wrong filesystem fd")
}
for _, name := range []string{"a.json", "b.json"} {
if _, err := os.Stat(filepath.Join(dir, name)); !os.IsNotExist(err) {
t.Fatalf("final record visible before syncfs: %s %v", name, err)
}
}
temps, _ := filepath.Glob(filepath.Join(dir, "*.tmp"))
if len(temps) != 2 {
t.Fatalf("staged temps=%v", temps)
}
if snapshot() != 0 {
t.Fatal("published before syncfs")
}
if fail {
failedTemps = temps
events = append(events, "syncfs")
return fault
}
for _, temp := range temps {
for _, old := range failedTemps {
if temp == old {
t.Fatal("reused failed temp")
}
}
}
if err := syncRecordFilesystem(fd); err != nil {
return err
}
events = append(events, "syncfs")
return nil
},
dirSync: func(path string) error {
if snapshot() != 0 {
t.Fatal("published before directory barrier")
}
events = append(events, "directory")
return syncBindingParent(path)
},
})
}
defer durableRecordHooksForTest.Store(nil)
install(mode == "failure")
err := apply()
if mode == "failure" {
if !errors.Is(err, fault) || !reflect.DeepEqual(events, []string{"open", "syncfs"}) {
t.Fatalf("failed syncfs retried/renamed: %v %v", events, err)
}
if snapshot() != 0 {
t.Fatal("failed import published")
}
if err := apply(); !errors.Is(err, ErrLifecycleRecoveryRequired) {
t.Fatalf("failed store admitted retry: %v", err)
}
if !reflect.DeepEqual(events, []string{"open", "syncfs"}) {
t.Fatal("poisoned retry performed I/O")
}
durableRecordHooksForTest.Store(nil)
reopen()
events = nil
install(false)
err = apply()
}
if err != nil {
t.Fatal(err)
}
want := []string{"open", "syncfs", "rename", "rename", "directory"}
if !useSyncfs {
want = []string{"file", "rename", "file", "rename", "directory"}
}
if !reflect.DeepEqual(events, want) {
t.Fatalf("events=%v want=%v", events, want)
}
if snapshot() != 2 {
t.Fatal("successful import not published")
}
durableRecordHooksForTest.Store(nil)
reopen()
if snapshot() != 2 {
t.Fatal("completed import lost on reopen")
}
}
// Returned-error controls complement the process-crash ordering controls:
// the published view stays old while complete disk records may be old or new.
func TestImportSyncfsReturnedFailurePolicyAndReplay(t *testing.T) {
for _, kind := range []string{"nodes", "placements"} {
for _, mode := range []string{"syncfs-failure", "syncfs-second-rename", "syncfs-directory"} {
t.Run(kind+"/"+mode, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestRecordEqualityRecoveryChild$", "-test.timeout=8s")
cmd.Env = append(os.Environ(), "RECORD_RECOVERY_KIND="+kind, "RECORD_RECOVERY_MODE="+mode)
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("returned syncfs failure control: %v context=%v\n%s", err, ctx.Err(), out)
}
})
}
}
}
func syncfsFailureReopenedView(old any, mode string) any {
changed := func(id string) bool {
return mode == "syncfs-directory" || (mode == "syncfs-second-rename" && id == "a")
}
switch records := old.(type) {
case []NodeRegistration:
out := make([]NodeRegistration, len(records))
for i, rec := range records {
out[i] = copyNodeRegistration(rec)
if changed(rec.ServerID) {
out[i].Addr = "127.0.0.1:19002"
}
}
return out
case []PlacementIntent:
out := make([]PlacementIntent, len(records))
for i, rec := range records {
out[i] = copyPlacementIntent(rec)
if changed(rec.VolumeID) {
out[i].Slots[0].ReplicaID = "r2"
}
}
return out
default:
panic("unexpected fixture records")
}
}
func TestSyncfsKernelGate(t *testing.T) {
for release, want := range map[string]bool{"5.7.19": false, "5.8.0": true, "6.8.0-azure": true, "4.19.0": false, "unknown": false, "5.x.0": false} {
if got := kernelHasSyncfsErrors(release); got != want {
t.Errorf("%s: got %v want %v", release, got, want)
}
}
}
func TestImportSyncfsCrashBoundaries(t *testing.T) {
for _, point := range []string{"before-syncfs", "after-syncfs", "after-rename"} {
t.Run(point, func(t *testing.T) {
dir := t.TempDir()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestImportSyncfsCrashChild$", "-test.timeout=8s")
cmd.Env = append(os.Environ(), "IMPORT_CRASH_DIR="+dir, "IMPORT_CRASH_POINT="+point)
out, err := cmd.CombinedOutput()
var exit *exec.ExitError
if ctx.Err() != nil || !errors.As(err, &exit) || exit.ExitCode() != 86 {
t.Fatalf("crash child: %v context=%v\n%s", err, ctx.Err(), out)
}
s, err := OpenNodeInventoryStore(dir)
if err != nil {
t.Fatal(err)
}
want := 0
if point == "after-rename" {
want = 1
}
if len(s.ListNodes()) != want {
t.Fatalf("reopen records=%v want=%d", s.ListNodes(), want)
}
for _, rec := range s.ListNodes() {
if rec.ServerID != "a" || rec.Addr != "127.0.0.1:19001" {
t.Fatalf("incomplete record: %+v", rec)
}
}
// A malformed final name is refused, never silently admitted; leftover
// unsynced temp names are ignored. This is a process-crash ordering
// control, not a claim to simulate a machine power loss.
if err := os.WriteFile(filepath.Join(dir, "broken.json"), []byte(`{"server_id":`), 0600); err != nil {
t.Fatal(err)
}
if _, err := OpenNodeInventoryStore(dir); err == nil {
t.Fatal("torn JSON accepted")
}
})
}
}
func TestImportSyncfsCrashChild(t *testing.T) {
dir := os.Getenv("IMPORT_CRASH_DIR")
if dir == "" {
t.Skip("bounded crash child")
}
s, err := OpenNodeInventoryStore(dir)
if err != nil {
t.Fatal(err)
}
useSyncfs := true
durableRecordHooksForTest.Store(&durableRecordHooks{batchSyncfs: &useSyncfs, crash: func(point string) {
if point == os.Getenv("IMPORT_CRASH_POINT") {
os.Exit(86)
}
}})
if err := s.ImportNodes([]NodeRegistration{{ServerID: "a", Addr: "127.0.0.1:19001"}, {ServerID: "b", Addr: "127.0.0.1:19002"}}); err != nil {
t.Fatal(err)
}
raw, _ := json.Marshal(s.ListNodes())
t.Fatalf("crash boundary not reached: %s", raw)
}
func TestSyncfsFilesystemGate(t *testing.T) {
for name, tc := range map[string]struct {
magic uint32
want bool
}{
"ext4": {unix.EXT4_SUPER_MAGIC, true}, "xfs": {unix.XFS_SUPER_MAGIC, true}, "btrfs": {unix.BTRFS_SUPER_MAGIC, true}, "tmpfs": {unix.TMPFS_MAGIC, true},
"overlay": {unix.OVERLAYFS_SUPER_MAGIC, false}, "fuse": {unix.FUSE_SUPER_MAGIC, false}, "nfs": {unix.NFS_SUPER_MAGIC, false}, "unknown": {0, false},
} {
if got := filesystemReportsSyncfsErrors(tc.magic); got != tc.want {
t.Errorf("%s: got %v want %v", name, got, tc.want)
}
}
if recordBatchSyncfsSupported(filepath.Join(t.TempDir(), "missing")) {
t.Error("an unreadable records directory selected syncfs")
}
}
@@ -126,6 +126,13 @@ func TestLifecycleLayoutIdentity(t *testing.T) {
t.Fatal(err)
}
failed = false
if _, err := loaded.CreateVolume(failedSpec); !errors.Is(err, ErrLifecycleRecoveryRequired) {
t.Fatalf("retry before recovery: %v", err)
}
loaded, err = OpenFileStore(dir)
if err != nil {
t.Fatal(err)
}
b, err = loaded.CreateVolume(failedSpec)
if err != nil || b.Spec.LayoutID != written.Spec.LayoutID {
t.Fatalf("unknown put retry changed identity: %v %+v", err, b)
@@ -61,8 +61,15 @@ func TestRedrawPendingLayoutID(t *testing.T) {
t.Fatal(e)
}
fail = false
if _, e := s.CreateVolume(spec); !errors.Is(e, ErrLifecycleRecoveryRequired) {
t.Fatalf("retry before recovery: %v", e)
}
s, e = OpenFileStore(s.dir)
if e != nil {
t.Fatal(e)
}
// Exercise the public retry path, including metadata enrichment. It
// must settle disk B before a metadata put could overwrite it with A.
// must preserve recovered disk B before a metadata put could overwrite it with A.
retry := spec
retry.PVCName, retry.PVName = "claim", "pv"
public, retryErr := s.CreateVolume(retry)
@@ -0,0 +1,95 @@
//go:build linux
package lifecycle
import (
"testing"
"time"
)
func TestUnchangedNodeRestartDoesNotRefreshAStaleObservation(t *testing.T) {
dir := t.TempDir()
now := time.Now().UTC()
oldSeen := now.Add(-2 * time.Hour)
reg := NodeRegistration{ServerID: "node", Addr: "127.0.0.1:19001", SeenAt: oldSeen}
store, err := OpenNodeInventoryStore(dir)
if err != nil {
t.Fatal(err)
}
if _, err := store.RegisterNode(reg); err != nil {
t.Fatal(err)
}
store, err = OpenNodeInventoryStore(dir)
if err != nil {
t.Fatal(err)
}
reg.SeenAt = time.Time{} // cluster-spec registrations have no observation time
if _, err := store.RegisterNode(reg); err != nil {
t.Fatal(err)
}
got, ok := store.GetNodeSnapshot("node")
if !ok {
t.Fatal("node missing after re-import")
}
intent := PlacementIntent{VolumeID: "volume", DesiredRF: 1, Slots: []PlacementSlotIntent{{ServerID: "node", PoolID: "pool", Source: PlacementSourceBlankPool}}}
verified := VerifyPlacementIntent(intent, []NodeRegistration{got}, VerificationConfig{Now: now, FreshnessWindow: time.Hour})
if verified.Verified || verified.Reason != VerifyReasonStaleObservation {
t.Fatalf("restart laundered a stale node fresh: seen=%s result=%+v", got.SeenAt, verified)
}
if !got.SeenAt.Equal(oldSeen) {
t.Fatalf("observation changed: got %s want %s", got.SeenAt, oldSeen)
}
// An explicit timestamp on otherwise identical declarative input cannot
// impersonate a heartbeat either.
reg.SeenAt = now
if _, err := store.RegisterNode(reg); err != nil {
t.Fatal(err)
}
got, _ = store.GetNodeSnapshot("node")
if !got.SeenAt.Equal(oldSeen) {
t.Fatal("timestamp-only registration refreshed the observation")
}
reopened, err := OpenNodeInventoryStore(dir)
if err != nil {
t.Fatal(err)
}
got, _ = reopened.GetNodeSnapshot("node")
if !got.SeenAt.Equal(oldSeen) {
t.Fatal("reloaded observation did not retain its original time")
}
}
func TestChangedNodeImportDoesNotRefreshAStaleObservation(t *testing.T) {
dir := t.TempDir()
now := time.Now().UTC()
oldSeen := now.Add(-2 * time.Hour)
store, err := OpenNodeInventoryStore(dir)
if err != nil {
t.Fatal(err)
}
reg := NodeRegistration{ServerID: "node", Addr: "127.0.0.1:19001", SeenAt: oldSeen, Pools: []StoragePool{{PoolID: "pool", BlockSize: 4096, TotalBytes: 1 << 30}}}
if _, err := store.RegisterNode(reg); err != nil {
t.Fatal(err)
}
store, err = OpenNodeInventoryStore(dir)
if err != nil {
t.Fatal(err)
}
reg.SeenAt = time.Time{}
reg.Pools = []StoragePool{{PoolID: "pool", BlockSize: 4096, TotalBytes: 2 << 30}}
if err := store.ImportNodes([]NodeRegistration{reg}); err != nil {
t.Fatal(err)
}
got, ok := store.GetNodeSnapshot("node")
if !ok || got.Pools[0].TotalBytes != 2<<30 {
t.Fatalf("changed declaration not imported: %+v", got)
}
if !got.SeenAt.Equal(oldSeen) {
t.Fatalf("changed declaration refreshed the observation: got %s want %s", got.SeenAt, oldSeen)
}
intent := PlacementIntent{VolumeID: "volume", DesiredRF: 1, Slots: []PlacementSlotIntent{{ServerID: "node", PoolID: "pool", Source: PlacementSourceBlankPool}}}
verified := VerifyPlacementIntent(intent, []NodeRegistration{got}, VerificationConfig{Now: now, FreshnessWindow: time.Hour})
if verified.Verified || verified.Reason != VerifyReasonStaleObservation {
t.Fatalf("restart laundered a stale node fresh: %+v", verified)
}
}
+115 -12
View File
@@ -7,6 +7,7 @@ import (
"log"
"os"
"path/filepath"
"reflect"
"sort"
"sync"
"time"
@@ -65,11 +66,13 @@ type NodeRegistration struct {
// NodeInventoryStore persists one JSON registration record per server.
type NodeInventoryStore struct {
mu sync.Mutex
dir string
records map[string]NodeRegistration
published sync.Map // committed NodeRegistration values; holder host checks never take mu (INV-WS-RENEW-NONBLOCKING-001)
failWrite func() error // tests: a non-nil error fails the next record write or removal
mu sync.Mutex
dir string
writeErr error // failed persistence requires reopen before another mutation
onPersistenceFailure PersistenceFailureHandler
records map[string]NodeRegistration
published sync.Map // committed NodeRegistration values; holder host checks never take mu (INV-WS-RENEW-NONBLOCKING-001)
failWrite func() error // tests: a non-nil error fails the next record write or removal
}
// SetPersistHookForTest installs (nil clears) a callback that each later
@@ -81,6 +84,14 @@ func (s *NodeInventoryStore) SetPersistHookForTest(hook func() error) {
s.failWrite = hook
}
// SetPersistenceFailureHandler installs the process host policy before serving.
// The callback runs under the writer mutex and must not reenter the store.
func (s *NodeInventoryStore) SetPersistenceFailureHandler(handler PersistenceFailureHandler) {
s.mu.Lock()
defer s.mu.Unlock()
s.onPersistenceFailure = handler
}
// OpenNodeInventoryStore opens or creates a node inventory store.
func OpenNodeInventoryStore(dir string) (*NodeInventoryStore, error) {
if dir == "" {
@@ -111,6 +122,11 @@ func OpenNodeInventoryStore(dir string) (*NodeInventoryStore, error) {
if err := s.load(); err != nil {
return nil, err
}
// Loaded names may come from a failed rename/barrier attempt. Establish
// their durability before exposing them or taking an equality shortcut.
if err := syncRecordDirectory(dir); err != nil {
return nil, &RecordPersistenceError{Store: dir, Record: "<recovery>", Err: err}
}
for id, rec := range s.records {
s.published.Store(id, copyNodeRegistration(rec))
}
@@ -137,24 +153,29 @@ func (s *NodeInventoryStore) HoldWritesForTest() (release func()) {
}
// RegisterNode records the latest observed inventory for a server.
// Repeating registration replaces observation fields, but still does not
// publish authority or readiness.
// Changed registration replaces observation fields, but still does not
// publish authority or readiness. A declaration without SeenAt retains the
// stored one (INV-NODE-REGISTRATION-FRESHNESS-001); only a heartbeat adds fresh evidence.
func (s *NodeInventoryStore) RegisterNode(reg NodeRegistration) (NodeRegistration, error) {
if err := validateNodeRegistration(reg); err != nil {
return NodeRegistration{}, err
}
s.mu.Lock()
defer s.mu.Unlock()
if reg.SeenAt.IsZero() {
reg.SeenAt = time.Now().UTC()
if err := recoveryRequired(s.writeErr); err != nil {
return NodeRegistration{}, err
}
reg, changed := s.registrationLocked(reg)
if !changed {
return copyNodeRegistration(reg), nil
}
reg = normalizeNodeRegistration(reg)
if err := s.putLocked(reg); err != nil {
latchPersistenceFailure(err, &s.writeErr, s.onPersistenceFailure)
return NodeRegistration{}, err
}
s.records[reg.ServerID] = reg
s.published.Store(reg.ServerID, copyNodeRegistration(reg)) // committed: the file is in place
return reg, nil
return copyNodeRegistration(reg), nil
}
// RemoveNode deletes one registration record. Missing nodes are a
@@ -165,15 +186,18 @@ func (s *NodeInventoryStore) RemoveNode(serverID string) error {
}
s.mu.Lock()
defer s.mu.Unlock()
if err := recoveryRequired(s.writeErr); err != nil {
return err
}
if s.failWrite != nil {
if err := s.failWrite(); err != nil {
return fmt.Errorf("lifecycle: remove node %s: %w", serverID, err)
}
}
delete(s.records, serverID)
if err := os.Remove(s.path(serverID)); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("lifecycle: remove node %s: %w", serverID, err)
}
delete(s.records, serverID)
s.published.Delete(serverID) // committed: the file is gone
return nil
}
@@ -327,3 +351,82 @@ func copyStringMap(in map[string]string) map[string]string {
}
return out
}
// ImportNodes replays one startup node step. All changed data is durable before
// rename; one directory barrier precedes publication of the changed snapshots.
func (s *NodeInventoryStore) ImportNodes(nodes []NodeRegistration) error {
s.mu.Lock()
defer s.mu.Unlock()
if err := recoveryRequired(s.writeErr); err != nil {
return err
}
changed := make(map[string]NodeRegistration)
seen := make(map[string]bool)
order := make([]string, 0, len(nodes))
for _, node := range nodes {
if err := validateNodeRegistration(node); err != nil {
return fmt.Errorf("lifecycle: import node %s: %w", node.ServerID, err)
}
reg, differs := s.registrationLocked(node)
if !seen[reg.ServerID] {
order = append(order, reg.ServerID)
seen[reg.ServerID] = true
}
if !differs {
delete(changed, reg.ServerID)
continue
}
changed[reg.ServerID] = reg
}
writes := make([]recordWrite, 0, len(order))
for _, id := range order {
if _, ok := changed[id]; !ok {
continue
}
if s.failWrite != nil {
if err := s.failWrite(); err != nil {
return err
}
}
raw, err := json.MarshalIndent(changed[id], "", " ")
if err != nil {
return fmt.Errorf("lifecycle: marshal node %s: %w", id, err)
}
writes = append(writes, recordWrite{name: id + ".json", raw: raw})
}
if err := writeRecordBatchDurably(s.dir, writes); err != nil {
latchPersistenceFailure(err, &s.writeErr, s.onPersistenceFailure)
return err
}
for _, id := range order {
if _, ok := changed[id]; !ok {
continue
}
reg := changed[id]
s.records[id] = reg
s.published.Store(id, copyNodeRegistration(reg))
}
return nil
}
func (s *NodeInventoryStore) registrationLocked(reg NodeRegistration) (NodeRegistration, bool) {
// Retain an independent value: a caller may reuse its pool slices.
reg = copyNodeRegistration(reg)
if old, ok := s.records[reg.ServerID]; ok {
unchanged := reg
unchanged.SeenAt = old.SeenAt
if reflect.DeepEqual(old, unchanged) {
// Declarative replay is not a new observation. Heartbeats supply
// freshness independently of this durable registration.
return copyNodeRegistration(old), false
}
if reg.SeenAt.IsZero() {
// A changed declaration is not an observation either.
reg.SeenAt = old.SeenAt
}
}
if reg.SeenAt.IsZero() {
reg.SeenAt = time.Now().UTC()
}
return reg, true
}
+113 -25
View File
@@ -7,6 +7,7 @@ import (
"log"
"os"
"path/filepath"
"slices"
"sort"
"sync"
)
@@ -36,10 +37,20 @@ type PlacementIntent struct {
// PlacementIntentStore persists one placement intent per volume.
type PlacementIntentStore struct {
mu sync.Mutex
dir string
records map[string]PlacementIntent
published sync.Map // committed immutable PlacementIntent values; renewal never takes mu
mu sync.Mutex
dir string
writeErr error // failed persistence requires reopen before another mutation
onPersistenceFailure PersistenceFailureHandler
records map[string]PlacementIntent
published sync.Map // committed immutable PlacementIntent values; renewal never takes mu
}
// SetPersistenceFailureHandler installs the process host policy before serving.
// The callback runs under the writer mutex and must not reenter the store.
func (s *PlacementIntentStore) SetPersistenceFailureHandler(handler PersistenceFailureHandler) {
s.mu.Lock()
defer s.mu.Unlock()
s.onPersistenceFailure = handler
}
// OpenPlacementIntentStore opens or creates a placement intent store.
@@ -72,6 +83,11 @@ func OpenPlacementIntentStore(dir string) (*PlacementIntentStore, error) {
if err := s.load(); err != nil {
return nil, err
}
// Loaded names may come from a failed rename/barrier attempt. Establish
// their durability before exposing them or taking an equality shortcut.
if err := syncRecordDirectory(dir); err != nil {
return nil, &RecordPersistenceError{Store: dir, Record: "<recovery>", Err: err}
}
for volume, rec := range s.records {
s.published.Store(volume, copyPlacementIntent(rec))
}
@@ -81,32 +97,21 @@ func OpenPlacementIntentStore(dir string) (*PlacementIntentStore, error) {
// ApplyPlan records placement intent from a sufficient plan. Insufficient
// plans are rejected rather than persisted as partial authority-shaped state.
func (s *PlacementIntentStore) ApplyPlan(plan PlacementPlan) (PlacementIntent, error) {
if !plan.EnoughCandidates() {
return PlacementIntent{}, ErrInsufficientPlacementCandidates
}
intent := PlacementIntent{
VolumeID: plan.VolumeID,
DesiredRF: plan.DesiredRF,
Slots: make([]PlacementSlotIntent, 0, plan.DesiredRF),
}
for _, candidate := range plan.Candidates[:plan.DesiredRF] {
intent.Slots = append(intent.Slots, PlacementSlotIntent{
ServerID: candidate.ServerID,
PoolID: candidate.PoolID,
ReplicaID: candidate.ReplicaID,
Source: candidate.Source,
DataAddr: candidate.DataAddr,
CtrlAddr: candidate.CtrlAddr,
ISCSIListenPort: candidate.ISCSIListenPort,
NVMeListenPort: candidate.NVMeListenPort,
})
}
if err := validatePlacementIntent(intent); err != nil {
intent, err := placementIntentFromPlan(plan)
if err != nil {
return PlacementIntent{}, err
}
s.mu.Lock()
defer s.mu.Unlock()
if err := recoveryRequired(s.writeErr); err != nil {
return PlacementIntent{}, err
}
// Equal input already has a durable record; preserve it on restart.
if old, ok := s.records[intent.VolumeID]; ok && old.DesiredRF == intent.DesiredRF && slices.Equal(old.Slots, intent.Slots) {
return copyPlacementIntent(old), nil
}
if err := s.putLocked(intent); err != nil {
latchPersistenceFailure(err, &s.writeErr, s.onPersistenceFailure)
return PlacementIntent{}, err
}
s.records[intent.VolumeID] = intent
@@ -122,6 +127,9 @@ func (s *PlacementIntentStore) DeletePlacement(volumeID string) error {
}
s.mu.Lock()
defer s.mu.Unlock()
if err := recoveryRequired(s.writeErr); err != nil {
return err
}
if err := os.Remove(s.path(volumeID)); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("lifecycle: remove placement intent %s: %w", volumeID, err)
}
@@ -262,3 +270,83 @@ func copyPlacementIntent(in PlacementIntent) PlacementIntent {
out.Slots = append([]PlacementSlotIntent(nil), in.Slots...)
return out
}
// ImportPlans replays one startup placement step and publishes only after
// the changed files and their shared directory barrier have completed.
func (s *PlacementIntentStore) ImportPlans(plans []PlacementPlan) error {
s.mu.Lock()
defer s.mu.Unlock()
if err := recoveryRequired(s.writeErr); err != nil {
return err
}
changed := make(map[string]PlacementIntent)
seen := make(map[string]bool)
order := make([]string, 0, len(plans))
for _, plan := range plans {
intent, err := placementIntentFromPlan(plan)
if err != nil {
return fmt.Errorf("lifecycle: import placement intent %s: %w", plan.VolumeID, err)
}
old, ok := s.records[intent.VolumeID]
if !seen[intent.VolumeID] {
order = append(order, intent.VolumeID)
seen[intent.VolumeID] = true
}
if ok && old.DesiredRF == intent.DesiredRF && slices.Equal(old.Slots, intent.Slots) {
delete(changed, intent.VolumeID)
continue
}
changed[intent.VolumeID] = intent
}
writes := make([]recordWrite, 0, len(order))
for _, id := range order {
if _, ok := changed[id]; !ok {
continue
}
raw, err := json.MarshalIndent(changed[id], "", " ")
if err != nil {
return fmt.Errorf("lifecycle: marshal placement intent %s: %w", id, err)
}
writes = append(writes, recordWrite{name: id + ".json", raw: raw})
}
if err := writeRecordBatchDurably(s.dir, writes); err != nil {
latchPersistenceFailure(err, &s.writeErr, s.onPersistenceFailure)
return err
}
for _, id := range order {
if _, ok := changed[id]; !ok {
continue
}
intent := changed[id]
s.records[id] = intent
s.published.Store(id, copyPlacementIntent(intent))
}
return nil
}
func placementIntentFromPlan(plan PlacementPlan) (PlacementIntent, error) {
if !plan.EnoughCandidates() {
return PlacementIntent{}, ErrInsufficientPlacementCandidates
}
intent := PlacementIntent{
VolumeID: plan.VolumeID,
DesiredRF: plan.DesiredRF,
Slots: make([]PlacementSlotIntent, 0, plan.DesiredRF),
}
for _, candidate := range plan.Candidates[:plan.DesiredRF] {
intent.Slots = append(intent.Slots, PlacementSlotIntent{
ServerID: candidate.ServerID,
PoolID: candidate.PoolID,
ReplicaID: candidate.ReplicaID,
Source: candidate.Source,
DataAddr: candidate.DataAddr,
CtrlAddr: candidate.CtrlAddr,
ISCSIListenPort: candidate.ISCSIListenPort,
NVMeListenPort: candidate.NVMeListenPort,
})
}
if err := validatePlacementIntent(intent); err != nil {
return PlacementIntent{}, err
}
return intent, nil
}
@@ -135,6 +135,7 @@ func TestPlacementSnapshotFailedCommitStaysCommitted(t *testing.T) {
if ok != existed || !reflect.DeepEqual(got, before) {
t.Fatal("reopen did not retain the committed placement")
}
s = reopened // failed persistence requires reopening before further writes
if _, err = s.ApplyPlan(plan); err != nil {
t.Fatal("unblocked commit", err)
}
@@ -0,0 +1,60 @@
//go:build linux
package lifecycle
import (
"os"
"path/filepath"
"testing"
)
func TestPlacementRepeatKeepsRecordAndChangedPlanReplacesIt(t *testing.T) {
dir := t.TempDir()
store, err := OpenPlacementIntentStore(dir)
if err != nil {
t.Fatal(err)
}
plan := PlacementPlan{VolumeID: "volume", DesiredRF: 1, Candidates: []PlacementCandidate{{ServerID: "node", ReplicaID: "r1", Source: PlacementSourceExistingReplica}}}
if _, err := store.ApplyPlan(plan); err != nil {
t.Fatal(err)
}
path := filepath.Join(dir, "volume.json")
original, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
// Reloading must not cause an otherwise equal import to rewrite the file.
store, err = OpenPlacementIntentStore(dir)
if err != nil {
t.Fatal(err)
}
if _, err := store.ApplyPlan(plan); err != nil {
t.Fatal(err)
}
repeated, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
if !os.SameFile(original, repeated) || !original.ModTime().Equal(repeated.ModTime()) {
t.Fatal("equal placement plan rewrote its durable record")
}
plan.Candidates[0].ReplicaID = "r2"
if _, err := store.ApplyPlan(plan); err != nil {
t.Fatal(err)
}
changed, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
if os.SameFile(repeated, changed) {
t.Fatal("changed placement did not replace its record")
}
reopened, err := OpenPlacementIntentStore(dir)
if err != nil {
t.Fatal(err)
}
got, ok := reopened.GetPlacementSnapshot("volume")
if !ok || len(got.Slots) != 1 || got.Slots[0].ReplicaID != "r2" {
t.Fatalf("changed plan did not survive reload: %+v", got)
}
}
+193 -20
View File
@@ -1,18 +1,63 @@
package lifecycle
import (
"errors"
"fmt"
"os"
"path/filepath"
"sync/atomic"
)
// ErrLifecycleRecoveryRequired means a failed persistence operation may have
// changed disk. Reopen the store before making further mutations.
var ErrLifecycleRecoveryRequired = errors.New("lifecycle: store recovery required")
// RecordPersistenceError identifies the operation whose durable outcome is
// uncertain. A process host can fail-stop rather than remain alive and poisoned.
type RecordPersistenceError struct {
Store string
Record string
Err error
}
func (e *RecordPersistenceError) Error() string {
return fmt.Sprintf("lifecycle: persist store %q record %q: %v", e.Store, e.Record, e.Err)
}
func (e *RecordPersistenceError) Unwrap() error { return e.Err }
// PersistenceFailureHandler is called synchronously after a failed I/O has
// poisoned a store. It must not reenter a store; production exits the process.
type PersistenceFailureHandler func(*RecordPersistenceError)
// Only a write that may have touched disk poisons the store; a marshal error
// happens before any I/O, so the caller can correct the input and retry.
func latchPersistenceFailure(err error, prior *error, handler PersistenceFailureHandler) {
var failure *RecordPersistenceError
if !errors.As(err, &failure) {
return
}
*prior = err
if handler != nil {
handler(failure)
}
}
func recoveryRequired(writeErr error) error {
if writeErr == nil {
return nil
}
return fmt.Errorf("%w: %v", ErrLifecycleRecoveryRequired, writeErr)
}
// Hooks are installed only in isolated subprocess tests. Production uses
// the real filesystem operations; one helper owns all publication seams.
type durableRecordHooks struct {
crash func(string)
fileSync func(*os.File) error
dirSync func(string) error
crash func(string)
fileSync func(*os.File) error
dirSync func(string) error
batchSyncfs *bool
fsSync func(*os.File) error
}
var durableRecordHooksForTest atomic.Pointer[durableRecordHooks]
@@ -20,42 +65,170 @@ var durableRecordHooksForTest atomic.Pointer[durableRecordHooks]
// writeRecordDurably implements INV-LIFECYCLE-STORE-DURABLE-001 for puts and
// replacements. A post-rename error may leave the new record on disk.
func writeRecordDurably(dir, name string, raw []byte) error {
if err := writeRecordBeforeDirectorySync(dir, name, raw); err != nil {
return &RecordPersistenceError{Store: dir, Record: name, Err: err}
}
if err := syncRecordDirectory(dir); err != nil {
return &RecordPersistenceError{Store: dir, Record: name, Err: err}
}
return nil
}
type recordWrite struct {
name string
raw []byte
}
// A startup import makes all changed data durable before rename, then shares
// a directory barrier before publication. A failed step leaves complete old/new
// names. Linux >= 5.8 on ext4, xfs, btrfs or tmpfs uses one syncfs for staged
// temps; other systems sync each.
func writeRecordBatchDurably(dir string, records []recordWrite) error {
if len(records) == 0 {
return nil
}
useSyncfs := recordBatchSyncfsSupported(dir)
hooks := durableRecordHooksForTest.Load()
if hooks != nil && hooks.batchSyncfs != nil {
useSyncfs = *hooks.batchSyncfs
}
if useSyncfs {
return writeRecordBatchWithSyncfs(dir, records)
}
for _, record := range records {
if err := writeRecordBeforeDirectorySync(dir, record.name, record.raw); err != nil {
return &RecordPersistenceError{Store: dir, Record: record.name, Err: err}
}
}
if err := syncRecordDirectory(dir); err != nil {
return &RecordPersistenceError{Store: dir, Record: "<import-step>", Err: err}
}
return nil
}
// ImportDurabilityMode reports the batch persistence path for records under dir.
// Single-record mutations always retain their file and directory fsyncs.
func ImportDurabilityMode(dir string) string {
if recordBatchSyncfsSupported(dir) {
return "syncfs (Linux >= 5.8, local filesystem)"
}
return "per-file fsync (syncfs writeback error reporting unavailable)"
}
func writeRecordBatchWithSyncfs(dir string, records []recordWrite) error {
// Opening before any write samples the filesystem's writeback errseq.
fd, err := os.Open(dir)
if err != nil {
return &RecordPersistenceError{Store: dir, Record: "<import-step>", Err: err}
}
defer fd.Close()
hooks := durableRecordHooksForTest.Load()
if hooks != nil && hooks.crash != nil {
hooks.crash("batch-open")
}
temps := make([]string, 0, len(records))
defer func() {
for _, temp := range temps {
_ = os.Remove(temp)
}
}()
for _, record := range records {
temp, err := writeRecordTemp(dir, record.name, record.raw, false)
if err != nil {
return &RecordPersistenceError{Store: dir, Record: record.name, Err: err}
}
temps = append(temps, temp)
}
fsSync := syncRecordFilesystem
if hooks != nil && hooks.fsSync != nil {
fsSync = hooks.fsSync
}
// Never retry a failed syncfs: it consumes the writeback error. The caller
// poisons the store; recovery creates fresh temps for any subsequent import.
if hooks != nil && hooks.crash != nil {
hooks.crash("before-syncfs")
}
if err := fsSync(fd); err != nil {
return &RecordPersistenceError{Store: dir, Record: "<import-step>", Err: fmt.Errorf("lifecycle: sync record filesystem: %w", err)}
}
if hooks != nil && hooks.crash != nil {
hooks.crash("after-syncfs")
}
for i, record := range records {
if hooks != nil && hooks.crash != nil {
hooks.crash("before-rename")
}
if err := os.Rename(temps[i], filepath.Join(dir, record.name)); err != nil {
return &RecordPersistenceError{Store: dir, Record: record.name, Err: err}
}
if hooks != nil && hooks.crash != nil {
hooks.crash("after-rename")
}
}
if err := syncRecordDirectory(dir); err != nil {
return &RecordPersistenceError{Store: dir, Record: "<import-step>", Err: err}
}
return nil
}
func writeRecordBeforeDirectorySync(dir, name string, raw []byte) error {
temp, err := writeRecordTemp(dir, name, raw, true)
if err != nil {
return err
}
defer os.Remove(temp)
hooks := durableRecordHooksForTest.Load()
if hooks != nil && hooks.crash != nil {
hooks.crash("before-rename")
}
if err := os.Rename(temp, filepath.Join(dir, name)); err != nil {
return fmt.Errorf("lifecycle: rename record %s: %w", name, err)
}
if hooks != nil && hooks.crash != nil {
hooks.crash("after-rename")
}
return nil
}
func writeRecordTemp(dir, name string, raw []byte, syncFile bool) (temp string, resultErr error) {
f, err := os.CreateTemp(dir, name+".*.tmp")
if err != nil {
return fmt.Errorf("lifecycle: temp record %s: %w", name, err)
return "", fmt.Errorf("lifecycle: temp record %s: %w", name, err)
}
defer os.Remove(f.Name())
defer func() {
if resultErr != nil {
_ = os.Remove(f.Name())
}
}()
if _, err := f.Write(raw); err != nil {
_ = f.Close()
return fmt.Errorf("lifecycle: write record %s: %w", name, err)
return "", fmt.Errorf("lifecycle: write record %s: %w", name, err)
}
hooks := durableRecordHooksForTest.Load()
fileSync := f.Sync
if hooks != nil && hooks.fileSync != nil {
fileSync = func() error { return hooks.fileSync(f) }
}
if err := fileSync(); err != nil {
_ = f.Close()
return fmt.Errorf("lifecycle: sync record %s: %w", name, err)
if syncFile {
if err := fileSync(); err != nil {
_ = f.Close()
return "", fmt.Errorf("lifecycle: sync record %s: %w", name, err)
}
}
if err := f.Close(); err != nil {
return fmt.Errorf("lifecycle: close record %s: %w", name, err)
}
if hooks != nil && hooks.crash != nil {
hooks.crash("before-rename")
}
if err := os.Rename(f.Name(), filepath.Join(dir, name)); err != nil {
return fmt.Errorf("lifecycle: rename record %s: %w", name, err)
}
if hooks != nil && hooks.crash != nil {
hooks.crash("after-rename")
return "", fmt.Errorf("lifecycle: close record %s: %w", name, err)
}
return f.Name(), nil
}
func syncRecordDirectory(dir string) error {
hooks := durableRecordHooksForTest.Load()
dirSync := syncBindingParent
if hooks != nil && hooks.dirSync != nil {
dirSync = hooks.dirSync
}
if err := dirSync(dir); err != nil {
return fmt.Errorf("lifecycle: sync record directory %s: %w", name, err)
return fmt.Errorf("lifecycle: sync record directory %s: %w", dir, err)
}
return nil
}
@@ -0,0 +1,61 @@
//go:build linux
package lifecycle
import (
"os"
"strconv"
"strings"
"golang.org/x/sys/unix"
)
var recordKernelSyncfsErrors = detectRecordSyncfs()
// recordBatchSyncfsSupported reports whether syncfs on dir's filesystem
// returns the writeback errors a per-file fsync would. Overlay, FUSE and
// network mounts keep per-file fsync: syncfs does not reach their backing files.
func recordBatchSyncfsSupported(dir string) bool {
if !recordKernelSyncfsErrors {
return false
}
var st unix.Statfs_t
if unix.Statfs(dir, &st) != nil {
return false
}
return filesystemReportsSyncfsErrors(uint32(st.Type))
}
func filesystemReportsSyncfsErrors(fsType uint32) bool {
switch fsType {
case unix.EXT4_SUPER_MAGIC, unix.XFS_SUPER_MAGIC, unix.BTRFS_SUPER_MAGIC, unix.TMPFS_MAGIC:
return true
}
return false
}
func detectRecordSyncfs() bool {
var u unix.Utsname
if unix.Uname(&u) != nil {
return false
}
return kernelHasSyncfsErrors(unix.ByteSliceToString(u.Release[:]))
}
func kernelHasSyncfsErrors(release string) bool {
parts := strings.SplitN(release, ".", 3)
if len(parts) < 2 {
return false
}
major, err := strconv.Atoi(parts[0])
if err != nil {
return false
}
minor, err := strconv.Atoi(parts[1])
if err != nil {
return false
}
return major > 5 || major == 5 && minor >= 8
}
func syncRecordFilesystem(fd *os.File) error { return unix.Syncfs(int(fd.Fd())) }
@@ -0,0 +1,12 @@
//go:build !linux
package lifecycle
import (
"fmt"
"os"
)
func recordBatchSyncfsSupported(string) bool { return false }
func syncRecordFilesystem(*os.File) error { return fmt.Errorf("syncfs unavailable on this platform") }
@@ -0,0 +1,106 @@
package lifecycle
import (
"os"
"path/filepath"
"testing"
"time"
)
func TestFailedRemoveKeepsRecordForRetry(t *testing.T) {
for _, kind := range []string{"node", "placement", "volume"} {
t.Run(kind, func(t *testing.T) {
dir := t.TempDir()
var remove func() error
var present func() (record, snapshot bool)
switch kind {
case "node":
s, err := OpenNodeInventoryStore(dir)
if err != nil {
t.Fatal(err)
}
if _, err := s.RegisterNode(NodeRegistration{ServerID: "v", Addr: "127.0.0.1:19001"}); err != nil {
t.Fatal(err)
}
remove = func() error { return s.RemoveNode("v") }
present = func() (bool, bool) { _, a := s.GetNode("v"); _, b := s.GetNodeSnapshot("v"); return a, b }
case "placement":
s, err := OpenPlacementIntentStore(dir)
if err != nil {
t.Fatal(err)
}
if _, err := s.ApplyPlan(PlacementPlan{VolumeID: "v", DesiredRF: 1, Candidates: []PlacementCandidate{{ServerID: "node", ReplicaID: "r1", Source: PlacementSourceExistingReplica}}}); err != nil {
t.Fatal(err)
}
remove = func() error { return s.DeletePlacement("v") }
present = func() (bool, bool) { _, a := s.GetPlacement("v"); _, b := s.GetPlacementSnapshot("v"); return a, b }
case "volume":
s, err := OpenFileStore(dir)
if err != nil {
t.Fatal(err)
}
if _, err := s.CreateVolume(VolumeSpec{VolumeID: "v", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil {
t.Fatal(err)
}
remove = func() error { return s.DeleteVolume("v") }
present = func() (bool, bool) { _, a := s.GetVolume("v"); _, b := s.GetVolumeSnapshot("v"); return a, b }
}
path := filepath.Join(dir, "v.json")
backup := path + ".saved"
if err := os.Rename(path, backup); err != nil {
t.Fatal(err)
}
if err := os.Mkdir(path, 0700); err != nil {
t.Fatal(err)
}
blocker := filepath.Join(path, "blocker")
if err := os.WriteFile(blocker, []byte("fixture"), 0600); err != nil {
t.Fatal(err)
}
if err := remove(); err == nil {
t.Fatal("nonempty-directory removal succeeded")
}
if record, snapshot := present(); !record || !snapshot {
t.Fatalf("failed removal hid retry state: record=%v snapshot=%v", record, snapshot)
}
if err := os.Remove(blocker); err != nil {
t.Fatal(err)
}
if err := os.Remove(path); err != nil {
t.Fatal(err)
}
if err := os.Rename(backup, path); err != nil {
t.Fatal(err)
}
if err := remove(); err != nil {
t.Fatalf("later removal retry: %v", err)
}
if record, snapshot := present(); record || snapshot {
t.Fatalf("successful removal left state: record=%v snapshot=%v", record, snapshot)
}
if _, err := os.Stat(path); !os.IsNotExist(err) {
t.Fatalf("record file survived successful retry: %v", err)
}
})
}
}
func TestNodeMarshalErrorDoesNotRequireRecovery(t *testing.T) {
s, err := OpenNodeInventoryStore(t.TempDir())
if err != nil {
t.Fatal(err)
}
var latched []*RecordPersistenceError
s.SetPersistenceFailureHandler(func(f *RecordPersistenceError) { latched = append(latched, f) })
reg := NodeRegistration{ServerID: "n", Addr: "127.0.0.1:19001", SeenAt: time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC)}
if _, err := s.RegisterNode(reg); err == nil {
t.Fatal("unencodable SeenAt was accepted")
}
reg.SeenAt = time.Now().UTC()
if _, err := s.RegisterNode(reg); err != nil {
t.Fatalf("corrected registration after a marshal error: %v", err)
}
if len(latched) != 0 {
t.Fatalf("marshal error reached the persistence policy: %v", latched)
}
}
+43 -6
View File
@@ -67,9 +67,11 @@ type VolumeRecord struct {
// FileStore persists one JSON record per volume ID.
type FileStore struct {
mu sync.Mutex
dir string
records map[string]VolumeRecord
mu sync.Mutex
dir string
writeErr error // a failed put requires reopen before another mutation
onPersistenceFailure PersistenceFailureHandler
records map[string]VolumeRecord
// snap mirrors records as an immutable copy, republished at every change
// of records, for lock-free renewal-path reads.
snap atomic.Pointer[map[string]VolumeRecord]
@@ -97,6 +99,14 @@ func (s *FileStore) GetVolumeSnapshot(volumeID string) (VolumeRecord, bool) {
return rec, ok
}
// SetPersistenceFailureHandler installs the process host policy before serving.
// The callback runs under the writer mutex and must not reenter the store.
func (s *FileStore) SetPersistenceFailureHandler(handler PersistenceFailureHandler) {
s.mu.Lock()
defer s.mu.Unlock()
s.onPersistenceFailure = handler
}
// OpenFileStore opens or creates a lifecycle intent store.
func OpenFileStore(dir string) (*FileStore, error) {
if dir == "" {
@@ -127,6 +137,11 @@ func OpenFileStore(dir string) (*FileStore, error) {
if err := s.load(); err != nil {
return nil, err
}
// Visible names can come from a failed directory barrier. Recover their
// durability before publication or an equal create can acknowledge them.
if err := syncRecordDirectory(dir); err != nil {
return nil, &RecordPersistenceError{Store: dir, Record: "<recovery>", Err: err}
}
s.publishLocked()
return s, nil
}
@@ -137,6 +152,9 @@ func (s *FileStore) CreateVolume(spec VolumeSpec) (VolumeRecord, error) {
spec = normalizeVolumeSpec(spec)
s.mu.Lock()
defer s.mu.Unlock()
if err := recoveryRequired(s.writeErr); err != nil {
return VolumeRecord{}, err
}
if existing, ok := s.records[spec.VolumeID]; ok {
if existing.Spec.SourceVolume != spec.SourceVolume || existing.Spec.SourceLayoutID != spec.SourceLayoutID || existing.Spec.SourceSnapshot != spec.SourceSnapshot || existing.Spec.CreateRequestID != spec.CreateRequestID {
return VolumeRecord{}, ErrVolumeConflict
@@ -221,6 +239,9 @@ func (s *FileStore) CreateVolume(spec VolumeSpec) (VolumeRecord, error) {
func (s *FileStore) RedrawPendingLayoutID(volumeID, rejectedID string) (VolumeRecord, error) {
s.mu.Lock()
defer s.mu.Unlock()
if err := recoveryRequired(s.writeErr); err != nil {
return VolumeRecord{}, err
}
rec, ok := s.records[volumeID]
if !ok {
return VolumeRecord{}, ErrVolumeNotFound
@@ -301,6 +322,9 @@ func (s *FileStore) settlePendingLayoutIDLocked(rec VolumeRecord) (VolumeRecord,
func (s *FileStore) MarkStoreReady(volumeID, layoutID string) (VolumeRecord, error) {
s.mu.Lock()
defer s.mu.Unlock()
if err := recoveryRequired(s.writeErr); err != nil {
return VolumeRecord{}, err
}
rec, ok := s.records[volumeID]
if !ok {
return VolumeRecord{}, ErrVolumeNotFound
@@ -362,11 +386,14 @@ func (s *FileStore) DeleteVolume(volumeID string) error {
}
s.mu.Lock()
defer s.mu.Unlock()
delete(s.records, volumeID)
s.publishLocked()
if err := recoveryRequired(s.writeErr); err != nil {
return err
}
if err := os.Remove(s.path(volumeID)); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("lifecycle: remove %s: %w", volumeID, err)
}
delete(s.records, volumeID)
s.publishLocked()
return nil
}
@@ -381,6 +408,9 @@ func (s *FileStore) AttachVolume(volumeID, nodeID string) (VolumeRecord, error)
}
s.mu.Lock()
defer s.mu.Unlock()
if err := recoveryRequired(s.writeErr); err != nil {
return VolumeRecord{}, err
}
rec, ok := s.records[volumeID]
if !ok {
return VolumeRecord{}, ErrVolumeNotFound
@@ -405,6 +435,9 @@ func (s *FileStore) DetachVolume(volumeID, nodeID string) (VolumeRecord, error)
}
s.mu.Lock()
defer s.mu.Unlock()
if err := recoveryRequired(s.writeErr); err != nil {
return VolumeRecord{}, err
}
rec, ok := s.records[volumeID]
if !ok {
return VolumeRecord{}, ErrVolumeNotFound
@@ -480,7 +513,11 @@ func (s *FileStore) putLocked(rec VolumeRecord) error {
if err != nil {
return fmt.Errorf("lifecycle: marshal %s: %w", rec.Spec.VolumeID, err)
}
return writeRecordDurably(s.dir, rec.Spec.VolumeID+".json", raw)
err = writeRecordDurably(s.dir, rec.Spec.VolumeID+".json", raw)
if err != nil {
latchPersistenceFailure(err, &s.writeErr, s.onPersistenceFailure)
}
return err
}
func (s *FileStore) path(volumeID string) string {
@@ -60,6 +60,8 @@ func TestLifecycleStoreParentSyncChild(t *testing.T) {
want = append(want, "/"+strings.Join(parts[:n], "/"))
}
want = append(want, "/")
ancestor := want[len(want)-2]
want = append(want, abs)
var calls []string
var warnings bytes.Buffer
log.SetOutput(&warnings)
@@ -68,7 +70,7 @@ func TestLifecycleStoreParentSyncChild(t *testing.T) {
fault := &os.PathError{Op: "open", Path: want[0], Err: os.ErrPermission}
syncBindingParent = func(path string) error {
calls = append(calls, path)
if shape == "ancestor-permission" && path == want[len(want)-2] {
if shape == "ancestor-permission" && path == ancestor {
return &os.PathError{Op: "open", Path: path, Err: os.ErrPermission}
}
if failFirst {
@@ -0,0 +1,111 @@
//go:build linux
package lifecycle
import (
"context"
"errors"
"os"
"os/exec"
"reflect"
"testing"
"time"
)
func TestVolumeEqualityRequiresRecovery(t *testing.T) {
for _, mode := range []string{"reopen", "failed-put"} {
t.Run(mode, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestVolumeRecoveryChild$", "-test.timeout=8s")
cmd.Env = append(os.Environ(), "VOLUME_RECOVERY_MODE="+mode)
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("volume recovery: %v context=%v\n%s", err, ctx.Err(), out)
}
})
}
}
func TestVolumeRecoveryChild(t *testing.T) {
mode := os.Getenv("VOLUME_RECOVERY_MODE")
if mode == "" {
t.Skip("isolated recovery hooks")
}
dir := t.TempDir()
s, err := OpenFileStore(dir)
if err != nil {
t.Fatal(err)
}
spec := VolumeSpec{VolumeID: "v", SizeBytes: 1 << 20, ReplicationFactor: 1}
rec, err := s.CreateVolume(spec)
if err != nil {
t.Fatal(err)
}
if _, err := s.MarkStoreReady("v", rec.Spec.LayoutID); err != nil {
t.Fatal(err)
}
old, _ := s.GetVolumeSnapshot("v")
fault := errors.New("injected volume directory barrier failure")
callbacks := 0
s.SetPersistenceFailureHandler(func(failure *RecordPersistenceError) {
callbacks++
if s.writeErr == nil || failure.Store != dir || failure.Record != "v.json" || !errors.Is(failure, fault) {
t.Fatalf("incorrect volume policy context: %+v", failure)
}
})
durableRecordHooksForTest.Store(&durableRecordHooks{dirSync: func(string) error { return fault }})
defer durableRecordHooksForTest.Store(nil)
if mode == "reopen" {
if _, err := OpenFileStore(dir); !errors.Is(err, fault) {
t.Fatalf("loaded volume published without recovery barrier: %v", err)
}
durableRecordHooksForTest.Store(nil)
reopened, err := OpenFileStore(dir)
if err != nil {
t.Fatal(err)
}
if got, _ := reopened.GetVolumeSnapshot("v"); got != old {
t.Fatal("recovery changed volume")
}
return
}
if _, err := s.AttachVolume("v", "node"); !errors.Is(err, fault) {
t.Fatalf("attachment did not fail at barrier: %v", err)
}
if callbacks != 1 {
t.Fatalf("volume failure callbacks=%d want1", callbacks)
}
if got, _ := s.GetVolumeSnapshot("v"); got != old {
t.Fatal("failed attach published")
}
durableRecordHooksForTest.Store(nil)
if _, err := s.CreateVolume(spec); !errors.Is(err, ErrLifecycleRecoveryRequired) {
t.Fatalf("equal create must refuse after possibly-applied failure: %v", err)
}
_, redrawErr := s.RedrawPendingLayoutID("v", rec.Spec.LayoutID)
_, markErr := s.MarkStoreReady("v", rec.Spec.LayoutID)
_, attachErr := s.AttachVolume("v", "node")
_, detachErr := s.DetachVolume("v", "node")
for _, err := range []error{redrawErr, markErr, attachErr, detachErr, s.DeleteVolume("v")} {
if !errors.Is(err, ErrLifecycleRecoveryRequired) {
t.Fatalf("mutation after uncertainty: %v", err)
}
}
reopened, err := OpenFileStore(dir)
if err != nil {
t.Fatal(err)
}
if got, _ := reopened.GetVolumeSnapshot("v"); got.AttachedTo != "node" {
t.Fatal("fixture did not retain renamed attachment")
}
if _, err := reopened.DetachVolume("v", "node"); err != nil {
t.Fatal(err)
}
again, err := OpenFileStore(dir)
if err != nil {
t.Fatal(err)
}
if got, _ := again.GetVolumeSnapshot("v"); !reflect.DeepEqual(got, old) {
t.Fatal("recovered successful detach differs on disk")
}
}
+54 -8
View File
@@ -48,6 +48,55 @@ The design is described in three documents, and this one collects their machines
Each machine lists its states, the allowed transitions, the guard that must hold for each transition, where the guard is enforced, and the IDs of the Part B rows that protect it. A state name in `code font` is a value in the code; the other names describe a condition and are not code types.
### Lifecycle record I/O and supervised master recovery
This is the process projection of `INV-LIFECYCLE-STORE-DURABLE-001` and
`INV-LIFECYCLE-FAILSTOP-001`; it adds no record format or authority state.
```mermaid
stateDiagram-v2
[*] --> Recovering: supervisor starts master
Recovering --> Ready: complete records loaded, directory barriers succeed
Ready --> Ready: changed files synced, renamed, directory synced
Ready --> Faulted: record put/import persistence failure
Recovering --> Faulted: recovery directory sync failure
Faulted --> Exited: one ERROR attempt, exit 1 within 1 s
Exited --> Recovering: supervisor restarts
```
| From | To | Guard | Enforced in | Protects |
|---|---|---|---|---|
| — | Recovering | the supervisor starts blockmaster with a lifecycle store | `cmd/blockmaster/main.go` `run`; `deploy/systemd/sw-blockmaster.service` | `INV-LIFECYCLE-FAILSTOP-001` |
| Recovering | Ready | each node, placement and volume store loads complete records and its records-directory barrier succeeds; the cluster-spec import completes before serving | `core/lifecycle/node_inventory.go` `OpenNodeInventoryStore`; `core/lifecycle/placement_intent.go` `OpenPlacementIntentStore`; `core/lifecycle/store.go` `OpenFileStore`; `cmd/blockmaster/main.go` `run` | `INV-LIFECYCLE-STORE-DURABLE-001`, `INV-LIFECYCLE-FAILSTOP-001` |
| Ready | Ready | a changed put or import: changed files are durable before rename (per-file fsync, or one `syncfs` on a qualified filesystem) and one directory barrier precedes publication; an unchanged record does no I/O and keeps its SeenAt | `core/lifecycle/record_file.go` `writeRecordDurably`, `writeRecordBatchDurably`; `core/lifecycle/node_inventory.go` `ImportNodes`, `registrationLocked`; `core/lifecycle/placement_intent.go` `ImportPlans` | `INV-LIFECYCLE-STORE-DURABLE-001`, `INV-NODE-REGISTRATION-FRESHNESS-001` |
| Ready | Faulted | a put or import returns a `RecordPersistenceError`; the store latches it, so later mutations return `ErrLifecycleRecoveryRequired`, before calling the process policy; a marshal error before any I/O does not latch | `core/lifecycle/record_file.go` `latchPersistenceFailure`; each store's `putLocked`, `ImportNodes`, `ImportPlans` | `INV-LIFECYCLE-STORE-DURABLE-001`, `INV-LIFECYCLE-FAILSTOP-001` |
| Recovering | Faulted | a store open's records-directory sync fails; `New` hands the `RecordPersistenceError` to the process policy | `core/lifecycle/record_file.go` `syncRecordDirectory`; `core/host/master/host.go` `New` | `INV-LIFECYCLE-STORE-DURABLE-001`, `INV-LIFECYCLE-FAILSTOP-001` |
| Faulted | Exited | the policy arms a one-second exit timer, attempts one ERROR line, then exits 1 | `core/host/master/lifecycle_failure.go` `lifecycleFailStop` | `INV-LIFECYCLE-FAILSTOP-001` |
| Exited | Recovering | the supervisor restarts blockmaster (`Restart=on-failure`) | `deploy/systemd/sw-blockmaster.service` | `INV-LIFECYCLE-FAILSTOP-001` |
A store latches the error before calling the process policy. A failed step may
leave a mix of complete old and new files; recovery syncs their directory and
startup reconciles the declarative import before serving. Temporary files are
not records. On Linux >= 5.8 with the records on ext4, xfs, btrfs or tmpfs,
startup import opens the records-directory fd before writing, writes and
closes every changed temp, calls one `syncfs`, then renames all temps and
syncs the directory before publication. A failed `syncfs` is never retried
within the step: its writeback error may have been consumed. Recovery writes
fresh temps. Older kernels, other filesystems (overlay, FUSE, NFS: syncfs does
not reach their backing files) and other platforms retain per-file fsync
before rename; startup reports the chosen path. The filesystem-wide sync can
also wait for unrelated writeback on that filesystem.
The executable arms a one-second process-exit timer before logging
and exits immediately after the log returns, rather than waiting for graceful
shutdown behind a writer. Embedders without this process policy must reopen a
failed store before any further mutation. Removal errors do not invoke this
policy: the in-memory record and its published snapshot stay present until
removal succeeds, so a later retirement tick can retry. This is covered by
`TestFailedRemoveKeepsRecordForRetry` and
`TestSpecRetirementLocalFailureDoesNotStopOtherVolumesOrProductTick`.
A successful removal still has the separate directory-sync limitation
recorded below.
### M1 walstore: open, recover, serve, fault
The local storage engine and the durable backend in front of it. Diagrams in the core design: the per-I/O gate in [§1.1](block-design.md#11-frontends-and-the-backend-contract), and the life of one write (appended, synced, in the extent, checkpointed, reusable) in [§1.2](block-design.md#12-walstore-wal-plus-extent).
@@ -592,8 +641,6 @@ stateDiagram-v2
idle --> clean: BeginClean(c)
clean --> idle: EndClean(c)
snap --> snap: PublishList (durable session pages, base CAS)
idle --> idle: DeleteSnapshotWithIntent (adopted pages read again, one CAS)
snap --> snap: DeleteSnapshotWithIntent (adopted pages read again, one CAS)
clean --> clean: AdvanceList (effects then cursor CAS)
clean --> clean: roots, segments, chunk shards and unreached list pages (conditional removal)
idle --> deleting: MarkDeleting (no holder, no dependents)
@@ -608,7 +655,7 @@ stateDiagram-v2
| snap(s), list slot empty | snap(s), list cursor published | same full holder, open session and original base generation; every page durable; full slot returns queue_full without replacing work; unknown reply retains protection | `list_chain.go` `StageListPage`, `RunPublishList` | `INV-LIST-PUBLISH-001` |
| clean(c), current list page | clean(c), next continuation or none | exact observed cursor CAS only after authenticated page effects succeed; failed reads and failed effects leave cursor unchanged | `list_chain.go` `RunAdvanceList` | `INV-LIST-CURSOR-001` |
| clean(c), stored list page | clean(c), unreached page removed | tags before HEAD; current clean session; spare all current-chain pages; conditional mark then delete | `remove.go` `Cleaner.Page` | `INV-LIST-RETIRE-001` |
| idle/snap, retained snapshot | same activity, row removed and intent published | one CAS removes only captured name/gen and names its durable chain; each page present, this attempt's tag, unmarked, then read and authenticated again after adoption; clean activity refuses | `delete_intent.go` `RunDeleteSnapshotWithIntent` | `INV-SNAPSHOT-DELETE-INTENT-001`, `INV-SNAPSHOT-DELETE-ADOPT-001`, `INV-SNAPSHOT-DELETE-ADOPT-002` |
| idle/snap, retained snapshot | same activity, row removed and intent published | one CAS removes only captured name/gen and names its durable chain; each page present, this attempt's tag, unmarked; clean activity refuses | `delete_intent.go` `RunDeleteSnapshotWithIntent` | `INV-SNAPSHOT-DELETE-INTENT-001`, `INV-SNAPSHOT-DELETE-ADOPT-001` |
| idle live/detached, persisted delete intent | idle live/detached, next intent page or none | receipt-independent continuation from current HEAD; live-root and conditional effect guards; cursor follows completed effects | `delete_intent.go` `RunConsumeSnapshotDeleteIntent`; `BCatalog.CleanSnapshotDeletePage`; `LayoutRemote.Clean` | `INV-SNAPSHOT-DELETE-CONSUME-001` |
| idle | snap(s) | caller is the holder at HEAD's epoch (epoch, server and claim id); HEAD present; snap(s) again is a replay, any other activity is refused | head.go `Head.Begin`, `runTransition` | `INV-SNAPK-HEAD-WRITE-001`, `INV-SNAPK-BEGIN-001` |
| snap(s) | idle | holder at HEAD's epoch (epoch, server and claim id); activity is snap(s); over idle it succeeds without a write and means only that no activity remains; before resuming a failed stop, abort its still-open session and re-read HEAD: only matching live/idle resumes, detached goes Down, absent/unknown stays stopped | head.go `Head.Abort`; durable/provider_layout.go `settleLayoutStop` | `INV-SNAPK-ABORT-001` |
@@ -973,14 +1020,16 @@ Notes:
| `INV-FMT-LEVEL0-V100-001` | At format level 0 the master writes as v1.0: grants clamp to the persisted horizon, an extender keeps it current, forced moves and re-grants wait for the later of horizon and deadline plus skew, records are version 1. Every grant raises the deadline at both levels. | M2 Granted → Granted; Expired → Moved (forced); Expired → Granted (level 0) | `core/authority/workspace_lease_v100.go` `renewV100Locked`, `extendWorkspaceLease`, `forcedMoveBarrierV100Locked`, `ackValidityLocked`, `envelopeVersionLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease` | `TestALevel0RenewalKeepsTheHorizonCurrent`, `TestALevel0GrantIsClampedToTheHorizon`, `TestTheForcedBarrierFollowsTheFormatLevel`, `TestRecordEnvelopeVersionFollowsTheFormatLevel` (`core/authority/workspace_format_level_test.go`) | `FormatGateMaster` `OneServer`, `GraceOnlyFinal` (mutations `level0_no_horizon`, `old_starts_after_finalize`) | ACTIVE |
| `INV-FMT-RETIRE-001` | A host retire, the node registry's only writer after start, is refused, naming the volumes, while the host holds a placement or a live line, and unless confirm repeats the id. A retired id is unregistered; if the host returns it registers again at its reported level. | FormatGate Retire | `core/host/master/format_gate.go` `RetireHost`; `core/host/master/journal_isolation.go` `volumesServedBy` | `TestRetireHostRefusesAHostThatHoldsWork` (`core/host/master/format_gate_test.go`); `TestACleanMoveReleasesTheTopologyHome`, `TestTheTopologyHomeHoldsTheVolumeBeforeAMove`, `TestTheTopologyHomeAloneHoldsTheVolumeBeforeAMove` (`core/host/master/served_topology_move_test.go`); `TestClusterRetireHost` (`cmd/sw-block/cluster_format_test.go`); `TestNodeRegistryIsWrittenOnlyAtStartup` (`cmd/blockmaster/node_registry_guard_test.go`) | `FormatGate` r2 `OneServer` (mutation `retire_holding_host`) | ACTIVE |
| `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE |
| `INV-LIFECYCLE-STORE-DURABLE-001` | Node registration, volume record and placement-intent puts/replacements are atomic and durable: after a crash the record file is the complete old or the complete new record; a put that returned nil has fsynced the file and its directory. | M2 lifecycle record publication | `core/lifecycle/record_file.go` `writeRecordDurably`; `node_inventory.go`, `store.go`, `placement_intent.go` `putLocked` | `TestNodeInventoryCrashKeepsCompleteRegistration` (`core/lifecycle/node_inventory_crash_test.go`); `TestFileStoreCrashKeepsCompleteRecord`, `TestPlacementStoreCrashKeepsCompleteRecord`, `TestLifecyclePutSyncOrderAndFailure` (`core/lifecycle/store_crash_test.go`); `TestLifecycleStoreParentSync` (`core/lifecycle/store_parent_sync_test.go`) | � | ACTIVE |
| `INV-NODE-REGISTRATION-FRESHNESS-001` | Replaying a node registration without an observation time preserves its stored SeenAt; unchanged non-time fields do not rewrite its record. A restart is not a fresh observation, also when the declaration changed; a live heartbeat supplies freshness independently. | M2 lifecycle registration replay (no authority transition) | `core/lifecycle/node_inventory.go` `ImportNodes`, `RegisterNode`, `registrationLocked`; `core/host/master/observation_snapshot.go` `nodeHeartbeat`; `core/lifecycle/verified_placement.go` `VerifyPlacementIntent` | `TestUnchangedNodeRestartDoesNotRefreshAStaleObservation`, `TestChangedNodeImportDoesNotRefreshAStaleObservation` (`core/lifecycle/node_import_freshness_test.go`); `TestObservationNodesReportTheNewestHeartbeat` (`core/host/master/observation_heartbeat_test.go`); live-holder process restart qualification pending | Observation time is evidence, not authority; a declaration is not an observation | STUB |
| `INV-LIFECYCLE-STORE-DURABLE-001` | A successful record put/import publishes only after complete replacement records and their directory are durable. Open syncs the records directory before publication. A possibly-applied failure blocks mutations until reopen; recovery reconciles complete old/new records. | M2 lifecycle record publication | `core/lifecycle/record_file.go` `writeRecordDurably`, `writeRecordBatchDurably`; `node_inventory.go` `ImportNodes`; `placement_intent.go` `ImportPlans`; `node_inventory.go`, `store.go`, `placement_intent.go` `putLocked` | `TestNodeInventoryCrashKeepsCompleteRegistration` (`core/lifecycle/node_inventory_crash_test.go`); `TestFileStoreCrashKeepsCompleteRecord`, `TestPlacementStoreCrashKeepsCompleteRecord`, `TestLifecyclePutSyncOrderAndFailure` (`core/lifecycle/store_crash_test.go`); `TestLifecycleStoreParentSync` (`core/lifecycle/store_parent_sync_test.go`); `TestImportStepSyncsChangedFilesThenOneDirectory` (`core/lifecycle/import_step_sync_test.go`); `TestImportSyncfsFailureAndOrdering`, `TestImportSyncfsReturnedFailurePolicyAndReplay`, `TestImportSyncfsCrashBoundaries`, `TestSyncfsKernelGate`, `TestSyncfsFilesystemGate` (`core/lifecycle/import_syncfs_test.go`); `TestRecordEqualityRequiresRecoveredDirectoryAndConsistentDisk` (`core/lifecycle/import_recovery_test.go`); `TestVolumeEqualityRequiresRecovery` (`core/lifecycle/volume_recovery_test.go`); `TestNodeMarshalErrorDoesNotRequireRecovery` (`core/lifecycle/remove_retry_test.go`) | Lifecycle record publication, including startup-step durability barrier | ACTIVE |
| `INV-LIFECYCLE-FAILSTOP-001` | A supervised master exits nonzero within one second of a lifecycle put/import or open-barrier persistence failure, independently of logging. It attempts one ERROR; restart completes recovery barriers and import before serving. | Lifecycle process ready/recovering → faulted → exited → recovering | `core/host/master/lifecycle_failure.go` `lifecycleFailStop`; `host.go` `New`; `cmd/blockmaster/main.go` `run`; lifecycle store failure handlers | `TestMasterImportPersistenceFailureExitsAndRecovers` (`cmd/blockmaster/persist_exit_test.go`); `TestLifecyclePersistenceFailureStopsTheProcess`, `TestLifecycleFailStopExitsWithBlockedLogger` (`core/host/master/lifecycle_failure_test.go`) | Manual process-fault/recovery projection of lifecycle record durability; no new wire or format state | ACTIVE |
| `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/layout/create.go` `createVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCreateVolume_OverAnExistingHeadByState` (`core/frontend/chunkstore/layout/create_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE |
| `INV-MASTER-JOURNAL-ISOLATION-001` | Under strict journal isolation, blockmaster gives no new work to a node whose durable root shares the authority store's file system: it refuses that node's heartbeat while it serves no volume, a new placement on it and a move onto it; work the node already has is kept. | M2 workspace move: Acked or Expired → (move refused, nothing written); workspace placement admission; node heartbeat | `core/host/master/journal_isolation.go` `refuseColocatedHeartbeat`, `colocatedTargetRefused`, `reconcilePlacements`, `nodeServesVolumes`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/host/master/workspace_binding.go` `PlaceWorkspace` | `TestColocatedNodeIsAlarmedButAcceptedByDefault`, `TestStrictRefusesColocatedNodeWithoutVolumes`, `TestStrictAcceptsColocatedNodeThatAlreadyServes`, `TestStrictRefusesPlacementAndMoveOntoColocatedNode`, `TestStrictProductLoopSkipsColocatedNodeForNewPlacement` (`core/host/master/journal_isolation_test.go`); `TestStrictReplaysAnIssuedMoveToANowColocatedTarget`, `TestStrictKeepsAnIdempotentPlacementOnANowColocatedNode` (`core/host/master/journal_isolation_fold_test.go`) | — | ACTIVE |
| `INV-SEC-CONTROL-BIND-001` | blockmaster's unauthenticated control listeners bind only loopback: --listen without mutual TLS, and the runtime HTTP listener always; a non-loopback address, and --insecure-external-bind, are refused at startup. | AUTHORITY: control API reachability | `core/host/master/journal_isolation.go` `ValidateControlListen`; `cmd/blockmaster/main.go` `parseFlags` | `TestParseFlags_PlaintextControlListenersStayOnLoopback`, `TestManifests_NoPlaintextExternalBlockmasterBind` (`cmd/blockmaster/external_bind_test.go`); `TestAuthFlags` (`cmd/blockmaster/auth_flags_test.go`) | — (no state machine; the flag test is the proof form) | ACTIVE |
Notes:
- `INV-LIFECYCLE-STORE-DURABLE-001` open gaps: Store-directory ancestor sync on Open is best-effort: failures are logged and do not block startup; a new directory entry may not survive an immediate crash when an ancestor cannot be synced. Record-file and store-directory sync after a put remain mandatory. `NodeInventoryStore.RemoveNode` does not fsync its directory after deletion, so a removed node can reappear after a crash. A failed put may still be on disk: if directory fsync fails after rename, restart can load the new record.
- `INV-LIFECYCLE-STORE-DURABLE-001` open gaps: Store-directory ancestor sync on Open is best-effort: failures are logged and do not block startup; a new directory entry may not survive an immediate crash when an ancestor cannot be synced. Record-file and store-directory sync after a put remain mandatory. `NodeInventoryStore.RemoveNode`, `PlacementIntentStore.DeletePlacement` and `FileStore.DeleteVolume` do not fsync their directory after deletion, so a removed node, placement or volume record can reappear after a crash. A failed put may still be on disk: if directory fsync fails after rename, restart can load the new record.
- `INV-AUTH-PERSIST-BEFORE-PUBLISH-001`: a failure before the rename leaves the old record and is reported failed (the in-memory rollback test); a directory open or fsync failure after the rename leaves the outcome unknown and fail-stops the process, for every record type, so the restart reloads whatever survived and callers re-read. A workspace volume's uncertainty latch (`INV-AUTH-UNCERTAIN-001`) stays for its other causes.
- `INV-AUTH-UNCERTAIN-001`: The cited test asserts the refusal after an unknown-outcome lease extension (rename landed, then a failure; the file store fail-stops on a directory fsync failure instead, `INV-AUTH-PERSIST-BEFORE-PUBLISH-001`): the next renewal, a revocation and an endpoint change are all refused. The TLA+ configuration `S5_red_noUncertain` violates `UniqueEpoch` without it. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended: see M2 any (workspace) → Uncertain. A failed move on an uncertain volume is answered as an unknown outcome before any admission refusal, the request's own cancellation or deadline stays typed, and an issued move's replay still returns its stored grant: see M2 Uncertain → Uncertain (move answer). The renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`), not from `persistWorkspaceLocked`.
- `INV-WS-LEASE-HORIZON-001`: The forced-barrier argument (a renewal that reads its clock after the barrier has read the deadline is refused) assumes nondecreasing master time. That is an assumption of the current `WorkspaceTakeover` model, whose `Tick` and `SlowTick` actions only advance `now`; it is not a consequence of `time.Now` carrying a monotonic reading, because persisted `UnixNano` deadlines are compared as wall-clock values. The existing deadline check stays alongside the horizon. The model still renews with `exp = deadline = now + TTL`; the horizon/grant split is a pending specification update (Part C rule 2).
@@ -1046,7 +1095,6 @@ Notes:
| `INV-WS-ONE-PROCESS-PER-HOST-001` | One host runs at most one live blockvolume per volume: each takes the volume's exclusive host lock before its store opens and holds it until the store closes; a second is refused before it opens anything, whatever its `--durable-root`. | M4 (start) → Attaching, Refused | `core/frontend/durable/provider.go` `DurableProvider.lockVolumeOnHost` | `TestOneLiveProcessPerVolumePerHost`, `TestHostVolumeLockDirectoryCreatedOrRefused`, `TestHostVolumeLockRefusesNonDirectoryLockPath`, `TestHostVolumeLockTakesReadOnlyLockFile` (`core/frontend/durable/one_process_per_volume_test.go`); `TestHostVolumeLockCreatesParent0755AndLocks0700`, `TestHostVolumeLockKeepsExistingDirectoryModes` (`core/frontend/durable/volume_lock_parent_mode_test.go`); `TestVolumeLockDirTestOnlyRefusedUnderSystemd` (`cmd/blockvolume/volume_lock_flag_test.go`) | — | ACTIVE |
| `INV-CHUNK-LEASE-REQUIRED-001` | Blockvolume refuses walstore-chunk startup without --workspace-lease before any host or store is opened. The refusal names concurrent acknowledging writers and acknowledged-write loss after a forced move; plain walstore startup is unchanged. | M4 startup → Refused | `cmd/blockvolume/main.go` `parseFlags` | `TestChunkVolumeRequiresWorkspaceLeaseBeforeStart` | — | ACTIVE |
| `INV-WS-CONDITIONAL-HEAD-001` | Catalog startup requires a wrong-generation conditional update of a disposable HEAD to be definitely refused and leave its bytes and generation unchanged. Unknown probe outcomes refuse admission; cleanup failures only warn with the leftover path. No volume HEAD is used. | M4 startup → Refused | `core/frontend/chunkstore/swfs_catalog.go` `DialBCatalog`; `startup_head_probe.go` `checkConditionalHead` | `TestCatalogStartupRequiresWrongGenerationHeadRefusal`, `TestConditionalHeadNextStartCleansCrashLeftovers`, `TestConditionalHeadSweepWaitsAndLeavesNewProbes`, `TestCatalogStartupDoesNotWaitForUndeletableProbe`, `TestLayoutIdentityWriterAndReaders` | — | ACTIVE |
| `INV-WS-CHUNK-CONDITION-PROBE-001` | Catalog startup turns the chunk guard on only if the filer definitely refuses a mismatched chunk-condition update of the disposable HEAD; any other answer leaves the page re-read as the only check. No version string is read; the startup log and /status/chunk name the guard. | M4 startup | `core/frontend/chunkstore/startup_head_probe.go` `probeChunkCondition`; `catalog_b.go` `Store`, `MetadataGuard`, `Usage` | `TestTheStartupProbeTurnsTheChunkGuardOnOnlyForAFilerThatEnforcesIt` (`core/frontend/chunkstore/startup_chunk_condition_probe_test.go`), `TestCatalogStartupRequiresWrongGenerationHeadRefusal` (`core/frontend/chunkstore/startup_head_probe_test.go`), `TestStatusServer_StatusChunkUsage` (`core/host/volume/status_chunk_test.go`) | MetaABA r2, checked outside the repository: guard on = `safe_chunks_equal`; the fallback is the re-read, which a chunk still queued for deletion defeats (`mut_reread_delayed`) | ACTIVE |
| `INV-WS-SINGLE-FILER-001` | Startup requires all configured masters to answer and agree on a leader; only that leader listing exactly the target filer and confirming leadership afterward admits. Followers' lists do not decide. Unknown views retry within 60 s. This census does not fence later filer registration. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring`; `cmd/sw-block/chunk.go` `refuseUnlessSingleFiler` | `TestSingleFilerCensusUsesTheAgreedLeader`; `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerNeedsEveryMasterToAnswer`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`), `TestOpsChunk_WritingCommandsRunTheSingleFilerCheck` (`cmd/sw-block/chunk_start_check_test.go`), `TestOpsChunk_VerifyRunsTheSingleFilerCheck` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE |
| `INV-CLI-SINGLE-FILER-CLIENT-001` | Chunk metadata commands refuse missing, typed-nil and non-SWFS clients before catalog access; only a live SWFS client can run the census. | M4 startup client admission | `cmd/sw-block/chunk.go` `checkSingleFiler`, `refuseUnlessSingleFiler` | `TestSingleFilerCheckRefusesUnsupportedClients`, `TestOpsChunkWritingRefusesUnsupportedFilerBeforeCatalogAccess` | — (client capability guard) | ACTIVE |
| `INV-WS-LEASE-REGRANT-001` | Re-grant after expiry keeps the same holder and epoch, with no pending move or revocation, a certain store, and one durable write after the horizon/deadline plus skew barrier. Restart begins a new session and voids the old; ordinary reopen keeps HEAD identity (epoch, holder, claim) unchanged. | M2 Expired → Granted; M9 Start | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`; `core/frontend/chunkstore/layout/start.go` `Start` | `TestWorkspaceLeaseExpiredSameHolderRegrantIsDurable`, `TestWorkspaceLeaseRegrantWaitsForFullSkew`, `TestWorkspaceLeaseRegrantDefeatsAlreadyPassedForcedPreflight`, `TestWorkspaceLeaseForcedIssueDefeatsOldHolderRegrant`, `TestWorkspaceLeaseRegrantWaitsForDurabilityAndLatchesFailure` (`core/authority/workspace_regrant_test.go`); `TestWorkspaceLeaseRegrantPreservesLocalLogThroughFirstCut` (`core/authority/workspace_regrant_storage_test.go`); `TestStart_OwnEpochFreshRootRefusedBeforeClaim`, `TestStart_OwnEpochSameRootContinues` (`core/frontend/chunkstore/layout/start_test.go`); `TestClaim_WritesItsClaimID`, `TestRunClaim_VoidsTheOldSession` (`core/frontend/chunkstore/layout/claim_test.go`); `TestLocalReopenClaimsBeforeServing` (`core/frontend/durable/provider_reopen_belt_test.go`) | `WorkspaceRegrant` `NoDualServingInc`, `RegrantNoLoss`, `DiskCoversMemory`; `INV-SNAPK-START-ROOT-001` | ACTIVE |
@@ -1499,8 +1547,6 @@ Notes:
| `INV-SNAPSHOT-DELETE-INTENT-001` | Removing a captured snapshot incarnation and publishing its durable intent are one HEAD CAS; an unrelated metadata retry keeps the same target and durable pages. | M9 metadata delete | `delete_intent.go` `RunDeleteSnapshotWithIntent` | `TestDeleteSnapshotWithIntent_Closure`, `TestRunDeleteSnapshotWithIntent_InterruptAtEveryStep`, `TestDeleteIntentRetryKeepsDurablePagesAcrossMetadataCAS` | SnapDelete 241-245; PageChain 246-249 | DORMANT |
| `INV-SNAPSHOT-DELETE-CONSUME-001` | Only current persisted delete intent authorizes offline reclamation; live roots remain protected, failed effects retain the cursor, and receipt retirement cannot erase work. | M9 idle intent continuation | `core/frontend/chunkstore/layout/delete_intent.go` `RunConsumeSnapshotDeleteIntent`; `core/frontend/chunkstore/layout/remove.go` `Cleaner.removePlanned`; `core/frontend/chunkstore/layout_remote.go` `LayoutRemote.Clean` | `TestConsumeSnapshotDeleteIntent_Closure`, `TestDeleteIntentOfflineAndReplacementPreserved`, `TestDeleteIntentMarkConflictKeepsUnfinishedPage`, `TestLayoutSnapshotDeleteIntentResumesWithoutReceipt`, `TestCatalogDeleteIntentResumesOnePageWithoutNamespaceScan`, `TestCatalogIntentCursorInterruptAndLostReply`, `TestHolderMaintenanceResumesThePersistedDeleteIntent`, `TestHolderMaintenanceIntentIsCancelledBeforeTheCutJoins` | PageChain r2 246,251-253 (az1 13/13); StaleClean 159-161 | ACTIVE |
| `INV-SNAPSHOT-DELETE-ADOPT-001` | Publication adopts every intent page with a fresh CAS-base tag and checks it is present, this attempt's and unmarked; stale cleaners/adopters cannot remove or retag a published page, and staging never restores old tags. | M9 delete intent publication | `delete_intent.go` `adoptDeleteIntentPage`, `RunDeleteSnapshotWithIntent`, `StageSnapshotDeletePage` | `TestDeleteIntentRefreshedBaseFencesDelayedCleanerMark`, `TestDeleteIntentRefreshedBaseFencesDelayedCleanerDelete`, `TestDeleteIntentAdoptionCannotRestoreStaleTags`, `TestDeleteIntentStagingNeverRevertsPublishedTags`, `TestDeleteIntentPublicationChecksAdoptedPageMetadata`, `TestGenericIntentStagingCannotUndoRefreshedPublication` | StaleClean 159-161; exact-head refinement read required | DORMANT |
| `INV-SNAPSHOT-DELETE-ADOPT-002` | After adopting an intent page under its own tag, publication reads the page again and authenticates it; a page that no longer reads or holds other bytes refuses the publication. The filer frees chunks from a deletion queue, so a reference whose chunk is still queued reads intact and publishes. | M9 delete intent publication | `delete_intent.go` `RunDeleteSnapshotWithIntent`, `readListPage` | `TestASnapshotDeleteIsNotPublishedOverAPageWhoseDataWasFreed` (`core/frontend/chunkstore/layout/delete_intent_reread_test.go`); store witness `TestWithoutTheChunkGuardAStaleMetadataChangeOverwritesARecreatedObject` (`core/frontend/chunkstore/layout_change_meta_recreated_test.go`) | MetaABA r1, checked outside the repository: `PublishedReadable` (`safe_reread_only`; the run stays refused: `mut_reread_only_page`) | ACTIVE |
| `INV-LAYOUT-META-CHUNKS-001` | With the chunk guard on, an adoption or mark writes its looked-up entry back only while the entry's chunk fids are unchanged, so it cannot land on an object deleted and created again since its lookup; a cleaner's delete expects its own mark, so it follows. | M9 delete intent publication | `core/frontend/chunkstore/layout_store.go` `changeMeta`; `swfs.go` `UpdateEntryIfChunks` | `TestAStaleMetadataChangeDoesNotOverwriteARecreatedObject`, `TestAStaleCleanerMarkDoesNotDeleteARecreatedObject`, `TestWithTheChunkGuardAnUnchangedObjectIsStillAdoptedMarkedAndDeleted` (`core/frontend/chunkstore/layout_change_meta_recreated_test.go`) | MetaABA r2, checked outside the repository: `PublishedReadable` (`safe_chunks_equal`, `safe_legacy_chunks_equal`) | ACTIVE |
The snapshot-delete consumer and list-page retirement above are reachable through holder maintenance and covered by Go assertions. Their ACTIVE status describes that reachability and test coverage, not fresh Linux, composed-operation or release qualification. Cut and upload-intent producers remain deferred; their dormant publication rows are not activated by this consumer slice.
+13
View File
@@ -242,6 +242,19 @@ with its size and home placement. A volume's record comes from the cluster spec:
blockmaster reads the cluster spec only when it starts. After editing the spec, run
`sudo systemctl restart sw-blockmaster`. Serving volumes keep serving across that restart.
blockmaster must run under systemd or an equivalent restart supervisor. A node, placement
or volume lifecycle record write or recovery-directory sync failure attempts one `ERROR` naming the store,
record and error, ending with `exiting so the supervisor restarts from durable state`,
and exits with status 1. Termination is armed before logging and occurs within one second even if the log writer or its lock is blocked; a blocked sink may lose that diagnostic. It does not remain alive with a failed store. The shipped
`sw-blockmaster.service` has `Restart=on-failure` and `RestartSec=5s`; restart reloads
complete records through the recovery barriers before serving again.
Deletion-reservation and workspace-binding write failures do not exit: the request returns
the error and blockmaster keeps serving. A deletion reservation whose write outcome is unknown
keeps a new exclusion in memory. A workspace-binding rename or directory-sync failure leaves
the binding store uncertain, and every later binding operation fails with `restart required`
until `sudo systemctl restart sw-blockmaster`.
## 3. Create and attach a volume
1. **Add the volume to the cluster spec** with its `size_bytes` (edit it as root, as in section 2), and restart
-1
View File
@@ -468,7 +468,6 @@ Chunk store usage of a walstore-chunk volume (only with --chunk-control-endpoint
| `dependents` | int | — |
| `own_chunks` | int | — |
| `foreign_chunks` | int | — |
| `metadata_guard` | string | MetadataGuard names the protection of the volume's metadata changes: filer_chunk_condition (the filer enforces the chunk condition) or page_reread_only (it does not; delete intent pages are re-read). |
### `GET /status/nvme`
+1
View File
@@ -201,6 +201,7 @@ core/host/master/host.go New http.Server.ReadHeaderTimeout 1 per-call NONE: no m
core/host/master/host.go New http.Server.ReadTimeout 1 per-call NONE: no model row maps this file yet one HTTP request or connection
core/host/master/host.go New http.Server.WriteTimeout 1 per-call NONE: no model row maps this file yet one HTTP request or connection
core/host/master/host.go New http.Server.IdleTimeout 1 per-call NONE: no model row maps this file yet one HTTP request or connection
core/host/master/lifecycle_failure.go lifecycleFailStop time.AfterFunc 1 availability-contract NONE: process-fault exit projection of INV-LIFECYCLE-FAILSTOP-001, no wire state one-second exit deadline armed before logger; independent of blocked sink
core/host/master/probe_round.go roundEvidenceProvider.round time.NewTimer 1 per-call FencingRound.Deliver; FencingRound.Open one probe round's evidence wait
core/host/master/services.go services.deleteHolderEvidence context.WithTimeout 1 per-call FormatGate.Report one RPC or request
core/host/master/spec_retirement.go Host.reconcileDeletedSpecVolumes context.WithTimeout 1 per-call DeleteRetire.ReadOK one fresh HEAD read after the no-live-lease barrier
Can't render this file because it contains an unexpected character in line 49 and column 123.