From 1ec7b9975bfe445f54e759e471c4bc4181156696 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 03:37:17 -0800 Subject: [PATCH 1/7] chunkstore, storage: snapshot catalog, fork, detached HEAD and Detach MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Control-plane metadata and operations over the filer (B9 W2 spec §3-§5): - Catalog (core/frontend/chunkstore/catalog.go): - VOLUME entry //VOLUME: identity, geometry, origin and parent, write-once. EnsureVolume applies the attach rules (create a missing one; geometry_mismatch; fork_incomplete for a fork without HEAD). - CreateSnapshot stores the HEAD a cut installed as snaps/ (o_excl; the same request id replays, another is snapshot_exists), under an intent naming its keys until the entry is written, and refuses the write past OpDeadline. - ListSnapshots pages in name order (deleting ones hidden unless asked); DeleteSnapshot only marks deleting (conditional on state and gen); ListVolumes lists volume directories for GC. - Fork: VOLUME (origin fork, parent) then HEAD at gen 1, epoch 0, no holder, the snapshot's remote_lsn (LSNs carry forward), every ref owner-qualified as "@/" (an already qualified ref keeps its owner), under an intent on the target; replays by request id. - Typed errors with the spec's codes (CatalogError, CodeOf). - HEAD gains Detached (JSON "detached", omitted when false). The chunk layer's Detach takes a final cut, then CASes the same image once more with Detached set; afterwards cuts are refused (ErrChunkLayerDetached) and a repeated Detach returns the first result. A normal cut always publishes Detached = false. No entry carries filer chunks. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/catalog.go | 800 ++++++++++++++++++ .../core/frontend/chunkstore/catalog_test.go | 490 +++++++++++ .../core/frontend/chunkstore/chunk_remote.go | 46 +- .../core/frontend/chunkstore/fake_test.go | 6 + seaweed-block/core/storage/chunk_layer.go | 85 +- .../core/storage/chunk_layer_detach_test.go | 138 +++ seaweed-block/core/storage/chunk_public.go | 1 + seaweed-block/core/storage/chunk_seam.go | 13 + 8 files changed, 1564 insertions(+), 15 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/catalog.go create mode 100644 seaweed-block/core/frontend/chunkstore/catalog_test.go create mode 100644 seaweed-block/core/storage/chunk_layer_detach_test.go diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go new file mode 100644 index 0000000000..37a5643740 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -0,0 +1,800 @@ +package chunkstore + +// Catalog: the chunk control plane's filer metadata and Fork (B9 W2 spec +// §3-§5). Under the chunk base directory, per volume: +// +// //HEAD the published HEAD (ChunkRemote) +// //keys/ chunk key bindings (ChunkRemote) +// //intents/ live intents (ChunkRemote; GC roots) +// //VOLUME identity, geometry and lineage; write-once +// //snaps/ 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 deletes it after, +// and refuses the final write once OpDeadline has passed since it read its +// source (the GC contract of spec §2.3). + +import ( + "context" + "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" + 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" +) + +// 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"` +} + +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) + } + 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 +} + +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/. 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, + } + + id, err := putIntent(ctx, c.f, root, storage.ChunkIntent{Gen: head.Gen, Epoch: head.Epoch, Holder: head.Holder, Keys: headKeys(head)}) + if err != nil { + return SnapshotInfo{}, remoteErr(err, "intent for snapshot %s/%s", vol, req.Name) + } + defer func() { _ = c.f.DeleteEntry(context.WithoutCancel(ctx), path.Join(root, intentsDir), id, nil) }() + + if c.now().Sub(readAt) > c.deadline() { + 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()) + } + if err := c.f.CreateEntry(ctx, path.Join(root, snapsDir), e, true); err != nil { + if !errors.Is(err, ErrExists) { + return SnapshotInfo{}, remoteErr(err, "create snapshot %s/%s", vol, req.Name) + } + // Lost response of our own write, or a concurrent writer. + existing, prev, _, rerr := c.readSnap(ctx, vol, req.Name) + if rerr != nil { + return SnapshotInfo{}, rerr + } + if prev != req.RequestID { + return SnapshotInfo{}, catErr(CodeSnapshotExists, false, nil, "snapshot %s/%s exists (another request)", vol, req.Name) + } + existing.Replayed = true + return existing, nil + } + info, _, err := decodeSnap(path.Join(root, snapsDir, req.Name), e) + return info, err +} + +// 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/ 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: +// 1. read the snapshot (snapshot_not_found, snapshot_deleting); +// 2. exclusively create Target's VOLUME (origin fork, the snapshot's +// geometry, parent {Source, Snapshot, gen}); an existing one from the +// same request id is reused, another is target_exists; +// 3. qualify every chunk ref as "@/" (a ref already qualified +// keeps its owner), under an intent naming them in Target; +// 4. exclusively create Target's HEAD: gen 1, epoch 0, no holder, and the +// snapshot's remote_lsn (LSNs carry forward); a HEAD from the same +// request is a replay, another is target_exists. +// +// The final write is refused once OpDeadline has passed since step 1. +func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) { + readAt := c.now() + srcRoot, err := c.volRoot(req.Source) + if 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) + } + _ = srcRoot + 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 + } + 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) + } + + 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}} + ve, err := volumeEntry(vol, req.RequestID) + if err != nil { + return ForkResult{}, err + } + if err := c.f.CreateEntry(ctx, dstRoot, ve, true); err != nil { + if !errors.Is(err, ErrExists) { + return ForkResult{}, remoteErr(err, "create VOLUME of %s", req.Target) + } + got, lerr := c.f.LookupEntry(ctx, dstRoot, volumeName) + if lerr != nil { + return ForkResult{}, remoteErr(lerr, "re-read VOLUME of %s", req.Target) + } + if string(got.Extended[extReq]) != req.RequestID { + return ForkResult{}, catErr(CodeTargetExists, false, nil, "volume %s exists (another request)", req.Target) + } + } + + src := snap.Head() + head := storage.ChunkHead{Gen: 1, Epoch: 0, Holder: "", RemoteLSN: src.RemoteLSN, Chunks: make(map[uint64]storage.ChunkRef, len(src.Chunks))} + qualified := 0 + for idx, ref := range src.Chunks { + if !strings.HasPrefix(ref.Key, "@") { + ref.Key = "@" + req.Source + "/" + ref.Key + qualified++ + } + head.Chunks[idx] = ref + } + result := ForkResult{Target: req.Target, Source: req.Source, Snapshot: req.Snapshot, SourceGen: snap.HeadGen, + HeadGen: 1, HeadEpoch: 0, RemoteLSN: head.RemoteLSN, ChunkCount: len(head.Chunks), QualifiedRefs: qualified} + + 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: "fork:" + req.RequestID, Keys: headKeys(head)}) + if err != nil { + return ForkResult{}, remoteErr(err, "intent for fork %s", req.Target) + } + defer func() { _ = c.f.DeleteEntry(context.WithoutCancel(ctx), path.Join(dstRoot, intentsDir), id, nil) }() + + if c.now().Sub(readAt) > c.deadline() { + 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()) + } + if err := c.f.CreateEntry(ctx, dstRoot, he, true); err != nil { + if !errors.Is(err, ErrExists) { + return ForkResult{}, remoteErr(err, "create HEAD of %s", req.Target) + } + // HEAD exists: ours (lost response or retry) if VOLUME is ours. + got, lerr := c.f.LookupEntry(ctx, dstRoot, volumeName) + if lerr != nil { + return ForkResult{}, remoteErr(lerr, "re-read VOLUME of %s", req.Target) + } + if string(got.Extended[extReq]) != req.RequestID { + return ForkResult{}, catErr(CodeTargetExists, false, nil, "volume %s has a HEAD (another request)", req.Target) + } + result.Replayed = true + } + return result, nil +} diff --git a/seaweed-block/core/frontend/chunkstore/catalog_test.go b/seaweed-block/core/frontend/chunkstore/catalog_test.go new file mode 100644 index 0000000000..aade43ee3a --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/catalog_test.go @@ -0,0 +1,490 @@ +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. + vol := VolumeInfo{Format: volumeFormat, VolumeID: "v5", Geometry: catGeo, Origin: OriginFork, Parent: &Parent{VolumeID: "v1", Snapshot: "s1", Gen: h.Gen}} + 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)) + } +} + +func TestHeadDoc_DetachedRoundTrip(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{}}) + if err != nil { + t.Fatal(err) + } + e, _ := f.LookupEntry(ctx, catBase+"/v1", "HEAD") + if strings.Contains(string(e.Content), "detached") { + t.Fatalf("a normal HEAD document mentions detached: %s", e.Content) + } + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: gen, Epoch: 1}, storage.ChunkHead{Epoch: 1, Holder: "h", RemoteLSN: 5, Chunks: map[uint64]storage.ChunkRef{}, Detached: true}); err != nil { + t.Fatal(err) + } + h, err := r.GetHead(ctx) + if err != nil || !h.Detached || h.Gen != gen+1 { + t.Fatalf("detached HEAD read back as %+v %v", h, err) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote.go b/seaweed-block/core/frontend/chunkstore/chunk_remote.go index 732b35d586..7e9e45a827 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote.go @@ -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 /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,9 @@ type headDoc struct { Holder string `json:"holder"` RemoteLSN uint64 `json:"remote_lsn"` Chunks map[uint64]refDoc `json:"chunks"` + // Detached: published by Detach, the holder's clean stop (omitted when + // false, so earlier documents read unchanged). + Detached bool `json:"detached,omitempty"` } type refDoc struct { @@ -383,7 +392,7 @@ 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)), Detached: h.Detached} for idx, ref := range h.Chunks { if ref.Key == "" { return nil, fmt.Errorf("chunkstore: HEAD chunk %d has no key", idx) @@ -424,8 +433,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 +464,8 @@ 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) - } 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)), Detached: doc.Detached} for idx, ref := range doc.Chunks { sum, err := hex.DecodeString(ref.SHA256) if err != nil || len(sum) != 32 || ref.Key == "" { diff --git a/seaweed-block/core/frontend/chunkstore/fake_test.go b/seaweed-block/core/frontend/chunkstore/fake_test.go index ec6cc785f7..8b8386441e 100644 --- a/seaweed-block/core/frontend/chunkstore/fake_test.go +++ b/seaweed-block/core/frontend/chunkstore/fake_test.go @@ -32,6 +32,9 @@ 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) } func newFakeFiler() *fakeFiler { return &fakeFiler{entries: map[string]*filerpb.Entry{}} } @@ -53,6 +56,9 @@ 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) + } c := proto.Clone(e).(*filerpb.Entry) f.entries[p] = c f.written = append(f.written, proto.Clone(e).(*filerpb.Entry)) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 211e609993..ec1b210189 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -63,6 +63,7 @@ type chunkLayerImpl struct { head chunkHead pending *chunkHead // a proposal whose CAS outcome is unresolved fenced bool + detached *chunkCutResult // set by a successful Detach remoteLSN uint64 hdr chunkBitmapHeader // last header written or loaded dirty map[uint64]bool // chunks dirtied since the cut in progress or the last HEAD @@ -460,13 +461,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) } @@ -496,11 +499,14 @@ 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) } @@ -603,6 +609,7 @@ 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.Detached = false // a normal cut is never a clean-stop mark var changed []uint64 newKeys := map[uint64]string{} for _, c := range captured { @@ -624,7 +631,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 len(changed) == 0 && h == baseHead.RemoteLSN && baseHead.Gen != 0 && !baseHead.Detached { l.finishCut(baseHead, h, nil, nil) // nothing new: no CAS return chunkCutResult{H: h, Head: copyHead(baseHead), Noop: true, FullHash: all}, nil } @@ -675,6 +682,78 @@ 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() + l.stMu.Lock() + if d := l.detached; d != nil { + r := *d + r.Head = copyHead(d.Head) + l.stMu.Unlock() + return r, nil + } + l.stMu.Unlock() + + r, err := l.captureLocked(ctx) // the final cut + if err != nil { + return chunkCutResult{}, err + } + done, err := l.register() + if err != nil { + return chunkCutResult{}, err + } + defer done() + ctx, cancel := l.opCtx(ctx) + defer cancel() + + base := r.Head + next := copyHead(base) + next.Detached = true + gen, casErr := l.remote.CASHead(ctx, chunkHeadVersion{Gen: base.Gen, Epoch: base.Epoch}, next) + if casErr == nil { + next.Gen = gen + } else { + // Precondition or unknown outcome: resolve by re-reading HEAD. + cur, gerr := l.remote.GetHead(ctx) + if gerr != nil { + return chunkCutResult{}, fmt.Errorf("storage: detach mark CAS outcome unresolved (%v): %w", casErr, gerr) + } + if !(sameProposal(cur, next) && cur.Detached) { + l.stMu.Lock() + if l.supersededBy(cur) { + l.fenced = true + } + l.head = copyHead(cur) + l.stMu.Unlock() + if l.supersededBy(cur) { + return chunkCutResult{}, errors.Join(errChunkLayerFenced, casErr) + } + return chunkCutResult{}, fmt.Errorf("storage: detach mark CAS not applied: %w", casErr) + } + next = cur + } + + // The bitmap header follows HEAD's generation; a failed write only leaves + // a stale header, which a restart treats as a mismatch (hash compare). + l.bmMu.Lock() + hdr := chunkBitmapHeader{BaseLSN: r.H, HeadGen: next.Gen, Epoch: next.Epoch, Base: chunkBaseNone} + if err := l.cfg.Bitmap.WriteHeader(hdr); err == nil { + l.stMu.Lock() + l.hdr = hdr + l.stMu.Unlock() + } + l.bmMu.Unlock() + + res := chunkCutResult{H: r.H, Head: copyHead(next), FullHash: r.FullHash, Stats: r.Stats} + l.stMu.Lock() + l.head = copyHead(next) + stored := res + stored.Head = copyHead(next) + l.detached = &stored + l.stMu.Unlock() + return res, nil +} + // 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) diff --git a/seaweed-block/core/storage/chunk_layer_detach_test.go b/seaweed-block/core/storage/chunk_layer_detach_test.go new file mode 100644 index 0000000000..9fe1e297dd --- /dev/null +++ b/seaweed-block/core/storage/chunk_layer_detach_test.go @@ -0,0 +1,138 @@ +package storage + +import ( + "errors" + "testing" +) + +// Detach publishes a final cut, then the same image once more with Detached +// set, so the next holder and the block master can tell from HEAD alone +// that this holder stopped after its last cut. Afterwards the layer refuses +// every cut; a repeated Detach returns the first result. +func TestChunkDetach_FinalCutThenDetachedHead(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) != 2 { + t.Fatalf("installed %d HEADs, want the final cut and the detached mark", len(heads)) + } + cut, mark := heads[0], heads[1] + if cut.Detached || !mark.Detached || mark.Gen != cut.Gen+1 { + t.Fatalf("final cut gen %d detached=%v, mark gen %d detached=%v", cut.Gen, cut.Detached, mark.Gen, mark.Detached) + } + if mark.RemoteLSN != cut.RemoteLSN || mark.RemoteLSN != s.NextLSN()-1 || mark.Holder != cut.Holder || mark.Epoch != cut.Epoch || !sameChunks(mark, cut) { + t.Fatalf("the detached mark changed the image: %+v vs %+v", mark, cut) + } + if !r.Head.Detached || !sameHead(r.Head, mark) || r.H != cut.RemoteLSN { + t.Fatalf("Detach returned %+v H %d, the remote holds %+v", r.Head, r.H, mark) + } + 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, mark) || again.H != r.H { + 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 marks HEAD detached. +func TestChunkDetach_NothingNewStillMarks(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 + r, err := layer.Detach(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + after := f.stats().head + if !after.Detached || after.Gen != before.Gen+1 || !sameChunks(after, before) || after.RemoteLSN != before.RemoteLSN || !r.Head.Detached { + t.Fatalf("detach with nothing new: before %+v after %+v", before, after) + } +} + +// A detached-mark 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) + if _, err := layer.Capture(ctTimeout(t)); err != nil { + t.Fatal(err) + } + f.mu.Lock() + f.casModes = []fakeCASMode{casAppliedLost} + f.mu.Unlock() + r, err := layer.Detach(ctTimeout(t)) + if err != nil { + t.Fatalf("detach whose mark CAS applied but lost its response: %v", err) + } + if h := f.stats().head; !h.Detached || !sameHead(r.Head, h) { + t.Fatalf("Detach returned %+v, remote %+v", r.Head, h) + } +} + +// A normal cut by a new holder clears a predecessor's Detached mark. +func TestChunkCut_ClearsDetachedMark(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.Detached = true + f.installLocked(h) + f.mu.Unlock() + + s, _ := newChunkTestStore(t) + cfg := ctConfig(2) + cfg.FreshFromHead = true + layer := mustAttach(t, s, f, cfg) + if _, err := s.Write(6, makeBlock(ctBlockSize, 0x66)); err != nil { + t.Fatal(err) + } + r, err := layer.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if r.Head.Detached || f.stats().head.Detached { + t.Fatalf("the new holder's cut kept the predecessor's Detached mark: %+v", f.stats().head) + } +} + +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 +} diff --git a/seaweed-block/core/storage/chunk_public.go b/seaweed-block/core/storage/chunk_public.go index 7cc9361454..a4310e4270 100644 --- a/seaweed-block/core/storage/chunk_public.go +++ b/seaweed-block/core/storage/chunk_public.go @@ -39,6 +39,7 @@ var ( ErrChunkEvictRefused = errChunkEvictRefused ErrChunkCaptureRefused = errChunkCaptureRefused ErrChunkKeyInvalid = errChunkKeyInvalid + ErrChunkLayerDetached = errChunkLayerDetached ) // ValidChunkKey enforces the chunk key domain (non-empty valid UTF-8); a diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 8d16a3d81a..063f2cea79 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -166,12 +166,18 @@ 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. +// +// Detached marks a HEAD its holder published with Detach: the same image as +// that holder's final cut, one generation later. It tells the next holder +// and the block master that the holder stopped after its last cut (a clean +// move). Every normal cut publishes Detached = false. type chunkHead struct { Gen uint64 Epoch uint64 Holder string RemoteLSN uint64 Chunks map[uint64]chunkRef + Detached bool } // chunkRemote is the remote store. Keys are non-empty valid UTF-8 strings @@ -326,6 +332,12 @@ 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: a Cut, then one more CAS of + // the same image with Detached set. It returns the detached HEAD (H is + // the final cut's LSN). The caller stops new writes first. Afterwards + // Cut, Capture and MakeRemoteDurable fail with errChunkLayerDetached; + // a repeated Detach returns the first result. + 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 +363,7 @@ 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") ) // attachChunkLayer attaches a chunk layer to an open store (chunk_layer.go). From 681becfff0b83d0481885b79439e0c8a5809bc20 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 03:56:54 -0800 Subject: [PATCH 2/7] chunkstore, storage: settle intents and fork replays; settle a pending detach Review fixes for the snapshot catalog, fork and Detach: - Intents stay until the operation's outcome is settled. An exclusive create that fails is resolved by re-reading the entry: our entry confirms the publish; another entry means our create can never land (clean abort); a failed re-read or no entry leaves the outcome unknown (it may still land), so the intents are kept and the call reports outcome_unknown. A retry with the same request id settles it and removes every intent of the operation (by its holder tag). - Fork records its operation in the target's VOLUME (request id, source, snapshot, source gen, the SHA-256 of the snapshot's HEAD document and the original result). A retry resolves the target first: a completed fork replays the recorded result without reading the source (also after the source snapshot is deleting, or the target advanced); a request id reused with other parameters is target_exists; an incomplete fork resumes only if the snapshot still has the bound image. - An unresolved Detach mark (CAS outcome and re-read both failed) becomes a pending detach that every later capture, durability point and Detach settles first: applied means detached, not applied continues, a newer holder fences, still unreadable is ErrChunkCASOutcomeUnknown. A cut can no longer succeed at the pre-mark generation. Unresolved capture CAS outcomes now also wrap ErrChunkCASOutcomeUnknown. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/catalog.go | 290 +++++++++++++----- .../chunkstore/catalog_settle_test.go | 231 ++++++++++++++ .../core/frontend/chunkstore/catalog_test.go | 8 +- .../core/frontend/chunkstore/fake_test.go | 17 + seaweed-block/core/storage/chunk_layer.go | 120 ++++++-- .../storage/chunk_layer_detach_settle_test.go | 80 +++++ seaweed-block/core/storage/chunk_public.go | 15 +- seaweed-block/core/storage/chunk_seam.go | 1 + 8 files changed, 653 insertions(+), 109 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/catalog_settle_test.go create mode 100644 seaweed-block/core/storage/chunk_layer_detach_settle_test.go diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index 37a5643740..9eaa34e8d8 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -14,12 +14,19 @@ package chunkstore // 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 deletes it after, -// and refuses the final write once OpDeadline has passed since it read its -// source (the GC contract of spec §2.3). +// 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" @@ -84,6 +91,7 @@ const ( CodeForkIncomplete = "fork_incomplete" CodeDeadlineExceeded = "deadline_exceeded" CodeRemoteUnavailable = "remote_unavailable" + CodeOutcomeUnknown = "outcome_unknown" ) // CatalogError is a typed control-plane failure. @@ -143,6 +151,21 @@ type VolumeInfo struct { 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 { @@ -339,6 +362,9 @@ func decodeVolume(p string, e *filerpb.Entry) (VolumeInfo, error) { 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 } @@ -471,6 +497,68 @@ func decodeSnap(p string, e *filerpb.Entry) (SnapshotInfo, string, error) { }, doc.RequestID, nil } +// settleIntents removes every intent under root that operation tag wrote: +// those of this attempt and of earlier ones whose outcome it has now +// settled. A failure leaves intents behind, which only over-protects. +func (c *Catalog) settleIntents(ctx context.Context, root, tag string) { + ctx = context.WithoutCancel(ctx) + dir := path.Join(root, intentsDir) + after := "" + for { + page, err := c.f.ListEntries(ctx, dir, "", after, listPage) + if err != nil { + return + } + for _, e := range page { + after = e.GetName() + if string(e.Extended[extHolder]) == tag { + _ = c.f.DeleteEntry(ctx, dir, e.GetName(), nil) + } + } + if len(page) < listPage { + return + } + } +} + +type createOutcome int + +const ( + createdNow createOutcome = iota // this call's create applied (confirmed) + existsOurs // the entry exists and is this operation's + existsOther // another entry holds the name: our create can never land + createUnknown // the create's outcome is not known +) + +// createResolved makes an exclusive create and resolves its outcome against +// the operation's identity (ours) by re-reading the entry on any failure. +// Only a re-read that finds the entry settles an ambiguous failure; a +// failed re-read, or not finding it, leaves the outcome unknown (the create +// may still land later). +func (c *Catalog) createResolved(ctx context.Context, dir string, e *filerpb.Entry, ours func(*filerpb.Entry) bool) (createOutcome, error) { + err := c.f.CreateEntry(ctx, dir, e, true) + if err == nil { + return createdNow, nil + } + got, lerr := c.f.LookupEntry(ctx, dir, e.GetName()) + if lerr != nil { + return createUnknown, err + } + if ours(got) { + return existsOurs, nil + } + return existsOther, nil +} + +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 { @@ -514,6 +602,7 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe } if existing, prev, _, err := c.readSnap(ctx, vol, req.Name); err == nil { if prev == req.RequestID { + c.settleIntents(ctx, root, "snapshot:"+vol+"/"+req.Name+"/"+req.RequestID) existing.Replayed = true return existing, nil } @@ -555,32 +644,33 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe Content: body, } - id, err := putIntent(ctx, c.f, root, storage.ChunkIntent{Gen: head.Gen, Epoch: head.Epoch, Holder: head.Holder, Keys: headKeys(head)}) + 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) } - defer func() { _ = c.f.DeleteEntry(context.WithoutCancel(ctx), path.Join(root, intentsDir), id, nil) }() - if c.now().Sub(readAt) > c.deadline() { + // Clean abort: the snapshot entry was never sent. + _ = c.f.DeleteEntry(context.WithoutCancel(ctx), path.Join(root, intentsDir), id, nil) 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()) } - if err := c.f.CreateEntry(ctx, path.Join(root, snapsDir), e, true); err != nil { - if !errors.Is(err, ErrExists) { - return SnapshotInfo{}, remoteErr(err, "create snapshot %s/%s", vol, req.Name) - } - // Lost response of our own write, or a concurrent writer. - existing, prev, _, rerr := c.readSnap(ctx, vol, req.Name) - if rerr != nil { - return SnapshotInfo{}, rerr - } - if prev != req.RequestID { - return SnapshotInfo{}, catErr(CodeSnapshotExists, false, nil, "snapshot %s/%s exists (another request)", vol, req.Name) - } - existing.Replayed = true - return existing, nil + dir := path.Join(root, snapsDir) + ours := func(got *filerpb.Entry) bool { return string(got.Extended[extReq]) == req.RequestID } + outcome, cerr := c.createResolved(ctx, dir, e, ours) + switch outcome { + case createUnknown: + 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) + case existsOther: + c.settleIntents(ctx, root, tag) // our exclusive create can never land + return SnapshotInfo{}, catErr(CodeSnapshotExists, false, nil, "snapshot %s/%s exists (another request)", vol, req.Name) } - info, _, err := decodeSnap(path.Join(root, snapsDir, req.Name), e) - return info, err + c.settleIntents(ctx, root, tag) // confirmed published + info, _, _, err := c.readSnap(ctx, vol, req.Name) + if err != nil { + return SnapshotInfo{}, err + } + info.Replayed = outcome == existsOurs && errors.Is(cerr, ErrExists) + return info, nil } // ListSnapshots lists vol's snapshots in name order, after opts.StartAfter. @@ -689,22 +779,30 @@ func (c *Catalog) ListVolumes(ctx context.Context) ([]string, error) { // ---- 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: -// 1. read the snapshot (snapshot_not_found, snapshot_deleting); -// 2. exclusively create Target's VOLUME (origin fork, the snapshot's -// geometry, parent {Source, Snapshot, gen}); an existing one from the -// same request id is reused, another is target_exists; -// 3. qualify every chunk ref as "@/" (a ref already qualified -// keeps its owner), under an intent naming them in Target; -// 4. exclusively create Target's HEAD: gen 1, epoch 0, no holder, and the -// snapshot's remote_lsn (LSNs carry forward); a HEAD from the same -// request is a replay, another is target_exists. +// req.Source/req.Snapshot, in O(1) filer writes and no data copy. // -// The final write is refused once OpDeadline has passed since step 1. +// 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 "@/" (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 and keeps the intent; +// a retry with the same request id settles it. func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) { - readAt := c.now() - srcRoot, err := c.volRoot(req.Source) - if err != nil { + if _, err := c.volRoot(req.Source); err != nil { return ForkResult{}, err } dstRoot, err := c.volRoot(req.Target) @@ -714,7 +812,6 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) if req.Source == req.Target { return ForkResult{}, catErr(CodeTargetExists, false, nil, "fork target %s is the source", req.Target) } - _ = srcRoot if err := CheckSnapshotName(req.Snapshot); err != nil { return ForkResult{}, err } @@ -724,6 +821,28 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) 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 { + c.settleIntents(ctx, dstRoot, tag) + return forkResult(existing, true), nil + } + } + + readAt := c.now() snap, _, _, err := c.readSnap(ctx, req.Source, req.Snapshot) if err != nil { return ForkResult{}, err @@ -734,27 +853,11 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) if snap.geo == (Geometry{}) { return ForkResult{}, fmt.Errorf("chunkstore: snapshot %s/%s has no geometry", req.Source, req.Snapshot) } - - 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}} - ve, err := volumeEntry(vol, req.RequestID) + src := snap.Head() + digest, err := headDigest(src) if err != nil { return ForkResult{}, err } - if err := c.f.CreateEntry(ctx, dstRoot, ve, true); err != nil { - if !errors.Is(err, ErrExists) { - return ForkResult{}, remoteErr(err, "create VOLUME of %s", req.Target) - } - got, lerr := c.f.LookupEntry(ctx, dstRoot, volumeName) - if lerr != nil { - return ForkResult{}, remoteErr(lerr, "re-read VOLUME of %s", req.Target) - } - if string(got.Extended[extReq]) != req.RequestID { - return ForkResult{}, catErr(CodeTargetExists, false, nil, "volume %s exists (another request)", req.Target) - } - } - - src := snap.Head() head := storage.ChunkHead{Gen: 1, Epoch: 0, Holder: "", RemoteLSN: src.RemoteLSN, Chunks: make(map[uint64]storage.ChunkRef, len(src.Chunks))} qualified := 0 for idx, ref := range src.Chunks { @@ -764,37 +867,74 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) } head.Chunks[idx] = ref } - result := ForkResult{Target: req.Target, Source: req.Source, Snapshot: req.Snapshot, SourceGen: snap.HeadGen, - HeadGen: 1, HeadEpoch: 0, RemoteLSN: head.RemoteLSN, ChunkCount: len(head.Chunks), QualifiedRefs: qualified} + 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 + } + outcome, cerr := c.createResolved(ctx, dstRoot, ve, func(got *filerpb.Entry) bool { + v, err := decodeVolume(path.Join(dstRoot, volumeName), got) + return err == nil && c.checkForkRecord(v, req) == nil && v.Fork.HeadSHA256 == digest + }) + switch outcome { + case createUnknown: + return ForkResult{}, catErr(CodeOutcomeUnknown, true, cerr, "fork %s: VOLUME create outcome unknown; retry with the same request id", req.Target) + case existsOther: + 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: "fork:" + req.RequestID, Keys: headKeys(head)}) + 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) } - defer func() { _ = c.f.DeleteEntry(context.WithoutCancel(ctx), path.Join(dstRoot, intentsDir), id, nil) }() - if c.now().Sub(readAt) > c.deadline() { + // Clean abort: HEAD was never sent. + _ = c.f.DeleteEntry(context.WithoutCancel(ctx), path.Join(dstRoot, intentsDir), id, nil) 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()) } - if err := c.f.CreateEntry(ctx, dstRoot, he, true); err != nil { - if !errors.Is(err, ErrExists) { - return ForkResult{}, remoteErr(err, "create HEAD of %s", req.Target) - } - // HEAD exists: ours (lost response or retry) if VOLUME is ours. - got, lerr := c.f.LookupEntry(ctx, dstRoot, volumeName) - if lerr != nil { - return ForkResult{}, remoteErr(lerr, "re-read VOLUME of %s", req.Target) - } - if string(got.Extended[extReq]) != req.RequestID { - return ForkResult{}, catErr(CodeTargetExists, false, nil, "volume %s has a HEAD (another request)", req.Target) - } - result.Replayed = true + // Under this request's VOLUME only this fork ever writes HEAD (attach + // refuses a fork without HEAD), so any HEAD found there is ours. + outcome, cerr := c.createResolved(ctx, dstRoot, he, func(*filerpb.Entry) bool { return true }) + if outcome == createUnknown { + 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 result, nil + c.settleIntents(ctx, dstRoot, tag) + return forkResult(existing, outcome == existsOurs && errors.Is(cerr, ErrExists)), nil +} + +// 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} } diff --git a/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go b/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go new file mode 100644 index 0000000000..b5030f6c79 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go @@ -0,0 +1,231 @@ +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; a retry with the same request id settles it and removes +// every intent of the operation (review of #111, P1). +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 in := intentsOf(t, f, "v1"); len(in) != 0 { + t.Fatalf("a settled snapshot left %d intents", len(in)) + } +} + +// 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 in := intentsOf(t, f, "v2"); len(in) != 0 { + t.Fatalf("a settled fork left %d intents", len(in)) + } + + // 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) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/catalog_test.go b/seaweed-block/core/frontend/chunkstore/catalog_test.go index aade43ee3a..14765c6496 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_test.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_test.go @@ -333,7 +333,13 @@ func TestFork_RefusalsAndDeadline(t *testing.T) { t.Fatalf("retry after the late attempt: %+v %v", res, err) } // A fork whose VOLUME is written but HEAD is not refuses to attach. - vol := VolumeInfo{Format: volumeFormat, VolumeID: "v5", Geometry: catGeo, Origin: OriginFork, Parent: &Parent{VolumeID: "v1", Snapshot: "s1", Gen: h.Gen}} + 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) diff --git a/seaweed-block/core/frontend/chunkstore/fake_test.go b/seaweed-block/core/frontend/chunkstore/fake_test.go index 8b8386441e..86b563c492 100644 --- a/seaweed-block/core/frontend/chunkstore/fake_test.go +++ b/seaweed-block/core/frontend/chunkstore/fake_test.go @@ -35,6 +35,13 @@ type fakeFiler struct { // 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 } func newFakeFiler() *fakeFiler { return &fakeFiler{entries: map[string]*filerpb.Entry{}} } @@ -59,9 +66,19 @@ func (f *fakeFiler) CreateEntry(_ context.Context, dir string, e *filerpb.Entry, if f.beforeCreate != nil { f.beforeCreate(p) } + if f.failCreate != nil { + if err := f.failCreate(p); err != nil { + return err + } + } 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 } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index ec1b210189..abaf994d3f 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -58,20 +58,25 @@ 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 - detached *chunkCutResult // set by a successful Detach - 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 is a Detach mark whose CAS outcome is unresolved (the + // re-read failed too); pendingDetachCut is that Detach's final cut. + // Every later capture, durability point or Detach settles it first. + pendingDetach *chunkHead + pendingDetachCut chunkCutResult + 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 @@ -542,6 +547,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context) (chunkCutResult, err ctx, cancel := l.opCtx(ctx) defer cancel() + if err := l.settlePendingDetach(ctx); err != nil { + return chunkCutResult{}, err + } if err := l.resolvePending(ctx); err != nil { return chunkCutResult{}, err } @@ -662,7 +670,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context) (chunkCutResult, err l.pending = &p l.stMu.Unlock() l.abortCut(all) - return chunkCutResult{}, fmt.Errorf("storage: capture CAS outcome unresolved (%v): %w", casErr, gerr) + return chunkCutResult{}, fmt.Errorf("storage: capture CAS outcome unresolved (%v): %w: %w", casErr, errChunkCASOutcomeUnknown, gerr) } if sameProposal(cur, next) { l.finishCut(cur, h, changed, newKeys) @@ -685,14 +693,34 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context) (chunkCutResult, err func (l *chunkLayerImpl) Detach(ctx context.Context) (chunkCutResult, error) { l.capMu.Lock() defer l.capMu.Unlock() - l.stMu.Lock() - if d := l.detached; d != nil { - r := *d - r.Head = copyHead(d.Head) - l.stMu.Unlock() + stored := func() (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 + } + if r, ok := stored(); ok { return r, nil } - l.stMu.Unlock() + if err := func() error { + done, err := l.register() + if err != nil { + return err + } + defer done() + sctx, cancel := l.opCtx(ctx) + defer cancel() + return l.settlePendingDetach(sctx) + }(); err != nil { + if r, ok := stored(); ok && errors.Is(err, errChunkLayerDetached) { + return r, nil // the earlier mark had applied + } + return chunkCutResult{}, err + } r, err := l.captureLocked(ctx) // the final cut if err != nil { @@ -716,7 +744,11 @@ func (l *chunkLayerImpl) Detach(ctx context.Context) (chunkCutResult, error) { // Precondition or unknown outcome: resolve by re-reading HEAD. cur, gerr := l.remote.GetHead(ctx) if gerr != nil { - return chunkCutResult{}, fmt.Errorf("storage: detach mark CAS outcome unresolved (%v): %w", casErr, gerr) + l.stMu.Lock() + p := copyHead(next) + l.pendingDetach, l.pendingDetachCut = &p, r + l.stMu.Unlock() + return chunkCutResult{}, fmt.Errorf("storage: detach mark CAS outcome unresolved (%v): %w: %w", casErr, errChunkCASOutcomeUnknown, gerr) } if !(sameProposal(cur, next) && cur.Detached) { l.stMu.Lock() @@ -747,13 +779,49 @@ func (l *chunkLayerImpl) Detach(ctx context.Context) (chunkCutResult, error) { res := chunkCutResult{H: r.H, Head: copyHead(next), FullHash: r.FullHash, Stats: r.Stats} l.stMu.Lock() l.head = copyHead(next) - stored := res - stored.Head = copyHead(next) - l.detached = &stored + keep := res + keep.Head = copyHead(next) + l.detached = &keep l.stMu.Unlock() return res, nil } +// settlePendingDetach resolves an unresolved Detach mark by re-reading HEAD. +// It returns errChunkLayerDetached when the mark had applied (the layer is +// detached from then on), errChunkLayerFenced when a newer holder took +// over, an outcome-unknown error when HEAD still cannot be read, and nil +// when the mark did not apply (the layer continues as before). +func (l *chunkLayerImpl) settlePendingDetach(ctx context.Context) error { + l.stMu.Lock() + p, cut := l.pendingDetach, l.pendingDetachCut + l.stMu.Unlock() + if p == nil { + return nil + } + cur, err := l.remote.GetHead(ctx) + if err != nil { + return fmt.Errorf("storage: an earlier detach mark is still unresolved: %w: %w", errChunkCASOutcomeUnknown, err) + } + l.stMu.Lock() + defer l.stMu.Unlock() + l.pendingDetach = nil + switch { + case sameProposal(cur, *p) && cur.Detached: + res := cut + res.Head = copyHead(cur) + l.head = copyHead(cur) + l.detached = &res + return errChunkLayerDetached + case l.supersededBy(cur): + l.fenced = true + l.head = copyHead(cur) + return errChunkLayerFenced + default: + l.head = copyHead(cur) // the mark did not apply + return nil + } +} + // 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) @@ -781,7 +849,7 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) error { } 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) } l.stMu.Lock() defer l.stMu.Unlock() diff --git a/seaweed-block/core/storage/chunk_layer_detach_settle_test.go b/seaweed-block/core/storage/chunk_layer_detach_settle_test.go new file mode 100644 index 0000000000..153da704b1 --- /dev/null +++ b/seaweed-block/core/storage/chunk_layer_detach_settle_test.go @@ -0,0 +1,80 @@ +package storage + +import ( + "errors" + "testing" +) + +// unresolvedMark runs a Detach whose final cut succeeds and whose mark CAS +// has mode m while HEAD cannot be re-read, so the mark stays unresolved. +func unresolvedMark(t *testing.T, m fakeCASMode) (*WALStore, *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{casNormal, m} + f.afterCAS = nil + f.mu.Unlock() + // Fail HEAD re-reads only after the final cut's CAS. + f.mu.Lock() + f.beforeCAS = func(f *fakeChunkRemote) { + 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 mark: %v, want errChunkCASOutcomeUnknown", err) + } + return s, f, layer +} + +// An applied mark whose outcome was unresolved must not let a later cut +// succeed at the pre-mark generation; once HEAD is readable the layer is +// detached (review of #111, P2). +func TestChunkDetach_UnresolvedAppliedMarkIsSettled(t *testing.T) { + _, f, layer := unresolvedMark(t, casAppliedLost) + if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) { + t.Fatalf("Cut while the mark is unresolved: %v, want errChunkCASOutcomeUnknown", err) + } + f.mu.Lock() + f.failGet = nil + f.mu.Unlock() + if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkLayerDetached) { + t.Fatalf("Cut after the applied mark 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.Detached || !sameHead(r.Head, f.stats().head) { + t.Fatalf("Detach after settlement: %+v %v, remote %+v", r.Head, err, f.stats().head) + } +} + +// A mark that did not apply leaves the layer as it was: Detach marks anew. +func TestChunkDetach_UnresolvedNotAppliedMarkRetries(t *testing.T) { + _, f, layer := unresolvedMark(t, casUnknownNotApplied) + f.mu.Lock() + f.failGet = nil + f.mu.Unlock() + r, err := layer.Detach(ctTimeout(t)) + if err != nil || !r.Head.Detached || !f.stats().head.Detached { + t.Fatalf("Detach after a mark that did not apply: %+v %v", r.Head, err) + } +} + +// A takeover while the mark is unresolved fences the layer. +func TestChunkDetach_UnresolvedMarkThenTakeoverFences(t *testing.T) { + _, f, layer := unresolvedMark(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) + } +} diff --git a/seaweed-block/core/storage/chunk_public.go b/seaweed-block/core/storage/chunk_public.go index a4310e4270..e358983fba 100644 --- a/seaweed-block/core/storage/chunk_public.go +++ b/seaweed-block/core/storage/chunk_public.go @@ -33,13 +33,14 @@ const ( ) var ( - ErrChunkKeyExists = errChunkKeyExists - ErrChunkHeadPrecondition = errChunkHeadPrecondition - ErrChunkLayerFenced = errChunkLayerFenced - ErrChunkEvictRefused = errChunkEvictRefused - ErrChunkCaptureRefused = errChunkCaptureRefused - ErrChunkKeyInvalid = errChunkKeyInvalid - ErrChunkLayerDetached = errChunkLayerDetached + 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 diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 063f2cea79..236cd40ae4 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -364,6 +364,7 @@ var ( 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). From d0e3107c570fbb94678742b9074a32cb30339e43 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 04:03:51 -0800 Subject: [PATCH 3/7] storage, chunkstore: HEAD state/detachedBy per the schema ruling; one-CAS Detach Follows the HEAD schema ruling (2026-11-15), replacing the boolean detached flag of the previous revision: - HEAD carries a canonical "state": "active" | "detached" (a document without it reads as active), and "detachedBy": {holder, epoch, gen} only when detached; a reader refuses a detachedBy that is not the HEAD's own holder, epoch and generation. - Detach is one detach cut: its CAS publishes the final cut with state detached and detachedBy = {holder, epoch, the generation that CAS installs}. It always CASes, also with nothing new. Afterwards cuts are refused (ErrChunkLayerDetached); a repeated Detach returns the result. - Every normal cut publishes state active and no detachedBy, so a new holder's cut over a detached HEAD clears it. - An unresolved detach CAS is settled like any unresolved CAS, before the next capture or Detach: applied means detached, not applied continues, a newer holder fences, unreadable is ErrChunkCASOutcomeUnknown. This replaces the separate pending-mark state. - A fork's HEAD is published with state active. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/catalog.go | 2 +- .../core/frontend/chunkstore/catalog_test.go | 96 +++++++- .../core/frontend/chunkstore/chunk_remote.go | 37 +++- seaweed-block/core/storage/chunk_layer.go | 205 ++++++------------ .../storage/chunk_layer_detach_settle_test.go | 75 ++++--- .../core/storage/chunk_layer_detach_test.go | 70 +++--- seaweed-block/core/storage/chunk_public.go | 7 + seaweed-block/core/storage/chunk_seam.go | 51 +++-- 8 files changed, 305 insertions(+), 238 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index 9eaa34e8d8..6886570398 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -858,7 +858,7 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) 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))} + 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, "@") { diff --git a/seaweed-block/core/frontend/chunkstore/catalog_test.go b/seaweed-block/core/frontend/chunkstore/catalog_test.go index 14765c6496..ed1b2fcfb8 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_test.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_test.go @@ -474,23 +474,107 @@ func TestCatalog_SnapshotIntentAroundEntry(t *testing.T) { } } -func TestHeadDoc_DetachedRoundTrip(t *testing.T) { +// 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{}}) + 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), "detached") { - t.Fatalf("a normal HEAD document mentions detached: %s", e.Content) + if !strings.Contains(string(e.Content), `"state":"active"`) || strings.Contains(string(e.Content), "detachedBy") { + t.Fatalf("an active HEAD document: %s", e.Content) } - if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: gen, Epoch: 1}, storage.ChunkHead{Epoch: 1, Holder: "h", RemoteLSN: 5, Chunks: map[uint64]storage.ChunkRef{}, Detached: true}); err != nil { + 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.Detached || h.Gen != gen+1 { + 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)) + } } diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote.go b/seaweed-block/core/frontend/chunkstore/chunk_remote.go index 7e9e45a827..fb5a0ee388 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote.go @@ -333,9 +333,17 @@ type headDoc struct { Holder string `json:"holder"` RemoteLSN uint64 `json:"remote_lsn"` Chunks map[uint64]refDoc `json:"chunks"` - // Detached: published by Detach, the holder's clean stop (omitted when - // false, so earlier documents read unchanged). - Detached bool `json:"detached,omitempty"` + // 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 { @@ -392,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)), Detached: h.Detached} + 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) @@ -464,8 +475,24 @@ func decodeHeadDoc(p string, content []byte) (storage.ChunkHead, error) { if doc.Gen == 0 { return fail("generation 0") } + 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)), Detached: doc.Detached} + 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 == "" { diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index abaf994d3f..a548a5776a 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -64,19 +64,19 @@ type chunkLayerImpl struct { pending *chunkHead // a proposal whose CAS outcome is unresolved fenced bool detached *chunkCutResult // set by a successful Detach - // pendingDetach is a Detach mark whose CAS outcome is unresolved (the - // re-read failed too); pendingDetachCut is that Detach's final cut. - // Every later capture, durability point or Detach settles it first. - pendingDetach *chunkHead - pendingDetachCut chunkCutResult - 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 + // 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 + 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 @@ -182,6 +182,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 @@ -489,7 +493,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) { @@ -515,7 +519,7 @@ func (l *chunkLayerImpl) MakeRemoteDurable(ctx context.Context, t uint64) error 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 } @@ -532,7 +536,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 @@ -547,9 +551,6 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context) (chunkCutResult, err ctx, cancel := l.opCtx(ctx) defer cancel() - if err := l.settlePendingDetach(ctx); err != nil { - return chunkCutResult{}, err - } if err := l.resolvePending(ctx); err != nil { return chunkCutResult{}, err } @@ -617,7 +618,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.Detached = false // a normal cut is never a clean-stop mark + 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 { @@ -639,7 +644,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 && !baseHead.Detached { + 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 } @@ -659,7 +664,7 @@ 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. @@ -668,13 +673,14 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context) (chunkCutResult, err l.stMu.Lock() p := copyHead(next) l.pending = &p + l.pendingDetach, l.pendingCut = detach, chunkCutResult{H: h, FullHash: all} l.stMu.Unlock() l.abortCut(all) return chunkCutResult{}, fmt.Errorf("storage: capture CAS outcome unresolved (%v): %w: %w", casErr, errChunkCASOutcomeUnknown, gerr) } 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) { @@ -693,133 +699,39 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context) (chunkCutResult, err func (l *chunkLayerImpl) Detach(ctx context.Context) (chunkCutResult, error) { l.capMu.Lock() defer l.capMu.Unlock() - stored := func() (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 - } - if r, ok := stored(); ok { + if r, ok := l.storedDetach(); ok { return r, nil } - if err := func() error { - done, err := l.register() - if err != nil { - return err + 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 } - defer done() - sctx, cancel := l.opCtx(ctx) - defer cancel() - return l.settlePendingDetach(sctx) - }(); err != nil { - if r, ok := stored(); ok && errors.Is(err, errChunkLayerDetached) { - return r, nil // the earlier mark had applied - } - return chunkCutResult{}, err } - - r, err := l.captureLocked(ctx) // the final cut - if err != nil { - return chunkCutResult{}, err - } - done, err := l.register() - if err != nil { - return chunkCutResult{}, err - } - defer done() - ctx, cancel := l.opCtx(ctx) - defer cancel() - - base := r.Head - next := copyHead(base) - next.Detached = true - gen, casErr := l.remote.CASHead(ctx, chunkHeadVersion{Gen: base.Gen, Epoch: base.Epoch}, next) - if casErr == nil { - next.Gen = gen - } else { - // Precondition or unknown outcome: resolve by re-reading HEAD. - cur, gerr := l.remote.GetHead(ctx) - if gerr != nil { - l.stMu.Lock() - p := copyHead(next) - l.pendingDetach, l.pendingDetachCut = &p, r - l.stMu.Unlock() - return chunkCutResult{}, fmt.Errorf("storage: detach mark CAS outcome unresolved (%v): %w: %w", casErr, errChunkCASOutcomeUnknown, gerr) - } - if !(sameProposal(cur, next) && cur.Detached) { - l.stMu.Lock() - if l.supersededBy(cur) { - l.fenced = true - } - l.head = copyHead(cur) - l.stMu.Unlock() - if l.supersededBy(cur) { - return chunkCutResult{}, errors.Join(errChunkLayerFenced, casErr) - } - return chunkCutResult{}, fmt.Errorf("storage: detach mark CAS not applied: %w", casErr) - } - next = cur - } - - // The bitmap header follows HEAD's generation; a failed write only leaves - // a stale header, which a restart treats as a mismatch (hash compare). - l.bmMu.Lock() - hdr := chunkBitmapHeader{BaseLSN: r.H, HeadGen: next.Gen, Epoch: next.Epoch, Base: chunkBaseNone} - if err := l.cfg.Bitmap.WriteHeader(hdr); err == nil { - l.stMu.Lock() - l.hdr = hdr - l.stMu.Unlock() - } - l.bmMu.Unlock() - - res := chunkCutResult{H: r.H, Head: copyHead(next), FullHash: r.FullHash, Stats: r.Stats} - l.stMu.Lock() - l.head = copyHead(next) - keep := res - keep.Head = copyHead(next) - l.detached = &keep - l.stMu.Unlock() - return res, nil + return r, err } -// settlePendingDetach resolves an unresolved Detach mark by re-reading HEAD. -// It returns errChunkLayerDetached when the mark had applied (the layer is -// detached from then on), errChunkLayerFenced when a newer holder took -// over, an outcome-unknown error when HEAD still cannot be read, and nil -// when the mark did not apply (the layer continues as before). -func (l *chunkLayerImpl) settlePendingDetach(ctx context.Context) error { - l.stMu.Lock() - p, cut := l.pendingDetach, l.pendingDetachCut - l.stMu.Unlock() - if p == nil { - return nil - } - cur, err := l.remote.GetHead(ctx) - if err != nil { - return fmt.Errorf("storage: an earlier detach mark is still unresolved: %w: %w", errChunkCASOutcomeUnknown, err) - } +func (l *chunkLayerImpl) storedDetach() (chunkCutResult, bool) { l.stMu.Lock() defer l.stMu.Unlock() - l.pendingDetach = nil - switch { - case sameProposal(cur, *p) && cur.Detached: - res := cut - res.Head = copyHead(cur) - l.head = copyHead(cur) - l.detached = &res - return errChunkLayerDetached - case l.supersededBy(cur): - l.fenced = true - l.head = copyHead(cur) - return errChunkLayerFenced - default: - l.head = copyHead(cur) // the mark did not apply - return nil + 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. @@ -831,6 +743,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 @@ -854,9 +770,16 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) error { l.stMu.Lock() defer l.stMu.Unlock() l.pending = nil + wasDetach, cut := l.pendingDetach, l.pendingCut + l.pendingDetach, l.pendingCut = false, chunkCutResult{} 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) diff --git a/seaweed-block/core/storage/chunk_layer_detach_settle_test.go b/seaweed-block/core/storage/chunk_layer_detach_settle_test.go index 153da704b1..f798a78587 100644 --- a/seaweed-block/core/storage/chunk_layer_detach_settle_test.go +++ b/seaweed-block/core/storage/chunk_layer_detach_settle_test.go @@ -5,43 +5,41 @@ import ( "testing" ) -// unresolvedMark runs a Detach whose final cut succeeds and whose mark CAS -// has mode m while HEAD cannot be re-read, so the mark stays unresolved. -func unresolvedMark(t *testing.T, m fakeCASMode) (*WALStore, *fakeChunkRemote, chunkLayer) { +// 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{casNormal, m} - f.afterCAS = nil - f.mu.Unlock() - // Fail HEAD re-reads only after the final cut's CAS. - f.mu.Lock() - f.beforeCAS = func(f *fakeChunkRemote) { - f.beforeCAS = func(f *fakeChunkRemote) { f.failGet = errFakeRemoteDown } - } + 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 mark: %v, want errChunkCASOutcomeUnknown", err) + t.Fatalf("Detach with an unresolved CAS: %v, want errChunkCASOutcomeUnknown", err) } - return s, f, layer + return f, layer } -// An applied mark whose outcome was unresolved must not let a later cut -// succeed at the pre-mark generation; once HEAD is readable the layer is -// detached (review of #111, P2). -func TestChunkDetach_UnresolvedAppliedMarkIsSettled(t *testing.T) { - _, f, layer := unresolvedMark(t, casAppliedLost) - if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) { - t.Fatalf("Cut while the mark is unresolved: %v, want errChunkCASOutcomeUnknown", err) - } +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 mark settles: %v, want errChunkLayerDetached", err) + 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) @@ -50,26 +48,35 @@ func TestChunkDetach_UnresolvedAppliedMarkIsSettled(t *testing.T) { t.Fatalf("MakeRemoteDurable: %v", err) } r, err := layer.Detach(ctTimeout(t)) - if err != nil || !r.Head.Detached || !sameHead(r.Head, f.stats().head) { + 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) } } -// A mark that did not apply leaves the layer as it was: Detach marks anew. -func TestChunkDetach_UnresolvedNotAppliedMarkRetries(t *testing.T) { - _, f, layer := unresolvedMark(t, casUnknownNotApplied) - f.mu.Lock() - f.failGet = nil - f.mu.Unlock() +// 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.Detached || !f.stats().head.Detached { - t.Fatalf("Detach after a mark that did not apply: %+v %v", r.Head, err) + 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 takeover while the mark is unresolved fences the layer. -func TestChunkDetach_UnresolvedMarkThenTakeoverFences(t *testing.T) { - _, f, layer := unresolvedMark(t, casUnknownNotApplied) +// 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") diff --git a/seaweed-block/core/storage/chunk_layer_detach_test.go b/seaweed-block/core/storage/chunk_layer_detach_test.go index 9fe1e297dd..fe8d54629b 100644 --- a/seaweed-block/core/storage/chunk_layer_detach_test.go +++ b/seaweed-block/core/storage/chunk_layer_detach_test.go @@ -5,11 +5,11 @@ import ( "testing" ) -// Detach publishes a final cut, then the same image once more with Detached -// set, so the next holder and the block master can tell from HEAD alone -// that this holder stopped after its last cut. Afterwards the layer refuses -// every cut; a repeated Detach returns the first result. -func TestChunkDetach_FinalCutThenDetachedHead(t *testing.T) { +// 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)) @@ -22,18 +22,15 @@ func TestChunkDetach_FinalCutThenDetachedHead(t *testing.T) { t.Fatal(err) } heads := f.installedHeads() - if len(heads) != 2 { - t.Fatalf("installed %d HEADs, want the final cut and the detached mark", len(heads)) + if len(heads) != 1 { + t.Fatalf("installed %d HEADs, want the one detach cut", len(heads)) } - cut, mark := heads[0], heads[1] - if cut.Detached || !mark.Detached || mark.Gen != cut.Gen+1 { - t.Fatalf("final cut gen %d detached=%v, mark gen %d detached=%v", cut.Gen, cut.Detached, mark.Gen, mark.Detached) + 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 mark.RemoteLSN != cut.RemoteLSN || mark.RemoteLSN != s.NextLSN()-1 || mark.Holder != cut.Holder || mark.Epoch != cut.Epoch || !sameChunks(mark, cut) { - t.Fatalf("the detached mark changed the image: %+v vs %+v", mark, cut) - } - if !r.Head.Detached || !sameHead(r.Head, mark) || r.H != cut.RemoteLSN { - t.Fatalf("Detach returned %+v H %d, the remote holds %+v", r.Head, r.H, mark) + 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) @@ -48,7 +45,7 @@ func TestChunkDetach_FinalCutThenDetachedHead(t *testing.T) { t.Fatalf("MakeRemoteDurable after Detach: %v, want errChunkLayerDetached", err) } again, err := layer.Detach(ctTimeout(t)) - if err != nil || !sameHead(again.Head, mark) || again.H != r.H { + 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 { @@ -56,8 +53,8 @@ func TestChunkDetach_FinalCutThenDetachedHead(t *testing.T) { } } -// With nothing new since the last HEAD, Detach still marks HEAD detached. -func TestChunkDetach_NothingNewStillMarks(t *testing.T) { +// 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)) @@ -66,46 +63,50 @@ func TestChunkDetach_NothingNewStillMarks(t *testing.T) { t.Fatal(err) } before := f.stats().head - r, err := layer.Detach(ctTimeout(t)) - if err != nil { + 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.Detached || after.Gen != before.Gen+1 || !sameChunks(after, before) || after.RemoteLSN != before.RemoteLSN || !r.Head.Detached { + 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 detached-mark CAS whose response is lost is resolved by re-reading HEAD. +// 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) - if _, err := layer.Capture(ctTimeout(t)); err != nil { - t.Fatal(err) - } f.mu.Lock() f.casModes = []fakeCASMode{casAppliedLost} f.mu.Unlock() r, err := layer.Detach(ctTimeout(t)) if err != nil { - t.Fatalf("detach whose mark CAS applied but lost its response: %v", err) + t.Fatalf("detach whose CAS applied but lost its response: %v", err) } - if h := f.stats().head; !h.Detached || !sameHead(r.Head, h) { + 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 normal cut by a new holder clears a predecessor's Detached mark. -func TestChunkCut_ClearsDetachedMark(t *testing.T) { +// 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.Detached = true + h.State = chunkHeadDetached + h.DetachedBy = &chunkDetachedBy{Holder: h.Holder, Epoch: h.Epoch, Gen: h.Gen + 1} f.installLocked(h) f.mu.Unlock() @@ -113,15 +114,12 @@ func TestChunkCut_ClearsDetachedMark(t *testing.T) { cfg := ctConfig(2) cfg.FreshFromHead = true layer := mustAttach(t, s, f, cfg) - if _, err := s.Write(6, makeBlock(ctBlockSize, 0x66)); err != nil { - t.Fatal(err) - } - r, err := layer.Cut(ctTimeout(t)) + r, err := layer.Cut(ctTimeout(t)) // nothing new locally: still a CAS, the base is detached if err != nil { t.Fatal(err) } - if r.Head.Detached || f.stats().head.Detached { - t.Fatalf("the new holder's cut kept the predecessor's Detached mark: %+v", f.stats().head) + 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) } } diff --git a/seaweed-block/core/storage/chunk_public.go b/seaweed-block/core/storage/chunk_public.go index e358983fba..e77580522d 100644 --- a/seaweed-block/core/storage/chunk_public.go +++ b/seaweed-block/core/storage/chunk_public.go @@ -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 "-" for a remote diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 236cd40ae4..bc18444ff1 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -167,19 +167,39 @@ type chunkHeadVersion struct { // 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. // -// Detached marks a HEAD its holder published with Detach: the same image as -// that holder's final cut, one generation later. It tells the next holder -// and the block master that the holder stopped after its last cut (a clean -// move). Every normal cut publishes Detached = false. +// 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 - Detached bool + 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 @@ -332,11 +352,12 @@ 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: a Cut, then one more CAS of - // the same image with Detached set. It returns the detached HEAD (H is - // the final cut's LSN). The caller stops new writes first. Afterwards - // Cut, Capture and MakeRemoteDurable fail with errChunkLayerDetached; - // a repeated Detach returns the first result. + // 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 From fe9df65af839d5fed8a6f89d5ffd2d2f5b0d9766 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 04:17:31 -0800 Subject: [PATCH 4/7] storage: settle a held cut CAS by re-proposing it at the same base A cut or detach CAS whose outcome is unknown while HEAD still reads its base generation may still be applied by the server later. Reading HEAD alone no longer settles it: the capture keeps the proposal pending, and the next cut, durability point or Detach re-issues the same proposal at the same base. Whichever lands first, HEAD ends at that proposal and the other fails its precondition, so a delayed detach can never land after a no-op cut. The fake remote gains a held CAS mode (casDeferred) and releaseDeferredCAS, which applies held CAS calls later only if HEAD is still at their base. Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_fake_remote_test.go | 30 ++++++ seaweed-block/core/storage/chunk_layer.go | 40 +++++++- .../core/storage/chunk_layer_deferred_test.go | 97 +++++++++++++++++++ 3 files changed, 162 insertions(+), 5 deletions(-) create mode 100644 seaweed-block/core/storage/chunk_layer_deferred_test.go diff --git a/seaweed-block/core/storage/chunk_fake_remote_test.go b/seaweed-block/core/storage/chunk_fake_remote_test.go index 1b75746537..98c4f0a58d 100644 --- a/seaweed-block/core/storage/chunk_fake_remote_test.go +++ b/seaweed-block/core/storage/chunk_fake_remote_test.go @@ -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. @@ -72,6 +96,7 @@ type fakeChunkRemote struct { beforeCAS func(f *fakeChunkRemote) // runs once, under mu, before the next CAS is decided afterCAS func(f *fakeChunkRemote) // runs once, under mu, after the next CAS is decided intents map[string]chunkIntent + deferred []deferredCAS } func newFakeChunkRemote() *fakeChunkRemote { @@ -243,6 +268,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 diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index a548a5776a..6953b04678 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -69,6 +69,9 @@ type chunkLayerImpl struct { // 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 @@ -668,16 +671,26 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (chunkC } // 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 = detach, chunkCutResult{H: h, FullHash: all} + l.pendingDetach, l.pendingCut, l.pendingBase = detach, chunkCutResult{H: h, FullHash: all}, expected l.stMu.Unlock() l.abortCut(all) + } + 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 l.cutDone(chunkCutResult{H: h, Head: copyHead(cur), FullHash: all}, detach), nil @@ -758,7 +771,7 @@ 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 @@ -767,11 +780,26 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) error { if err != nil { 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. + 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 = false, chunkCutResult{} + l.pendingDetach, l.pendingCut, l.pendingBase = false, chunkCutResult{}, chunkHeadVersion{} switch { case sameProposal(cur, *pending): l.head, l.remoteLSN = copyHead(cur), cur.RemoteLSN @@ -785,6 +813,8 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) error { 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 diff --git a/seaweed-block/core/storage/chunk_layer_deferred_test.go b/seaweed-block/core/storage/chunk_layer_deferred_test.go new file mode 100644 index 0000000000..d95334711e --- /dev/null +++ b/seaweed-block/core/storage/chunk_layer_deferred_test.go @@ -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) +} From 24cbab0f274e8aafb9febc88760e0d81e3cb9cc6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 04:17:32 -0800 Subject: [PATCH 5/7] chunkstore: each attempt deletes only its own intent Snapshot and fork attempts stamp the entry they create with their intent id (swb.attempt). An attempt deletes its own intent only when its own create is confirmed (applied, or found by the re-read with its attempt id) or refused by the filer's "already exists" answer, or when it never sent the create (deadline). Any other failure leaves the create unsettled and the intent in place, even when the re-read finds another attempt's entry: the held create may land after that entry is removed. No attempt, and no replay, deletes another attempt's intent (W5 rule); tag-wide settleIntents is removed. The fake filer gains held creates (deferCreate) and releaseDeferredCreates, which applies them later only if the name is still free. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/catalog.go | 140 ++++----- .../chunkstore/catalog_held_create_test.go | 266 ++++++++++++++++++ .../chunkstore/catalog_settle_test.go | 14 +- .../core/frontend/chunkstore/fake_test.go | 35 +++ 4 files changed, 383 insertions(+), 72 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/catalog_held_create_test.go diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index 6886570398..50e2498a81 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -47,6 +47,7 @@ const ( 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" @@ -497,57 +498,49 @@ func decodeSnap(p string, e *filerpb.Entry) (SnapshotInfo, string, error) { }, doc.RequestID, nil } -// settleIntents removes every intent under root that operation tag wrote: -// those of this attempt and of earlier ones whose outcome it has now -// settled. A failure leaves intents behind, which only over-protects. -func (c *Catalog) settleIntents(ctx context.Context, root, tag string) { - ctx = context.WithoutCancel(ctx) - dir := path.Join(root, intentsDir) - after := "" - for { - page, err := c.f.ListEntries(ctx, dir, "", after, listPage) - if err != nil { - return - } - for _, e := range page { - after = e.GetName() - if string(e.Extended[extHolder]) == tag { - _ = c.f.DeleteEntry(ctx, dir, e.GetName(), nil) - } - } - if len(page) < listPage { - return - } - } +// 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 call's create applied (confirmed) - existsOurs // the entry exists and is this operation's - existsOther // another entry holds the name: our create can never land - createUnknown // the create's outcome is not known + 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 an exclusive create and resolves its outcome against -// the operation's identity (ours) by re-reading the entry on any failure. -// Only a re-read that finds the entry settles an ambiguous failure; a -// failed re-read, or not finding it, leaves the outcome unknown (the create -// may still land later). -func (c *Catalog) createResolved(ctx context.Context, dir string, e *filerpb.Entry, ours func(*filerpb.Entry) bool) (createOutcome, error) { +// 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, nil + return createdNow, e, nil } got, lerr := c.f.LookupEntry(ctx, dir, e.GetName()) if lerr != nil { - return createUnknown, err + got = nil } - if ours(got) { - return existsOurs, nil + if got != nil && attempt != "" && string(got.Extended[extAttempt]) == attempt { + return createdNow, got, nil } - return existsOther, nil + if errors.Is(err, ErrExists) { + return createRefused, got, err + } + return createUnsettled, got, err } func headDigest(h storage.ChunkHead) (string, error) { @@ -602,7 +595,6 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe } if existing, prev, _, err := c.readSnap(ctx, vol, req.Name); err == nil { if prev == req.RequestID { - c.settleIntents(ctx, root, "snapshot:"+vol+"/"+req.Name+"/"+req.RequestID) existing.Replayed = true return existing, nil } @@ -651,25 +643,34 @@ func (c *Catalog) CreateSnapshot(ctx context.Context, vol string, req SnapshotRe } if c.now().Sub(readAt) > c.deadline() { // Clean abort: the snapshot entry was never sent. - _ = c.f.DeleteEntry(context.WithoutCancel(ctx), path.Join(root, intentsDir), id, nil) + 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) - ours := func(got *filerpb.Entry) bool { return string(got.Extended[extReq]) == req.RequestID } - outcome, cerr := c.createResolved(ctx, dir, e, ours) - switch outcome { - case createUnknown: + 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) - case existsOther: - c.settleIntents(ctx, root, tag) // our exclusive create can never land + } + 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) } - c.settleIntents(ctx, root, tag) // confirmed published - info, _, _, err := c.readSnap(ctx, vol, req.Name) + info, _, err := decodeSnap(path.Join(dir, req.Name), got) if err != nil { return SnapshotInfo{}, err } - info.Replayed = outcome == existsOurs && errors.Is(cerr, ErrExists) + info.Replayed = true // another attempt of this request wrote it return info, nil } @@ -799,8 +800,10 @@ func (c *Catalog) ListVolumes(ctx context.Context) ([]string, error) { // 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 and keeps the intent; -// a retry with the same request id settles it. +// 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 @@ -837,7 +840,6 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) return ForkResult{}, remoteErr(err, "read HEAD of %s", req.Target) } if has { - c.settleIntents(ctx, dstRoot, tag) return forkResult(existing, true), nil } } @@ -884,15 +886,17 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) if err != nil { return ForkResult{}, err } - outcome, cerr := c.createResolved(ctx, dstRoot, ve, func(got *filerpb.Entry) bool { + // 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) - return err == nil && c.checkForkRecord(v, req) == nil && v.Fork.HeadSHA256 == digest - }) - switch outcome { - case createUnknown: - return ForkResult{}, catErr(CodeOutcomeUnknown, true, cerr, "fork %s: VOLUME create outcome unknown; retry with the same request id", req.Target) - case existsOther: - return ForkResult{}, catErr(CodeTargetExists, false, nil, "volume %s exists (another request, or another image)", req.Target) + 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 } @@ -908,17 +912,21 @@ func (c *Catalog) Fork(ctx context.Context, req ForkRequest) (ForkResult, error) } if c.now().Sub(readAt) > c.deadline() { // Clean abort: HEAD was never sent. - _ = c.f.DeleteEntry(context.WithoutCancel(ctx), path.Join(dstRoot, intentsDir), id, nil) + 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 fork ever writes HEAD (attach - // refuses a fork without HEAD), so any HEAD found there is ours. - outcome, cerr := c.createResolved(ctx, dstRoot, he, func(*filerpb.Entry) bool { return true }) - if outcome == createUnknown { + // 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) } - c.settleIntents(ctx, dstRoot, tag) - return forkResult(existing, outcome == existsOurs && errors.Is(cerr, ErrExists)), nil + return forkResult(existing, outcome != createdNow), nil // refused: the filer says HEAD exists } // checkForkRecord refuses a target VOLUME that is not this fork request's. diff --git a/seaweed-block/core/frontend/chunkstore/catalog_held_create_test.go b/seaweed-block/core/frontend/chunkstore/catalog_held_create_test.go new file mode 100644 index 0000000000..275863f173 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/catalog_held_create_test.go @@ -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)) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go b/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go index b5030f6c79..82e4702d54 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go @@ -45,8 +45,10 @@ func sameStrings(a, b []string) bool { } // An uncertain snapshot create keeps the intent that protects the -// snapshot's keys; a retry with the same request id settles it and removes -// every intent of the operation (review of #111, P1). +// 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() @@ -68,8 +70,8 @@ func TestCatalog_SnapshotUncertainCreateKeepsIntent(t *testing.T) { if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { t.Fatalf("retry: %v", err) } - if in := intentsOf(t, f, "v1"); len(in) != 0 { - t.Fatalf("a settled snapshot left %d intents", len(in)) + 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) } } @@ -118,8 +120,8 @@ func TestFork_UncertainHeadCreateKeepsIntent(t *testing.T) { if err != nil || res.Replayed { t.Fatalf("retry: %+v %v", res, err) } - if in := intentsOf(t, f, "v2"); len(in) != 0 { - t.Fatalf("a settled fork left %d intents", len(in)) + 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. diff --git a/seaweed-block/core/frontend/chunkstore/fake_test.go b/seaweed-block/core/frontend/chunkstore/fake_test.go index 86b563c492..a9286fb823 100644 --- a/seaweed-block/core/frontend/chunkstore/fake_test.go +++ b/seaweed-block/core/frontend/chunkstore/fake_test.go @@ -42,6 +42,14 @@ type fakeFiler struct { // 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{}} } @@ -71,6 +79,10 @@ func (f *fakeFiler) CreateEntry(_ context.Context, dir string, e *filerpb.Entry, 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)) @@ -157,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() From 2d598a4dbd566d766b4ff1dc94bd2edebb087134 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 04:38:07 -0800 Subject: [PATCH 6/7] storage: gofmt the chunk layer's state fields The r4 field pendingBase left the rest of the block misaligned. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_layer.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 6953b04678..8e97d3226c 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -72,14 +72,14 @@ type chunkLayerImpl struct { // 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 + 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 From 53e5262fda78d792a801230e60f57286d2577195 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 04:47:55 -0800 Subject: [PATCH 7/7] storage: re-check capture admission before re-proposing a held CAS Re-proposing an unresolved CAS at its base is a new publication. It now passes the capture admission again right before the CAS is sent, after the blocking HEAD read: a demotion or lineage change during that read sends no CAS, keeps the CAS unresolved, and returns the refusal (with errChunkCASOutcomeUnknown still in the chain). Once authority is back, the same proposal settles at the same base. The fake remote gains onGetHead, a hook that runs inside each HEAD read. Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_fake_remote_test.go | 4 + seaweed-block/core/storage/chunk_layer.go | 8 +- .../chunk_layer_pending_admission_test.go | 95 +++++++++++++++++++ 3 files changed, 106 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/core/storage/chunk_layer_pending_admission_test.go diff --git a/seaweed-block/core/storage/chunk_fake_remote_test.go b/seaweed-block/core/storage/chunk_fake_remote_test.go index 98c4f0a58d..ad9008eabc 100644 --- a/seaweed-block/core/storage/chunk_fake_remote_test.go +++ b/seaweed-block/core/storage/chunk_fake_remote_test.go @@ -94,6 +94,7 @@ 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 @@ -238,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 } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 8e97d3226c..6f81e8b395 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -784,7 +784,13 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) error { // 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. + // 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) diff --git a/seaweed-block/core/storage/chunk_layer_pending_admission_test.go b/seaweed-block/core/storage/chunk_layer_pending_admission_test.go new file mode 100644 index 0000000000..5d541024f8 --- /dev/null +++ b/seaweed-block/core/storage/chunk_layer_pending_admission_test.go @@ -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) +}