Merge pull request #111 from seaweedfs/w2/catalog-fork-detach

chunkstore, storage: snapshot catalog, fork, detached HEAD and Detach
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-15 09:10:11 -08:00
commit b15faeea96
14 files changed
+2781 -48

No files matched your search

@@ -0,0 +1,948 @@
package chunkstore
// Catalog: the chunk control plane's filer metadata and Fork (B9 W2 spec
// §3-§5). Under the chunk base directory, per volume:
//
// <base>/<vol>/HEAD the published HEAD (ChunkRemote)
// <base>/<vol>/keys/<key> chunk key bindings (ChunkRemote)
// <base>/<vol>/intents/<id> live intents (ChunkRemote; GC roots)
// <base>/<vol>/VOLUME identity, geometry and lineage; write-once
// <base>/<vol>/snaps/<name> snapshots: a full copy of one HEAD document
//
// No entry carries filer chunks (UpdateEntry would delete chunks a new
// entry drops); every entry carries swb.kind and is checked on read, and an
// entry that does not check out is an error, never "absent".
//
// Snapshot and fork are read-then-write. Each writes an intent naming the
// keys it references before its final manifest write, and refuses that
// write once OpDeadline has passed since it read its source (spec §2.3).
// The operation's intents are removed only once its outcome is settled: the
// manifest is confirmed published (re-read shows it), or the attempt
// cleanly aborted (it never sent the write, or another entry already holds
// the name, so its exclusive create can never land). An uncertain outcome
// keeps them and reports outcome_unknown; a retry with the same request id
// settles it and removes every intent of the operation.
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"path"
"strconv"
"strings"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/storage"
)
const (
kindChunkVolume = "chunkvolume"
kindChunkSnap = "chunksnap"
volumeName = "VOLUME"
snapsDir = "snaps"
extReq = "swb.req"
extAttempt = "swb.attempt" // the id of the intent of the attempt that wrote the entry
extSnapGen = "swb.snap.gen"
extSnapEpoch = "swb.snap.epoch"
extSnapLSN = "swb.snap.lsn"
extSnapState = "swb.snap.state"
extSnapDeletedNs = "swb.snap.deleted_ns"
volumeFormat = 1
snapFormat = 1
// SnapActive and SnapDeleting are a snapshot's states.
SnapActive = "active"
SnapDeleting = "deleting"
// SnapAbsent is DeleteSnapshot's answer for a snapshot that is not there.
SnapAbsent = "absent"
// OriginCreate and OriginFork are a volume's origins.
OriginCreate = "create"
OriginFork = "fork"
// DefaultOpDeadline bounds a snapshot or fork from reading its source to
// its final write (spec §2.3).
DefaultOpDeadline = 5 * time.Minute
defaultListLimit = 100
maxListLimit = 1000
maxLabels = 32
maxLabelKey = 64
maxLabelValue = 256
maxSnapName = 128
)
// Error codes of the control plane (spec §2.2), as the HTTP API and the CLI
// report them.
const (
CodeNotChunkVolume = "not_chunk_volume"
CodeInvalidName = "invalid_name"
CodeSnapshotExists = "snapshot_exists"
CodeSnapshotNotFound = "snapshot_not_found"
CodeSnapshotDeleting = "snapshot_deleting"
CodeTargetExists = "target_exists"
CodeGeometryMismatch = "geometry_mismatch"
CodeForkIncomplete = "fork_incomplete"
CodeDeadlineExceeded = "deadline_exceeded"
CodeRemoteUnavailable = "remote_unavailable"
CodeOutcomeUnknown = "outcome_unknown"
)
// CatalogError is a typed control-plane failure.
type CatalogError struct {
Code string
Message string
Retryable bool
Err error
}
func (e *CatalogError) Error() string {
if e.Err != nil {
return fmt.Sprintf("chunkstore: %s: %s: %v", e.Code, e.Message, e.Err)
}
return fmt.Sprintf("chunkstore: %s: %s", e.Code, e.Message)
}
func (e *CatalogError) Unwrap() error { return e.Err }
// CodeOf returns the control-plane code of err, or "" when it has none.
func CodeOf(err error) string {
var ce *CatalogError
if errors.As(err, &ce) {
return ce.Code
}
return ""
}
func catErr(code string, retryable bool, err error, format string, a ...any) error {
return &CatalogError{Code: code, Message: fmt.Sprintf(format, a...), Retryable: retryable, Err: err}
}
// remoteErr wraps a filer failure as remote_unavailable, keeping the cause.
func remoteErr(err error, format string, a ...any) error {
return catErr(CodeRemoteUnavailable, true, err, format, a...)
}
// Geometry is a volume's shape; a chunk index means nothing without it.
type Geometry struct {
NumBlocks uint64 `json:"num_blocks"`
BlockSize uint32 `json:"block_size"`
ChunkBlocks uint32 `json:"chunk_blocks"`
}
// Parent is a forked volume's source.
type Parent struct {
VolumeID string `json:"volume_id"`
Snapshot string `json:"snapshot"`
Gen uint64 `json:"gen"`
}
// VolumeInfo is the VOLUME entry (spec §4.2).
type VolumeInfo struct {
Format int `json:"format"`
VolumeID string `json:"volume_id"`
Geometry
Origin string `json:"origin"`
CreatedNs int64 `json:"created_ns"`
Parent *Parent `json:"parent"`
// Fork records the fork operation that made this volume (origin fork):
// a retry is bound to it, and a completed fork replays it.
Fork *ForkRecord `json:"fork,omitempty"`
}
// ForkRecord is the operation identity and original result of a fork.
type ForkRecord struct {
RequestID string `json:"request_id"`
Source string `json:"source"`
Snapshot string `json:"snapshot"`
SourceGen uint64 `json:"source_gen"`
HeadSHA256 string `json:"head_sha256"` // SHA-256 of the snapshot's HEAD document
RemoteLSN uint64 `json:"remote_lsn"`
ChunkCount int `json:"chunk_count"`
QualifiedRefs int `json:"qualified_refs"`
}
type snapDoc struct {
Format int `json:"format"`
VolumeID string `json:"volume_id"`
Name string `json:"name"`
RequestID string `json:"request_id"`
CreatedNs int64 `json:"created_ns"`
CreatedBy string `json:"created_by"`
Consistency string `json:"consistency"`
Head json.RawMessage `json:"head"`
Geometry Geometry `json:"geometry"`
Parent *Parent `json:"parent"`
Labels map[string]string `json:"labels"`
ExpiresAtNs int64 `json:"expires_at_ns"`
}
// SnapshotInfo describes one snapshot, with the field names of the HTTP API
// (spec §3.2-§3.3).
type SnapshotInfo struct {
VolumeID string `json:"volumeID"`
Name string `json:"name"`
HeadGen uint64 `json:"headGen"`
HeadEpoch uint64 `json:"headEpoch"`
CutLSN uint64 `json:"cutLSN"`
CreatedNs int64 `json:"createdNs"`
State string `json:"state"`
ChunkCount int `json:"chunkCount"`
ManifestBytes int `json:"manifestBytes"`
Consistency string `json:"consistency"`
Labels map[string]string `json:"labels"`
Parent *Parent `json:"parent"`
ExpiresAtNs int64 `json:"expiresAtNs"`
Replayed bool `json:"replayed"`
head storage.ChunkHead
geo Geometry
}
// Head returns the HEAD the snapshot copied.
func (s SnapshotInfo) Head() storage.ChunkHead { return s.head }
// SnapshotRequest names a snapshot of the HEAD a cut installed.
type SnapshotRequest struct {
Name string
RequestID string // required; a retry with the same id replays
Labels map[string]string
Consistency string // "crash" (default) or "app"
ExpiresAtNs int64
CreatedBy string
// SourceReadAt is when the caller obtained the HEAD it snapshots (the
// cut's return); OpDeadline counts from it. Zero means now.
SourceReadAt time.Time
}
// ListOptions pages a snapshot listing.
type ListOptions struct {
Prefix string
StartAfter string
Limit int
IncludeDeleting bool
}
// ForkRequest makes a new volume from a snapshot.
type ForkRequest struct {
Source string
Snapshot string
Target string
RequestID string // required; a retry with the same id replays
Labels map[string]string
}
// ForkResult reports a fork, with the field names of the CLI output
// (spec §3.5).
type ForkResult struct {
Target string `json:"target"`
Source string `json:"source"`
Snapshot string `json:"snapshot"`
SourceGen uint64 `json:"sourceGen"`
HeadGen uint64 `json:"headGen"`
HeadEpoch uint64 `json:"headEpoch"`
RemoteLSN uint64 `json:"remoteLSN"`
ChunkCount int `json:"chunkCount"`
QualifiedRefs int `json:"qualifiedRefs"`
Replayed bool `json:"replayed"`
}
// Catalog reads and writes the control-plane entries under one chunk base.
type Catalog struct {
f Filer
base string
// OpDeadline bounds a snapshot or fork (DefaultOpDeadline when zero).
OpDeadline time.Duration
now func() time.Time
}
// NewCatalog returns the catalog for the chunk base directory base (the
// blockvolume --chunk-path), a clean absolute directory other than /.
func NewCatalog(f Filer, base string) (*Catalog, error) {
if f == nil {
return nil, errors.New("chunkstore: catalog needs a filer")
}
if !path.IsAbs(base) || path.Clean(base) != base || base == "/" {
return nil, fmt.Errorf("chunkstore: chunk base %q must be a clean absolute directory other than /", base)
}
return &Catalog{f: f, base: base, now: time.Now}, nil
}
// SetClock replaces the catalog's clock (tests).
func (c *Catalog) SetClock(now func() time.Time) { c.now = now }
func (c *Catalog) deadline() time.Duration {
if c.OpDeadline > 0 {
return c.OpDeadline
}
return DefaultOpDeadline
}
func (c *Catalog) volRoot(vol string) (string, error) {
if err := CheckVolumeID(vol); err != nil {
return "", catErr(CodeInvalidName, false, err, "volume %q", vol)
}
return path.Join(c.base, vol), nil
}
// CheckSnapshotName enforces the snapshot name rule (spec §4.4).
func CheckSnapshotName(name string) error {
if name == "" || len(name) > maxSnapName || strings.HasPrefix(name, ".") {
return catErr(CodeInvalidName, false, nil, "snapshot name %q: 1-%d characters, not starting with '.'", name, maxSnapName)
}
switch name {
case headName, volumeName, keysDir, snapsDir, intentsDir:
return catErr(CodeInvalidName, false, nil, "snapshot name %q is reserved", name)
}
for _, r := range name {
if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '.' || r == '_' || r == '-') {
return catErr(CodeInvalidName, false, nil, "snapshot name %q: only [A-Za-z0-9._-]", name)
}
}
return nil
}
func checkLabels(labels map[string]string) error {
if len(labels) > maxLabels {
return catErr(CodeInvalidName, false, nil, "%d labels, at most %d", len(labels), maxLabels)
}
for k, v := range labels {
if k == "" || len(k) > maxLabelKey || len(v) > maxLabelValue {
return catErr(CodeInvalidName, false, nil, "label %q: key 1-%d characters, value at most %d bytes", k, maxLabelKey, maxLabelValue)
}
for _, r := range k {
if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '.' || r == '_' || r == '-') {
return catErr(CodeInvalidName, false, nil, "label key %q: only [a-z0-9._-]", k)
}
}
}
return nil
}
// ---- VOLUME ----
func volumeEntry(v VolumeInfo, req string) (*filerpb.Entry, error) {
body, err := json.Marshal(v)
if err != nil {
return nil, err
}
now := time.Now().Unix()
ext := map[string][]byte{extKind: []byte(kindChunkVolume)}
if req != "" {
ext[extReq] = []byte(req)
}
return &filerpb.Entry{
Name: volumeName,
Attributes: &filerpb.FuseAttributes{FileSize: uint64(len(body)), Mtime: now, Crtime: now, FileMode: 0o644, Mime: "application/json"},
Extended: ext,
Content: body,
}, nil
}
func decodeVolume(p string, e *filerpb.Entry) (VolumeInfo, error) {
if len(e.GetChunks()) != 0 {
return VolumeInfo{}, fmt.Errorf("chunkstore: VOLUME %s carries %d filer chunks", p, len(e.Chunks))
}
if k := string(e.Extended[extKind]); k != kindChunkVolume {
return VolumeInfo{}, fmt.Errorf("chunkstore: VOLUME %s: kind %q, want %q", p, k, kindChunkVolume)
}
var v VolumeInfo
if err := json.Unmarshal(e.GetContent(), &v); err != nil {
return VolumeInfo{}, fmt.Errorf("chunkstore: VOLUME %s: decode: %v", p, err)
}
if v.Format != volumeFormat {
return VolumeInfo{}, fmt.Errorf("chunkstore: VOLUME %s: format %d not supported", p, v.Format)
}
if v.Origin != OriginCreate && v.Origin != OriginFork {
return VolumeInfo{}, fmt.Errorf("chunkstore: VOLUME %s: origin %q", p, v.Origin)
}
if v.Origin == OriginFork && (v.Fork == nil || v.Fork.RequestID == "") {
return VolumeInfo{}, fmt.Errorf("chunkstore: VOLUME %s: a fork without its fork record", p)
}
return v, nil
}
// ReadVolume returns the VOLUME entry; ok is false when it does not exist.
func (c *Catalog) ReadVolume(ctx context.Context, vol string) (VolumeInfo, bool, error) {
root, err := c.volRoot(vol)
if err != nil {
return VolumeInfo{}, false, err
}
e, err := c.f.LookupEntry(ctx, root, volumeName)
if errors.Is(err, ErrNotFound) {
return VolumeInfo{}, false, nil
}
if err != nil {
return VolumeInfo{}, false, remoteErr(err, "read VOLUME of %s", vol)
}
v, err := decodeVolume(path.Join(root, volumeName), e)
if err != nil {
return VolumeInfo{}, false, err
}
return v, true, nil
}
func (c *Catalog) headExists(ctx context.Context, root string) (bool, error) {
_, err := c.f.LookupEntry(ctx, root, headName)
if errors.Is(err, ErrNotFound) {
return false, nil
}
if err != nil {
return false, err
}
return true, nil
}
// EnsureVolume applies the attach rules of spec §4.2 for a volume served
// with geometry g: it creates a missing VOLUME entry (origin create), and
// refuses with geometry_mismatch when VOLUME disagrees with g, or with
// fork_incomplete when VOLUME is a fork whose HEAD is not written yet.
func (c *Catalog) EnsureVolume(ctx context.Context, vol string, g Geometry) (VolumeInfo, error) {
root, err := c.volRoot(vol)
if err != nil {
return VolumeInfo{}, err
}
v, ok, err := c.ReadVolume(ctx, vol)
if err != nil {
return VolumeInfo{}, err
}
if !ok {
v = VolumeInfo{Format: volumeFormat, VolumeID: vol, Geometry: g, Origin: OriginCreate, CreatedNs: c.now().UnixNano()}
e, err := volumeEntry(v, "")
if err != nil {
return VolumeInfo{}, err
}
if err := c.f.CreateEntry(ctx, root, e, true); err != nil {
if !errors.Is(err, ErrExists) {
return VolumeInfo{}, remoteErr(err, "create VOLUME of %s", vol)
}
// Another writer created it first: check theirs.
if v, ok, err = c.ReadVolume(ctx, vol); err != nil || !ok {
return VolumeInfo{}, remoteErr(err, "re-read VOLUME of %s", vol)
}
}
}
if v.Geometry != g {
return VolumeInfo{}, catErr(CodeGeometryMismatch, false, nil, "volume %s: VOLUME geometry %+v, this host serves %+v", vol, v.Geometry, g)
}
if v.Origin == OriginFork {
has, err := c.headExists(ctx, root)
if err != nil {
return VolumeInfo{}, remoteErr(err, "read HEAD of %s", vol)
}
if !has {
return VolumeInfo{}, catErr(CodeForkIncomplete, false, nil, "volume %s is a fork whose HEAD is not written yet", vol)
}
}
return v, nil
}
// ---- snapshots ----
func (c *Catalog) readSnap(ctx context.Context, vol, name string) (SnapshotInfo, string, *filerpb.Entry, error) {
root, err := c.volRoot(vol)
if err != nil {
return SnapshotInfo{}, "", nil, err
}
e, err := c.f.LookupEntry(ctx, path.Join(root, snapsDir), name)
if errors.Is(err, ErrNotFound) {
return SnapshotInfo{}, "", nil, catErr(CodeSnapshotNotFound, false, nil, "snapshot %s/%s", vol, name)
}
if err != nil {
return SnapshotInfo{}, "", nil, remoteErr(err, "read snapshot %s/%s", vol, name)
}
info, req, err := decodeSnap(path.Join(root, snapsDir, name), e)
return info, req, e, err
}
func decodeSnap(p string, e *filerpb.Entry) (SnapshotInfo, string, error) {
fail := func(format string, a ...any) (SnapshotInfo, string, error) {
return SnapshotInfo{}, "", fmt.Errorf("chunkstore: snapshot %s: "+format, append([]any{p}, a...)...)
}
if len(e.GetChunks()) != 0 {
return fail("carries %d filer chunks; refusing", len(e.Chunks))
}
if k := string(e.Extended[extKind]); k != kindChunkSnap {
return fail("kind %q, want %q", k, kindChunkSnap)
}
var doc snapDoc
if err := json.Unmarshal(e.GetContent(), &doc); err != nil {
return fail("decode: %v", err)
}
if doc.Format != snapFormat {
return fail("format %d not supported", doc.Format)
}
head, err := decodeHeadDoc(p+"#head", doc.Head)
if err != nil {
return fail("%v", err)
}
state := string(e.Extended[extSnapState])
if state != SnapActive && state != SnapDeleting {
return fail("state %q", state)
}
if string(e.Extended[extSnapGen]) != strconv.FormatUint(head.Gen, 10) {
return fail("extended gen %q disagrees with the document's HEAD gen %d", e.Extended[extSnapGen], head.Gen)
}
return SnapshotInfo{
VolumeID: doc.VolumeID, Name: doc.Name, HeadGen: head.Gen, HeadEpoch: head.Epoch, CutLSN: head.RemoteLSN,
CreatedNs: doc.CreatedNs, State: state, ChunkCount: len(head.Chunks), ManifestBytes: len(e.GetContent()),
Consistency: doc.Consistency, Labels: doc.Labels, Parent: doc.Parent, ExpiresAtNs: doc.ExpiresAtNs,
head: head, geo: doc.Geometry,
}, doc.RequestID, nil
}
// dropIntent deletes one attempt's own intent, once that attempt's create
// is confirmed or can never apply. It never touches another attempt's
// intent, even under the same operation: an earlier attempt's create may
// still be held by the server and land later (W5 rule). A failed delete
// leaves the intent, which only over-protects.
func (c *Catalog) dropIntent(ctx context.Context, root, id string) {
_ = c.f.DeleteEntry(context.WithoutCancel(ctx), path.Join(root, intentsDir), id, nil)
}
type createOutcome int
const (
createdNow createOutcome = iota // this attempt's create applied (confirmed)
createRefused // the filer refused it (the name exists): it will never apply
createUnsettled // no answer: it may still apply, even later
)
// createResolved makes this attempt's exclusive create of e under dir and
// returns its outcome and the entry now under the name (nil if unread).
// attempt, when not empty, is stored in e as extAttempt; a re-read that
// finds it confirms this attempt's create. Only the filer's own "already
// exists" answer settles a failure as refused; any other failure leaves
// the create unsettled, whatever entry the re-read finds (that entry may
// be another attempt's, and this one may still land after it is gone).
func (c *Catalog) createResolved(ctx context.Context, dir string, e *filerpb.Entry, attempt string) (createOutcome, *filerpb.Entry, error) {
if attempt != "" {
e.Extended[extAttempt] = []byte(attempt)
}
err := c.f.CreateEntry(ctx, dir, e, true)
if err == nil {
return createdNow, e, nil
}
got, lerr := c.f.LookupEntry(ctx, dir, e.GetName())
if lerr != nil {
got = nil
}
if got != nil && attempt != "" && string(got.Extended[extAttempt]) == attempt {
return createdNow, got, nil
}
if errors.Is(err, ErrExists) {
return createRefused, got, err
}
return createUnsettled, got, err
}
func headDigest(h storage.ChunkHead) (string, error) {
e, err := headEntry(h)
if err != nil {
return "", err
}
sum := sha256.Sum256(e.Content)
return hex.EncodeToString(sum[:]), nil
}
func headKeys(h storage.ChunkHead) []string {
keys := make([]string, 0, len(h.Chunks))
for _, ref := range h.Chunks {
keys = append(keys, ref.Key)
}
return keys
}
// CreateSnapshot stores head, which must be the HEAD a cut of vol installed
// (ChunkCutResult.Head), as snaps/<req.Name>. A retry with the same
// RequestID returns the existing snapshot (Replayed); another RequestID
// gets snapshot_exists. An intent names the snapshot's keys from before
// the entry is written until after.
func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRequest, head storage.ChunkHead) (SnapshotInfo, error) {
readAt := req.SourceReadAt
if readAt.IsZero() {
readAt = c.now()
}
root, err := c.volRoot(vol)
if err != nil {
return SnapshotInfo{}, err
}
if err := CheckSnapshotName(req.Name); err != nil {
return SnapshotInfo{}, err
}
if req.RequestID == "" {
return SnapshotInfo{}, catErr(CodeInvalidName, false, nil, "snapshot %s/%s: a request id is required", vol, req.Name)
}
if err := checkLabels(req.Labels); err != nil {
return SnapshotInfo{}, err
}
consistency := req.Consistency
if consistency == "" {
consistency = "crash"
}
if consistency != "crash" && consistency != "app" {
return SnapshotInfo{}, catErr(CodeInvalidName, false, nil, "consistency %q: crash or app", consistency)
}
if head.Gen == 0 {
return SnapshotInfo{}, catErr(CodeNotChunkVolume, false, nil, "volume %s has no published HEAD to snapshot", vol)
}
if existing, prev, _, err := c.readSnap(ctx, vol, req.Name); err == nil {
if prev == req.RequestID {
existing.Replayed = true
return existing, nil
}
return SnapshotInfo{}, catErr(CodeSnapshotExists, false, nil, "snapshot %s/%s exists (another request)", vol, req.Name)
} else if CodeOf(err) != CodeSnapshotNotFound {
return SnapshotInfo{}, err
}
v, ok, err := c.ReadVolume(ctx, vol)
if err != nil {
return SnapshotInfo{}, err
}
if !ok {
return SnapshotInfo{}, catErr(CodeNotChunkVolume, false, nil, "volume %s has no VOLUME entry", vol)
}
headEnt, err := headEntry(head)
if err != nil {
return SnapshotInfo{}, err
}
doc := snapDoc{Format: snapFormat, VolumeID: vol, Name: req.Name, RequestID: req.RequestID, CreatedNs: c.now().UnixNano(),
CreatedBy: req.CreatedBy, Consistency: consistency, Head: headEnt.Content, Geometry: v.Geometry, Parent: v.Parent,
Labels: req.Labels, ExpiresAtNs: req.ExpiresAtNs}
body, err := json.Marshal(doc)
if err != nil {
return SnapshotInfo{}, err
}
now := time.Now().Unix()
e := &filerpb.Entry{
Name: req.Name,
Attributes: &filerpb.FuseAttributes{FileSize: uint64(len(body)), Mtime: now, Crtime: now, FileMode: 0o644, Mime: "application/json"},
Extended: map[string][]byte{
extKind: []byte(kindChunkSnap),
extSnapGen: []byte(strconv.FormatUint(head.Gen, 10)),
extSnapEpoch: []byte(strconv.FormatUint(head.Epoch, 10)),
extSnapLSN: []byte(strconv.FormatUint(head.RemoteLSN, 10)),
extSnapState: []byte(SnapActive),
extReq: []byte(req.RequestID),
},
Content: body,
}
tag := "snapshot:" + vol + "/" + req.Name + "/" + req.RequestID
id, err := putIntent(ctx, c.f, root, storage.ChunkIntent{Gen: head.Gen, Epoch: head.Epoch, Holder: tag, Keys: headKeys(head)})
if err != nil {
return SnapshotInfo{}, remoteErr(err, "intent for snapshot %s/%s", vol, req.Name)
}
if c.now().Sub(readAt) > c.deadline() {
// Clean abort: the snapshot entry was never sent.
c.dropIntent(ctx, root, id)
return SnapshotInfo{}, catErr(CodeDeadlineExceeded, true, nil, "snapshot %s/%s: %v since the cut, over the %v deadline; nothing written", vol, req.Name, c.now().Sub(readAt), c.deadline())
}
dir := path.Join(root, snapsDir)
outcome, got, cerr := c.createResolved(ctx, dir, e, id)
if outcome != createUnsettled {
c.dropIntent(ctx, root, id) // confirmed, or refused for good
}
if outcome == createdNow {
info, _, _, err := c.readSnap(ctx, vol, req.Name)
return info, err
}
// Not this attempt's entry. When unsettled, its intent stays: this
// create may still land after the entry found here is removed.
if got == nil && outcome == createUnsettled {
return SnapshotInfo{}, catErr(CodeOutcomeUnknown, true, cerr, "snapshot %s/%s: create outcome unknown; its intent is kept, retry with the same request id", vol, req.Name)
}
if got == nil {
return SnapshotInfo{}, remoteErr(cerr, "snapshot %s/%s exists but could not be read; retry with the same request id", vol, req.Name)
}
if string(got.Extended[extReq]) != req.RequestID {
return SnapshotInfo{}, catErr(CodeSnapshotExists, false, nil, "snapshot %s/%s exists (another request)", vol, req.Name)
}
info, _, err := decodeSnap(path.Join(dir, req.Name), got)
if err != nil {
return SnapshotInfo{}, err
}
info.Replayed = true // another attempt of this request wrote it
return info, nil
}
// ListSnapshots lists vol's snapshots in name order, after opts.StartAfter.
// next is the last name returned when more may follow, else "".
func (c *Catalog) ListSnapshots(ctx context.Context, vol string, opts ListOptions) ([]SnapshotInfo, string, error) {
root, err := c.volRoot(vol)
if err != nil {
return nil, "", err
}
limit := opts.Limit
if limit <= 0 {
limit = defaultListLimit
}
if limit > maxListLimit {
limit = maxListLimit
}
dir := path.Join(root, snapsDir)
var out []SnapshotInfo
after := opts.StartAfter
for {
page, err := c.f.ListEntries(ctx, dir, opts.Prefix, after, uint32(limit))
if err != nil {
return nil, "", remoteErr(err, "list snapshots of %s", vol)
}
for _, e := range page {
info, _, err := decodeSnap(path.Join(dir, e.GetName()), e)
if err != nil {
return nil, "", err
}
after = e.GetName()
if info.State == SnapDeleting && !opts.IncludeDeleting {
continue
}
out = append(out, info)
if len(out) == limit {
return out, after, nil
}
}
if len(page) < limit {
return out, "", nil
}
}
}
// DeleteSnapshot marks snaps/<name> deleting; GC removes it later (spec
// §3.4). It returns SnapDeleting, or SnapAbsent when there is no such
// snapshot; both are success, so a retry is always safe.
func (c *Catalog) DeleteSnapshot(ctx context.Context, vol, name string) (string, error) {
root, err := c.volRoot(vol)
if err != nil {
return "", err
}
if err := CheckSnapshotName(name); err != nil {
return "", err
}
for attempt := 0; attempt < 2; attempt++ {
info, _, e, err := c.readSnap(ctx, vol, name)
if CodeOf(err) == CodeSnapshotNotFound {
return SnapAbsent, nil
}
if err != nil {
return "", err
}
if info.State == SnapDeleting {
return SnapDeleting, nil
}
e.Extended[extSnapState] = []byte(SnapDeleting)
e.Extended[extSnapDeletedNs] = []byte(strconv.FormatInt(c.now().UnixNano(), 10))
err = c.f.UpdateEntry(ctx, path.Join(root, snapsDir), e, map[string][]byte{
extSnapState: []byte(SnapActive),
extSnapGen: []byte(strconv.FormatUint(info.HeadGen, 10)),
})
switch {
case err == nil:
return SnapDeleting, nil
case errors.Is(err, ErrPrecondition), errors.Is(err, ErrNotFound):
continue // re-read once
default:
return "", remoteErr(err, "mark snapshot %s/%s deleting", vol, name)
}
}
return "", remoteErr(nil, "mark snapshot %s/%s deleting: it kept changing", vol, name)
}
// ListVolumes returns the ids of every volume directory under the base (GC).
func (c *Catalog) ListVolumes(ctx context.Context) ([]string, error) {
var out []string
after := ""
for {
page, err := c.f.ListEntries(ctx, c.base, "", after, listPage)
if err != nil {
return nil, remoteErr(err, "list volumes under %s", c.base)
}
for _, e := range page {
after = e.GetName()
if e.GetIsDirectory() && CheckVolumeID(e.GetName()) == nil {
out = append(out, e.GetName())
}
}
if len(page) < listPage {
return out, nil
}
}
}
// ---- fork ----
// Fork makes req.Target a new volume whose content is snapshot
// req.Source/req.Snapshot, in O(1) filer writes and no data copy.
//
// The target is resolved first, independently of the source:
// - a target VOLUME from another request is target_exists, and so is one
// from this request id with other parameters;
// - a completed fork of this request (VOLUME and HEAD exist) replays the
// result recorded in VOLUME, even if the source has changed since.
//
// Otherwise:
// 1. read the snapshot (snapshot_not_found, snapshot_deleting);
// 2. exclusively create the target's VOLUME (origin fork, the snapshot's
// geometry, parent, and a fork record binding the request to the
// snapshot's image digest and the result). An incomplete fork of this
// request resumes only if the snapshot still has that exact image;
// 3. qualify every chunk ref as "@<owner>/<key>" (a ref already qualified
// keeps its owner), under an intent in the target;
// 4. exclusively create the target's HEAD: gen 1, epoch 0, no holder, and
// the snapshot's remote_lsn (LSNs carry forward).
//
// The HEAD write is refused once OpDeadline has passed since step 1. An
// uncertain outcome of step 2 or 4 is outcome_unknown; a retry with the same
// request id completes the fork. An attempt whose HEAD create stays
// unsettled keeps its own intent (that create may still land); no attempt
// or replay deletes another attempt's intent.
func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) {
if _, err := c.volRoot(req.Source); err != nil {
return ForkResult{}, err
}
dstRoot, err := c.volRoot(req.Target)
if err != nil {
return ForkResult{}, err
}
if req.Source == req.Target {
return ForkResult{}, catErr(CodeTargetExists, false, nil, "fork target %s is the source", req.Target)
}
if err := CheckSnapshotName(req.Snapshot); err != nil {
return ForkResult{}, err
}
if req.RequestID == "" {
return ForkResult{}, catErr(CodeInvalidName, false, nil, "fork %s: a request id is required", req.Target)
}
if err := checkLabels(req.Labels); err != nil {
return ForkResult{}, err
}
tag := "fork:" + req.Target + "/" + req.RequestID
// The target first: replay or refuse without reading the source.
existing, ok, err := c.ReadVolume(ctx, req.Target)
if err != nil {
return ForkResult{}, err
}
if ok {
if err := c.checkForkRecord(existing, req); err != nil {
return ForkResult{}, err
}
has, err := c.headExists(ctx, dstRoot)
if err != nil {
return ForkResult{}, remoteErr(err, "read HEAD of %s", req.Target)
}
if has {
return forkResult(existing, true), nil
}
}
readAt := c.now()
snap, _, _, err := c.readSnap(ctx, req.Source, req.Snapshot)
if err != nil {
return ForkResult{}, err
}
if snap.State == SnapDeleting {
return ForkResult{}, catErr(CodeSnapshotDeleting, false, nil, "snapshot %s/%s is being deleted", req.Source, req.Snapshot)
}
if snap.geo == (Geometry{}) {
return ForkResult{}, fmt.Errorf("chunkstore: snapshot %s/%s has no geometry", req.Source, req.Snapshot)
}
src := snap.Head()
digest, err := headDigest(src)
if err != nil {
return ForkResult{}, err
}
head := storage.ChunkHead{Gen: 1, Epoch: 0, Holder: "", RemoteLSN: src.RemoteLSN, Chunks: make(map[uint64]storage.ChunkRef, len(src.Chunks)), State: storage.ChunkHeadActive}
qualified := 0
for idx, ref := range src.Chunks {
if !strings.HasPrefix(ref.Key, "@") {
ref.Key = "@" + req.Source + "/" + ref.Key
qualified++
}
head.Chunks[idx] = ref
}
record := &ForkRecord{RequestID: req.RequestID, Source: req.Source, Snapshot: req.Snapshot, SourceGen: snap.HeadGen,
HeadSHA256: digest, RemoteLSN: head.RemoteLSN, ChunkCount: len(head.Chunks), QualifiedRefs: qualified}
if ok {
// An incomplete fork of this request resumes only on the same image.
if existing.Fork.HeadSHA256 != digest || existing.Fork.SourceGen != snap.HeadGen || existing.Geometry != snap.geo {
return ForkResult{}, catErr(CodeTargetExists, false, nil,
"fork %s: snapshot %s/%s changed since this request's first attempt (gen %d -> %d); not resuming onto another image",
req.Target, req.Source, req.Snapshot, existing.Fork.SourceGen, snap.HeadGen)
}
} else {
vol := VolumeInfo{Format: volumeFormat, VolumeID: req.Target, Geometry: snap.geo, Origin: OriginFork, CreatedNs: c.now().UnixNano(),
Parent: &Parent{VolumeID: req.Source, Snapshot: req.Snapshot, Gen: snap.HeadGen}, Fork: record}
ve, err := volumeEntry(vol, req.RequestID)
if err != nil {
return ForkResult{}, err
}
// VOLUME names no chunk keys, so it needs no intent; a found VOLUME
// is this request's when it binds the same request and image.
outcome, got, cerr := c.createResolved(ctx, dstRoot, ve, "")
if outcome != createdNow {
if got == nil {
return ForkResult{}, catErr(CodeOutcomeUnknown, true, cerr, "fork %s: VOLUME create outcome unknown; retry with the same request id", req.Target)
}
v, err := decodeVolume(path.Join(dstRoot, volumeName), got)
if err != nil || c.checkForkRecord(v, req) != nil || v.Fork.HeadSHA256 != digest {
return ForkResult{}, catErr(CodeTargetExists, false, nil, "volume %s exists (another request, or another image)", req.Target)
}
}
existing = vol
}
he, err := headEntry(head)
if err != nil {
return ForkResult{}, err
}
he.Extended[extReq] = []byte(req.RequestID)
id, err := putIntent(ctx, c.f, dstRoot, storage.ChunkIntent{Gen: 0, Epoch: 0, Holder: tag, Keys: headKeys(head)})
if err != nil {
return ForkResult{}, remoteErr(err, "intent for fork %s", req.Target)
}
if c.now().Sub(readAt) > c.deadline() {
// Clean abort: HEAD was never sent.
c.dropIntent(ctx, dstRoot, id)
return ForkResult{}, catErr(CodeDeadlineExceeded, true, nil, "fork %s: %v since reading the snapshot, over the %v deadline; HEAD not written", req.Target, c.now().Sub(readAt), c.deadline())
}
// Under this request's VOLUME only this request's attempts write HEAD
// (attach refuses a fork without HEAD), so a HEAD found there completes
// the fork; if it is another attempt's and this create is unsettled,
// this attempt's intent stays (the create may land after HEAD is gone).
outcome, got, cerr := c.createResolved(ctx, dstRoot, he, id)
if outcome != createUnsettled {
c.dropIntent(ctx, dstRoot, id) // confirmed, or refused for good
}
if outcome == createUnsettled && got == nil {
return ForkResult{}, catErr(CodeOutcomeUnknown, true, cerr, "fork %s: HEAD create outcome unknown; its intent is kept, retry with the same request id", req.Target)
}
return forkResult(existing, outcome != createdNow), nil // refused: the filer says HEAD exists
}
// checkForkRecord refuses a target VOLUME that is not this fork request's.
func (c *Catalog) checkForkRecord(v VolumeInfo, req ForkRequest) error {
if v.Fork == nil || v.Fork.RequestID != req.RequestID {
return catErr(CodeTargetExists, false, nil, "volume %s exists (another request)", req.Target)
}
if v.Fork.Source != req.Source || v.Fork.Snapshot != req.Snapshot {
return catErr(CodeTargetExists, false, nil, "volume %s: request id %s was used for a fork of %s/%s", req.Target, req.RequestID, v.Fork.Source, v.Fork.Snapshot)
}
return nil
}
// forkResult is the result recorded when the fork created VOLUME.
func forkResult(v VolumeInfo, replayed bool) ForkResult {
r := v.Fork
return ForkResult{Target: v.VolumeID, Source: r.Source, Snapshot: r.Snapshot, SourceGen: r.SourceGen, HeadGen: 1, HeadEpoch: 0,
RemoteLSN: r.RemoteLSN, ChunkCount: r.ChunkCount, QualifiedRefs: r.QualifiedRefs, Replayed: replayed}
}
@@ -0,0 +1,266 @@
package chunkstore
import (
"context"
"path"
"testing"
"google.golang.org/protobuf/proto"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
)
// Schedules where the filer holds an attempt's create and runs it after the
// attempt has returned (second review of #111, P1). The rule (W5): an
// attempt deletes only its own intent, and only once its own create is
// confirmed or can never apply; never another attempt's, even under the same
// request, since that attempt's create may still land.
// holdFirst makes the filer hold the first create of p.
func holdFirst(f *fakeFiler, p string) {
held := false
f.deferCreate = func(q string, _ *filerpb.Entry) bool {
if q != p || held {
return false
}
held = true
return true
}
}
// holdFirstBehindAnother holds the first create of p and, in the same
// moment, lets another attempt of the same request write p (a copy of the
// held entry stamped with another attempt id).
func holdFirstBehindAnother(f *fakeFiler, p string) {
held := false
f.deferCreate = func(q string, e *filerpb.Entry) bool {
if q != p || held {
return false
}
held = true
other := proto.Clone(e).(*filerpb.Entry)
other.Extended["swb.attempt"] = []byte("0-00000000000000ff")
f.entries[q] = other
return true
}
}
// gcRemove removes an entry, as GC does after a delete.
func gcRemove(f *fakeFiler, p string) {
f.mu.Lock()
delete(f.entries, p)
f.mu.Unlock()
}
// assertKeysProtected fails unless every key is named by an intent of vol.
func assertKeysProtected(t *testing.T, f *fakeFiler, vol string, keys []string) {
t.Helper()
named := map[string]bool{}
for _, in := range intentsOf(t, f, vol) {
for _, k := range in.Keys {
named[k] = true
}
}
for _, k := range keys {
if !named[k] {
t.Fatalf("key %s of the late entry is named by no intent of %s: GC may delete it", k, vol)
}
}
}
func lateSnapshotKeys(t *testing.T, f *fakeFiler, vol, name string) []string {
t.Helper()
dir := path.Join(catBase, vol, snapsDir)
e, err := f.LookupEntry(context.Background(), dir, name)
if err != nil {
t.Fatalf("the held create did not land: %v", err)
}
info, _, err := decodeSnap(path.Join(dir, name), e)
if err != nil {
t.Fatal(err)
}
return sortedKeysOf(info.Head(), "")
}
func lateHeadKeys(t *testing.T, f *fakeFiler, b *fakeBlobs, vol string) []string {
t.Helper()
r, _ := NewChunkRemote(f, b, path.Join(catBase, vol))
h, err := r.GetHead(context.Background())
if err != nil {
t.Fatalf("the held HEAD create did not land: %v", err)
}
return sortedKeysOf(h, "")
}
// Attempt A's snapshot create is held; retry B of the same request publishes
// the snapshot and deletes only B's intent. The snapshot is deleted and GC
// removes it; then A's held create lands. Its keys are still protected by
// A's intent.
func TestCatalog_HeldSnapshotCreateKeepsItsIntent(t *testing.T) {
f, _, c, h := catalogFixture(t)
ctx := context.Background()
p := catBase + "/v1/snaps/s1"
holdFirst(f, p)
req := SnapshotRequest{Name: "s1", RequestID: "r"}
if _, err := c.CreateSnapshot(ctx, "v1", req, h); CodeOf(err) != CodeOutcomeUnknown {
t.Fatalf("attempt A, create held: %v, want outcome_unknown", err)
}
a := intentsOf(t, f, "v1")
if len(a) != 1 {
t.Fatalf("attempt A left %d intents, want its own", len(a))
}
if info, err := c.CreateSnapshot(ctx, "v1", req, h); err != nil || info.Replayed {
t.Fatalf("retry B: %+v %v", info, err)
}
if in := intentsOf(t, f, "v1"); len(in) != 1 || in[0].ID != a[0].ID {
t.Fatalf("after B: intents %+v, want only A's %s (A's create is still held)", in, a[0].ID)
}
if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil {
t.Fatal(err)
}
gcRemove(f, p)
if n := f.releaseDeferredCreates(); n != 1 {
t.Fatalf("A's held create applied %d times, want 1", n)
}
assertKeysProtected(t, f, "v1", lateSnapshotKeys(t, f, "v1", "s1"))
}
// Attempt A's create is held while another attempt of the same request
// writes the snapshot. A reports the snapshot but keeps its own intent; when
// the snapshot is later removed, A's create lands with its keys protected.
func TestCatalog_HeldSnapshotCreateBehindAnotherAttempt(t *testing.T) {
f, _, c, h := catalogFixture(t)
ctx := context.Background()
p := catBase + "/v1/snaps/s1"
holdFirstBehindAnother(f, p)
info, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h)
if in := intentsOf(t, f, "v1"); len(in) != 1 {
t.Fatalf("attempt A (err %v) left %d intents; its held create needs its own", err, len(in))
}
if err != nil || !info.Replayed || info.HeadGen != h.Gen {
t.Fatalf("attempt A behind another attempt: %+v %v, want the replayed snapshot", info, err)
}
if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil {
t.Fatal(err)
}
gcRemove(f, p)
if n := f.releaseDeferredCreates(); n != 1 {
t.Fatalf("A's held create applied %d times, want 1", n)
}
assertKeysProtected(t, f, "v1", lateSnapshotKeys(t, f, "v1", "s1"))
}
// The filer's own "already exists" answer refuses the create for good: the
// attempt deletes its own intent and leaks none.
func TestCatalog_RefusedSnapshotCreateDropsItsIntent(t *testing.T) {
f, _, c, h := catalogFixture(t)
ctx := context.Background()
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "other"}, h); err != nil {
t.Fatal(err)
}
// The name is taken after this request's read and before its create.
taken := f.entries[catBase+"/v1/snaps/s1"]
gcRemove(f, catBase+"/v1/snaps/s1")
f.beforeCreate = func(p string) {
if path.Dir(p) == catBase+"/v1/intents" {
f.entries[catBase+"/v1/snaps/s1"] = taken
}
}
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); CodeOf(err) != CodeSnapshotExists {
t.Fatalf("refused create: %v, want snapshot_exists", err)
}
if in := intentsOf(t, f, "v1"); len(in) != 0 {
t.Fatalf("a refused create left %d intents", len(in))
}
}
// Fork: attempt A's HEAD create is held; retry B completes the fork and
// deletes only B's intent; a replay C deletes none. The target's HEAD is
// later removed; A's held create lands with its qualified keys protected.
func TestFork_HeldHeadCreateKeepsItsIntent(t *testing.T) {
f, b, c, h := catalogFixture(t)
ctx := context.Background()
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
t.Fatal(err)
}
p := catBase + "/v2/HEAD"
holdFirst(f, p)
req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}
if _, err := c.Fork(ctx, req); CodeOf(err) != CodeOutcomeUnknown {
t.Fatalf("attempt A, HEAD create held: %v, want outcome_unknown", err)
}
a := intentsOf(t, f, "v2")
if len(a) != 1 {
t.Fatalf("attempt A left %d intents, want its own", len(a))
}
if res, err := c.Fork(ctx, req); err != nil || res.Replayed {
t.Fatalf("retry B: %+v %v", res, err)
}
if res, err := c.Fork(ctx, req); err != nil || !res.Replayed {
t.Fatalf("replay C: %+v %v", res, err)
}
if in := intentsOf(t, f, "v2"); len(in) != 1 || in[0].ID != a[0].ID {
t.Fatalf("after B and C: intents %+v, want only A's %s (A's HEAD create is still held)", in, a[0].ID)
}
gcRemove(f, p)
if n := f.releaseDeferredCreates(); n != 1 {
t.Fatalf("A's held HEAD create applied %d times, want 1", n)
}
assertKeysProtected(t, f, "v2", lateHeadKeys(t, f, b, "v2"))
}
// Fork: attempt A's HEAD create is held while another attempt writes HEAD.
// A reports the completed fork and keeps its own intent.
func TestFork_HeldHeadCreateBehindAnotherAttempt(t *testing.T) {
f, b, c, h := catalogFixture(t)
ctx := context.Background()
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
t.Fatal(err)
}
p := catBase + "/v2/HEAD"
holdFirstBehindAnother(f, p)
res, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"})
if in := intentsOf(t, f, "v2"); len(in) != 1 {
t.Fatalf("attempt A (err %v) left %d intents; its held create needs its own", err, len(in))
}
if err != nil || !res.Replayed || res.HeadGen != 1 {
t.Fatalf("attempt A behind another attempt: %+v %v, want the completed fork", res, err)
}
gcRemove(f, p)
if n := f.releaseDeferredCreates(); n != 1 {
t.Fatalf("A's held HEAD create applied %d times, want 1", n)
}
assertKeysProtected(t, f, "v2", lateHeadKeys(t, f, b, "v2"))
}
// The filer's "already exists" answer to a fork's HEAD create: HEAD is there
// (only this request writes it), so the fork is complete and the attempt
// deletes its own intent.
func TestFork_RefusedHeadCreateDropsItsIntent(t *testing.T) {
f, _, c, h := catalogFixture(t)
ctx := context.Background()
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
t.Fatal(err)
}
req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}
if _, err := c.Fork(ctx, req); err != nil {
t.Fatal(err)
}
// HEAD is written by another attempt after this attempt finds it absent
// and before this attempt's create.
p := catBase + "/v2/HEAD"
head := f.entries[p]
gcRemove(f, p)
f.beforeCreate = func(q string) {
if path.Dir(q) == catBase+"/v2/intents" {
f.entries[p] = head
}
}
res, err := c.Fork(ctx, req)
if err != nil || !res.Replayed || res.HeadGen != 1 {
t.Fatalf("refused HEAD create: %+v %v, want the completed fork", res, err)
}
if in := intentsOf(t, f, "v2"); len(in) != 0 {
t.Fatalf("a refused HEAD create left %d intents", len(in))
}
}
@@ -0,0 +1,233 @@
package chunkstore
import (
"context"
"crypto/sha256"
"errors"
"sort"
"strings"
"testing"
"github.com/seaweedfs/seaweed-block/core/storage"
)
var errTransport = errors.New("fake: transport error")
func sha256Of(b []byte) [32]byte { return sha256.Sum256(b) }
func intentsOf(t *testing.T, f *fakeFiler, vol string) []storage.ChunkIntent {
t.Helper()
r, _ := NewChunkRemote(f, newFakeBlobs(), catBase+"/"+vol)
got, err := r.ListIntents(context.Background())
if err != nil {
t.Fatal(err)
}
return got
}
func sortedKeysOf(h storage.ChunkHead, qualify string) []string {
var out []string
for _, ref := range h.Chunks {
k := ref.Key
if qualify != "" && !strings.HasPrefix(k, "@") {
k = "@" + qualify + "/" + k
}
out = append(out, k)
}
sort.Strings(out)
return out
}
func sameStrings(a, b []string) bool {
sort.Strings(a)
sort.Strings(b)
return strings.Join(a, "\x00") == strings.Join(b, "\x00")
}
// An uncertain snapshot create keeps the intent that protects the
// snapshot's keys (review of #111, P1). A retry with the same
// request id publishes the snapshot and deletes only its own intent: from
// the catalog's view the first create may still land, so its intent stays
// (W5 rule; second review).
func TestCatalog_SnapshotUncertainCreateKeepsIntent(t *testing.T) {
f, _, c, h := catalogFixture(t)
ctx := context.Background()
f.failCreate = func(p string) error {
if p == catBase+"/v1/snaps/s1" {
return errTransport
}
return nil
}
_, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h)
if CodeOf(err) != CodeOutcomeUnknown {
t.Fatalf("uncertain create: %v, want outcome_unknown", err)
}
in := intentsOf(t, f, "v1")
if len(in) != 1 || !sameStrings(in[0].Keys, sortedKeysOf(h, "")) {
t.Fatalf("after an uncertain create the intent must still protect the snapshot's keys: %+v", in)
}
f.failCreate = nil
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
t.Fatalf("retry: %v", err)
}
if got := intentsOf(t, f, "v1"); len(got) != 1 || got[0].ID != in[0].ID {
t.Fatalf("after the retry: intents %+v, want only the first attempt's %s", got, in[0].ID)
}
}
// A create that applied but lost its response is confirmed by the re-read.
func TestCatalog_SnapshotAppliedResponseLostIsConfirmed(t *testing.T) {
f, _, c, h := catalogFixture(t)
ctx := context.Background()
f.failCreateAfterApply = func(p string) error {
if p == catBase+"/v1/snaps/s1" {
return errTransport
}
return nil
}
info, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h)
if err != nil || info.HeadGen != h.Gen {
t.Fatalf("applied create with a lost response: %+v %v", info, err)
}
if in := intentsOf(t, f, "v1"); len(in) != 0 {
t.Fatalf("a confirmed snapshot left %d intents", len(in))
}
}
// The same for the fork's HEAD create, with the qualified keys protected in
// the target.
func TestFork_UncertainHeadCreateKeepsIntent(t *testing.T) {
f, _, c, h := catalogFixture(t)
ctx := context.Background()
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
t.Fatal(err)
}
f.failCreate = func(p string) error {
if p == catBase+"/v2/HEAD" {
return errTransport
}
return nil
}
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown {
t.Fatalf("uncertain HEAD create: %v, want outcome_unknown", err)
}
in := intentsOf(t, f, "v2")
if len(in) != 1 || !sameStrings(in[0].Keys, sortedKeysOf(h, "v1")) {
t.Fatalf("after an uncertain HEAD create the intent must still protect the qualified keys: %+v", in)
}
f.failCreate = nil
res, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"})
if err != nil || res.Replayed {
t.Fatalf("retry: %+v %v", res, err)
}
if got := intentsOf(t, f, "v2"); len(got) != 1 || got[0].ID != in[0].ID {
t.Fatalf("after the retry: intents %+v, want only the first attempt's %s", got, in[0].ID)
}
// Applied, response lost: confirmed by the re-read.
f.failCreateAfterApply = func(p string) error {
if p == catBase+"/v3/HEAD" {
return errTransport
}
return nil
}
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v3", RequestID: "g"}); err != nil {
t.Fatalf("applied HEAD create with a lost response: %v", err)
}
if in := intentsOf(t, f, "v3"); len(in) != 0 {
t.Fatalf("a confirmed fork left %d intents", len(in))
}
}
// An incomplete fork resumes only onto the image its first attempt bound,
// and a request id reused with other parameters is refused (P1).
func TestFork_IncompleteRetryBoundToOriginalImage(t *testing.T) {
f, b, c, h := catalogFixture(t)
ctx := context.Background()
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
t.Fatal(err)
}
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s2", RequestID: "r2"}, h); err != nil {
t.Fatal(err)
}
f.failCreate = func(p string) error {
if p == catBase+"/v2/HEAD" {
return errTransport
}
return nil
}
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown {
t.Fatalf("first attempt: %v", err)
}
f.failCreate = nil
// The same request id with another snapshot is refused.
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s2", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeTargetExists {
t.Fatalf("request id reused for another snapshot: %v, want target_exists", err)
}
// s1 is deleted and recreated over a newer source image.
f.mu.Lock()
delete(f.entries, catBase+"/v1/snaps/s1")
f.mu.Unlock()
r1, _ := NewChunkRemote(f, b, catBase+"/v1")
if err := r1.Put(ctx, "chunks/e1/c5/new", chunkBytes(0x55)); err != nil {
t.Fatal(err)
}
next := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 99, Chunks: map[uint64]storage.ChunkRef{}}
for k, v := range h.Chunks {
next.Chunks[k] = v
}
next.Chunks[5] = storage.ChunkRef{Key: "chunks/e1/c5/new", SHA256: sha256Of(chunkBytes(0x55))}
gen, err := r1.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: 1}, next)
if err != nil {
t.Fatal(err)
}
next.Gen = gen
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r-new"}, next); err != nil {
t.Fatal(err)
}
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeTargetExists {
t.Fatalf("resume after the snapshot changed image: %v, want target_exists", err)
}
if _, err := f.LookupEntry(ctx, catBase+"/v2", "HEAD"); err == nil {
t.Fatal("a fork resumed onto another image and wrote HEAD")
}
}
// A completed fork replays its recorded result without reading the source:
// after the source snapshot is deleting, and after the target advanced (P2).
func TestFork_CompletedReplayIndependentOfSource(t *testing.T) {
f, b, c, h := catalogFixture(t)
ctx := context.Background()
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
t.Fatal(err)
}
first, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"})
if err != nil {
t.Fatal(err)
}
if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil {
t.Fatal(err)
}
again, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"})
if err != nil || !again.Replayed {
t.Fatalf("replay after the source snapshot started deleting: %+v %v", again, err)
}
again.Replayed = false
if again != first {
t.Fatalf("replayed %+v, recorded %+v", again, first)
}
// The target's holder advances HEAD; the replay still reports the fork.
r2, _ := NewChunkRemote(f, b, catBase+"/v2")
cur, _ := r2.GetHead(ctx)
adv := cur
adv.Epoch, adv.Holder, adv.RemoteLSN = 1, "host-2", 50
if _, err := r2.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, adv); err != nil {
t.Fatal(err)
}
later, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"})
if err != nil || !later.Replayed || later.HeadGen != 1 || later.RemoteLSN != first.RemoteLSN || later.SourceGen != first.SourceGen {
t.Fatalf("replay after the target advanced: %+v %v", later, err)
}
}
@@ -0,0 +1,580 @@
package chunkstore
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"path"
"path/filepath"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/storage"
)
const catBase = "/swblock/chunks"
var catGeo = Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}
// publishSource writes chunks for vol and installs its first HEAD (epoch 1,
// remote_lsn 42) through the real ChunkRemote; it returns the HEAD.
func publishSource(t *testing.T, f *fakeFiler, b *fakeBlobs, vol string, chunks map[uint64][]byte) storage.ChunkHead {
t.Helper()
ctx := context.Background()
r, err := NewChunkRemote(f, b, path.Join(catBase, vol))
if err != nil {
t.Fatal(err)
}
h := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 42, Chunks: map[uint64]storage.ChunkRef{}}
for idx, data := range chunks {
key := "chunks/e1/c" + string(rune('0'+idx)) + "/k"
if err := r.Put(ctx, key, data); err != nil {
t.Fatal(err)
}
h.Chunks[idx] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)}
}
gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{}, h)
if err != nil {
t.Fatal(err)
}
h.Gen = gen
return h
}
func newCat(t *testing.T, f *fakeFiler) *Catalog {
t.Helper()
c, err := NewCatalog(f, catBase)
if err != nil {
t.Fatal(err)
}
return c
}
func chunkBytes(fill byte) []byte {
return bytes.Repeat([]byte{fill}, int(catGeo.ChunkBlocks)*int(catGeo.BlockSize))
}
func catalogFixture(t *testing.T) (*fakeFiler, *fakeBlobs, *Catalog, storage.ChunkHead) {
t.Helper()
f, b := newFakeFiler(), newFakeBlobs()
c := newCat(t, f)
if _, err := c.EnsureVolume(context.Background(), "v1", catGeo); err != nil {
t.Fatal(err)
}
h := publishSource(t, f, b, "v1", map[uint64][]byte{0: chunkBytes(0x10), 3: chunkBytes(0x13)})
return f, b, c, h
}
func assertNoFilerChunks(t *testing.T, f *fakeFiler) {
t.Helper()
for _, e := range f.allWritten() {
if len(e.Chunks) != 0 {
t.Fatalf("entry %q written with filer chunks", e.Name)
}
}
}
func TestCatalog_SnapshotCreateExclusive(t *testing.T) {
f, _, c, h := catalogFixture(t)
ctx := context.Background()
s1, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "req-a", Labels: map[string]string{"agent.step": "npm-ci"}}, h)
if err != nil {
t.Fatal(err)
}
if s1.Replayed || s1.HeadGen != h.Gen || s1.HeadEpoch != 1 || s1.CutLSN != 42 || s1.ChunkCount != 2 || s1.State != SnapActive || s1.Consistency != "crash" {
t.Fatalf("created %+v", s1)
}
again, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "req-a"}, h)
if err != nil || !again.Replayed || again.HeadGen != s1.HeadGen {
t.Fatalf("same request id: %+v %v, want a replay", again, err)
}
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "req-b"}, h); CodeOf(err) != CodeSnapshotExists {
t.Fatalf("other request id: %v, want snapshot_exists", err)
}
for _, bad := range []string{"", ".hidden", "HEAD", "snaps", "a/b", strings.Repeat("x", 129)} {
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: bad, RequestID: "r"}, h); CodeOf(err) != CodeInvalidName {
t.Errorf("name %q: %v, want invalid_name", bad, err)
}
}
assertNoFilerChunks(t, f)
// The stored HEAD copy is byte-for-byte the HEAD document.
e, _ := f.LookupEntry(ctx, catBase+"/v1/snaps", "s1")
var doc snapDoc
if err := json.Unmarshal(e.Content, &doc); err != nil {
t.Fatal(err)
}
headEnt, _ := f.LookupEntry(ctx, catBase+"/v1", "HEAD")
if !bytes.Equal(doc.Head, headEnt.Content) {
t.Fatal("snapshot's head is not the HEAD document")
}
}
func TestCatalog_SnapshotEntryNeverCarriesChunks(t *testing.T) {
f, _, c, h := catalogFixture(t)
ctx := context.Background()
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
t.Fatal(err)
}
assertNoFilerChunks(t, f)
f.mu.Lock()
f.entries[catBase+"/v1/snaps/s1"].Chunks = []*filerpb.FileChunk{{FileId: "3,01"}}
f.mu.Unlock()
if _, _, err := c.ListSnapshots(ctx, "v1", ListOptions{}); err == nil || CodeOf(err) == CodeSnapshotNotFound {
t.Fatalf("a snapshot entry with filer chunks listed: %v", err)
}
}
func TestCatalog_ListPagesAndFilters(t *testing.T) {
_, _, c, h := catalogFixture(t)
ctx := context.Background()
for _, n := range []string{"a1", "a2", "b1", "b2", "b3"} {
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: n, RequestID: n}, h); err != nil {
t.Fatal(err)
}
}
if _, err := c.DeleteSnapshot(ctx, "v1", "b2"); err != nil {
t.Fatal(err)
}
names := func(s []SnapshotInfo) string {
var out []string
for _, x := range s {
out = append(out, x.Name)
}
return strings.Join(out, ",")
}
page, next, err := c.ListSnapshots(ctx, "v1", ListOptions{Limit: 2})
if err != nil || names(page) != "a1,a2" || next != "a2" {
t.Fatalf("page 1: %s next %q %v", names(page), next, err)
}
page, next, _ = c.ListSnapshots(ctx, "v1", ListOptions{Limit: 2, StartAfter: next})
if names(page) != "b1,b3" || next != "b3" {
t.Fatalf("page 2 (deleting b2 skipped): %s next %q", names(page), next)
}
page, next, _ = c.ListSnapshots(ctx, "v1", ListOptions{Limit: 2, StartAfter: next})
if names(page) != "" || next != "" {
t.Fatalf("page 3: %s next %q", names(page), next)
}
page, _, _ = c.ListSnapshots(ctx, "v1", ListOptions{Prefix: "b", IncludeDeleting: true})
if names(page) != "b1,b2,b3" || page[1].State != SnapDeleting {
t.Fatalf("prefix b with deleting: %s", names(page))
}
if page, _, err := c.ListSnapshots(ctx, "v9", ListOptions{}); err != nil || len(page) != 0 {
t.Fatalf("volume without snapshots: %v %v", page, err)
}
vols, err := c.ListVolumes(ctx)
if err != nil {
t.Fatal(err)
}
_ = vols // the fake filer has no directory entries; the real filer is covered by the integration test
}
func TestCatalog_DeleteMarksThenIdempotent(t *testing.T) {
f, _, c, h := catalogFixture(t)
ctx := context.Background()
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
t.Fatal(err)
}
before, _ := f.LookupEntry(ctx, catBase+"/v1/snaps", "s1")
f.mu.Lock()
deletesBefore := f.deletes
f.mu.Unlock()
st, err := c.DeleteSnapshot(ctx, "v1", "s1")
if err != nil || st != SnapDeleting {
t.Fatalf("delete: %q %v", st, err)
}
after, _ := f.LookupEntry(ctx, catBase+"/v1/snaps", "s1")
if !bytes.Equal(before.Content, after.Content) || string(after.Extended[extSnapState]) != SnapDeleting || len(after.Extended[extSnapDeletedNs]) == 0 {
t.Fatal("delete must only mark the entry (content unchanged, state deleting, deleted_ns set)")
}
if st, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || st != SnapDeleting {
t.Fatalf("repeated delete: %q %v", st, err)
}
if st, err := c.DeleteSnapshot(ctx, "v1", "nope"); err != nil || st != SnapAbsent {
t.Fatalf("delete of a missing snapshot: %q %v", st, err)
}
f.mu.Lock()
removed := f.deletes - deletesBefore
f.mu.Unlock()
if removed != 0 {
t.Fatalf("DeleteSnapshot removed %d entries; it must only mark", removed)
}
}
func TestFork_HeadIsEpochZeroWithQualifiedKeys(t *testing.T) {
f, _, c, h := catalogFixture(t)
ctx := context.Background()
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
t.Fatal(err)
}
intentsAtHead := -1
f.beforeCreate = func(p string) {
if p == catBase+"/v2/HEAD" {
intentsAtHead = 0
for k := range f.entries {
if strings.HasPrefix(k, catBase+"/v2/intents/") {
intentsAtHead++
}
}
}
}
res, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork-1"})
if err != nil {
t.Fatal(err)
}
if intentsAtHead != 1 {
t.Fatalf("intents in v2 when its HEAD was written: %d, want 1", intentsAtHead)
}
if got, _ := f.ListEntries(ctx, catBase+"/v2/intents", "", "", 0); len(got) != 0 {
t.Fatalf("fork left %d intents", len(got))
}
r2, _ := NewChunkRemote(f, newFakeBlobs(), catBase+"/v2")
head, err := r2.GetHead(ctx)
if err != nil {
t.Fatal(err)
}
if head.Gen != 1 || head.Epoch != 0 || head.Holder != "" || head.RemoteLSN != 42 || len(head.Chunks) != 2 {
t.Fatalf("fork HEAD %+v: want gen 1, epoch 0, no holder, the snapshot's remote_lsn 42", head)
}
for idx, ref := range head.Chunks {
src := h.Chunks[idx]
if ref.Key != "@v1/"+src.Key || ref.SHA256 != src.SHA256 {
t.Fatalf("chunk %d ref %+v, want @v1/%s with the same hash", idx, ref, src.Key)
}
}
if res.HeadGen != 1 || res.HeadEpoch != 0 || res.QualifiedRefs != 2 || res.SourceGen != h.Gen || res.RemoteLSN != 42 || res.Replayed {
t.Fatalf("result %+v", res)
}
v, ok, err := c.ReadVolume(ctx, "v2")
if err != nil || !ok || v.Origin != OriginFork || v.Geometry != catGeo || v.Parent == nil || v.Parent.VolumeID != "v1" || v.Parent.Snapshot != "s1" || v.Parent.Gen != h.Gen {
t.Fatalf("fork VOLUME %+v %v %v", v, ok, err)
}
again, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork-1"})
if err != nil || !again.Replayed {
t.Fatalf("retried fork: %+v %v", again, err)
}
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork-2"}); CodeOf(err) != CodeTargetExists {
t.Fatalf("fork onto an existing volume: %v, want target_exists", err)
}
assertNoFilerChunks(t, f)
}
func TestFork_ForkOfForkKeepsOriginalOwner(t *testing.T) {
f, b, c, h := catalogFixture(t)
ctx := context.Background()
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
t.Fatal(err)
}
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f1"}); err != nil {
t.Fatal(err)
}
r2, _ := NewChunkRemote(f, b, catBase+"/v2")
h2, _ := r2.GetHead(ctx)
if _, err := c.CreateSnapshot(ctx, "v2", SnapshotRequest{Name: "t1", RequestID: "r2"}, h2); err != nil {
t.Fatal(err)
}
if _, err := c.Fork(ctx, ForkRequest{Source: "v2", Snapshot: "t1", Target: "v3", RequestID: "f2"}); err != nil {
t.Fatal(err)
}
r3, _ := NewChunkRemote(f, b, catBase+"/v3")
h3, _ := r3.GetHead(ctx)
for idx, ref := range h3.Chunks {
if ref.Key != "@v1/"+h.Chunks[idx].Key {
t.Fatalf("second-level fork chunk %d names %q, want the original owner @v1/%s", idx, ref.Key, h.Chunks[idx].Key)
}
if got, err := r3.Get(ctx, ref.Key); err != nil || sha256.Sum256(got) != ref.SHA256 {
t.Fatalf("v3 reads chunk %d through its ref: %v", idx, err)
}
}
}
func TestFork_RefusalsAndDeadline(t *testing.T) {
f, _, c, h := catalogFixture(t)
ctx := context.Background()
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "nope", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeSnapshotNotFound {
t.Fatalf("fork of a missing snapshot: %v", err)
}
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
t.Fatal(err)
}
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "gone", RequestID: "g"}, h); err != nil {
t.Fatal(err)
}
if _, err := c.DeleteSnapshot(ctx, "v1", "gone"); err != nil {
t.Fatal(err)
}
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "gone", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeSnapshotDeleting {
t.Fatalf("fork of a deleting snapshot: %v", err)
}
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "../x", RequestID: "f"}); CodeOf(err) != CodeInvalidName {
t.Fatalf("fork onto a non-plain volume id: %v", err)
}
// The clock passes OpDeadline between reading the snapshot and the HEAD write.
start := time.Unix(1000, 0)
calls := 0
c.SetClock(func() time.Time {
calls++
if calls > 2 {
return start.Add(DefaultOpDeadline + time.Second)
}
return start
})
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v4", RequestID: "late"}); CodeOf(err) != CodeDeadlineExceeded {
t.Fatalf("late fork: %v, want deadline_exceeded", err)
}
if _, err := f.LookupEntry(ctx, catBase+"/v4", "HEAD"); err == nil {
t.Fatal("a fork past its deadline wrote a HEAD")
}
c.SetClock(time.Now)
// The VOLUME from the late attempt is reused by its own retry.
if res, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v4", RequestID: "late"}); err != nil || res.Replayed {
t.Fatalf("retry after the late attempt: %+v %v", res, err)
}
// A fork whose VOLUME is written but HEAD is not refuses to attach.
s1, _, _, err := c.readSnap(ctx, "v1", "s1")
if err != nil {
t.Fatal(err)
}
digest, _ := headDigest(s1.Head())
vol := VolumeInfo{Format: volumeFormat, VolumeID: "v5", Geometry: catGeo, Origin: OriginFork, Parent: &Parent{VolumeID: "v1", Snapshot: "s1", Gen: h.Gen},
Fork: &ForkRecord{RequestID: "crashed", Source: "v1", Snapshot: "s1", SourceGen: h.Gen, HeadSHA256: digest, RemoteLSN: 42, ChunkCount: 2, QualifiedRefs: 2}}
ve, _ := volumeEntry(vol, "crashed")
if err := f.CreateEntry(ctx, catBase+"/v5", ve, true); err != nil {
t.Fatal(err)
}
if _, err := c.EnsureVolume(ctx, "v5", catGeo); CodeOf(err) != CodeForkIncomplete {
t.Fatalf("attach of an incomplete fork: %v, want fork_incomplete", err)
}
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v5", RequestID: "crashed"}); err != nil {
t.Fatalf("retry completes the crashed fork: %v", err)
}
if _, err := c.EnsureVolume(ctx, "v5", catGeo); err != nil {
t.Fatalf("attach after the fork completed: %v", err)
}
if _, err := c.EnsureVolume(ctx, "v5", Geometry{NumBlocks: 128, BlockSize: 4096, ChunkBlocks: 8}); CodeOf(err) != CodeGeometryMismatch {
t.Fatalf("attach with other geometry: %v, want geometry_mismatch", err)
}
}
// End to end over the walstore chunk layer: a fork attached as a fresh host
// reads exactly the snapshot's image, lazily, through the owner-qualified
// refs; its own first cut writes only into its own keys/.
func TestFork_ThenFreshHostReadsSnapshotImage(t *testing.T) {
ctx := context.Background()
const blocks, chunkBlocks = 64, 8
f, b := newFakeFiler(), newFakeBlobs()
c := newCat(t, f)
geo := Geometry{NumBlocks: blocks, BlockSize: 4096, ChunkBlocks: chunkBlocks}
dir := t.TempDir()
attach := func(vol string, fresh bool, epoch uint64) (*storage.WALStore, storage.ChunkLayer) {
if _, err := c.EnsureVolume(ctx, vol, geo); err != nil && !fresh {
t.Fatal(err)
}
p := filepath.Join(dir, vol)
s, err := storage.CreateWALStore(p, blocks, 4096)
if err != nil {
t.Fatal(err)
}
if _, err := s.Recover(); err != nil {
t.Fatal(err)
}
r, _ := NewChunkRemote(f, b, path.Join(catBase, vol))
l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: chunkBlocks, Epoch: epoch, Holder: vol, FreshFromHead: fresh,
Bitmap: storage.NewFileChunkBitmapStore(p + ".chunkbitmap")})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.Close() })
return s, l
}
src, layer := attach("v1", false, 1)
want := map[uint32][]byte{}
for _, lba := range []uint32{0, 9, 17, 63} {
want[lba] = bytes.Repeat([]byte{byte(lba + 1)}, 4096)
if _, err := src.Write(lba, want[lba]); err != nil {
t.Fatal(err)
}
}
cut, err := layer.Cut(ctx)
if err != nil {
t.Fatal(err)
}
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, cut.Head); err != nil {
t.Fatal(err)
}
// The source keeps writing after the snapshot; the fork must not see it.
if _, err := src.Write(9, bytes.Repeat([]byte{0xee}, 4096)); err != nil {
t.Fatal(err)
}
if _, err := layer.Cut(ctx); err != nil {
t.Fatal(err)
}
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); err != nil {
t.Fatal(err)
}
dst, dlayer := attach("v2", true, 1)
zero := make([]byte, 4096)
for lba := uint32(0); lba < blocks; lba++ {
got, err := dst.Read(lba)
if err != nil {
t.Fatalf("fork read %d: %v", lba, err)
}
exp, ok := want[lba]
if !ok {
exp = zero
}
if !bytes.Equal(got, exp) {
t.Fatalf("fork block %d = %x..., want the snapshot's %x...", lba, got[:2], exp[:2])
}
}
keysBefore, _ := f.ListEntries(ctx, catBase+"/v1/keys", "", "", 0)
if _, err := dst.Write(40, bytes.Repeat([]byte{0x40}, 4096)); err != nil {
t.Fatal(err)
}
r2, err := dlayer.Cut(ctx)
if err != nil {
t.Fatalf("fork's first cut: %v", err)
}
if r2.Head.Epoch != 1 || r2.Head.RemoteLSN < 1 {
t.Fatalf("fork's first HEAD %+v", r2.Head)
}
keysAfter, _ := f.ListEntries(ctx, catBase+"/v1/keys", "", "", 0)
if len(keysAfter) != len(keysBefore) {
t.Fatalf("the fork's cut wrote %d keys into the source volume", len(keysAfter)-len(keysBefore))
}
if own, _ := f.ListEntries(ctx, catBase+"/v2/keys", "", "", 0); len(own) != 1 {
t.Fatalf("the fork's cut wrote %d keys of its own, want 1", len(own))
}
}
func TestCatalog_SnapshotIntentAroundEntry(t *testing.T) {
f, _, c, h := catalogFixture(t)
ctx := context.Background()
seen := -1
f.beforeCreate = func(p string) {
if p == catBase+"/v1/snaps/s1" {
seen = 0
for k := range f.entries {
if strings.HasPrefix(k, catBase+"/v1/intents/") {
seen++
}
}
}
}
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
t.Fatal(err)
}
if seen != 1 {
t.Fatalf("intents when the snapshot entry was written: %d, want 1", seen)
}
if got, _ := f.ListEntries(ctx, catBase+"/v1/intents", "", "", 0); len(got) != 0 {
t.Fatalf("snapshot left %d intents", len(got))
}
}
// The HEAD document carries "state" ("active" by every normal cut) and,
// only when detached, "detachedBy" {holder, epoch, gen} naming its own
// holder, epoch and generation; a document without "state" reads as active,
// and an inconsistent detachedBy is refused.
func TestHeadDoc_StateAndDetachedBy(t *testing.T) {
f, b := newFakeFiler(), newFakeBlobs()
r, _ := NewChunkRemote(f, b, catBase+"/v1")
ctx := context.Background()
gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "h", RemoteLSN: 5, Chunks: map[uint64]storage.ChunkRef{}, State: storage.ChunkHeadActive})
if err != nil {
t.Fatal(err)
}
e, _ := f.LookupEntry(ctx, catBase+"/v1", "HEAD")
if !strings.Contains(string(e.Content), `"state":"active"`) || strings.Contains(string(e.Content), "detachedBy") {
t.Fatalf("an active HEAD document: %s", e.Content)
}
det := storage.ChunkHead{Epoch: 1, Holder: "h", RemoteLSN: 5, Chunks: map[uint64]storage.ChunkRef{}, State: storage.ChunkHeadDetached,
DetachedBy: &storage.ChunkDetachedBy{Holder: "h", Epoch: 1, Gen: gen + 1}}
if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: gen, Epoch: 1}, det); err != nil {
t.Fatal(err)
}
h, err := r.GetHead(ctx)
if err != nil || h.State != storage.ChunkHeadDetached || h.DetachedBy == nil || *h.DetachedBy != (storage.ChunkDetachedBy{Holder: "h", Epoch: 1, Gen: gen + 1}) {
t.Fatalf("detached HEAD read back as %+v %v", h, err)
}
// An older document without "state" reads as active.
e, _ = f.LookupEntry(ctx, catBase+"/v1", "HEAD")
var doc map[string]any
_ = json.Unmarshal(e.Content, &doc)
delete(doc, "state")
delete(doc, "detachedBy")
old, _ := json.Marshal(doc)
f.mu.Lock()
f.entries[catBase+"/v1/HEAD"].Content = old
f.mu.Unlock()
if h, err := r.GetHead(ctx); err != nil || h.State == storage.ChunkHeadDetached {
t.Fatalf("a HEAD without state: %+v %v, want active", h, err)
}
// detachedBy that is not the HEAD's own holder/epoch/gen is refused.
doc["state"] = "detached"
doc["detachedBy"] = map[string]any{"holder": "h", "epoch": 1, "gen": gen} // stale gen
bad, _ := json.Marshal(doc)
f.mu.Lock()
f.entries[catBase+"/v1/HEAD"].Content = bad
f.mu.Unlock()
if _, err := r.GetHead(ctx); err == nil {
t.Fatal("a detached HEAD with another generation in detachedBy was accepted")
}
}
// Production serialization end to end: the walstore chunk layer's Detach,
// over the SeaweedFS remote, writes HEAD to the filer with exactly the
// ruled fields, in one CAS with the final cut.
func TestDetach_ProductionSerializedHead(t *testing.T) {
ctx := context.Background()
f, b := newFakeFiler(), newFakeBlobs()
p := filepath.Join(t.TempDir(), "v1")
s, err := storage.CreateWALStore(p, 64, 4096)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.Close() })
if _, err := s.Recover(); err != nil {
t.Fatal(err)
}
r, _ := NewChunkRemote(f, b, catBase+"/v1")
l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 3, Holder: "host-a",
Bitmap: storage.NewFileChunkBitmapStore(p + ".chunkbitmap")})
if err != nil {
t.Fatal(err)
}
if _, err := s.Write(9, bytes.Repeat([]byte{9}, 4096)); err != nil {
t.Fatal(err)
}
res, err := l.Detach(ctx)
if err != nil {
t.Fatal(err)
}
e, err := f.LookupEntry(ctx, catBase+"/v1", "HEAD")
if err != nil {
t.Fatal(err)
}
var doc struct {
Gen uint64 `json:"gen"`
Epoch uint64 `json:"epoch"`
Holder string `json:"holder"`
RemoteLSN uint64 `json:"remote_lsn"`
State string `json:"state"`
DetachedBy map[string]any `json:"detachedBy"`
}
if err := json.Unmarshal(e.Content, &doc); err != nil {
t.Fatal(err)
}
if doc.Gen != 1 || doc.State != "detached" || doc.Holder != "host-a" || doc.Epoch != 3 || doc.RemoteLSN != res.H {
t.Fatalf("serialized HEAD: %s", e.Content)
}
if len(doc.DetachedBy) != 3 || doc.DetachedBy["holder"] != "host-a" || doc.DetachedBy["epoch"] != float64(3) || doc.DetachedBy["gen"] != float64(1) {
t.Fatalf("serialized detachedBy %v, want exactly {holder host-a, epoch 3, gen 1}", doc.DetachedBy)
}
if string(e.Extended[extGen]) != "1" || len(e.Chunks) != 0 {
t.Fatalf("HEAD entry extended gen %q, filer chunks %d", e.Extended[extGen], len(e.Chunks))
}
}
@@ -228,6 +228,12 @@ func (r *ChunkRemote) intentDir() string { return path.Join(r.root, intentsDir)
// The entry is durable when the filer's fsync rule covers the chunk path,
// the same condition as for HEAD.
func (r *ChunkRemote) PutIntent(ctx context.Context, in storage.ChunkIntent) (string, error) {
return putIntent(ctx, r.f, r.root, in)
}
// putIntent writes an intent under <root>/intents/; the catalog uses it for
// snapshots and forks, which have no ChunkRemote.
func putIntent(ctx context.Context, f Filer, root string, in storage.ChunkIntent) (string, error) {
for _, k := range in.Keys {
if err := storage.ValidChunkKey(k); err != nil {
return "", fmt.Errorf("%w: %v", ErrInvalidKey, err)
@@ -253,7 +259,7 @@ func (r *ChunkRemote) PutIntent(ctx context.Context, in storage.ChunkIntent) (st
},
Content: body,
}
if err := r.f.CreateEntry(ctx, r.intentDir(), e, true); err != nil {
if err := f.CreateEntry(ctx, path.Join(root, intentsDir), e, true); err != nil {
return "", fmt.Errorf("chunkstore: put intent %s: %w", id, err)
}
return id, nil
@@ -327,6 +333,17 @@ type headDoc struct {
Holder string `json:"holder"`
RemoteLSN uint64 `json:"remote_lsn"`
Chunks map[uint64]refDoc `json:"chunks"`
// State is "active" or "detached"; a document without it is active.
// DetachedBy names the holder whose final cut (this generation) a
// detached HEAD is; it is absent unless State is detached.
State string `json:"state,omitempty"`
DetachedBy *detachedByDoc `json:"detachedBy,omitempty"`
}
type detachedByDoc struct {
Holder string `json:"holder"`
Epoch uint64 `json:"epoch"`
Gen uint64 `json:"gen"`
}
type refDoc struct {
@@ -383,7 +400,10 @@ func (r *ChunkRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVer
func headEntry(h storage.ChunkHead) (*filerpb.Entry, error) {
doc := headDoc{Format: headFormat, Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN,
Chunks: make(map[uint64]refDoc, len(h.Chunks))}
Chunks: make(map[uint64]refDoc, len(h.Chunks)), State: h.State}
if h.DetachedBy != nil {
doc.DetachedBy = &detachedByDoc{Holder: h.DetachedBy.Holder, Epoch: h.DetachedBy.Epoch, Gen: h.DetachedBy.Gen}
}
for idx, ref := range h.Chunks {
if ref.Key == "" {
return nil, fmt.Errorf("chunkstore: HEAD chunk %d has no key", idx)
@@ -424,8 +444,29 @@ func decodeHead(p string, e *filerpb.Entry) (storage.ChunkHead, error) {
if k := string(e.Extended[extKind]); k != kindChunkHead {
return fail("kind %q, want %q", k, kindChunkHead)
}
h, err := decodeHeadDoc(p, e.GetContent())
if err != nil {
return storage.ChunkHead{}, err
}
// The CAS compares the extended attributes, so they must agree with the
// document or a CAS could validate against a different state.
if string(e.Extended[extGen]) != strconv.FormatUint(h.Gen, 10) ||
string(e.Extended[extEpoch]) != strconv.FormatUint(h.Epoch, 10) ||
string(e.Extended[extHolder]) != h.Holder {
return fail("extended gen/epoch/holder (%q/%q/%q) disagree with the document (%d/%d/%q)",
e.Extended[extGen], e.Extended[extEpoch], e.Extended[extHolder], h.Gen, h.Epoch, h.Holder)
}
return h, nil
}
// decodeHeadDoc decodes and checks a HEAD document: HEAD's own content, or
// the copy a snapshot embeds.
func decodeHeadDoc(p string, content []byte) (storage.ChunkHead, error) {
fail := func(format string, a ...any) (storage.ChunkHead, error) {
return storage.ChunkHead{}, fmt.Errorf("chunkstore: HEAD %s: "+format, append([]any{p}, a...)...)
}
var doc headDoc
if err := json.Unmarshal(e.GetContent(), &doc); err != nil {
if err := json.Unmarshal(content, &doc); err != nil {
return fail("decode: %v", err)
}
if doc.Format != headFormat {
@@ -434,16 +475,24 @@ func decodeHead(p string, e *filerpb.Entry) (storage.ChunkHead, error) {
if doc.Gen == 0 {
return fail("generation 0")
}
// The CAS compares the extended attributes, so they must agree with the
// document or a CAS could validate against a different state.
if string(e.Extended[extGen]) != strconv.FormatUint(doc.Gen, 10) ||
string(e.Extended[extEpoch]) != strconv.FormatUint(doc.Epoch, 10) ||
string(e.Extended[extHolder]) != doc.Holder {
return fail("extended gen/epoch/holder (%q/%q/%q) disagree with the document (%d/%d/%q)",
e.Extended[extGen], e.Extended[extEpoch], e.Extended[extHolder], doc.Gen, doc.Epoch, doc.Holder)
switch doc.State {
case "", storage.ChunkHeadActive:
if doc.DetachedBy != nil {
return fail("detachedBy on a HEAD that is not detached")
}
case storage.ChunkHeadDetached:
d := doc.DetachedBy
if d == nil || d.Gen != doc.Gen || d.Holder != doc.Holder || d.Epoch != doc.Epoch {
return fail("detached HEAD whose detachedBy %+v is not its own holder, epoch and generation", d)
}
default:
return fail("state %q", doc.State)
}
h := storage.ChunkHead{Gen: doc.Gen, Epoch: doc.Epoch, Holder: doc.Holder, RemoteLSN: doc.RemoteLSN,
Chunks: make(map[uint64]storage.ChunkRef, len(doc.Chunks))}
Chunks: make(map[uint64]storage.ChunkRef, len(doc.Chunks)), State: doc.State}
if doc.DetachedBy != nil {
h.DetachedBy = &storage.ChunkDetachedBy{Holder: doc.DetachedBy.Holder, Epoch: doc.DetachedBy.Epoch, Gen: doc.DetachedBy.Gen}
}
for idx, ref := range doc.Chunks {
sum, err := hex.DecodeString(ref.SHA256)
if err != nil || len(sum) != 32 || ref.Key == "" {
@@ -32,6 +32,24 @@ type fakeFiler struct {
failUpdateAfterApply func(p string) error
updates int
deletes int
// beforeCreate, if set, runs under the lock just before an entry is
// created (it may read f.entries but must not call f's methods).
beforeCreate func(p string)
// failCreate, if set, is called before a create is applied; a non-nil
// return fails the call and the entry is NOT created (an ambiguous
// transport error from the caller's view).
failCreate func(p string) error
// failCreateAfterApply, if set, is called after a create was applied; a
// non-nil return is reported to the caller (applied, response lost).
failCreateAfterApply func(p string) error
// deferCreate, if set and true for a create, makes the server retain
// it (not applied yet) and return an error; releaseDeferredCreates
// applies retained creates later, each only if its name is still free
// (exclusive create, evaluated when the server finally runs it). It
// runs under the lock and may read or change f.entries (e is the
// caller's entry: read it, do not keep it).
deferCreate func(p string, e *filerpb.Entry) bool
deferredCreates []deferredCreate
}
func newFakeFiler() *fakeFiler { return &fakeFiler{entries: map[string]*filerpb.Entry{}} }
@@ -53,9 +71,26 @@ func (f *fakeFiler) CreateEntry(_ context.Context, dir string, e *filerpb.Entry,
if _, ok := f.entries[p]; ok && oExcl {
return fmt.Errorf("%w: %s", ErrExists, p)
}
if f.beforeCreate != nil {
f.beforeCreate(p)
}
if f.failCreate != nil {
if err := f.failCreate(p); err != nil {
return err
}
}
if f.deferCreate != nil && f.deferCreate(p, e) {
f.deferredCreates = append(f.deferredCreates, deferredCreate{p: p, e: proto.Clone(e).(*filerpb.Entry)})
return errors.New("fake: create retained by the server")
}
c := proto.Clone(e).(*filerpb.Entry)
f.entries[p] = c
f.written = append(f.written, proto.Clone(e).(*filerpb.Entry))
if f.failCreateAfterApply != nil {
if err := f.failCreateAfterApply(p); err != nil {
return err
}
}
return nil
}
@@ -134,6 +169,29 @@ func (f *fakeFiler) DeleteEntry(_ context.Context, dir, name string, expected ma
return nil
}
type deferredCreate struct {
p string
e *filerpb.Entry
}
// releaseDeferredCreates lets the server finish retained creates; it returns
// how many applied (a name that is taken by then is not overwritten).
func (f *fakeFiler) releaseDeferredCreates() int {
f.mu.Lock()
defer f.mu.Unlock()
applied := 0
for _, d := range f.deferredCreates {
if _, taken := f.entries[d.p]; taken {
continue
}
f.entries[d.p] = d.e
f.written = append(f.written, proto.Clone(d.e).(*filerpb.Entry))
applied++
}
f.deferredCreates = nil
return applied
}
// bumpExtended mutates a stored entry's extended key, as another writer would.
func (f *fakeFiler) bumpExtended(p, key, val string) {
f.mu.Lock()
@@ -36,8 +36,32 @@ const (
casNormal fakeCASMode = iota
casUnknownNotApplied // not applied, returns errFakeCASUnknown
casAppliedLost // applied, returns errFakeCASResponseLost
casDeferred // retained server-side, returns errFakeCASUnknown; applied later by releaseDeferredCAS
)
type deferredCAS struct {
expected chunkHeadVersion
next chunkHead
}
// releaseDeferredCAS lets the server finish every retained CAS now: each
// applies only if HEAD is still at its expected version (as a real filer
// would evaluate the precondition when it finally runs). It returns how
// many applied.
func (f *fakeChunkRemote) releaseDeferredCAS() int {
f.mu.Lock()
defer f.mu.Unlock()
applied := 0
for _, d := range f.deferred {
if f.head.Gen == d.expected.Gen && f.head.Epoch == d.expected.Epoch {
f.installLocked(copyChunkHead(d.next))
applied++
}
}
f.deferred = nil
return applied
}
// fakeChunkRemote enforces immutable keys, chunk hashes and the HEAD CAS,
// logs every call in order, and injects faults on request. Every field is
// guarded by mu.
@@ -70,8 +94,10 @@ type fakeChunkRemote struct {
failGet error // Get and GetHead
casModes []fakeCASMode // consumed one per CAS; empty = casNormal
beforeCAS func(f *fakeChunkRemote) // runs once, under mu, before the next CAS is decided
onGetHead func(f *fakeChunkRemote) // runs under mu inside every GetHead while set (a read that blocks across a change)
afterCAS func(f *fakeChunkRemote) // runs once, under mu, after the next CAS is decided
intents map[string]chunkIntent
deferred []deferredCAS
}
func newFakeChunkRemote() *fakeChunkRemote {
@@ -213,6 +239,9 @@ func (f *fakeChunkRemote) GetHead(ctx context.Context) (chunkHead, error) {
defer f.mu.Unlock()
f.ops = append(f.ops, "gethead")
f.getHeadCalls++
if hook := f.onGetHead; hook != nil {
hook(f)
}
if f.failGet != nil {
return chunkHead{}, f.failGet
}
@@ -243,6 +272,11 @@ func (f *fakeChunkRemote) CASHead(ctx context.Context, expected chunkHeadVersion
outcome = "cas:unknown"
return 0, errFakeCASUnknown
}
if mode == casDeferred {
outcome = "cas:deferred"
f.deferred = append(f.deferred, deferredCAS{expected: expected, next: copyChunkHead(next)})
return 0, errFakeCASUnknown
}
if expected.Gen != f.head.Gen || expected.Epoch != f.head.Epoch {
outcome = "cas:pre"
return 0, errChunkHeadPrecondition
+132 -26
View File
@@ -58,19 +58,28 @@ type chunkLayerImpl struct {
closeDone chan struct{} // closed when Close has finished
stMu sync.Mutex
closed bool
head chunkHead
pending *chunkHead // a proposal whose CAS outcome is unresolved
fenced bool
remoteLSN uint64
hdr chunkBitmapHeader // last header written or loaded
dirty map[uint64]bool // chunks dirtied since the cut in progress or the last HEAD
inflight map[uint64]bool // chunks captured by a cut whose HEAD is not yet installed
allDirty bool // a BASE block landed: every chunk is dirty
hashMode bool // the dirty set is unknown: compare every chunk by hash
cutLSN uint64 // H of the latest cut taken (in flight or installed)
keySeq uint64
stMu sync.Mutex
closed bool
head chunkHead
pending *chunkHead // a proposal whose CAS outcome is unresolved
fenced bool
detached *chunkCutResult // set by a successful Detach
// pendingDetach says the unresolved proposal in pending is a Detach;
// pendingCut is its cut result, installed as the detach result if the
// re-read shows it applied.
pendingDetach bool
pendingCut chunkCutResult
// pendingBase is the version the unresolved CAS expected. While HEAD is
// still at it, that CAS may still land, so a read alone never settles it.
pendingBase chunkHeadVersion
remoteLSN uint64
hdr chunkBitmapHeader // last header written or loaded
dirty map[uint64]bool // chunks dirtied since the cut in progress or the last HEAD
inflight map[uint64]bool // chunks captured by a cut whose HEAD is not yet installed
allDirty bool // a BASE block landed: every chunk is dirty
hashMode bool // the dirty set is unknown: compare every chunk by hash
cutLSN uint64 // H of the latest cut taken (in flight or installed)
keySeq uint64
// Test-only scheduling hooks; nil in production.
testPresenceSnapshotHook func() // after a presence snapshot, before it is written
@@ -176,6 +185,10 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
func copyHead(h chunkHead) chunkHead {
out := h
if h.DetachedBy != nil {
d := *h.DetachedBy
out.DetachedBy = &d
}
out.Chunks = make(map[uint64]chunkRef, len(h.Chunks))
for k, v := range h.Chunks {
out.Chunks[k] = v
@@ -460,13 +473,15 @@ func (l *chunkLayerImpl) register() (done func(), err error) {
func (l *chunkLayerImpl) admit() error {
l.stMu.Lock()
closed, fenced, base := l.closed, l.fenced, l.hdr.Base
closed, fenced, base, detached := l.closed, l.fenced, l.hdr.Base, l.detached != nil
l.stMu.Unlock()
switch {
case closed:
return errors.New("storage: chunk layer closed")
case fenced:
return errChunkLayerFenced
case detached:
return errChunkLayerDetached
case base == chunkBaseInstalling:
return fmt.Errorf("%w: BASE install in progress", errChunkCaptureRefused)
}
@@ -481,7 +496,7 @@ func (l *chunkLayerImpl) admit() error {
func (l *chunkLayerImpl) Cut(ctx context.Context) (chunkCutResult, error) {
l.capMu.Lock()
defer l.capMu.Unlock()
return l.captureLocked(ctx)
return l.captureLocked(ctx, false)
}
func (l *chunkLayerImpl) Capture(ctx context.Context) (uint64, error) {
@@ -496,15 +511,18 @@ func (l *chunkLayerImpl) MakeRemoteDurable(ctx context.Context, t uint64) error
l.capMu.Lock()
defer l.capMu.Unlock()
l.stMu.Lock()
fenced := l.fenced
fenced, detached := l.fenced, l.detached != nil
l.stMu.Unlock()
if fenced {
return errChunkLayerFenced
}
if detached {
return errChunkLayerDetached
}
if last := l.s.NextLSN() - 1; t > last {
return fmt.Errorf("storage: MakeRemoteDurable(%d): LSN was never written (last %d)", t, last)
}
r, err := l.captureLocked(ctx)
r, err := l.captureLocked(ctx, false)
if err != nil {
return err
}
@@ -521,7 +539,7 @@ type capturedChunk struct {
zero bool
}
func (l *chunkLayerImpl) captureLocked(ctx context.Context) (chunkCutResult, error) {
func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (chunkCutResult, error) {
done, err := l.register()
if err != nil {
return chunkCutResult{}, err
@@ -603,6 +621,11 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context) (chunkCutResult, err
// Upload only what changed against HEAD.
next := copyHead(baseHead)
next.Epoch, next.Holder, next.RemoteLSN = l.cfg.Epoch, l.cfg.Holder, h
next.State, next.DetachedBy = chunkHeadActive, nil
if detach {
next.State = chunkHeadDetached
next.DetachedBy = &chunkDetachedBy{Holder: l.cfg.Holder, Epoch: l.cfg.Epoch, Gen: baseHead.Gen + 1}
}
var changed []uint64
newKeys := map[uint64]string{}
for _, c := range captured {
@@ -624,7 +647,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context) (chunkCutResult, err
newKeys[c.idx] = key
changed = append(changed, c.idx)
}
if len(changed) == 0 && h == baseHead.RemoteLSN && baseHead.Gen != 0 {
if !detach && len(changed) == 0 && h == baseHead.RemoteLSN && baseHead.Gen != 0 && !chunkHeadIsDetached(baseHead) {
l.finishCut(baseHead, h, nil, nil) // nothing new: no CAS
return chunkCutResult{H: h, Head: copyHead(baseHead), Noop: true, FullHash: all}, nil
}
@@ -644,22 +667,33 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context) (chunkCutResult, err
if casErr == nil {
next.Gen = gen
l.finishCut(next, h, changed, newKeys)
return chunkCutResult{H: h, Head: copyHead(next), FullHash: all}, nil
return l.cutDone(chunkCutResult{H: h, Head: copyHead(next), FullHash: all}, detach), nil
}
// Precondition or unknown outcome: resolve by re-reading HEAD, never by
// a blind retry.
cur, gerr := l.remote.GetHead(ctx)
if gerr != nil {
keepPending := func() {
l.stMu.Lock()
p := copyHead(next)
l.pending = &p
l.pendingDetach, l.pendingCut, l.pendingBase = detach, chunkCutResult{H: h, FullHash: all}, expected
l.stMu.Unlock()
l.abortCut(all)
return chunkCutResult{}, fmt.Errorf("storage: capture CAS outcome unresolved (%v): %w", casErr, gerr)
}
cur, gerr := l.remote.GetHead(ctx)
if gerr != nil {
keepPending()
return chunkCutResult{}, fmt.Errorf("storage: capture CAS outcome unresolved (%v): %w: %w", casErr, errChunkCASOutcomeUnknown, gerr)
}
if !errors.Is(casErr, errChunkHeadPrecondition) && !sameProposal(cur, next) && cur.Gen == expected.Gen && cur.Epoch == expected.Epoch {
// HEAD is still the CAS's base and the server gave no definite
// refusal: the CAS may still land. Settle it before any later
// capture or durability point (resolvePending re-proposes it).
keepPending()
return chunkCutResult{}, fmt.Errorf("storage: capture CAS outcome unresolved (%v): HEAD unchanged: %w", casErr, errChunkCASOutcomeUnknown)
}
if sameProposal(cur, next) {
l.finishCut(cur, h, changed, newKeys)
return chunkCutResult{H: h, Head: copyHead(cur), FullHash: all}, nil
return l.cutDone(chunkCutResult{H: h, Head: copyHead(cur), FullHash: all}, detach), nil
}
l.abortCut(all)
if l.supersededBy(cur) {
@@ -675,6 +709,44 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context) (chunkCutResult, err
return chunkCutResult{}, fmt.Errorf("storage: capture CAS not applied: %w", casErr)
}
func (l *chunkLayerImpl) Detach(ctx context.Context) (chunkCutResult, error) {
l.capMu.Lock()
defer l.capMu.Unlock()
if r, ok := l.storedDetach(); ok {
return r, nil
}
r, err := l.captureLocked(ctx, true)
if errors.Is(err, errChunkLayerDetached) {
if d, ok := l.storedDetach(); ok {
return d, nil // an earlier, unresolved detach CAS had applied
}
}
return r, err
}
func (l *chunkLayerImpl) storedDetach() (chunkCutResult, bool) {
l.stMu.Lock()
defer l.stMu.Unlock()
if d := l.detached; d != nil {
r := *d
r.Head = copyHead(d.Head)
return r, true
}
return chunkCutResult{}, false
}
// cutDone records a successful detach cut; the layer is detached from then on.
func (l *chunkLayerImpl) cutDone(r chunkCutResult, detach bool) chunkCutResult {
if detach {
l.stMu.Lock()
keep := r
keep.Head = copyHead(r.Head)
l.detached = &keep
l.stMu.Unlock()
}
return r
}
// supersededBy reports whether cur belongs to a newer or competing holder.
func (l *chunkLayerImpl) supersededBy(cur chunkHead) bool {
return cur.Epoch > l.cfg.Epoch || (cur.Epoch == l.cfg.Epoch && cur.Holder != l.cfg.Holder && cur.Gen != 0)
@@ -684,6 +756,10 @@ func sameProposal(cur, next chunkHead) bool {
if cur.Epoch != next.Epoch || cur.Holder != next.Holder || cur.RemoteLSN != next.RemoteLSN || len(cur.Chunks) != len(next.Chunks) {
return false
}
if chunkHeadIsDetached(cur) != chunkHeadIsDetached(next) || (cur.DetachedBy == nil) != (next.DetachedBy == nil) ||
(cur.DetachedBy != nil && *cur.DetachedBy != *next.DetachedBy) {
return false
}
for k, v := range next.Chunks {
if cur.Chunks[k] != v {
return false
@@ -695,26 +771,56 @@ func sameProposal(cur, next chunkHead) bool {
// resolvePending re-reads HEAD when an earlier CAS outcome is unresolved.
func (l *chunkLayerImpl) resolvePending(ctx context.Context) error {
l.stMu.Lock()
pending := l.pending
pending, base := l.pending, l.pendingBase
l.stMu.Unlock()
if pending == nil {
return nil
}
cur, err := l.remote.GetHead(ctx)
if err != nil {
return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved: %w", err)
return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved: %w: %w", errChunkCASOutcomeUnknown, err)
}
if !sameProposal(cur, *pending) && !l.supersededBy(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch {
// HEAD is still the unresolved CAS's base, so that CAS may still
// land. Settle it by issuing the same proposal at the same base:
// whichever lands first, HEAD ends at this proposal and the other
// fails its precondition. That is a new publication, so it passes
// the capture admission again first: the HEAD read above may have
// blocked across a demotion or a lineage change. A refusal keeps
// the CAS unresolved.
if err := l.admit(); err != nil {
return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved (%w); re-proposal refused: %w", errChunkCASOutcomeUnknown, err)
}
gen, casErr := l.remote.CASHead(ctx, base, copyHead(*pending))
if casErr == nil {
cur = copyHead(*pending)
cur.Gen = gen
} else if cur, err = l.remote.GetHead(ctx); err != nil {
return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved (%v): %w: %w", casErr, errChunkCASOutcomeUnknown, err)
} else if !sameProposal(cur, *pending) && !l.supersededBy(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch {
return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved (%v): HEAD unchanged: %w", casErr, errChunkCASOutcomeUnknown)
}
}
l.stMu.Lock()
defer l.stMu.Unlock()
l.pending = nil
wasDetach, cut := l.pendingDetach, l.pendingCut
l.pendingDetach, l.pendingCut, l.pendingBase = false, chunkCutResult{}, chunkHeadVersion{}
switch {
case sameProposal(cur, *pending):
l.head, l.remoteLSN = copyHead(cur), cur.RemoteLSN
if wasDetach {
cut.Head = copyHead(cur)
l.detached = &cut
return errChunkLayerDetached
}
case l.supersededBy(cur):
l.fenced = true
l.head = copyHead(cur)
return errChunkLayerFenced
default:
// HEAD moved past the unresolved CAS's base without it: that CAS
// can never land.
l.head = copyHead(cur)
}
return nil
@@ -0,0 +1,97 @@
package storage
import (
"errors"
"fmt"
"testing"
)
// A detach CAS the server retains after the caller saw an unknown outcome
// must never let a later cut succeed at the old generation, and must not be
// able to land after the layer has moved on (second review of #111, P2).
func TestChunkDetach_DeferredDetachSettledBeforeNextCut(t *testing.T) {
for _, rereadFails := range []bool{false, true} {
t.Run(fmt.Sprintf("rereadFails=%v", rereadFails), func(t *testing.T) { deferredDetachSchedule(t, rereadFails) })
}
}
func deferredDetachSchedule(t *testing.T, rereadFails bool) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
layer := mustAttach(t, s, f, ctConfig(1))
w := newWriteLog()
w.write(t, s, 2, 0x22)
if _, err := layer.Capture(ctTimeout(t)); err != nil {
t.Fatal(err)
}
base := f.stats().head
f.mu.Lock()
f.casModes = []fakeCASMode{casDeferred}
if rereadFails {
f.beforeCAS = func(f *fakeChunkRemote) { f.failGet = errFakeRemoteDown }
}
f.mu.Unlock()
if _, err := layer.Detach(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) {
t.Fatalf("Detach with a retained CAS: %v, want errChunkCASOutcomeUnknown", err)
}
healRemote(f)
// HEAD still reads as the old active generation; the retained CAS may
// still land. The next cut must settle it, not take the no-op path.
if r, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkLayerDetached) {
t.Fatalf("Cut after a retained detach CAS: %+v %v, want errChunkLayerDetached", r.Head, err)
}
if n := f.releaseDeferredCAS(); n != 0 {
t.Fatalf("the retained detach CAS still landed after settlement (%d applied)", n)
}
h := f.stats().head
if h.State != chunkHeadDetached || h.Gen != base.Gen+1 || h.DetachedBy == nil || h.DetachedBy.Gen != h.Gen {
t.Fatalf("HEAD after settlement %+v (base gen %d)", h, base.Gen)
}
r, err := layer.Detach(ctTimeout(t))
if err != nil || !sameHead(r.Head, h) || r.Head.State != chunkHeadDetached {
t.Fatalf("Detach after settlement: %+v %v", r.Head, err)
}
assertEveryHeadIsPrefixImage(t, f, w)
}
// A normal cut's retained CAS: released before settlement it applies and is
// adopted; released after settlement it cannot apply. HEAD stays a prefix
// image either way.
func TestChunkCut_DeferredCASSettled(t *testing.T) {
for _, releaseFirst := range []bool{true, false} {
t.Run(fmt.Sprintf("releaseFirst=%v", releaseFirst), func(t *testing.T) { deferredCutSchedule(t, releaseFirst) })
}
}
func deferredCutSchedule(t *testing.T, releaseFirst bool) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
layer := mustAttach(t, s, f, ctConfig(1))
w := newWriteLog()
w.write(t, s, 5, 0x55)
f.mu.Lock()
f.casModes = []fakeCASMode{casDeferred}
f.mu.Unlock()
if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) {
t.Fatalf("Cut with a retained CAS: %v, want errChunkCASOutcomeUnknown", err)
}
if releaseFirst {
if n := f.releaseDeferredCAS(); n != 1 {
t.Fatalf("the retained CAS did not apply when released first (%d)", n)
}
}
r, err := layer.Cut(ctTimeout(t))
if err != nil {
t.Fatalf("Cut after the retained CAS: %v", err)
}
if !releaseFirst {
if n := f.releaseDeferredCAS(); n != 0 {
t.Fatalf("the retained CAS landed after settlement (%d applied)", n)
}
}
h := f.stats().head
if h.RemoteLSN != s.NextLSN()-1 || !sameHead(r.Head, h) {
t.Fatalf("HEAD %+v, cut %+v", h, r.Head)
}
assertEveryHeadIsPrefixImage(t, f, w)
}
@@ -0,0 +1,87 @@
package storage
import (
"errors"
"testing"
)
// unresolvedDetach runs a Detach whose detach CAS has mode m while HEAD
// cannot be re-read, so its outcome stays unresolved.
func unresolvedDetach(t *testing.T, m fakeCASMode) (*fakeChunkRemote, chunkLayer) {
t.Helper()
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
layer := mustAttach(t, s, f, ctConfig(1))
newWriteLog().write(t, s, 2, 0x22)
f.mu.Lock()
f.casModes = []fakeCASMode{m}
f.beforeCAS = func(f *fakeChunkRemote) { f.failGet = errFakeRemoteDown }
f.mu.Unlock()
if _, err := layer.Detach(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) {
t.Fatalf("Detach with an unresolved CAS: %v, want errChunkCASOutcomeUnknown", err)
}
return f, layer
}
func healRemote(f *fakeChunkRemote) {
f.mu.Lock()
f.failGet = nil
f.mu.Unlock()
}
// An applied detach CAS whose outcome was unresolved must not let a later
// cut succeed; once HEAD is readable the layer is detached (review
// of #111, P2).
func TestChunkDetach_UnresolvedAppliedDetachIsSettled(t *testing.T) {
f, layer := unresolvedDetach(t, casAppliedLost)
if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) {
t.Fatalf("Cut while the detach is unresolved: %v, want errChunkCASOutcomeUnknown", err)
}
healRemote(f)
if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkLayerDetached) {
t.Fatalf("Cut after the applied detach settles: %v, want errChunkLayerDetached", err)
}
if _, err := layer.Capture(ctTimeout(t)); !errors.Is(err, errChunkLayerDetached) {
t.Fatalf("Capture: %v", err)
}
if err := layer.MakeRemoteDurable(ctTimeout(t), 1); !errors.Is(err, errChunkLayerDetached) {
t.Fatalf("MakeRemoteDurable: %v", err)
}
r, err := layer.Detach(ctTimeout(t))
if err != nil || r.Head.State != chunkHeadDetached || !sameHead(r.Head, f.stats().head) {
t.Fatalf("Detach after settlement: %+v %v, remote %+v", r.Head, err, f.stats().head)
}
}
// Detach itself settles an unresolved detach that had applied.
func TestChunkDetach_RepeatedDetachSettlesAppliedDetach(t *testing.T) {
f, layer := unresolvedDetach(t, casAppliedLost)
healRemote(f)
casBefore := f.stats().cas
r, err := layer.Detach(ctTimeout(t))
if err != nil || r.Head.State != chunkHeadDetached || !sameHead(r.Head, f.stats().head) || f.stats().cas != casBefore {
t.Fatalf("Detach settling an applied detach: %+v %v (CAS %d -> %d)", r.Head, err, casBefore, f.stats().cas)
}
}
// A detach CAS that did not apply leaves the layer as it was: Detach runs anew.
func TestChunkDetach_UnresolvedNotAppliedDetachRetries(t *testing.T) {
f, layer := unresolvedDetach(t, casUnknownNotApplied)
healRemote(f)
r, err := layer.Detach(ctTimeout(t))
if err != nil || r.Head.State != chunkHeadDetached || f.stats().head.State != chunkHeadDetached {
t.Fatalf("Detach after a detach that did not apply: %+v %v", r.Head, err)
}
}
// A takeover while the detach is unresolved fences the layer.
func TestChunkDetach_UnresolvedDetachThenTakeoverFences(t *testing.T) {
f, layer := unresolvedDetach(t, casUnknownNotApplied)
f.mu.Lock()
f.failGet = nil
f.takeOverLocked("host-b")
f.mu.Unlock()
if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkLayerFenced) {
t.Fatalf("Cut after a takeover: %v, want errChunkLayerFenced", err)
}
}
@@ -0,0 +1,136 @@
package storage
import (
"errors"
"testing"
)
// Detach publishes its final cut with State = detached and DetachedBy =
// {holder, epoch, the generation that CAS installs} in that one CAS (HEAD
// schema ruling, 2026-11-15). Afterwards the layer refuses every cut; a
// repeated Detach returns the first result.
func TestChunkDetach_OneCASPublishesDetachedFinalCut(t *testing.T) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
layer := mustAttach(t, s, f, ctConfig(1))
w := newWriteLog()
w.write(t, s, 3, 0x33)
w.write(t, s, 17, 0x17)
r, err := layer.Detach(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
heads := f.installedHeads()
if len(heads) != 1 {
t.Fatalf("installed %d HEADs, want the one detach cut", len(heads))
}
h := heads[0]
if h.State != chunkHeadDetached || h.DetachedBy == nil || *h.DetachedBy != (chunkDetachedBy{Holder: "host-a", Epoch: 1, Gen: h.Gen}) {
t.Fatalf("detach cut HEAD state %q detachedBy %+v, want detached by {host-a 1 %d}", h.State, h.DetachedBy, h.Gen)
}
if h.RemoteLSN != s.NextLSN()-1 || !sameHead(r.Head, h) || r.Head.State != chunkHeadDetached || r.H != h.RemoteLSN {
t.Fatalf("Detach returned %+v H %d, the remote holds %+v", r.Head, r.H, h)
}
assertEveryHeadIsPrefixImage(t, f, w)
casBefore := f.stats().cas
if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkLayerDetached) {
t.Fatalf("Cut after Detach: %v, want errChunkLayerDetached", err)
}
if _, err := layer.Capture(ctTimeout(t)); !errors.Is(err, errChunkLayerDetached) {
t.Fatalf("Capture after Detach: %v, want errChunkLayerDetached", err)
}
if err := layer.MakeRemoteDurable(ctTimeout(t), 1); !errors.Is(err, errChunkLayerDetached) {
t.Fatalf("MakeRemoteDurable after Detach: %v, want errChunkLayerDetached", err)
}
again, err := layer.Detach(ctTimeout(t))
if err != nil || !sameHead(again.Head, h) || again.H != r.H || again.Head.State != chunkHeadDetached {
t.Fatalf("repeated Detach: %+v %v, want the first result", again, err)
}
if n := f.stats().cas; n != casBefore {
t.Fatalf("a detached layer issued %d more CAS calls", n-casBefore)
}
}
// With nothing new since the last HEAD, Detach still publishes one CAS.
func TestChunkDetach_NothingNewStillPublishes(t *testing.T) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
layer := mustAttach(t, s, f, ctConfig(1))
newWriteLog().write(t, s, 2, 0x22)
if _, err := layer.Capture(ctTimeout(t)); err != nil {
t.Fatal(err)
}
before := f.stats().head
if before.State != chunkHeadActive || before.DetachedBy != nil {
t.Fatalf("a normal cut published state %q detachedBy %+v", before.State, before.DetachedBy)
}
if _, err := layer.Detach(ctTimeout(t)); err != nil {
t.Fatal(err)
}
after := f.stats().head
if after.State != chunkHeadDetached || after.Gen != before.Gen+1 || after.DetachedBy == nil || after.DetachedBy.Gen != after.Gen ||
!sameChunks(after, before) || after.RemoteLSN != before.RemoteLSN {
t.Fatalf("detach with nothing new: before %+v after %+v", before, after)
}
}
// A detach CAS whose response is lost is resolved by re-reading HEAD.
func TestChunkDetach_LostResponseResolvedByReread(t *testing.T) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
layer := mustAttach(t, s, f, ctConfig(1))
newWriteLog().write(t, s, 2, 0x22)
f.mu.Lock()
f.casModes = []fakeCASMode{casAppliedLost}
f.mu.Unlock()
r, err := layer.Detach(ctTimeout(t))
if err != nil {
t.Fatalf("detach whose CAS applied but lost its response: %v", err)
}
if h := f.stats().head; h.State != chunkHeadDetached || !sameHead(r.Head, h) {
t.Fatalf("Detach returned %+v, remote %+v", r.Head, h)
}
if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkLayerDetached) {
t.Fatalf("Cut after the resolved detach: %v", err)
}
}
// A new holder's normal cut publishes State = active and clears DetachedBy.
func TestChunkCut_NewHolderClearsDetachedState(t *testing.T) {
src := make([]byte, ctNumBlocks*ctBlockSize)
copy(src, makeBlock(ctBlockSize, 0x44))
f := newFakeChunkRemote()
f.seedHead(t, src, 10, 1)
f.mu.Lock()
h := copyChunkHead(f.head)
h.State = chunkHeadDetached
h.DetachedBy = &chunkDetachedBy{Holder: h.Holder, Epoch: h.Epoch, Gen: h.Gen + 1}
f.installLocked(h)
f.mu.Unlock()
s, _ := newChunkTestStore(t)
cfg := ctConfig(2)
cfg.FreshFromHead = true
layer := mustAttach(t, s, f, cfg)
r, err := layer.Cut(ctTimeout(t)) // nothing new locally: still a CAS, the base is detached
if err != nil {
t.Fatal(err)
}
if got := f.stats().head; r.Noop || got.State != chunkHeadActive || got.DetachedBy != nil || got.Holder != "host-a" {
t.Fatalf("the new holder's cut left state %q detachedBy %+v holder %q (noop %v)", got.State, got.DetachedBy, got.Holder, r.Noop)
}
}
func sameChunks(a, b chunkHead) bool {
if len(a.Chunks) != len(b.Chunks) {
return false
}
for k, v := range a.Chunks {
if b.Chunks[k] != v {
return false
}
}
return true
}
@@ -0,0 +1,95 @@
package storage
import (
"errors"
"fmt"
"sync/atomic"
"testing"
)
var errTestDemoted = errors.New("test: demoted during the HEAD read")
// Re-proposing a held CAS is a new publication: it passes the capture
// admission again right before it is sent, after the blocking HEAD read.
// A demotion or lineage change during that read sends no CAS and keeps the
// CAS unresolved; once authority is back, the same proposal settles at the
// same base (review of #111 on #114, P1).
func TestChunkCut_HeldCASReproposalRechecksAdmission(t *testing.T) {
for _, releaseWhileRefused := range []bool{false, true} {
t.Run(fmt.Sprintf("releaseWhileRefused=%v", releaseWhileRefused), func(t *testing.T) {
heldReproposalSchedule(t, releaseWhileRefused)
})
}
}
func heldReproposalSchedule(t *testing.T, releaseWhileRefused bool) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
var refuse atomic.Bool
cfg := ctConfig(1)
cfg.CaptureAllowed = func() error {
if refuse.Load() {
return errTestDemoted
}
return nil
}
layer := mustAttach(t, s, f, cfg)
w := newWriteLog()
w.write(t, s, 5, 0x55)
f.mu.Lock()
f.casModes = []fakeCASMode{casDeferred}
f.mu.Unlock()
if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) {
t.Fatalf("Cut with a retained CAS: %v, want errChunkCASOutcomeUnknown", err)
}
base := f.stats().head
f.mu.Lock()
held := copyChunkHead(f.deferred[0].next)
// The next cut passes its first admission; the projection is demoted
// while its HEAD read is in flight.
f.onGetHead = func(*fakeChunkRemote) { refuse.Store(true) }
f.mu.Unlock()
casBefore := f.stats().cas
_, err := layer.Cut(ctTimeout(t))
if !errors.Is(err, errChunkCaptureRefused) || !errors.Is(err, errTestDemoted) || !errors.Is(err, errChunkCASOutcomeUnknown) {
t.Fatalf("Cut demoted during its HEAD read: %v; want refused (demoted) with the CAS still unresolved", err)
}
if n := f.stats().cas - casBefore; n != 0 {
t.Fatalf("a layer demoted during its HEAD read sent %d new CAS calls", n)
}
if h := f.stats().head; !sameHead(h, base) {
t.Fatalf("HEAD moved under refused authority: %+v, base %+v", h, base)
}
f.mu.Lock()
f.onGetHead = nil
f.mu.Unlock()
if releaseWhileRefused {
if n := f.releaseDeferredCAS(); n != 1 {
t.Fatalf("the retained CAS did not apply when released (%d)", n)
}
}
if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkCaptureRefused) {
t.Fatalf("Cut while still demoted: %v; want refused", err)
}
if n := f.stats().cas - casBefore; n != 0 {
t.Fatalf("a demoted layer sent %d new CAS calls", n)
}
// Authority restored: the retained proposal settles at its base.
refuse.Store(false)
r, err := layer.Cut(ctTimeout(t))
if err != nil {
t.Fatalf("Cut after authority returned: %v", err)
}
if !releaseWhileRefused {
if n := f.releaseDeferredCAS(); n != 0 {
t.Fatalf("the retained CAS landed after settlement (%d applied)", n)
}
}
h := f.stats().head
if h.Gen != base.Gen+1 || !sameChunks(h, held) || h.RemoteLSN != s.NextLSN()-1 || !sameHead(r.Head, h) {
t.Fatalf("HEAD after recovery %+v (cut %+v); want the retained proposal at gen %d", h, r.Head, base.Gen+1)
}
assertEveryHeadIsPrefixImage(t, f, w)
}
+15 -6
View File
@@ -18,6 +18,13 @@ type (
ChunkCutResult = chunkCutResult
ChunkCutStats = chunkCutStats
ChunkIntent = chunkIntent
ChunkDetachedBy = chunkDetachedBy
)
// HEAD states.
const (
ChunkHeadActive = chunkHeadActive
ChunkHeadDetached = chunkHeadDetached
)
// NewChunkIntentID returns a fresh intent id "<gen>-<nonce>" for a remote
@@ -33,12 +40,14 @@ const (
)
var (
ErrChunkKeyExists = errChunkKeyExists
ErrChunkHeadPrecondition = errChunkHeadPrecondition
ErrChunkLayerFenced = errChunkLayerFenced
ErrChunkEvictRefused = errChunkEvictRefused
ErrChunkCaptureRefused = errChunkCaptureRefused
ErrChunkKeyInvalid = errChunkKeyInvalid
ErrChunkKeyExists = errChunkKeyExists
ErrChunkHeadPrecondition = errChunkHeadPrecondition
ErrChunkLayerFenced = errChunkLayerFenced
ErrChunkEvictRefused = errChunkEvictRefused
ErrChunkCaptureRefused = errChunkCaptureRefused
ErrChunkKeyInvalid = errChunkKeyInvalid
ErrChunkLayerDetached = errChunkLayerDetached
ErrChunkCASOutcomeUnknown = errChunkCASOutcomeUnknown
)
// ValidChunkKey enforces the chunk key domain (non-empty valid UTF-8); a
+40 -5
View File
@@ -166,14 +166,40 @@ type chunkHeadVersion struct {
// chunkHead is the published remote state. Chunks maps a chunk index to the
// chunk holding its bytes (block i of the chunk at offset i*BlockSize). A
// chunk index missing from the map is ZERO: every block in it reads as zeros.
//
// State is chunkHeadActive or chunkHeadDetached ("" reads as active: older
// HEADs carry no state). A holder's Detach publishes its final cut with
// State = detached and DetachedBy = {its holder, its epoch, the generation
// that CAS installs}, in that one CAS: the next holder and the block master
// can tell from HEAD alone that the holder stopped after that cut (a clean
// move). Every normal cut publishes State = active and no DetachedBy; a new
// holder's takeover does the same.
type chunkHead struct {
Gen uint64
Epoch uint64
Holder string
RemoteLSN uint64
Chunks map[uint64]chunkRef
Gen uint64
Epoch uint64
Holder string
RemoteLSN uint64
Chunks map[uint64]chunkRef
State string
DetachedBy *chunkDetachedBy
}
// HEAD states.
const (
chunkHeadActive = "active"
chunkHeadDetached = "detached"
)
// chunkDetachedBy names the holder whose final cut a detached HEAD is.
type chunkDetachedBy struct {
Holder string
Epoch uint64
Gen uint64
}
// chunkHeadIsDetached reports whether h is a detached HEAD.
func chunkHeadIsDetached(h chunkHead) bool { return h.State == chunkHeadDetached }
// chunkRemote is the remote store. Keys are non-empty valid UTF-8 strings
// (validChunkKey); Put and PutIntent refuse any other key before writing
// anything. Keys are immutable: Put of a key that
@@ -326,6 +352,13 @@ type chunkLayer interface {
Cut(ctx context.Context) (chunkCutResult, error)
// Capture is Cut, returning only H.
Capture(ctx context.Context) (uint64, error)
// Detach is the final cut of a clean stop: one cut whose CAS publishes
// State = detached and DetachedBy (always a CAS, even with nothing new).
// The caller stops new writes first. Afterwards Cut, Capture and
// MakeRemoteDurable fail with errChunkLayerDetached, and a repeated
// Detach returns the first result. An unresolved detach CAS is settled
// like any other unresolved CAS, before the next capture or Detach.
Detach(ctx context.Context) (chunkCutResult, error)
// MakeRemoteDurable is the durability point for snapshot, detach and
// migrate: a Capture whose H >= t. Only a nil return makes t remote
// durable; it requires the local Sync to cover t first, and fails
@@ -351,6 +384,8 @@ var (
errChunkEvictRefused = errors.New("storage: chunk eviction refused")
errChunkCaptureRefused = errors.New("storage: chunk capture refused")
errChunkKeyInvalid = errors.New("storage: chunk key is not non-empty valid UTF-8")
errChunkLayerDetached = errors.New("storage: chunk layer detached")
errChunkCASOutcomeUnknown = errors.New("storage: chunk HEAD CAS outcome unknown")
)
// attachChunkLayer attaches a chunk layer to an open store (chunk_layer.go).