fix(block): a snapshot replay with a relative --expires resends the original expiry

A relative --expires is fixed once at the first send and printed with
the request id. The holder's snapshot list entries now carry the
publishing request id (operationID, additive), next to expiresAtNs. A
run that the holder refuses as a changed request (operation_conflict)
reads the original expiry there and resends once with it; when the
entry or its operationID is missing it answers outcome_unknown with the
recovery line, never a new expiry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-12-06 01:37:19 -08:00
1 parent 32d1b6eaf7
commit bc18f4fdcc
9 files changed
+309 -7

No files matched your search

+7 -1
View File
@@ -325,12 +325,18 @@ func chunkSnapshot(args []string, stdout, stderr io.Writer) int {
requestID = newRequestID()
fmt.Fprintf(stderr, "sw-block ops chunk snapshot: request id %s (reuse it to retry)\n", requestID)
}
var replay func() (int64, error)
if expires > 0 {
// Fixed once here; a retry names it with --expires-at-ns.
fmt.Fprintf(stderr, "sw-block ops chunk snapshot: request id %s expires at %d (to retry, pass --request-id %s --expires-at-ns %d)\n", requestID, expiresAtNs, requestID, expiresAtNs)
replay = func() (int64, error) { return snapshotRecordedExpiry(statusAddr, volumeID, name, requestID, timeout) }
}
body := map[string]any{"volumeID": volumeID, "name": name,
"requestID": requestID, "labels": map[string]string(labels), "consistency": consistency, "expiresAtNs": expiresAtNs}
if class != "" {
body["class"] = class // only when set: the request otherwise keeps its spec fields
}
return chunkObserveSnapshot(statusAddr, timeout, body, noWait, stdout, stderr)
return chunkObserveSnapshot(statusAddr, timeout, body, noWait, stdout, stderr, replay)
}
func chunkDetach(args []string, stdout, stderr io.Writer) int {
@@ -0,0 +1,81 @@
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
// A relative --expires is turned into an absolute expiry once, when the
// command starts; every idempotency-key input is fixed at the first send. A
// later run of the same request id with the same relative --expires computes
// a different absolute value, so the holder refuses it as a changed request
// (operation_conflict). Such a run then reads the expiry the original
// request recorded, from the holder's snapshot list (the published entry
// whose operationID is this request id), and resends once with it. When that
// cannot be read (not published yet, published by another request, or a
// holder that does not report operation ids), the answer is outcome_unknown
// with the recovery line: never a new expiry.
// snapshotRecordedExpiry is the expiry the snapshot name recorded for the
// operation with requestID, as the holder at statusAddr lists it.
func snapshotRecordedExpiry(statusAddr, volumeID, name, requestID string, timeout time.Duration) (int64, error) {
base := statusAddr
if !strings.Contains(base, "://") {
base = "http://" + base
}
q := url.Values{"volume": {volumeID}, "prefix": {name}}
ctx, cancel := context.WithTimeout(context.Background(), min(timeout, chunkReadBound()))
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(base, "/")+"/chunk/snapshots?"+q.Encode(), nil)
if err != nil {
return 0, err
}
resp, err := answer.DoHTTP(chunkHTTPClient, req, answer.PossiblyAdmitted)
if err != nil {
return 0, fmt.Errorf("read the snapshot list: %w", err)
}
defer resp.Body.Close()
raw, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if err != nil || resp.StatusCode != http.StatusOK {
return 0, fmt.Errorf("read the snapshot list: HTTP %d %v", resp.StatusCode, err)
}
var list chunkstore.SnapshotListBody
if err := json.Unmarshal(raw, &list); err != nil {
return 0, fmt.Errorf("read the snapshot list: %w", err)
}
for _, s := range list.Snapshots {
if s.Name != name {
continue
}
switch {
case s.OperationID == "":
return 0, errors.New("the holder does not report which request published this snapshot (an older holder, or a snapshot named without an operation)")
case s.OperationID != requestID:
return 0, fmt.Errorf("snapshot %q was published by another request", name)
case s.ExpiresAtNs == 0:
return 0, fmt.Errorf("snapshot %q records no expiry", name)
}
return s.ExpiresAtNs, nil
}
return 0, fmt.Errorf("snapshot %q is not published yet", name)
}
// snapshotReplayUnknown is the outcome_unknown answer of a replay whose
// original expiry cannot be read, with the recovery line.
func snapshotReplayUnknown(requestID string, why error, stdout, stderr io.Writer) int {
err := fmt.Errorf("request %s was sent before with another expiry and its recorded expiry cannot be read (%v); "+
"rerun with --request-id %s --expires-at-ns <the original absolute expiry> (the one printed by the first run, "+
"or Meta.ExpiresNs of the snapshot whose Meta.Operation.id is %s in `sw-block ops chunk show`); never with a new --expires",
requestID, why, requestID, requestID)
return chunkResult("snapshot", nil, answer.Rekind(answer.Record(answer.PossiblyAdmitted, err), answer.Connection), stdout, stderr)
}
@@ -0,0 +1,114 @@
package main
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
)
// expiresHolder is a holder that keeps a request id's first expiry, refuses
// the same id with another expiry as a changed request (operation_conflict,
// as the real holder's fingerprint check does), and lists the published
// snapshot with its expiry and, unless old, the request id that published it.
type expiresHolder struct {
mu sync.Mutex
recorded map[string]int64
sent []int64
old bool // a holder that does not report operationID
published bool
}
func (h *expiresHolder) serve(w http.ResponseWriter, r *http.Request) {
h.mu.Lock()
defer h.mu.Unlock()
w.Header().Set("Content-Type", "application/json")
switch {
case r.Method == http.MethodPost && r.URL.Path == "/chunk/snapshot":
var req struct {
RequestID string `json:"requestID"`
ExpiresAtNs int64 `json:"expiresAtNs"`
}
_ = json.NewDecoder(r.Body).Decode(&req)
h.sent = append(h.sent, req.ExpiresAtNs)
if first, ok := h.recorded[req.RequestID]; ok && first != req.ExpiresAtNs {
w.WriteHeader(http.StatusConflict)
fmt.Fprint(w, `{"code":"operation_conflict","message":"chunkstore: snapshot operation intent conflict","retryable":false}`)
return
}
if _, ok := h.recorded[req.RequestID]; !ok {
h.recorded[req.RequestID] = req.ExpiresAtNs
}
w.Header().Set("Location", "/operations/"+req.RequestID)
w.WriteHeader(http.StatusAccepted)
fmt.Fprintf(w, `{"operation_id":%q,"state":"succeeded","result":{"name":"daily","expiresAtNs":%d}}`, req.RequestID, req.ExpiresAtNs)
case r.Method == http.MethodGet && r.URL.Path == "/chunk/snapshots":
var entries []string
if h.published {
for id, exp := range h.recorded {
if h.old {
entries = append(entries, fmt.Sprintf(`{"name":"daily","expiresAtNs":%d,"headGen":2,"headEpoch":1,"cutLSN":1,"createdNs":1,"state":"","labels":null,"consistency":"crash","parent":null}`, exp))
} else {
entries = append(entries, fmt.Sprintf(`{"name":"daily","expiresAtNs":%d,"operationID":%q,"headGen":2,"headEpoch":1,"cutLSN":1,"createdNs":1,"state":"","labels":null,"consistency":"crash","parent":null}`, exp, id))
}
}
}
fmt.Fprintf(w, `{"volumeID":"v1","snapshots":[%s],"next":""}`, strings.Join(entries, ","))
default:
http.NotFound(w, r)
}
}
// A relative --expires is fixed at the first send. Run again with the same
// request id after 2 s, it computes another expiry: the holder refuses that
// as a changed request, and the CLI resends once with the expiry the
// original recorded (read from the holder's list), never a new one. A holder
// that cannot say which request published the snapshot, or a snapshot not
// published yet, answers outcome_unknown with the recovery line, no resend.
func TestSnapshotReplayWithRelativeExpiresKeepsTheOriginalExpiry(t *testing.T) {
for _, c := range []struct {
name string
old, published bool
wantExit int
wantResent bool
wantOutContains string
}{
{name: "replay reads the recorded expiry", published: true, wantExit: 0, wantResent: true, wantOutContains: `"name":"daily"`},
{name: "older holder without operationID", old: true, published: true, wantExit: 3, wantOutContains: "outcome_unknown"},
{name: "not published yet", published: false, wantExit: 3, wantOutContains: "outcome_unknown"},
} {
h := &expiresHolder{recorded: map[string]int64{}, old: c.old, published: c.published}
server := httptest.NewServer(http.HandlerFunc(h.serve))
args := []string{"--volume", "v1", "--status-addr", server.URL, "--name", "daily", "--request-id", "req-1", "--expires", "1h"}
exit0, out0, diag0 := runChunk(append([]string{"snapshot"}, args...)...)
if exit0 != 0 {
t.Fatalf("%s: first send: exit %d out %s stderr %s", c.name, exit0, out0, diag0)
}
first := h.recorded["req-1"]
if !strings.Contains(diag0, fmt.Sprintf("--expires-at-ns %d", first)) {
t.Fatalf("%s: the first run did not print its absolute expiry %d: %s", c.name, first, diag0)
}
time.Sleep(2 * time.Second)
exit, out, diag := runChunk(append([]string{"snapshot"}, args...)...)
server.Close()
if exit != c.wantExit || !strings.Contains(out, c.wantOutContains) {
t.Fatalf("%s: replay: exit %d out %s stderr %s; want exit %d with %q", c.name, exit, out, diag, c.wantExit, c.wantOutContains)
}
last := h.sent[len(h.sent)-1]
if c.wantResent && (len(h.sent) != 3 || last != first) {
t.Fatalf("%s: sends %v; want the refused new expiry, then the original %d", c.name, h.sent, first)
}
if !c.wantResent {
if len(h.sent) != 2 {
t.Fatalf("%s: sends %v; want no resend after the refusal", c.name, h.sent)
}
if !strings.Contains(out+diag, "--expires-at-ns") {
t.Fatalf("%s: no recovery line: %s %s", c.name, out, diag)
}
}
}
}
@@ -1,6 +1,7 @@
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
@@ -33,9 +34,32 @@ type snapshotCLIAdmission struct {
// admitted, observation only GETs the returned handle; interrupt ends the
// observer, never the server operation. A synchronous answer (a holder
// older than this release) is an unknown outcome.
func chunkObserveSnapshot(addr string, timeout time.Duration, body map[string]any, noWait bool, stdout, stderr io.Writer) int {
//
// replay, when set (a relative --expires), reads the expiry the original
// request recorded: an operation_conflict answer is then resent once with it,
// or answers outcome_unknown when it cannot be read.
func chunkObserveSnapshot(addr string, timeout time.Duration, body map[string]any, noWait bool, stdout, stderr io.Writer, replay ...func() (int64, error)) int {
var a snapshotCLIAdmission
code := chunkPostLoop("snapshot", addr, "/chunk/snapshot", timeout, body, stdout, stderr, &a)
var admOut, admErr bytes.Buffer
code := chunkPostLoop("snapshot", addr, "/chunk/snapshot", timeout, body, &admOut, &admErr, &a)
if code != 0 && len(replay) > 0 && replay[0] != nil {
var e chunkErrBody
if json.Unmarshal(admOut.Bytes(), &e) == nil && e.Code == "operation_conflict" {
requestID, _ := body["requestID"].(string)
expiry, err := replay[0]()
if err != nil {
_, _ = stderr.Write(admErr.Bytes())
return snapshotReplayUnknown(requestID, err, stdout, stderr)
}
fmt.Fprintf(stderr, "sw-block ops chunk snapshot: request %s was sent before; resending it with its recorded expiry %d\n", requestID, expiry)
body["expiresAtNs"] = expiry
return chunkObserveSnapshot(addr, timeout, body, noWait, stdout, stderr)
}
}
_, _ = stderr.Write(admErr.Bytes())
if err := writeAll(stdout, admOut.Bytes()); err != nil {
return chunkExitFailed
}
if code != 0 || !a.Accepted {
return code
}
@@ -9,6 +9,7 @@ import "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
type SnapshotListItem struct {
Class string `json:"class,omitempty"`
ExpiresAtNs int64 `json:"expiresAtNs,omitempty"`
OperationID string `json:"operationID,omitempty"`
Root string `json:"root,omitempty"`
Dependents []layout.Dependent `json:"dependents,omitempty"`
Name string `json:"name"`
@@ -34,7 +35,7 @@ type SnapshotListBody struct {
func NewSnapshotListBody(vol string, list []SnapshotInfo, next string) SnapshotListBody {
body := SnapshotListBody{VolumeID: vol, Snapshots: make([]SnapshotListItem, 0, len(list)), Next: next}
for _, s := range list {
body.Snapshots = append(body.Snapshots, SnapshotListItem{Name: s.Name, Root: s.Root, Dependents: s.Dependents, Class: s.Class, ExpiresAtNs: s.ExpiresAtNs, HeadGen: s.HeadGen, HeadEpoch: s.HeadEpoch,
body.Snapshots = append(body.Snapshots, SnapshotListItem{Name: s.Name, Root: s.Root, Dependents: s.Dependents, Class: s.Class, ExpiresAtNs: s.ExpiresAtNs, OperationID: s.OperationID, HeadGen: s.HeadGen, HeadEpoch: s.HeadEpoch,
CutLSN: s.CutLSN, CreatedNs: s.CreatedNs, State: s.State, Labels: s.Labels,
Consistency: s.Consistency, Parent: s.Parent})
}
@@ -130,8 +130,12 @@ type SnapshotInfo struct {
Labels map[string]string `json:"labels"`
Parent *Parent `json:"parent"`
ExpiresAtNs int64 `json:"expiresAtNs"`
Replayed bool `json:"replayed"`
Class string `json:"class"`
// OperationID is the request id of the operation that published this
// snapshot (HEAD's Meta.Operation.ID); empty for one named without an
// operation. A replay of that request id reads its expiry here.
OperationID string `json:"operationID,omitempty"`
Replayed bool `json:"replayed"`
Class string `json:"class"`
attempt string // the attempt the name resolved to, when read by name
@@ -1103,7 +1103,11 @@ func (c *chunkControl) ListSnapshots(ctx context.Context, volumeID string, opts
out := make([]chunkstore.SnapshotInfo, 0, len(names))
for _, name := range names {
sn := h.Snapshots[name]
out = append(out, chunkstore.SnapshotInfo{VolumeID: volumeID, Name: name, Root: sn.Root.String(), Dependents: sn.Dependents, CreatedNs: sn.Meta.CreatedNs, Class: sn.Meta.Class, ExpiresAtNs: sn.Meta.ExpiresNs, Labels: maps.Clone(sn.Meta.Labels), ManifestBytes: sn.ManifestBytes})
info := chunkstore.SnapshotInfo{VolumeID: volumeID, Name: name, Root: sn.Root.String(), Dependents: sn.Dependents, CreatedNs: sn.Meta.CreatedNs, Class: sn.Meta.Class, ExpiresAtNs: sn.Meta.ExpiresNs, Labels: maps.Clone(sn.Meta.Labels), ManifestBytes: sn.ManifestBytes}
if sn.Meta.Operation != nil {
info.OperationID = sn.Meta.Operation.ID
}
out = append(out, info)
}
return out, next, nil
}
@@ -0,0 +1,62 @@
package volume
import (
"context"
"encoding/json"
"strings"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
)
// The snapshot list reports, for each snapshot, the request id that
// published it (HEAD's Meta.Operation.ID) and its expiry: a replay of that
// request id with a relative --expires reads them to resend with the
// original expiry. A snapshot named without an operation lists no id. Both
// are additive, read-only JSON fields of the list entry.
func TestSnapshotListReportsThePublishingRequestAndItsExpiry(t *testing.T) {
ctx := context.Background()
f := &adapterManifestFiler{Filer: chunkstore.NewMemFiler(), blobs: map[string][]byte{}}
cat, err := chunkstore.NewBCatalog(f, f, "/chunks")
if err != nil {
t.Fatal(err)
}
id, _ := layout.ParseVolumeID("00112233445566778899aabbccddeeff")
ref := chunkstore.VolumeRef{Name: "v1", ID: id}
if _, err := cat.CreateVolume(ctx, ref, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil {
t.Fatal(err)
}
h, _, err := cat.ReadHead(ctx, ref)
if err != nil {
t.Fatal(err)
}
const expires = int64(4102444800000000000)
r := layout.RootName{Hash: layout.Sum([]byte("root"))}
op := &layout.SnapshotOperationBinding{ID: "req-1", Instance: strings.Repeat("a", 32), Owner: strings.Repeat("b", 32), Sequence: 1, Fingerprint: strings.Repeat("c", 64), Generation: h.Gen + 1, Epoch: 1}
h.Version = 1 // an operation publication exists only on a v1.1 HEAD
h.Snapshots = map[string]layout.Snapshot{
"named": {Root: r, Meta: layout.SnapshotMeta{ExpiresNs: expires, Operation: op}},
"legacy": {Root: r},
}
s, _ := cat.Store(ref)
if err := s.UpdateHead(ctx, h.Gen, h, layout.CauseCommit); err != nil {
t.Fatal(err)
}
ctl := NewChunkControl(&fakeChunkProvider{}, cat, ref)
list, _, err := ctl.ListSnapshots(ctx, "v1", chunkstore.ListOptions{})
if err != nil || len(list) != 2 {
t.Fatalf("list: %+v %v", list, err)
}
byName := map[string]chunkstore.SnapshotInfo{list[0].Name: list[0], list[1].Name: list[1]}
if got := byName["named"]; got.OperationID != "req-1" || got.ExpiresAtNs != expires {
t.Fatalf("named: operationID %q expiresAtNs %d; want req-1 and %d", got.OperationID, got.ExpiresAtNs, expires)
}
if got := byName["legacy"]; got.OperationID != "" {
t.Fatalf("a snapshot named without an operation lists operationID %q", got.OperationID)
}
raw, err := json.Marshal(chunkstore.NewSnapshotListBody("v1", list, ""))
if err != nil || !strings.Contains(string(raw), `"operationID":"req-1"`) || strings.Count(string(raw), `"operationID"`) != 1 {
t.Fatalf("list body %s (%v): want operationID on the named entry only", raw, err)
}
}
+6
View File
@@ -568,3 +568,9 @@ bytes and may still contain `chunkCount: 0`; treat that value as unknown.
No full manifest scan is added to creation or listing responses. The `verify`
report counts references across all distinct roots named by HEAD, not the
distinct chunks of one snapshot.
From v1.1.3 each `GET /chunk/snapshots` entry also carries `operationID`, the request id of the operation
that published the snapshot (omitted for a snapshot named without one), next to its `expiresAtNs`. A
`sw-block ops chunk snapshot` run with a relative `--expires` that the holder refuses as a changed request
(`operation_conflict`) reads the original request's expiry there and resends once with it; when the entry
or its `operationID` is missing, it answers `outcome_unknown` with the recovery line instead.