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 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-15 04:20:41 -08:00
1 parent 1ec7b9975b
commit 681becfff0
8 files changed
+653 -109

No files matched your search

+215 -75
View File
@@ -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 "@<owner>/<key>" (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 "@<owner>/<key>" (a ref already qualified
// keeps its owner), under an intent in the target;
// 4. exclusively create the target's HEAD: gen 1, epoch 0, no holder, and
// the snapshot's remote_lsn (LSNs carry forward).
//
// The HEAD write is refused once OpDeadline has passed since step 1. An
// uncertain outcome of step 2 or 4 is outcome_unknown 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}
}
@@ -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)
}
}
@@ -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)
@@ -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
}
+94 -26
View File
@@ -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()
@@ -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)
}
}
+8 -7
View File
@@ -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
+1
View File
@@ -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).