Merge pull request #325 from seaweedfs/train/20261121-5

Train 5: #323 + #317 + #322
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-20 19:56:45 -08:00
commit a7d0b851bd
41 files changed
+3540 -111

No files matched your search

+19 -3
View File
@@ -226,19 +226,35 @@ func chunkSnapshot(args []string, stdout, stderr io.Writer) int {
func chunkDetach(args []string, stdout, stderr io.Writer) int {
fs := chunkFlagSet("detach", stderr)
var (
volumeID, statusAddr string
timeout time.Duration
volumeID, statusAddr string
timeout time.Duration
frozen, allowOverBudget bool
freezeStartedAtNs int64
)
fs.StringVar(&volumeID, "volume", "", "volume id")
fs.StringVar(&statusAddr, "status-addr", "", "blockvolume status address or URL (with --chunk-control-endpoint)")
fs.DurationVar(&timeout, "timeout", 120*time.Second, "operation bound (capped at the server's OpDeadline)")
fs.BoolVar(&frozen, "frozen", false, "guest is already frozen; use one cut within its remaining five-second budget")
fs.Int64Var(&freezeStartedAtNs, "freeze-started-at-ns", 0, "guest freeze start in Unix nanoseconds on the serving host clock")
fs.BoolVar(&allowOverBudget, "allow-over-budget", false, "explicit final frozen attempt; record over_budget rather than refuse its estimate")
if err := fs.Parse(args); err != nil {
return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
}
if volumeID == "" || statusAddr == "" {
return chunkFail("detach", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume and --status-addr are required", false)
}
return chunkPost("detach", statusAddr, "/chunk/detach", timeout, map[string]any{"volumeID": volumeID}, stdout, stderr)
if (frozen && freezeStartedAtNs <= 0) || (!frozen && (freezeStartedAtNs != 0 || allowOverBudget)) {
return chunkFail("detach", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--frozen requires --freeze-started-at-ns; --allow-over-budget requires --frozen", false)
}
body := map[string]any{"volumeID": volumeID}
if frozen {
body["frozen"] = true
body["freezeStartedAtNs"] = freezeStartedAtNs
if allowOverBudget {
body["allowOverBudget"] = true
}
}
return chunkPost("detach", statusAddr, "/chunk/detach", timeout, body, stdout, stderr)
}
// chunkCatalog opens the catalog under --chunk-path on --chunk-filer.
@@ -0,0 +1,19 @@
package main
import (
"testing"
)
func TestOpsChunkFrozenDetachFlags(t *testing.T) {
srv, got := chunkServer(t, 200, `{"volumeID":"v1"}`)
code, _, errs := runChunk("detach", "--volume=v1", "--status-addr="+srv.URL, "--frozen", "--freeze-started-at-ns=1234567", "--allow-over-budget")
if code != 0 || len(*got) != 1 || (*got)[0].body["frozen"] != true || (*got)[0].body["freezeStartedAtNs"] != float64(1234567) || (*got)[0].body["allowOverBudget"] != true {
t.Fatalf("frozen request lost budget: %d %s %+v", code, errs, *got)
}
for _, flags := range [][]string{{"--frozen"}, {"--allow-over-budget"}, {"--freeze-started-at-ns=123"}} {
args := append([]string{"detach", "--volume=v1", "--status-addr=" + srv.URL}, flags...)
if code, _, _ := runChunk(args...); code == 0 || len(*got) != 1 {
t.Fatalf("invalid flags sent request: %v", flags)
}
}
}
@@ -90,6 +90,8 @@ type ChunkRemote struct {
mu sync.Mutex
fids map[string]string // key -> fid; key entries are write-once
assigns assignCounters // reservations made by upload rounds
}
// NewChunkRemote returns the remote for the volume rooted at root, an
@@ -150,26 +152,42 @@ func (r *ChunkRemote) Put(ctx context.Context, key string, data []byte) error {
}
func (r *ChunkRemote) putObject(ctx context.Context, key string, data []byte, object string) error {
if err := storage.ValidChunkKey(key); err != nil {
return fmt.Errorf("%w: %v", ErrInvalidKey, err)
}
if strings.HasPrefix(key, "@") {
return fmt.Errorf("%w: %q is owner-qualified; a volume writes only its own keys", ErrInvalidKey, key)
}
name, err := keyName(key)
name, err := r.ownKeyName(key)
if err != nil {
return err
}
r.mu.Lock()
_, known := r.fids[key]
r.mu.Unlock()
if known {
if r.knownKey(key) {
return storage.ErrChunkKeyExists
}
fid, err := r.b.Put(ctx, data)
if err != nil {
return err
}
return r.bindKey(ctx, key, name, fid, data, object)
}
// ownKeyName checks that key is one of this volume's own keys and returns
// its binding's entry name.
func (r *ChunkRemote) ownKeyName(key string) (string, error) {
if err := storage.ValidChunkKey(key); err != nil {
return "", fmt.Errorf("%w: %v", ErrInvalidKey, err)
}
if strings.HasPrefix(key, "@") {
return "", fmt.Errorf("%w: %q is owner-qualified; a volume writes only its own keys", ErrInvalidKey, key)
}
return keyName(key)
}
// knownKey reports whether key is already bound (as far as this remote saw).
func (r *ChunkRemote) knownKey(key string) bool {
r.mu.Lock()
defer r.mu.Unlock()
_, known := r.fids[key]
return known
}
// bindKey binds key to the stored needle fid with an exclusive create.
func (r *ChunkRemote) bindKey(ctx context.Context, key, name, fid string, data []byte, object string) error {
now := time.Now().Unix()
e := &filerpb.Entry{
Name: name,
@@ -68,6 +68,13 @@ func waitTCP(t *testing.T, addr string, d time.Duration) {
}
func startWeed(t *testing.T) *weedCluster {
t.Helper()
return startWeedWith(t, "")
}
// startWeedWith starts the cluster with security (the contents of a
// security.toml in its working directory; "" for none).
func startWeedWith(t *testing.T, security string) *weedCluster {
t.Helper()
weed := os.Getenv("CHUNKSTORE_WEED")
if weed == "" {
@@ -112,6 +119,11 @@ func startWeed(t *testing.T) *weedCluster {
t.Fatal(err)
}
}
if security != "" {
if err := os.WriteFile(filepath.Join(dir, "security.toml"), []byte(security), 0o600); err != nil {
t.Fatal(err)
}
}
run("master", "master", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", mp), "-mdir="+filepath.Join(dir, "m"), "-volumeSizeLimitMB=256", "-defaultReplication=000")
waitTCP(t, c.master, 20*time.Second)
run("volume", "volume", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", vp), "-dir="+filepath.Join(dir, "v"), "-master="+c.master, "-max=32")
@@ -0,0 +1,391 @@
package chunkstore
// Upload rounds over batch assign. The n objects of one round are split into
// G = min(8, ceil(n/64)) groups (object i goes to group i % G, as slot i / G),
// and each group takes one reservation for all its slots, made when its
// first object is uploaded. So a round costs G assigns instead of n, its
// objects still spread over up to G volumes, and a round with no upload
// makes none.
//
// A slot is frozen once an upload was sent for it: until that upload is
// resolved (stored and bound, or definitely not stored), every retry uses
// the same fid, whatever happens to the group's ranges. Ranges change only
// for slots with no upload outstanding:
// - a short grant is topped up by a reservation for the remaining slots;
// - a refusal before append (read-only or full volume) moves this and the
// later slots of the group to a fresh range, at most roundMaxReplacements
// times per group;
// - a range whose token is past its stated expiry (less a skew) is never
// sent to: an upload is sent under that deadline, and a slot frozen on
// an expired range is resolved by reading its fid back first (the exact
// bytes: bind it; definitely absent: a fresh range takes it).
// A rejected token (401) and used-up replacements end the object for good
// (storage.ErrChunkPutFinal). A reservation reply that arrives after the
// group's ranges changed is discarded (its ids stay unused). AssignCounts
// counts every reservation attempt, by reason, failed ones included.
import (
"bytes"
"context"
"errors"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/seaweedfs/seaweed-block/core/storage"
)
const (
roundGroupSize = 64
roundMaxGroups = 8
roundMaxReplacements = 3
)
// AssignCounts counts the reservation attempts this remote's upload rounds
// made. Each attempt is counted once, by why it was made, whether or not it
// succeeded; Failed counts the ones that returned no usable range.
type AssignCounts struct {
Initial int64 // the first attempt of each group
Short int64 // top-ups after a short grant
Capacity int64 // replacements after a refusal before append
Expired int64 // replacements of ranges whose token expired before use
Retry int64 // attempts after a failed, lost or discarded reply
Failed int64 // attempts that returned an error or were discarded
}
// Extra is every attempt beyond the initial ones.
func (a AssignCounts) Extra() int64 { return a.Short + a.Capacity + a.Expired + a.Retry }
type assignCounters struct{ initial, short, capacity, expired, retry, failed atomic.Int64 }
// AssignCounts reports the reservation attempts made so far.
func (r *ChunkRemote) AssignCounts() AssignCounts {
return AssignCounts{
Initial: r.assigns.initial.Load(),
Short: r.assigns.short.Load(),
Capacity: r.assigns.capacity.Load(),
Expired: r.assigns.expired.Load(),
Retry: r.assigns.retry.Load(),
Failed: r.assigns.failed.Load(),
}
}
var _ storage.ChunkPutRounds = (*ChunkRemote)(nil)
// BeginPutRound starts a round of n objects of objSize bytes. Without batch
// support in the blob store, the round is one Put per object.
func (r *ChunkRemote) BeginPutRound(n, objSize int) storage.ChunkPutRound {
rb, ok := r.b.(rangeBlobs)
if !ok || n <= 0 {
return plainRound{r}
}
g := min(roundMaxGroups, (n+roundGroupSize-1)/roundGroupSize)
rd := &putRound{r: r, rb: rb, n: n, size: uint64(max(objSize, 0)), groups: make([]*roundGroup, g)}
for j := range rd.groups {
// Group j holds objects j, j+g, j+2g, ...
rd.groups[j] = &roundGroup{slots: (n - j + g - 1) / g, pins: map[int]slotPin{}, owners: map[int]chan struct{}{}}
}
return rd
}
type plainRound struct{ r *ChunkRemote }
func (p plainRound) Put(ctx context.Context, _ int, key string, data []byte) error {
return p.r.Put(ctx, key, data)
}
type putRound struct {
r *ChunkRemote
rb rangeBlobs
n int
size uint64
groups []*roundGroup
}
type reserveReason int
const (
reserveInitial reserveReason = iota
reserveShort
reserveCapacity
reserveExpired
reserveRetry
)
// roundGroup's ranges cover its slots [0, end) as consecutive spans.
type roundGroup struct {
slots int
mu sync.Mutex
spans []roundSpan
ver int // bumped by every change to spans other than an append
reserving chan struct{} // non-nil while a reservation is in flight
replacements int
next reserveReason // why the next reservation is made
pins map[int]slotPin
owners map[int]chan struct{} // slot -> held by one Put at a time
}
type roundSpan struct {
from int
rng blobRange
}
// slotPin freezes a slot on the fid an upload was sent to; stored records
// that the upload succeeded (only its binding is outstanding).
type slotPin struct {
rng blobRange
off int
stored bool
}
func (g *roundGroup) end() int {
if len(g.spans) == 0 {
return 0
}
last := g.spans[len(g.spans)-1]
return last.from + last.rng.count
}
// lookup returns the range and offset of slot s, if reserved. g.mu held.
func (g *roundGroup) lookup(s int) (blobRange, int, bool) {
for _, sp := range g.spans {
if s >= sp.from && s < sp.from+sp.rng.count {
return sp.rng, s - sp.from, true
}
}
return blobRange{}, 0, false
}
// own makes the caller the only Put working on slot s until release.
func (g *roundGroup) own(ctx context.Context, s int) (release func(), err error) {
for {
g.mu.Lock()
held, busy := g.owners[s]
if !busy {
done := make(chan struct{})
g.owners[s] = done
g.mu.Unlock()
return func() {
g.mu.Lock()
delete(g.owners, s)
g.mu.Unlock()
close(done)
}, nil
}
g.mu.Unlock()
select {
case <-held:
case <-ctx.Done():
return nil, ctx.Err()
}
}
}
func (g *roundGroup) pin(s int, p slotPin) {
g.mu.Lock()
g.pins[s] = p
g.mu.Unlock()
}
func (g *roundGroup) unpin(s int) {
g.mu.Lock()
delete(g.pins, s)
g.mu.Unlock()
}
func (g *roundGroup) pinned(s int) (slotPin, bool) {
g.mu.Lock()
defer g.mu.Unlock()
p, ok := g.pins[s]
return p, ok
}
// retire drops slots s and later of the span using rng, so they take a fresh
// range (slots with an upload outstanding keep their pinned fid); it reports
// false once the group's replacements are used up. A span already replaced
// (by a concurrent upload) is left as is.
func (g *roundGroup) retire(rng blobRange, s int, why reserveReason) bool {
g.mu.Lock()
defer g.mu.Unlock()
for k, sp := range g.spans {
if sp.rng.base != rng.base {
continue
}
if g.replacements >= roundMaxReplacements {
return false
}
g.replacements++
g.next = why
g.ver++
if s <= sp.from {
g.spans = g.spans[:k]
} else {
g.spans[k].rng.count = s - sp.from
g.spans = g.spans[:k+1]
}
return true
}
return true
}
func (rd *putRound) count(why reserveReason) {
switch why {
case reserveInitial:
rd.r.assigns.initial.Add(1)
case reserveShort:
rd.r.assigns.short.Add(1)
case reserveCapacity:
rd.r.assigns.capacity.Add(1)
case reserveExpired:
rd.r.assigns.expired.Add(1)
case reserveRetry:
rd.r.assigns.retry.Add(1)
}
}
// slot returns slot s's range and offset, reserving the group's remaining
// slots when s is not covered yet. Concurrent callers share one reservation;
// waiting follows ctx. A reply after ctx ends, or after the group's ranges
// changed while it was in flight, is not used.
func (rd *putRound) slot(ctx context.Context, g *roundGroup, s int) (blobRange, int, error) {
for {
g.mu.Lock()
if rng, off, ok := g.lookup(s); ok {
g.mu.Unlock()
return rng, off, nil
}
if wait := g.reserving; wait != nil {
g.mu.Unlock()
select {
case <-wait:
continue
case <-ctx.Done():
return blobRange{}, 0, ctx.Err()
}
}
from, ver, why := g.end(), g.ver, g.next
done := make(chan struct{})
g.reserving = done
g.mu.Unlock()
rd.count(why)
rng, err := rd.rb.reserve(ctx, g.slots-from, rd.size)
if err == nil {
err = ctx.Err()
}
g.mu.Lock()
g.reserving = nil
close(done)
switch {
case err != nil:
rd.r.assigns.failed.Add(1)
g.next = reserveRetry
case g.ver != ver || g.end() != from:
// The ranges changed while this reply was in flight: its ids
// stay unused, and the uncovered slots are reserved again.
rd.r.assigns.failed.Add(1)
g.next = reserveRetry
default:
g.spans = append(g.spans, roundSpan{from: from, rng: rng})
g.next = reserveShort // only a short grant leaves slots uncovered now
}
g.mu.Unlock()
if err != nil {
return blobRange{}, 0, err
}
}
}
// final marks an outcome no retry can change.
func final(err error) error { return errors.Join(storage.ErrChunkPutFinal, err) }
// Put stores object i under key in its group's range and binds key to it.
func (rd *putRound) Put(ctx context.Context, i int, key string, data []byte) error {
if i < 0 || i >= rd.n {
return fmt.Errorf("chunkstore: round object %d outside a round of %d", i, rd.n)
}
name, err := rd.r.ownKeyName(key)
if err != nil {
return err
}
if rd.r.knownKey(key) {
return storage.ErrChunkKeyExists
}
g := rd.groups[i%len(rd.groups)]
s := i / len(rd.groups)
release, err := g.own(ctx, s)
if err != nil {
return err
}
defer release()
for {
if err := ctx.Err(); err != nil {
return err
}
p, frozen := g.pinned(s)
if !frozen {
rng, off, err := rd.slot(ctx, g, s)
if err != nil {
return err
}
p = slotPin{rng: rng, off: off}
}
fid, err := p.rng.fid(p.off)
if err != nil {
return err
}
if p.stored {
if err := rd.r.bindKey(ctx, key, name, fid, data, ""); err != nil {
return err
}
g.unpin(s)
return nil
}
dl, hasDL := p.rng.sendDeadline()
if hasDL && !time.Now().Before(dl) {
if frozen {
// An earlier upload to fid is unresolved: read it back
// before giving the fid up.
got, perr := rd.rb.probe(ctx, p.rng, p.off)
switch {
case perr == nil && bytes.Equal(got, data):
g.pin(s, slotPin{rng: p.rng, off: p.off, stored: true})
continue
case perr == nil:
return final(fmt.Errorf("chunkstore: round object %d: %s holds other bytes", i, fid))
case !errors.Is(perr, errBlobAbsent):
return fmt.Errorf("chunkstore: round object %d: earlier upload to %s unresolved: %w", i, fid, perr)
}
g.unpin(s)
}
if !g.retire(p.rng, s, reserveExpired) {
return final(fmt.Errorf("chunkstore: round object %d: token expired before upload, replacements used up", i))
}
continue
}
pctx, cancel := ctx, context.CancelFunc(func() {})
if hasDL {
pctx, cancel = context.WithDeadline(ctx, dl)
}
g.pin(s, p) // sent: frozen until resolved
err = rd.rb.putRange(pctx, p.rng, p.off, data)
cancel()
switch {
case err == nil:
g.pin(s, slotPin{rng: p.rng, off: p.off, stored: true})
continue
case errors.Is(err, errRangeRefused):
g.unpin(s) // definitely not stored
if !g.retire(p.rng, s, reserveCapacity) {
return final(fmt.Errorf("chunkstore: round object %d: %w (replacements used up)", i, err))
}
continue
case errors.Is(err, errRangeAuth):
g.unpin(s) // definitely not stored
return final(err)
}
return err // outcome unknown: the slot stays frozen on fid
}
}
@@ -0,0 +1,726 @@
package chunkstore
import (
"bytes"
"context"
"errors"
"fmt"
"strings"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// rangeFake is a blob store with batch reservations: each reserve hands out
// a new volume id; puts are recorded by fid. Hooks shape the replies.
type rangeFake struct {
*fakeBlobs
mu sync.Mutex
nextVid int
reserves []int // requested counts, in order
grant func(requested int) int
auth func() string
refuse func(fid string) error // non-nil: the put fails with it (nothing stored)
// reserveHook, when set, runs before each reserve (call counts from 1);
// an error fails the reserve. It decides itself whether to follow ctx.
reserveHook func(ctx context.Context, call int) error
// putHook, when set, decides each put: store the bytes or not, and the
// error to return (a stored put with an error is a lost reply).
putHook func(ctx context.Context, fid string) (store bool, err error)
puts []string
putAuth map[string]string
putDL map[string]time.Time // deadline of the context each put was sent under
}
func newRangeFake() *rangeFake {
return &rangeFake{fakeBlobs: newFakeBlobs(), nextVid: 1, putAuth: map[string]string{}, putDL: map[string]time.Time{}}
}
func (b *rangeFake) reserve(ctx context.Context, n int, _ uint64) (blobRange, error) {
b.mu.Lock()
b.reserves = append(b.reserves, n)
call := len(b.reserves)
hook := b.reserveHook
b.mu.Unlock()
if hook != nil {
if err := hook(ctx, call); err != nil {
return blobRange{}, err
}
}
b.mu.Lock()
defer b.mu.Unlock()
count := n
if b.grant != nil {
count = b.grant(n)
}
auth := ""
if b.auth != nil {
auth = b.auth()
}
vid := b.nextVid
b.nextVid++
return blobRange{base: fmt.Sprintf("%d,0a0b0c0d0e", vid), count: count, url: "fake:1", auth: auth}, nil
}
func (b *rangeFake) putRange(ctx context.Context, r blobRange, i int, data []byte) error {
fid, err := r.fid(i)
if err != nil {
return err
}
b.mu.Lock()
b.puts = append(b.puts, fid)
b.putAuth[fid] = r.auth
if dl, ok := ctx.Deadline(); ok {
b.putDL[fid] = dl
}
refuse, hook := b.refuse, b.putHook
b.mu.Unlock()
store, perr := true, error(nil)
if refuse != nil {
if err := refuse(fid); err != nil {
store, perr = false, err
}
}
if hook != nil {
store, perr = hook(ctx, fid)
}
if store {
b.fakeBlobs.mu.Lock()
b.fakeBlobs.data[fid] = append([]byte(nil), data...)
b.fakeBlobs.mu.Unlock()
}
return perr
}
func (b *rangeFake) probe(_ context.Context, r blobRange, i int) ([]byte, error) {
fid, err := r.fid(i)
if err != nil {
return nil, err
}
b.fakeBlobs.mu.Lock()
defer b.fakeBlobs.mu.Unlock()
d, ok := b.fakeBlobs.data[fid]
if !ok {
return nil, fmt.Errorf("%w %s", errBlobAbsent, fid)
}
return append([]byte(nil), d...), nil
}
func (b *rangeFake) putList() []string {
b.mu.Lock()
defer b.mu.Unlock()
return append([]string(nil), b.puts...)
}
func (b *rangeFake) reserveCounts() []int {
b.mu.Lock()
defer b.mu.Unlock()
return append([]int(nil), b.reserves...)
}
func roundRemote(t *testing.T, b *rangeFake) *ChunkRemote {
t.Helper()
r, err := NewChunkRemote(newFakeFiler(), b, "/swblock/vols/v1")
if err != nil {
t.Fatal(err)
}
return r
}
func roundKey(i int) string { return fmt.Sprintf("k%05d", i) }
// putAll runs one round of n objects with w concurrent workers.
func putAll(t *testing.T, r *ChunkRemote, n, w int) error {
t.Helper()
rd := r.BeginPutRound(n, 4096)
var mu sync.Mutex
next := 0
var first error
var wg sync.WaitGroup
for j := 0; j < w; j++ {
wg.Add(1)
go func() {
defer wg.Done()
for {
mu.Lock()
i := next
next++
mu.Unlock()
if i >= n {
return
}
if err := rd.Put(context.Background(), i, roundKey(i), []byte(roundKey(i))); err != nil {
mu.Lock()
if first == nil {
first = err
}
mu.Unlock()
}
}
}()
}
wg.Wait()
return first
}
func checkBound(t *testing.T, r *ChunkRemote, n int) {
t.Helper()
for i := 0; i < n; i++ {
got, err := r.Get(context.Background(), roundKey(i))
if err != nil || !bytes.Equal(got, []byte(roundKey(i))) {
t.Fatalf("key %d: %q %v", i, got, err)
}
}
}
// D objects take G = min(8, ceil(D/64)) reservations, balanced across the
// groups; D = 0 makes none. Every key is bound to its own fid.
func TestChunkRound_GroupsPerRound(t *testing.T) {
for _, c := range []struct{ d, g int }{{0, 0}, {1, 1}, {64, 1}, {65, 2}, {512, 8}, {513, 8}, {1000, 8}} {
t.Run(fmt.Sprint(c.d), func(t *testing.T) {
b := newRangeFake()
r := roundRemote(t, b)
if err := putAll(t, r, c.d, 16); err != nil {
t.Fatal(err)
}
got := b.reserveCounts()
if len(got) != c.g {
t.Fatalf("%d reservations %v for %d objects, want %d", len(got), got, c.d, c.g)
}
total, lo, hi := 0, c.d, 0
for _, n := range got {
total += n
lo, hi = min(lo, n), max(hi, n)
}
if total != c.d || (c.g > 0 && hi-lo > 1) {
t.Fatalf("reservations %v: want %d ids balanced within one", got, c.d)
}
checkBound(t, r, c.d)
seen := map[string]bool{}
for i := 0; i < c.d; i++ {
fid := r.fids[roundKey(i)]
if seen[fid] {
t.Fatalf("fid %s bound twice", fid)
}
seen[fid] = true
}
if a := r.AssignCounts(); a.Initial != int64(c.g) || a.Extra() != 0 {
t.Fatalf("assign counts %+v, want %d initial, no extras", a, c.g)
}
})
}
}
// A short grant is topped up by a reservation for the remainder, counted as
// an extra, not an initial assign.
func TestChunkRound_ShortGrantReservesRemainder(t *testing.T) {
b := newRangeFake()
first := true
b.grant = func(n int) int {
if first {
first = false
return n / 2
}
return n
}
r := roundRemote(t, b)
if err := putAll(t, r, 10, 4); err != nil {
t.Fatal(err)
}
if got := b.reserveCounts(); len(got) != 2 || got[0] != 10 || got[1] != 5 {
t.Fatalf("reservations %v, want [10 5]", got)
}
checkBound(t, r, 10)
if a := r.AssignCounts(); a.Initial != 1 || a.Short != 1 || a.Extra() != 1 {
t.Fatalf("assign counts %+v", a)
}
}
// A definite capacity refusal leaves objects already stored on the old range
// alone and moves the rest of the group to a fresh range; a volume that keeps
// refusing ends the round after a bounded number of replacements.
func TestChunkRound_CapacityRefusalReplacesRemainder(t *testing.T) {
b := newRangeFake()
b.refuse = func(fid string) error {
// The first volume is full from its third id on.
if fid == "1,0a0b0c0d0e_2" || fid == "1,0a0b0c0d0e_3" {
return errRangeRefused
}
return nil
}
r := roundRemote(t, b)
if err := putAll(t, r, 6, 1); err != nil {
t.Fatal(err)
}
checkBound(t, r, 6)
if r.fids[roundKey(0)] != "1,0a0b0c0d0e" || r.fids[roundKey(1)] != "1,0a0b0c0d0e_1" {
t.Fatalf("committed prefix moved: %s %s", r.fids[roundKey(0)], r.fids[roundKey(1)])
}
if got := b.reserveCounts(); len(got) != 2 || got[1] != 4 {
t.Fatalf("reservations %v, want a fresh range for the remaining 4", got)
}
if a := r.AssignCounts(); a.Initial != 1 || a.Capacity != 1 {
t.Fatalf("assign counts %+v", a)
}
b2 := newRangeFake()
b2.refuse = func(string) error { return errRangeRefused }
r2 := roundRemote(t, b2)
err := putAll(t, r2, 3, 1)
if !errors.Is(err, errRangeRefused) {
t.Fatalf("always-full volumes: %v; want the refusal after bounded replacements", err)
}
if got := b2.reserveCounts(); len(got) != 1+roundMaxReplacements {
t.Fatalf("%d reservations %v; want 1 + %d replacements, then stop", len(got), got, roundMaxReplacements)
}
}
// An expired token is never sent: the remainder gets a fresh range. A 401 is
// terminal: no replacement.
func TestChunkRound_TokenExpiryAndAuth(t *testing.T) {
b := newRangeFake()
calls := 0
b.auth = func() string {
calls++
if calls == 1 {
return jwtWithExp(time.Now().Add(-time.Minute).Unix())
}
return jwtWithExp(time.Now().Add(time.Hour).Unix())
}
r := roundRemote(t, b)
if err := putAll(t, r, 3, 1); err != nil {
t.Fatal(err)
}
checkBound(t, r, 3)
b.mu.Lock()
for fid, a := range b.putAuth {
if exp, ok := (blobRange{auth: a}).sendDeadline(); !ok || exp.Before(time.Now()) {
t.Fatalf("upload to %s sent with an expired token", fid)
}
}
b.mu.Unlock()
if a := r.AssignCounts(); a.Initial != 1 || a.Expired != 1 {
t.Fatalf("assign counts %+v", a)
}
b2 := newRangeFake()
b2.refuse = func(string) error { return errRangeAuth }
r2 := roundRemote(t, b2)
if err := putAll(t, r2, 2, 1); !errors.Is(err, errRangeAuth) {
t.Fatalf("401: %v", err)
}
if got := b2.reserveCounts(); len(got) != 1 {
t.Fatalf("reservations %v after a 401; want no replacement", got)
}
}
// A transient failure leaves the slot frozen: the retry sends the same fid.
func TestChunkRound_RetryKeepsTheSlot(t *testing.T) {
b := newRangeFake()
failed := false
b.refuse = func(fid string) error {
if fid == "1,0a0b0c0d0e_1" && !failed {
failed = true
return errors.New("connection reset")
}
return nil
}
r := roundRemote(t, b)
rd := r.BeginPutRound(2, 4096)
ctx := context.Background()
if err := rd.Put(ctx, 0, roundKey(0), []byte(roundKey(0))); err != nil {
t.Fatal(err)
}
if err := rd.Put(ctx, 1, roundKey(1), []byte(roundKey(1))); err == nil {
t.Fatal("transient failure reported success")
}
if err := rd.Put(ctx, 1, roundKey(1), []byte(roundKey(1))); err != nil {
t.Fatal(err)
}
b.mu.Lock()
puts := append([]string(nil), b.puts...)
b.mu.Unlock()
if len(puts) != 3 || puts[1] != "1,0a0b0c0d0e_1" || puts[2] != "1,0a0b0c0d0e_1" {
t.Fatalf("uploads %v; want the retry on the same fid", puts)
}
if got := b.reserveCounts(); len(got) != 1 {
t.Fatalf("reservations %v; a transient failure takes no new range", got)
}
// A bound key is never rebound.
if err := rd.Put(ctx, 1, roundKey(1), []byte("other")); !errors.Is(err, storage.ErrChunkKeyExists) {
t.Fatalf("rebinding a key: %v", err)
}
}
// waitFor waits for ch, failing t after a bound.
func waitFor(t *testing.T, ch <-chan struct{}, what string) {
t.Helper()
select {
case <-ch:
case <-time.After(10 * time.Second):
t.Fatalf("timed out waiting for %s", what)
}
}
// releaser closes a channel once; registered as cleanup before any worker
// that waits on it starts, so a failing test never strands that worker.
func releaser(t *testing.T) (ch chan struct{}, release func()) {
ch = make(chan struct{})
var once sync.Once
release = func() { once.Do(func() { close(ch) }) }
t.Cleanup(release)
return ch, release
}
// A reservation waiting on the filer ends with the caller's context when it
// follows it; one that ignores it is still joined (Put does not return
// before it), and its late successful reply never starts an upload.
func TestChunkRound_ReserveFollowsTheCaller(t *testing.T) {
t.Run("cooperative", func(t *testing.T) {
b := newRangeFake()
hold, _ := releaser(t)
entered := make(chan struct{})
b.reserveHook = func(ctx context.Context, _ int) error {
close(entered)
select {
case <-hold:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
r := roundRemote(t, b)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
done := make(chan error, 1)
joined := false
t.Cleanup(func() { // ends and joins the worker whatever happens below
cancel()
if joined {
return
}
select {
case <-done:
case <-time.After(10 * time.Second):
t.Error("Put never returned")
}
})
go func() { done <- r.BeginPutRound(1, 4096).Put(ctx, 0, roundKey(0), []byte("x")) }()
waitFor(t, entered, "the reservation call")
cancel()
select {
case err := <-done:
joined = true
if !errors.Is(err, context.Canceled) {
t.Fatalf("cancelled reservation: %v", err)
}
case <-time.After(10 * time.Second):
t.Fatal("Put did not end with its context")
}
})
t.Run("uncooperative", func(t *testing.T) {
b := newRangeFake()
hold, release := releaser(t)
entered := make(chan struct{})
b.reserveHook = func(context.Context, int) error { close(entered); <-hold; return nil } // ignores ctx
r := roundRemote(t, b)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
done := make(chan error, 1)
go func() { done <- r.BeginPutRound(1, 4096).Put(ctx, 0, roundKey(0), []byte("x")) }()
t.Cleanup(func() { // joins the worker whatever happens below
release()
select {
case <-done:
case <-time.After(10 * time.Second):
t.Error("Put never returned")
}
})
waitFor(t, entered, "the reservation call")
cancel()
select {
case err := <-done:
done <- err
t.Fatalf("Put returned (%v) while its admitted reservation call was still running", err)
case <-time.After(200 * time.Millisecond):
}
release() // the late reply is a success
select {
case err := <-done:
done <- err
if !errors.Is(err, context.Canceled) {
t.Fatalf("late reply after the caller gave up: %v", err)
}
case <-time.After(10 * time.Second):
t.Fatal("Put did not return after its reservation call did")
}
if puts := b.putList(); len(puts) != 0 {
t.Fatalf("uploads %v after the caller gave up", puts)
}
})
}
// A replacement reply that arrives after a lower slot retired the group's
// ranges is discarded: the group is reserved again from its first uncovered
// slot, so no slot is left uncovered (and no zero-id reservation is asked).
func TestChunkRound_StaleReplacementIsDiscarded(t *testing.T) {
b := newRangeFake()
r := roundRemote(t, b)
rd := r.BeginPutRound(4, 4096).(*putRound)
g := rd.groups[0]
second := make(chan struct{})
var secondOnce sync.Once
release, releaseAll := releaser(t)
b.reserveHook = func(ctx context.Context, call int) error {
if call == 2 {
secondOnce.Do(func() { close(second) })
select {
case <-release:
case <-ctx.Done():
return ctx.Err()
}
}
return nil
}
slot0Sent := make(chan struct{})
b.putHook = func(ctx context.Context, fid string) (bool, error) {
switch fid {
case "1,0a0b0c0d0e_1": // slot 1: refused at once
return false, errRangeRefused
case "1,0a0b0c0d0e": // slot 0: sent, refused once the replacement is in flight
close(slot0Sent)
select {
case <-second:
case <-ctx.Done():
return false, ctx.Err()
}
return false, errRangeRefused
}
return true, nil
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
errs := make(chan error, 2)
started := 0
t.Cleanup(func() { // release and join every worker started
releaseAll()
cancel()
for ; started > 0; started-- {
select {
case <-errs:
case <-time.After(10 * time.Second):
t.Error("a round worker never returned")
return
}
}
})
started++
go func() { errs <- rd.Put(ctx, 0, roundKey(0), []byte(roundKey(0))) }()
waitFor(t, slot0Sent, "slot 0's upload")
started++
go func() { errs <- rd.Put(ctx, 1, roundKey(1), []byte(roundKey(1))) }()
waitFor(t, second, "the replacement reservation")
deadline := time.Now().Add(10 * time.Second)
for { // slot 0's refusal retires the rest of the group meanwhile
g.mu.Lock()
v := g.ver
g.mu.Unlock()
if v == 2 {
break
}
if time.Now().After(deadline) {
t.Fatalf("group version %d; slot 0's refusal never retired the range", v)
}
time.Sleep(time.Millisecond)
}
releaseAll()
for started > 0 {
select {
case err := <-errs:
started-- // joined, before any Fatal: cleanup must not wait for it again
if err != nil {
t.Fatal(err)
}
case <-time.After(10 * time.Second):
t.Fatal("a round worker did not finish")
}
}
got := b.reserveCounts()
for _, n := range got {
if n <= 0 {
t.Fatalf("reservations %v: asked for %d ids", got, n)
}
}
if len(got) != 3 || got[0] != 4 || got[1] != 3 || got[2] != 4 {
t.Fatalf("reservations %v; want [4 3 4] (the stale [1,4) reply discarded)", got)
}
for i := 0; i < 2; i++ {
if fid := r.fids[roundKey(i)]; !strings.HasPrefix(fid, "3,") {
t.Fatalf("slot %d bound to %s; want the fresh range", i, fid)
}
}
if a := r.AssignCounts(); a.Initial != 1 || a.Capacity != 1 || a.Retry != 1 || a.Failed != 1 {
t.Fatalf("assign counts %+v", a)
}
}
// A lost reservation reply is counted: the retry is an extra attempt.
func TestChunkRound_LostReservationReplyIsCounted(t *testing.T) {
b := newRangeFake()
b.reserveHook = func(_ context.Context, call int) error {
if call == 1 {
return errors.New("lost assign reply")
}
return nil
}
r := roundRemote(t, b)
rd := r.BeginPutRound(1, 4096)
ctx := context.Background()
if err := rd.Put(ctx, 0, roundKey(0), []byte("x")); err == nil {
t.Fatal("lost reply reported success")
}
if err := rd.Put(ctx, 0, roundKey(0), []byte("x")); err != nil {
t.Fatal(err)
}
if a := r.AssignCounts(); a.Initial != 1 || a.Retry != 1 || a.Failed != 1 || a.Extra() != 1 {
t.Fatalf("assign counts %+v; want 1 initial + 1 retry, 1 failed", a)
}
}
// An upload whose reply was lost keeps its fid: a retry after the group's
// lower slot retired the range, or after the token expired, does not move
// it. Past expiry the fid is read back: the exact bytes are bound there,
// definitely absent bytes go to a fresh range.
func TestChunkRound_AmbiguousUploadKeepsItsFid(t *testing.T) {
ctx := context.Background()
t.Run("lower slot retires the range", func(t *testing.T) {
b := newRangeFake()
lost := true
b.putHook = func(_ context.Context, fid string) (bool, error) {
switch {
case fid == "1,0a0b0c0d0e_1" && lost:
lost = false
return false, errors.New("connection reset") // outcome unknown to the client
case fid == "1,0a0b0c0d0e":
return false, errRangeRefused
}
return true, nil
}
r := roundRemote(t, b)
rd := r.BeginPutRound(2, 4096)
if err := rd.Put(ctx, 1, roundKey(1), []byte(roundKey(1))); err == nil {
t.Fatal("lost reply reported success")
}
if err := rd.Put(ctx, 0, roundKey(0), []byte(roundKey(0))); err != nil {
t.Fatal(err)
}
if err := rd.Put(ctx, 1, roundKey(1), []byte(roundKey(1))); err != nil {
t.Fatal(err)
}
if fid := r.fids[roundKey(1)]; fid != "1,0a0b0c0d0e_1" {
t.Fatalf("retried slot bound to %s; want its first fid", fid)
}
if fid := r.fids[roundKey(0)]; !strings.HasPrefix(fid, "2,") {
t.Fatalf("refused slot bound to %s; want the fresh range", fid)
}
})
for _, stored := range []bool{true, false} {
t.Run(fmt.Sprintf("token expires, stored=%v", stored), func(t *testing.T) {
b := newRangeFake()
calls := 0
b.auth = func() string {
calls++
if calls == 1 { // expires (less skew) about a second from now
return jwtWithExp(time.Now().Add(jwtSendSkew + time.Second).Unix())
}
return jwtWithExp(time.Now().Add(time.Hour).Unix())
}
lost := true
b.putHook = func(context.Context, string) (bool, error) {
if lost {
lost = false
return stored, errors.New("reply lost")
}
return true, nil
}
r := roundRemote(t, b)
rd := r.BeginPutRound(1, 4096)
if err := rd.Put(ctx, 0, roundKey(0), []byte(roundKey(0))); err == nil {
t.Fatal("lost reply reported success")
}
b.mu.Lock()
first := b.putAuth["1,0a0b0c0d0e"]
b.mu.Unlock()
dl, _ := (blobRange{auth: first}).sendDeadline()
time.Sleep(time.Until(dl) + 10*time.Millisecond)
if err := rd.Put(ctx, 0, roundKey(0), []byte(roundKey(0))); err != nil {
t.Fatal(err)
}
fid, puts := r.fids[roundKey(0)], b.putList()
if stored {
if fid != "1,0a0b0c0d0e" || len(puts) != 1 {
t.Fatalf("stored upload: bound %s after uploads %v; want its first fid, no resend", fid, puts)
}
return
}
if !strings.HasPrefix(fid, "2,") || len(puts) != 2 {
t.Fatalf("absent upload: bound %s after uploads %v; want a fresh range", fid, puts)
}
if a := r.AssignCounts(); a.Initial != 1 || a.Expired != 1 {
t.Fatalf("assign counts %+v", a)
}
})
}
}
// An upload is sent under its token's send deadline: a queued upload ends
// there, not at the caller's later deadline.
func TestChunkRound_UploadCarriesTheTokenDeadline(t *testing.T) {
b := newRangeFake()
b.auth = func() string { return jwtWithExp(time.Now().Add(jwtSendSkew + time.Second).Unix()) }
b.putHook = func(ctx context.Context, _ string) (bool, error) {
<-ctx.Done() // queued until its context ends
return false, ctx.Err()
}
r := roundRemote(t, b)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
start := time.Now()
err := r.BeginPutRound(1, 4096).Put(ctx, 0, roundKey(0), []byte("x"))
if !errors.Is(err, context.DeadlineExceeded) || time.Since(start) > 10*time.Second {
t.Fatalf("queued upload: %v after %v; want it ended at the token's deadline", err, time.Since(start))
}
b.mu.Lock()
defer b.mu.Unlock()
for f, a := range b.putAuth {
dl, _ := (blobRange{auth: a}).sendDeadline()
if !b.putDL[f].Equal(dl) {
t.Fatalf("upload to %s sent under deadline %v; want the token's %v", f, b.putDL[f], dl)
}
}
}
// A rejected token and used-up replacements are final for the caller; a
// transient failure is not.
func TestChunkRound_FinalOutcomes(t *testing.T) {
put := func(b *rangeFake) error {
return roundRemote(t, b).BeginPutRound(1, 4096).Put(context.Background(), 0, roundKey(0), []byte("x"))
}
b := newRangeFake()
b.refuse = func(string) error { return errRangeAuth }
if err := put(b); !errors.Is(err, storage.ErrChunkPutFinal) {
t.Fatalf("401: %v; want final", err)
}
b2 := newRangeFake()
b2.refuse = func(string) error { return errRangeRefused }
if err := put(b2); !errors.Is(err, storage.ErrChunkPutFinal) {
t.Fatalf("replacements used up: %v; want final", err)
}
b3 := newRangeFake()
b3.refuse = func(string) error { return errors.New("connection reset") }
if err := put(b3); err == nil || errors.Is(err, storage.ErrChunkPutFinal) {
t.Fatalf("transient failure: %v; want retryable", err)
}
}
+1 -27
View File
@@ -1,9 +1,7 @@
package chunkstore
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
@@ -219,33 +217,9 @@ func (c *SWFS) Put(ctx context.Context, data []byte) (string, error) {
if ar.GetFileId() == "" || ar.GetLocation().GetUrl() == "" {
return "", fmt.Errorf("chunkstore: assign returned no fid/location")
}
u := "http://" + ar.Location.Url + "/" + ar.FileId
if ar.GetFsync() {
u += "?fsync=true"
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(data))
if err != nil {
if err := c.upload(ctx, ar.Location.Url, ar.FileId, ar.GetAuth(), ar.GetFsync(), data); err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/octet-stream")
if ar.GetAuth() != "" {
req.Header.Set("Authorization", "BEARER "+ar.Auth)
}
resp, err := c.http.Do(req)
if err != nil {
return "", fmt.Errorf("chunkstore: upload %s: %w", ar.FileId, err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
if resp.StatusCode/100 != 2 {
return "", fmt.Errorf("chunkstore: upload %s: http %d: %s", ar.FileId, resp.StatusCode, strings.TrimSpace(string(body)))
}
var ur struct {
Error string `json:"error"`
}
if json.Unmarshal(body, &ur) == nil && ur.Error != "" {
return "", fmt.Errorf("chunkstore: upload %s: %s", ar.FileId, ur.Error)
}
return ar.FileId, nil
}
@@ -0,0 +1,262 @@
package chunkstore
// Batch assign: one AssignVolume(Count = n) reserves n consecutive needle ids
// on one volume. They are addressed in SeaweedFS's native form: offset 0 is
// the base fid, offset i is "<base>_<i>". The volume server adds i to the
// needle key and checks the assign's token against the base fid, so every
// offset carries the base's token and shares its cookie. Never write such an
// id as a different fid (key+i): that one has no token.
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
)
const (
// maxRangeCount bounds one reservation.
maxRangeCount = 1 << 16
// jwtSendSkew: an upload is not sent within this much of its token's
// stated expiry.
jwtSendSkew = 2 * time.Second
)
var (
// errRangeRefused: the volume refused the write before appending it
// (read-only or full). Nothing was stored; a fresh range may take it.
errRangeRefused = errors.New("chunkstore: volume refused the write before append")
// errRangeAuth: the volume rejected the upload's token. Terminal.
errRangeAuth = errors.New("chunkstore: volume rejected the upload token")
// errBlobAbsent: the volume server holding a range has no needle at
// the probed fid.
errBlobAbsent = errors.New("chunkstore: no needle at fid")
)
// blobRange is one batch reservation: count ids starting at base, on the
// volume server at url, with the assign's token and fsync policy.
type blobRange struct {
base string
count int
url string
auth string
fsync bool
}
// fid returns the native id of offset i.
func (r blobRange) fid(i int) (string, error) {
if i < 0 || i >= r.count {
return "", fmt.Errorf("chunkstore: offset %d outside a range of %d ids", i, r.count)
}
if i == 0 {
return r.base, nil
}
return r.base + "_" + strconv.Itoa(i), nil
}
// sendDeadline is the last time an upload with this range's token may be
// sent: the token's stated expiry less jwtSendSkew. The claim is read, not
// verified: it only ever stops an upload, it never authorizes one. A token
// without a readable expiry gives no deadline.
func (r blobRange) sendDeadline() (time.Time, bool) {
parts := strings.Split(r.auth, ".")
if len(parts) != 3 {
return time.Time{}, false
}
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return time.Time{}, false
}
var claims struct {
Exp *int64 `json:"exp"`
}
if json.Unmarshal(payload, &claims) != nil || claims.Exp == nil {
return time.Time{}, false
}
return time.Unix(*claims.Exp, 0).Add(-jwtSendSkew), true
}
// rangeBlobs is the optional batch capability of a blob store.
type rangeBlobs interface {
reserve(ctx context.Context, n int, objSize uint64) (blobRange, error)
putRange(ctx context.Context, r blobRange, i int, data []byte) error
// probe reads offset i back from the range's volume server:
// errBlobAbsent when that server definitely has no such needle.
probe(ctx context.Context, r blobRange, i int) ([]byte, error)
}
var _ rangeBlobs = (*SWFS)(nil)
// validBaseFid checks "<vid>,<key><cookie>" for a range of count ids: a
// 32-bit decimal volume id, a 64-bit hex needle key (1 to 16 digits) and an
// 8-digit hex cookie, no offset suffix, and room for key + count - 1.
func validBaseFid(fid string, count int) error {
vid, kc, ok := strings.Cut(fid, ",")
if !ok || vid == "" {
return fmt.Errorf("chunkstore: assign fid %q has no volume id", fid)
}
if _, err := strconv.ParseUint(vid, 10, 32); err != nil {
return fmt.Errorf("chunkstore: assign fid %q: volume id: %v", fid, err)
}
if len(kc) <= 8 || len(kc) > 16+8 {
return fmt.Errorf("chunkstore: assign fid %q: want a 1..16 digit key and an 8 digit cookie", fid)
}
for _, c := range kc {
if !strings.ContainsRune("0123456789abcdefABCDEF", c) {
return fmt.Errorf("chunkstore: assign fid %q: not a plain hex key and cookie", fid)
}
}
key, err := strconv.ParseUint(kc[:len(kc)-8], 16, 64)
if err != nil {
return fmt.Errorf("chunkstore: assign fid %q: key: %v", fid, err)
}
if count > 0 && key > math.MaxUint64-uint64(count-1) {
return fmt.Errorf("chunkstore: assign fid %q: key + %d overflows", fid, count-1)
}
return nil
}
// validHostPort checks a volume server location: a plain host:port HTTP
// authority ([v6]:port included), with no scheme, path, user, escape,
// space or control byte, so the range's uploads can be addressed at all.
func validHostPort(loc string) error {
for _, c := range loc {
if c <= ' ' || c == 0x7f || strings.ContainsRune("/?#@\\", c) {
return fmt.Errorf("chunkstore: assign location %q: not a plain host:port", loc)
}
}
host, port, err := net.SplitHostPort(loc)
if err != nil {
return fmt.Errorf("chunkstore: assign location %q: %v", loc, err)
}
if host == "" {
return fmt.Errorf("chunkstore: assign location %q: no host", loc)
}
if p, err := strconv.ParseUint(port, 10, 16); err != nil || p == 0 {
return fmt.Errorf("chunkstore: assign location %q: bad port", loc)
}
if u, err := url.Parse("http://" + loc + "/"); err != nil || u.Host != loc {
return fmt.Errorf("chunkstore: assign location %q: not an HTTP authority", loc)
}
return nil
}
// reserve asks for n ids of objSize bytes each (the master counts
// ExpectedDataSize per id). A shorter valid grant is returned as is; the
// caller reserves the rest.
func (c *SWFS) reserve(ctx context.Context, n int, objSize uint64) (blobRange, error) {
if n <= 0 || n > maxRangeCount {
return blobRange{}, fmt.Errorf("chunkstore: reserve %d ids: want 1..%d", n, maxRangeCount)
}
ar, err := c.fc.AssignVolume(ctx, &filerpb.AssignVolumeRequest{
Count: int32(n),
Collection: c.cfg.Collection,
Replication: c.cfg.Replication,
Path: c.cfg.AssignPath,
ExpectedDataSize: objSize,
})
if err != nil {
return blobRange{}, fmt.Errorf("chunkstore: assign %d: %w", n, err)
}
if ar.GetError() != "" {
return blobRange{}, fmt.Errorf("chunkstore: assign %d: %s", n, ar.GetError())
}
if err := validHostPort(ar.GetLocation().GetUrl()); err != nil {
return blobRange{}, err
}
count := int(ar.GetCount())
if count <= 0 || count > n {
return blobRange{}, fmt.Errorf("chunkstore: assign %d returned %d ids", n, count)
}
if err := validBaseFid(ar.GetFileId(), count); err != nil {
return blobRange{}, err
}
return blobRange{base: ar.FileId, count: count, url: ar.Location.Url, auth: ar.GetAuth(), fsync: ar.GetFsync()}, nil
}
// putRange uploads data as offset i of r. A refusal before append is
// errRangeRefused, a rejected token errRangeAuth; any other failure is
// returned as is (the caller retries the same offset).
func (c *SWFS) putRange(ctx context.Context, r blobRange, i int, data []byte) error {
fid, err := r.fid(i)
if err != nil {
return err
}
return c.upload(ctx, r.url, fid, r.auth, r.fsync, data)
}
// probe GETs offset i from the range's own volume server.
func (c *SWFS) probe(ctx context.Context, r blobRange, i int) ([]byte, error) {
fid, err := r.fid(i)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+r.url+"/"+fid, nil)
if err != nil {
return nil, err
}
resp, err := c.http.Do(req)
if err != nil {
return nil, fmt.Errorf("chunkstore: probe %s: %w", fid, err)
}
defer resp.Body.Close()
switch resp.StatusCode {
case http.StatusOK:
return io.ReadAll(resp.Body)
case http.StatusNotFound:
return nil, fmt.Errorf("%w %s", errBlobAbsent, fid)
}
return nil, fmt.Errorf("chunkstore: probe %s: http %d", fid, resp.StatusCode)
}
// upload POSTs data raw to fid on the volume server at host.
func (c *SWFS) upload(ctx context.Context, host, fid, auth string, fsync bool, data []byte) error {
u := "http://" + host + "/" + fid
if fsync {
u += "?fsync=true"
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(data))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/octet-stream")
if auth != "" {
req.Header.Set("Authorization", "BEARER "+auth)
}
resp, err := c.http.Do(req)
if err != nil {
return fmt.Errorf("chunkstore: upload %s: %w", fid, err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
if resp.StatusCode/100 != 2 {
err := fmt.Errorf("chunkstore: upload %s: http %d: %s", fid, resp.StatusCode, strings.TrimSpace(string(body)))
switch {
case resp.StatusCode == http.StatusUnauthorized:
return errors.Join(errRangeAuth, err)
case resp.StatusCode == http.StatusConflict,
resp.Header.Get("X-Seaweed-Write-Outcome") == "refused-before-append":
return errors.Join(errRangeRefused, err)
}
return err
}
var ur struct {
Error string `json:"error"`
}
if json.Unmarshal(body, &ur) == nil && ur.Error != "" {
return fmt.Errorf("chunkstore: upload %s: %s", fid, ur.Error)
}
return nil
}
@@ -0,0 +1,108 @@
//go:build chunkstore_integration
package chunkstore
import (
"bytes"
"context"
"errors"
"fmt"
"strconv"
"strings"
"testing"
"time"
)
const jwtSecurity = `[jwt.signing]
key = "batch-assign-integration"
expires_after_seconds = 60
`
// arithmeticFid is the fid key+i with the base's cookie: a different needle
// id, which the base's token does not cover.
func arithmeticFid(t *testing.T, base string, i int) string {
t.Helper()
vid, kc, _ := strings.Cut(base, ",")
key, err := strconv.ParseUint(kc[:len(kc)-8], 16, 64)
if err != nil {
t.Fatal(err)
}
return fmt.Sprintf("%s,%x%s", vid, key+uint64(i), kc[len(kc)-8:])
}
// With JWT on, every offset of a reservation is written with the base's
// token in the native "<base>_<i>" form and reads back as itself; the same
// token on the arithmetic fid key+i is refused.
func TestIntegrationBatch_JWTNativeOffsets(t *testing.T) {
c := startWeedWith(t, jwtSecurity)
cl := c.client(t, "/swblock/vols/v1")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
const n = 5
r, err := cl.reserve(ctx, n, 4096)
if err != nil {
t.Fatal(err)
}
if r.auth == "" {
t.Fatal("assign with JWT on returned no token")
}
if r.count != n {
t.Fatalf("reserved %d of %d", r.count, n)
}
data := func(i int) []byte { return bytes.Repeat([]byte(fmt.Sprintf("offset-%d|", i)), 400) }
for _, i := range []int{0, 2, n - 1} { // first, middle, last
if err := cl.putRange(ctx, r, i, data(i)); err != nil {
t.Fatalf("offset %d: %v", i, err)
}
}
for _, i := range []int{0, 2, n - 1} {
fid, _ := r.fid(i)
got, err := cl.Get(ctx, fid)
if err != nil || !bytes.Equal(got, data(i)) {
t.Fatalf("offset %d (%s) read back %d bytes, %v", i, fid, len(got), err)
}
}
arith := arithmeticFid(t, r.base, 1)
err = cl.upload(ctx, r.url, arith, r.auth, r.fsync, data(1))
if !errors.Is(err, errRangeAuth) {
t.Fatalf("upload to the arithmetic fid %s with the base token: %v; want a rejected token", arith, err)
}
}
// A round of more than one group writes through real assigns, binds every
// key, and reads every key back; it takes one assign per group.
func TestIntegrationBatch_RoundBindsAndReadsBack(t *testing.T) {
c := startWeedWith(t, jwtSecurity)
cl := c.client(t, "/swblock/vols/v1")
r, err := NewChunkRemote(cl, cl, "/swblock/vols/v1")
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
const n = 130 // three groups
rd := r.BeginPutRound(n, 4096)
for i := 0; i < n; i++ {
if err := rd.Put(ctx, i, roundKey(i), []byte(roundKey(i))); err != nil {
t.Fatalf("object %d: %v", i, err)
}
}
for i := 0; i < n; i++ {
got, err := r.Get(ctx, roundKey(i))
if err != nil || !bytes.Equal(got, []byte(roundKey(i))) {
t.Fatalf("key %d read back %q, %v", i, got, err)
}
}
if a := r.AssignCounts(); a.Initial != 3 || a.Extra() != 0 {
t.Fatalf("assign counts %+v; want 3 initial", a)
}
suffixed := 0
for i := 0; i < n; i++ {
if strings.Contains(r.fids[roundKey(i)], "_") {
suffixed++
}
}
if suffixed != n-3 {
t.Fatalf("%d of %d bindings use an offset fid; want all but the 3 bases", suffixed, n)
}
}
@@ -0,0 +1,285 @@
package chunkstore
import (
"bytes"
"context"
"encoding/base64"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
)
// batchVolume is a volume server that records every upload by its path (the
// fid as sent), with the Authorization header and query.
type batchVolume struct {
mu sync.Mutex
stored map[string][]byte
auth map[string]string
query map[string]string
refuse func(fid string) (status int, header string) // non-zero status: refuse
srv *httptest.Server
uploads []string
}
func newBatchVolume(t *testing.T) *batchVolume {
v := &batchVolume{stored: map[string][]byte{}, auth: map[string]string{}, query: map[string]string{}}
v.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fid := strings.TrimPrefix(r.URL.Path, "/")
b, _ := io.ReadAll(r.Body)
v.mu.Lock()
defer v.mu.Unlock()
if r.Method != http.MethodPost {
if d, ok := v.stored[fid]; ok {
_, _ = w.Write(d)
return
}
w.WriteHeader(http.StatusNotFound)
return
}
v.uploads = append(v.uploads, fid)
if v.refuse != nil {
if st, h := v.refuse(fid); st != 0 {
if h != "" {
w.Header().Set("X-Seaweed-Write-Outcome", h)
}
w.WriteHeader(st)
_, _ = w.Write([]byte(`{"error":"refused"}`))
return
}
}
v.stored[fid] = b
v.auth[fid] = r.Header.Get("Authorization")
v.query[fid] = r.URL.RawQuery
w.WriteHeader(http.StatusCreated)
_, _ = w.Write([]byte(`{"size":1}`))
}))
t.Cleanup(v.srv.Close)
return v
}
func (v *batchVolume) host() string { return strings.TrimPrefix(v.srv.URL, "http://") }
func (v *batchVolume) snapshot() (uploads []string, stored map[string][]byte, auth map[string]string) {
v.mu.Lock()
defer v.mu.Unlock()
stored, auth = map[string][]byte{}, map[string]string{}
for k, d := range v.stored {
stored[k] = d
}
for k, a := range v.auth {
auth[k] = a
}
return append([]string(nil), v.uploads...), stored, auth
}
// One reservation of n ids is addressed in SeaweedFS's native form: offset 0
// is the base fid, offset i is "<base>_<i>"; every offset carries the base's
// token and the assign's fsync policy.
func TestSWFSRange_NativeOffsetFids(t *testing.T) {
vol := newBatchVolume(t)
f := &fakeFilerGRPC{assignResp: &filerpb.AssignVolumeResponse{FileId: "7,01abcdef12", Count: 3, Auth: "tok", Fsync: true, Location: &filerpb.Location{Url: vol.host()}}}
c := startFakeFiler(t, f)
ctx := context.Background()
r, err := c.reserve(ctx, 3, 4096)
if err != nil {
t.Fatal(err)
}
if f.lastAssign.Count != 3 || f.lastAssign.ExpectedDataSize != 4096 || f.lastAssign.Collection != "swblock" || f.lastAssign.Path != "/swblock/vols/v1" {
t.Fatalf("assign request %+v; want count 3 and the per-object expected size", f.lastAssign)
}
want := []string{"7,01abcdef12", "7,01abcdef12_1", "7,01abcdef12_2"}
for i, w := range want {
fid, err := r.fid(i)
if err != nil || fid != w {
t.Fatalf("offset %d: fid %q %v, want %q", i, fid, err, w)
}
if err := c.putRange(ctx, r, i, []byte(fmt.Sprintf("obj%d", i))); err != nil {
t.Fatalf("offset %d: %v", i, err)
}
}
_, stored, auth := vol.snapshot()
vol.mu.Lock()
query := vol.query
vol.mu.Unlock()
for i, w := range want {
if !bytes.Equal(stored[w], []byte(fmt.Sprintf("obj%d", i))) {
t.Fatalf("offset %d stored %q at %s", i, stored[w], w)
}
if auth[w] != "BEARER tok" {
t.Fatalf("offset %d authorization %q; want the base token", i, auth[w])
}
if q := query[w]; q != "fsync=true" {
t.Fatalf("offset %d query %q; want the assign's fsync policy", i, q)
}
}
for _, i := range []int{-1, 3, 4} {
if fid, err := r.fid(i); err == nil {
t.Fatalf("offset %d outside a range of 3 gave fid %q", i, fid)
}
}
}
// A reservation reply is checked before any id in it is used.
func TestSWFSRange_ReserveValidates(t *testing.T) {
loc := &filerpb.Location{Url: "127.0.0.1:1"}
for _, c := range []struct {
name string
n int
resp *filerpb.AssignVolumeResponse
ok bool
want int
}{
{"full grant", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: loc}, true, 4},
{"short grant", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 2, Location: loc}, true, 2},
{"zero count", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 0, Location: loc}, false, 0},
{"more than asked", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 5, Location: loc}, false, 0},
{"no location", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4}, false, 0},
{"no fid", 4, &filerpb.AssignVolumeResponse{Count: 4, Location: loc}, false, 0},
{"fid with a suffix", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e_1", Count: 4, Location: loc}, false, 0},
{"fid without a comma", 4, &filerpb.AssignVolumeResponse{FileId: "30a0b0c0d0e", Count: 4, Location: loc}, false, 0},
{"non-numeric volume", 4, &filerpb.AssignVolumeResponse{FileId: "x,0a0b0c0d0e", Count: 4, Location: loc}, false, 0},
{"non-hex key", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0dzz", Count: 4, Location: loc}, false, 0},
{"key too short for a cookie", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d", Count: 4, Location: loc}, false, 0},
{"assign error", 4, &filerpb.AssignVolumeResponse{Error: "no free volumes"}, false, 0},
{"location with a scheme", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "http://127.0.0.1:1"}}, false, 0},
{"location without a port", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "127.0.0.1"}}, false, 0},
{"location with a bad port", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "127.0.0.1:x"}}, false, 0},
{"location with port 0", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "127.0.0.1:0"}}, false, 0},
{"location with a path", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "a/b:1"}}, false, 0},
{"location with a tab", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "127.0.0.1\t:1"}}, false, 0},
{"location with a newline", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "a\nb:1"}}, false, 0},
{"location with a bad escape", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "a%zz:1"}}, false, 0},
{"location with an escape", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "a%41:1"}}, false, 0},
{"location with a space", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "a b:1"}}, false, 0},
{"location with a user", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "u@a:1"}}, false, 0},
{"bracketed IPv6 location", 4, &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 4, Location: &filerpb.Location{Url: "[::1]:8080"}}, true, 4},
{"widest key", 4, &filerpb.AssignVolumeResponse{FileId: "3,0123456789abcdef0a0b0c0d", Count: 4, Location: loc}, true, 4},
{"key of 17 digits (leading zero)", 4, &filerpb.AssignVolumeResponse{FileId: "3,00123456789abcdef0a0b0c0d", Count: 4, Location: loc}, false, 0},
{"key wider than 64 bits", 4, &filerpb.AssignVolumeResponse{FileId: "3,10123456789abcdef0a0b0c0d", Count: 4, Location: loc}, false, 0},
{"last offset fits", 2, &filerpb.AssignVolumeResponse{FileId: "3,fffffffffffffffe0a0b0c0d", Count: 2, Location: loc}, true, 2},
{"last offset overflows the key", 3, &filerpb.AssignVolumeResponse{FileId: "3,fffffffffffffffe0a0b0c0d", Count: 3, Location: loc}, false, 0},
{"volume id wider than 32 bits", 4, &filerpb.AssignVolumeResponse{FileId: "4294967296,0a0b0c0d0e", Count: 4, Location: loc}, false, 0},
} {
t.Run(c.name, func(t *testing.T) {
s := startFakeFiler(t, &fakeFilerGRPC{assignResp: c.resp})
r, err := s.reserve(context.Background(), c.n, 4096)
if c.ok != (err == nil) {
t.Fatalf("reserve: %+v %v; want ok=%v", r, err, c.ok)
}
if c.ok && r.count != c.want {
t.Fatalf("count %d, want %d", r.count, c.want)
}
})
}
for _, n := range []int{1, 256, 4096} {
s := startFakeFiler(t, &fakeFilerGRPC{assignResp: &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: int32(n), Location: loc}})
r, err := s.reserve(context.Background(), n, 4096)
if err != nil || r.count != n {
t.Fatalf("reserve %d: %+v %v", n, r, err)
}
if _, err := r.fid(n - 1); err != nil {
t.Fatalf("reserve %d: last offset: %v", n, err)
}
if fid, err := r.fid(n); err == nil {
t.Fatalf("reserve %d: offset %d gave %q", n, n, fid)
}
}
// A rejected location leaves nothing to upload to: a round over it makes
// no upload at all.
vol := newBatchVolume(t)
bad := startFakeFiler(t, &fakeFilerGRPC{assignResp: &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 2, Location: &filerpb.Location{Url: vol.host() + "\t"}}})
rr, err := NewChunkRemote(newFakeFiler(), bad, "/swblock/vols/v1")
if err != nil {
t.Fatal(err)
}
if err := rr.BeginPutRound(2, 4096).Put(context.Background(), 0, "k00000", []byte("x")); err == nil {
t.Fatal("round over a malformed location stored an object")
}
if uploads, _, _ := vol.snapshot(); len(uploads) != 0 {
t.Fatalf("uploads %v after a malformed location", uploads)
}
s := startFakeFiler(t, &fakeFilerGRPC{assignResp: &filerpb.AssignVolumeResponse{FileId: "3,0a0b0c0d0e", Count: 1, Location: loc}})
for _, n := range []int{0, -1, maxRangeCount + 1} {
if _, err := s.reserve(context.Background(), n, 4096); err == nil {
t.Fatalf("reserve of %d ids accepted", n)
}
}
}
// A read-only volume (409, or a write refused before append) is a definite
// refusal: nothing was appended, so a fresh range may take the object. A 401
// is terminal. Anything else is not classified (the caller retries the same
// slot).
func TestSWFSRange_PutClassifiesRefusals(t *testing.T) {
vol := newBatchVolume(t)
f := &fakeFilerGRPC{assignResp: &filerpb.AssignVolumeResponse{FileId: "7,01abcdef12", Count: 4, Location: &filerpb.Location{Url: vol.host()}}}
c := startFakeFiler(t, f)
ctx := context.Background()
r, err := c.reserve(ctx, 4, 4096)
if err != nil {
t.Fatal(err)
}
vol.mu.Lock()
vol.refuse = func(fid string) (int, string) {
switch fid {
case "7,01abcdef12":
return http.StatusConflict, ""
case "7,01abcdef12_1":
return http.StatusInternalServerError, "refused-before-append"
case "7,01abcdef12_2":
return http.StatusUnauthorized, ""
case "7,01abcdef12_3":
return http.StatusInternalServerError, ""
}
return 0, ""
}
vol.mu.Unlock()
for i, want := range []error{errRangeRefused, errRangeRefused, errRangeAuth, nil} {
err := c.putRange(ctx, r, i, []byte("x"))
if err == nil {
t.Fatalf("offset %d: refused upload reported success", i)
}
for _, e := range []error{errRangeRefused, errRangeAuth} {
if errors.Is(err, e) != (e == want) {
t.Fatalf("offset %d: %v; classified as %v=%v, want %v", i, err, e, errors.Is(err, e), want)
}
}
}
}
// jwtWithExp returns an unsigned token whose payload names exp (unix seconds).
func jwtWithExp(exp int64) string {
enc := base64.RawURLEncoding
return enc.EncodeToString([]byte(`{"alg":"HS256","typ":"JWT"}`)) + "." +
enc.EncodeToString([]byte(fmt.Sprintf(`{"exp":%d,"fid":"7,01abcdef12"}`, exp))) + ".sig"
}
// The send deadline of a range is its token's stated expiry less a skew; a
// token with no readable expiry gives no deadline.
func TestSWFSRange_TokenSendDeadline(t *testing.T) {
now := time.Unix(1700000000, 0)
for _, c := range []struct {
name string
auth string
ok bool
want time.Time
}{
{"no token", "", false, time.Time{}},
{"opaque token", "tok", false, time.Time{}},
{"no exp claim", base64.RawURLEncoding.EncodeToString([]byte(`{}`)) + "." + base64.RawURLEncoding.EncodeToString([]byte(`{"fid":"x"}`)) + ".s", false, time.Time{}},
{"exp", jwtWithExp(now.Unix() + 10), true, now.Add(10*time.Second - jwtSendSkew)},
} {
got, ok := blobRange{auth: c.auth}.sendDeadline()
if ok != c.ok || !got.Equal(c.want) {
t.Errorf("%s: deadline %v %v, want %v %v", c.name, got, ok, c.want, c.ok)
}
}
}
@@ -21,6 +21,13 @@ func SetTestDetachTrace(p *DurableProvider, f func(stage string, deadline time.T
p.testDetachTrace = f
}
// SetTestChunkLoopTrace observes the cut loop's periodic cuts: "due" with the
// last cut it decided from, then "cut" with whether it was skipped
// (test-only; set before the volume opens).
func SetTestChunkLoopTrace(p *DurableProvider, f func(event string, lastCutNs int64, skipped bool)) {
p.testChunkLoopTrace = f
}
// SetTestBeforeIOLock runs f in the backend's admission, right before the I/O
// lock (test-only).
func SetTestBeforeIOLock(b frontend.Backend, f func()) { b.(*StorageBackend).testBeforeIOLock = f }
@@ -228,6 +228,10 @@ type DurableProvider struct {
// observes the detach's stages and their deadlines ("cut", "settle").
testDetachStopIO func(ctx context.Context) error
testDetachTrace func(stage string, deadline time.Time)
// testChunkLoopTrace, test-only, observes the cut loop's periodic cuts:
// "due" when it decides one from lastCutNs, then "cut" with whether it
// was skipped.
testChunkLoopTrace func(event string, lastCutNs int64, skipped bool)
// testBeforeChunkFreshRetire holds the real post-presence/pre-marker boundary.
testBeforeChunkFreshRetire func() error
@@ -760,7 +760,28 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer
if !ok {
continue
}
_, err := layer.Cut(ctx)
trace := p.testChunkLoopTrace
if trace != nil {
trace("due", ls.LastCutNs, false)
}
var err error
if pc, ok := layer.(storage.ChunkPeriodicCutter); ok {
// A cut that completed after this decision (an explicit one
// running meanwhile) restarted the timer: no cut now.
var skipped bool
_, skipped, err = pc.CutUnlessCutSince(ctx, ls.LastCutNs)
if trace != nil {
trace("cut", ls.LastCutNs, skipped)
}
if skipped {
continue
}
} else {
_, err = layer.Cut(ctx)
if trace != nil {
trace("cut", ls.LastCutNs, false)
}
}
s = pol.after(s, start, time.Now(), err)
if err != nil && !errors.Is(err, storage.ErrChunkCaptureRefused) && ctx.Err() == nil {
log.Printf("durable: %s chunk cut for volume=%s: %v (retry in %s)", reason, volumeID, err, s.backoff)
@@ -886,6 +907,15 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st
return p.detachVolume(ctx, volumeID, false)
}
// DetachVolumeFrozen uses one budgeted cut when the guest is already frozen.
func (p *DurableProvider) DetachVolumeFrozen(ctx context.Context, volumeID string, opts storage.FrozenDetachOptions) (storage.ChunkCutResult, uint64, error) {
ctx, err := storage.WithFrozenDetach(ctx, opts)
if err != nil {
return storage.ChunkCutResult{}, 0, err
}
return p.detachVolume(ctx, volumeID, false)
}
// ErrPlainDetachBusy refuses a plain detach without closing frontend admission.
var ErrPlainDetachBusy = errors.New("durable: plain detach requires idle frontend I/O")
@@ -913,11 +943,15 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla
return storage.ChunkCutResult{}, 0, err
}
}
precopy := p.cfg.ChunkDetachPrecopy && !plain
guestFreeze, guestFrozen := storage.FrozenDetachFromContext(ctx)
precopy := (p.cfg.ChunkDetachPrecopy || guestFrozen) && !plain
freeze := p.cfg.DetachFreezeTimeout
if freeze <= 0 {
freeze = defaultDetachFreezeTimeout
}
if guestFrozen && !guestFreeze.AllowOverBudget {
freeze = detachFreezeTarget
}
// One freeze budget covers the drain, the final cut AND the settlement:
// the cut gets three quarters, the settlement what is left. The bound is
// cooperative (contexts): a syscall that never returns is not bounded here.
@@ -934,10 +968,27 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla
cutCtx, cancel := context.WithCancelCause(accountCtx)
defer cancel(context.Canceled)
var timer *time.Timer
var settleDeadline time.Time
beginFreeze := func() {
if timer != nil {
return
}
start = time.Now()
if guestFrozen {
start = guestFreeze.StartedAt
}
casAtFreeze = countCAS()
timer = time.AfterFunc(freeze*3/4, func() { cancel(context.DeadlineExceeded) })
operationStart := start
if guestFrozen && guestFreeze.AllowOverBudget {
operationStart = time.Now()
}
settleDeadline = operationStart.Add(freeze)
remaining := max(time.Duration(0), time.Until(settleDeadline))
// An already exhausted normal guest budget must reach the no-I/O
// forecast refusal, rather than racing a zero-delay cancellation.
if remaining > 0 {
timer = time.AfterFunc(remaining*3/4, func() { cancel(context.DeadlineExceeded) })
}
}
defer func() {
if timer != nil {
@@ -959,6 +1010,9 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla
}
}
var r storage.ChunkCutResult
if guestFrozen {
beginFreeze()
}
if precopy {
owner, ok := layer.(interface {
PrecopyDetachWithAdmission(context.Context, func(context.Context) (func(), error), func() bool) (storage.ChunkCutResult, error)
@@ -981,12 +1035,21 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla
})
// Log only after capture releases its barrier; at most five records.
for _, a := range r.Precopy.Rounds {
p := a.FixedParts
log.Printf("durable: pre-copy fixed spans volume=%s attempt=%d candidate_ms=%.3f window_setup_ms=%.3f publish_prepare_ms=%.3f manifest_ms=%.3f commit_state_ms=%.3f intent_cleanup_ms=%.3f non_payload_copy_ms=%.3f barrier_overage_ms=%.3f live_drain_ms=%.3f live_capture_lock_ms=%.3f live_sync_ms=%.3f live_candidate_ms=%.3f live_other_ms=%.3f live_sync_lifecycle_wait_ms=%.3f live_sync_store_wait_ms=%.3f live_sync_group_commit_ms=%.3f live_sync_completion_wait_ms=%.3f", volumeID, a.Attempt, float64(p.Candidate)/float64(time.Millisecond), float64(p.WindowSetup)/float64(time.Millisecond), float64(p.PublishPrepare)/float64(time.Millisecond), float64(p.Manifest)/float64(time.Millisecond), float64(p.CommitState)/float64(time.Millisecond), float64(p.IntentCleanup)/float64(time.Millisecond), float64(p.NonPayloadCopy)/float64(time.Millisecond), float64(a.BarrierOverage)/float64(time.Millisecond), float64(a.BarrierParts.Drain)/float64(time.Millisecond), float64(a.BarrierParts.StoreLock)/float64(time.Millisecond), float64(a.BarrierParts.DataSync)/float64(time.Millisecond), float64(a.BarrierParts.Candidate)/float64(time.Millisecond), float64(a.BarrierParts.Other)/float64(time.Millisecond), float64(a.BarrierParts.SyncPhases.LifecycleWaitNs)/float64(time.Millisecond), float64(a.BarrierParts.SyncPhases.StoreWaitNs)/float64(time.Millisecond), float64(a.BarrierParts.SyncPhases.GroupCommitNs)/float64(time.Millisecond), float64(a.BarrierParts.SyncPhases.CompletionWaitNs)/float64(time.Millisecond))
log.Printf("durable: pre-copy attempt volume=%s attempt=%d drain_ms=%.3f barrier_ms=%.3f pause_ms=%.3f reason=%s tail=%d rate_samples=%d estimate_ms=%.3f frozen=%t fixed_ms=%.3f drain_cost_ms=%.3f store_lock_ms=%.3f local_sync_ms=%.3f head_cas_ms=%.3f readback_ms=%.3f map_persist_ms=%.3f other_fixed_ms=%.3f tail_ms=%.3f declared_freeze_ms=%.3f err=%s", volumeID, a.Attempt, float64(a.Drain)/float64(time.Millisecond), float64(a.Barrier)/float64(time.Millisecond), float64(a.Pause)/float64(time.Millisecond), a.Reason, a.TailBytes, a.RateSamples, float64(a.Estimate)/float64(time.Millisecond), a.Frozen, float64(a.Fixed)/float64(time.Millisecond), float64(a.FixedParts.Drain)/float64(time.Millisecond), float64(a.FixedParts.StoreLock)/float64(time.Millisecond), float64(a.FixedParts.DataSync)/float64(time.Millisecond), float64(a.FixedParts.HeadCAS)/float64(time.Millisecond), float64(a.FixedParts.HeadReadback)/float64(time.Millisecond), float64(a.FixedParts.MapPersist)/float64(time.Millisecond), float64(a.FixedParts.Other)/float64(time.Millisecond), float64(a.TailEstimate)/float64(time.Millisecond), float64(a.DeclaredFreeze)/float64(time.Millisecond), a.Error)
}
log.Printf("durable: pre-copy volume=%s attempts=%d measurement_rounds=%d samples_at_start=%d tail=%d rate=%.0f sample_age=%s fixed=%s estimate=%s frozen=%t reason=%s err=%v", volumeID, r.Precopy.Attempts, r.Precopy.MeasurementRounds, r.Precopy.SamplesAtStart, r.Precopy.TailBytes, r.Precopy.BytesPerSecond, r.Precopy.SampleAge, r.Precopy.Fixed, r.Precopy.Estimate, r.Precopy.Frozen, r.Precopy.Reason, err)
if err == nil {
if !start.IsZero() {
r.Precopy.Finish(time.Since(start)+r.Precopy.BarrierBeforeFreeze, 0, false)
if !start.IsZero() && !r.Precopy.IsReplay() {
elapsed := time.Since(start)
if !guestFrozen {
elapsed += r.Precopy.BarrierBeforeFreeze
}
r.Precopy.Finish(elapsed, 0, false)
if recorder, ok := layer.(interface{ RememberDetachReport(storage.PrecopyReport) }); ok {
recorder.RememberDetachReport(r.Precopy)
}
}
return r, h.storage.NextLSN() - 1, nil
}
@@ -1036,7 +1099,7 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla
// resumes: an earlier detach that applied, an unresolved detach CAS or a
// fenced layer must never resume serving. The settlement keeps the rest
// of the freeze budget even when the caller's context is gone.
sctx, scancel := context.WithDeadline(context.WithoutCancel(cutCtx), start.Add(freeze))
sctx, scancel := context.WithDeadline(context.WithoutCancel(cutCtx), settleDeadline)
defer scancel()
if trace := p.testDetachTrace; trace != nil {
dl, _ := sctx.Deadline()
@@ -1049,9 +1112,16 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla
if attempts > 0 {
extra = attempts - 1
}
r.Precopy.Finish(time.Since(start)+r.Precopy.BarrierBeforeFreeze, extra, true)
elapsed := time.Since(start)
if !guestFrozen {
elapsed += r.Precopy.BarrierBeforeFreeze
}
r.Precopy.Finish(elapsed, extra, true)
log.Printf("durable: pre-copy settlement volume=%s elapsed=%s extra_cas=%d declared_worst=%s latency_gate_failed=%t outcome=%v err=%v", volumeID, r.Precopy.FreezeElapsed, extra, r.Precopy.DeclaredWorst, r.Precopy.LatencyGateFailed, how, serr)
dr.Precopy = r.Precopy
if recorder, ok := layer.(interface{ RememberDetachReport(storage.PrecopyReport) }); ok {
recorder.RememberDetachReport(r.Precopy)
}
}
switch {
case serr != nil:
@@ -4,6 +4,8 @@ package durable_test
import (
"context"
"sync"
"sync/atomic"
"testing"
"time"
@@ -162,3 +164,140 @@ func TestWALStoreChunk_StatusHasNoChunkSectionForWALStore(t *testing.T) {
t.Fatalf("walstore status: %+v", st)
}
}
// gatedCASRemote holds the next HEAD CAS, once armed, until it is released
// (or its context ends), and reports when that CAS started.
type gatedCASRemote struct {
*storage.MemChunkRemote
armed atomic.Bool
entered chan struct{}
release chan struct{}
}
func (r *gatedCASRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) {
if r.armed.CompareAndSwap(true, false) {
close(r.entered)
select {
case <-r.release:
case <-ctx.Done():
return 0, ctx.Err()
}
}
return r.MemChunkRemote.CASHead(ctx, expected, next)
}
type loopEvent struct {
event string
lastCutNs int64
skipped bool
at time.Time
}
// An explicit cut still running when the loop's timer comes due restarts the
// timer all the same. Witnessed: the loop decides "due" from the old last
// cut while the explicit cut's CAS is held; once the explicit cut completes,
// that periodic cut is skipped (not taken as a no-op); and the next periodic
// decision is made from the explicit cut, a whole interval after it.
func TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt(t *testing.T) {
const interval = 3 * time.Second
remote := &gatedCASRemote{MemChunkRemote: storage.NewMemChunkRemote(), entered: make(chan struct{}), release: make(chan struct{})}
var releaseOnce sync.Once
release := func() { releaseOnce.Do(func() { close(remote.release) }) }
t.Cleanup(release)
p := schedProvider(t, remote, interval, 0)
events := make(chan loopEvent, 64)
durable.SetTestChunkLoopTrace(p, func(event string, lastCutNs int64, skipped bool) {
select {
case events <- loopEvent{event, lastCutNs, skipped, time.Now()}:
default:
}
})
next := func(what string) loopEvent {
t.Helper()
select {
case e := <-events:
return e
case <-time.After(30 * time.Second):
t.Fatalf("timed out waiting for the loop's %s", what)
}
return loopEvent{}
}
s := openRecovered(t, p)
begin := time.Now() // the loop started during open: its first deadline is at most begin + interval
if _, err := s.Write(1, block(0x01)); err != nil {
t.Fatal(err)
}
// Hold the explicit cut's CAS from a second before that deadline: the
// CAS's own 2 s operation deadline outlasts it.
time.Sleep(time.Until(begin.Add(interval - time.Second)))
remote.armed.Store(true)
explicitDone := make(chan error, 1)
go func() { _, err := p.CaptureVolume(context.Background(), "v1"); explicitDone <- err }()
t.Cleanup(func() {
release()
select {
case <-explicitDone:
case <-time.After(30 * time.Second):
t.Error("the explicit cut never returned")
}
})
select {
case <-remote.entered:
case <-time.After(30 * time.Second):
t.Fatal("the explicit cut never reached its CAS")
}
// The loop comes due while the explicit cut holds its CAS: it decides
// from the old last cut (none yet).
due := next("due decision")
if due.event != "due" || due.lastCutNs != 0 {
t.Fatalf("loop event %+v; want a due decision from no cut yet", due)
}
select {
case err := <-explicitDone:
explicitDone <- err
t.Fatal("the explicit cut finished before the loop's decision")
default:
}
release()
select {
case err := <-explicitDone:
explicitDone <- err
if err != nil {
t.Fatal(err)
}
case <-time.After(30 * time.Second):
t.Fatal("the explicit cut did not finish")
}
explicitAt := time.Now()
if h := headGen(t, remote); h.Gen != 1 {
t.Fatalf("explicit cut: HEAD gen %d, want 1", h.Gen)
}
if _, err := s.Write(pcChunkBlocks+1, block(0x02)); err != nil {
t.Fatal(err)
}
// The stale periodic cut is skipped, not run as a no-op.
cut := next("stale periodic cut")
if cut.event != "cut" || cut.lastCutNs != 0 || !cut.skipped {
t.Fatalf("loop event %+v; want the stale periodic cut skipped", cut)
}
// The next periodic decision is made from the explicit cut, a whole
// interval after it, and publishes the later write.
due2 := next("next due decision")
if due2.event != "due" || due2.lastCutNs == 0 {
t.Fatalf("loop event %+v; want a due decision from the explicit cut", due2)
}
last := time.Unix(0, due2.lastCutNs)
if last.After(explicitAt) {
t.Fatalf("decided from a cut at %v, after the explicit cut returned (%v)", last, explicitAt)
}
if due2.at.Before(last.Add(interval)) {
t.Fatalf("next periodic cut decided %v after the explicit cut; want a whole %v interval", due2.at.Sub(last), interval)
}
cut2 := next("next periodic cut")
if cut2.event != "cut" || cut2.skipped {
t.Fatalf("loop event %+v; want the next periodic cut taken", cut2)
}
if h := headGen(t, remote); h.Gen != 2 {
t.Fatalf("after the next periodic cut: HEAD gen %d, want 2", h.Gen)
}
}
@@ -0,0 +1,60 @@
package durable_test
import (
"bytes"
"context"
"encoding/json"
"errors"
"github.com/seaweedfs/seaweed-block/core/storage"
"sync/atomic"
"testing"
"time"
)
type frozenCountRemote struct {
storage.ChunkRemote
puts atomic.Int64
}
func (r *frozenCountRemote) Put(ctx context.Context, key string, p []byte) error {
r.puts.Add(1)
return r.ChunkRemote.Put(ctx, key, p)
}
func TestFrozenProviderFlagOffRefusesWithoutUploadThenFinalCommits(t *testing.T) {
mem := storage.NewMemChunkRemote()
remote := &frozenCountRemote{ChunkRemote: mem}
p, _ := parkedProvider(t, remote)
openRecovered(t, p)
b, err := p.Open(context.Background(), "v1")
if err != nil {
t.Fatal(err)
}
if _, err = b.Write(context.Background(), 4096, block(0x77)); err != nil {
t.Fatal(err)
}
before, _ := remote.GetHead(context.Background())
puts := remote.puts.Load()
r, _, err := p.DetachVolumeFrozen(context.Background(), "v1", storage.FrozenDetachOptions{StartedAt: time.Now().Add(-6 * time.Second)})
after, _ := remote.GetHead(context.Background())
if !errors.Is(err, storage.ErrFrozenTailTooLarge) || r.Precopy.Frozen || puts != remote.puts.Load() || before.Gen != after.Gen {
t.Fatalf("frozen refusal mutated remote: %+v %v puts=%d/%d", r.Precopy, err, puts, remote.puts.Load())
}
if _, err = b.Write(context.Background(), 8192, block(0x88)); err != nil {
t.Fatalf("refusal stopped serving before thaw: %v", err)
}
r, _, err = p.DetachVolumeFrozen(context.Background(), "v1", storage.FrozenDetachOptions{StartedAt: time.Now().Add(-time.Minute), AllowOverBudget: true})
if err != nil || !r.Precopy.GuestFrozen || !r.Precopy.OverBudget || !r.Precopy.Frozen || r.Head.State != storage.ChunkHeadDetached || len(r.Precopy.Rounds) != 1 || r.Precopy.FreezeElapsed < time.Minute || r.Precopy.DeclaredWorst < time.Minute || !r.Precopy.LatencyGateFailed {
t.Fatalf("explicit final failed/underreported total freeze: %+v %v", r, err)
}
original, _ := json.Marshal(r.Precopy)
originalHead := r.Head.Gen
puts = remote.puts.Load()
replay, _, replayErr := p.DetachVolumeFrozen(context.Background(), "v1", storage.FrozenDetachOptions{StartedAt: time.Now()})
replayJSON, _ := json.Marshal(replay.Precopy)
if replayErr != nil || replay.Head.Gen != originalHead || !bytes.Equal(original, replayJSON) || remote.puts.Load() != puts {
t.Fatalf("provider replay changed original freeze report or re-uploaded: original=%s replay=%s err=%v", original, replayJSON, replayErr)
}
if headBlock(t, mem, 1)[0] != 0x77 || headBlock(t, mem, 2)[0] != 0x88 {
t.Fatal("final detached point lost writes")
}
}
+66 -12
View File
@@ -39,13 +39,14 @@ type ChunkControl interface {
// ChunkCutResponse is the body of a successful POST /chunk/cut (§3.1).
type ChunkCutResponse struct {
VolumeID string `json:"volumeID"`
CutLSN uint64 `json:"cutLSN"`
HeadGen uint64 `json:"headGen"`
HeadEpoch uint64 `json:"headEpoch"`
Holder string `json:"holder"`
Noop bool `json:"noop"`
FullHash bool `json:"fullHash"`
CandidateTail *storage.ChunkCandidateTail `json:"candidateTail,omitempty"`
VolumeID string `json:"volumeID"`
CutLSN uint64 `json:"cutLSN"`
HeadGen uint64 `json:"headGen"`
HeadEpoch uint64 `json:"headEpoch"`
Holder string `json:"holder"`
Noop bool `json:"noop"`
FullHash bool `json:"fullHash"`
// Stats are the statistics the chunk layer measured for this cut
// (§3.1). A zero field is "not measured" or "none" (a Noop cut
// uploads nothing).
@@ -56,6 +57,15 @@ type ChunkCutResponse struct {
// mirrors storage.ChunkCutStats field for field (a test keeps the two in
// step); every duration is in nanoseconds.
type ChunkCutStatsBody struct {
SyncPhases storage.SyncPhaseStats `json:"syncPhases"`
CandidateNs int64 `json:"candidateNs"`
WindowSetupNs int64 `json:"windowSetupNs"`
PublishPrepareNs int64 `json:"publishPrepareNs"`
ManifestNs int64 `json:"manifestNs"`
CommitStateNs int64 `json:"commitStateNs"`
IntentCleanupNs int64 `json:"intentCleanupNs"`
NonPayloadCopyNs int64 `json:"nonPayloadCopyNs"`
PayloadNs int64 `json:"payloadNs"`
COWWALReadAttempts uint64 `json:"cowWALReadAttempts"`
COWLocalReadNs int64 `json:"cowLocalReadNs"`
@@ -88,6 +98,15 @@ type ChunkCutStatsBody struct {
func cutStatsBody(s storage.ChunkCutStats) ChunkCutStatsBody {
return ChunkCutStatsBody{
SyncPhases: s.SyncPhases,
CandidateNs: s.CandidateNs,
WindowSetupNs: s.WindowSetupNs,
PublishPrepareNs: s.PublishPrepareNs,
ManifestNs: s.ManifestNs,
CommitStateNs: s.CommitStateNs,
IntentCleanupNs: s.IntentCleanupNs,
NonPayloadCopyNs: s.NonPayloadCopyNs,
PayloadNs: s.PayloadNs,
COWWALReadAttempts: s.COWWALReadAttempts,
COWLocalReadNs: s.COWLocalReadNs,
@@ -286,6 +305,12 @@ func chunkErrorCode(err error) (int, string, bool) {
return http.StatusConflict, codeClosing, false // stays closed until a new attach
case errors.Is(err, storage.ErrChunkLayerClosed):
return http.StatusServiceUnavailable, codeClosing, false // the process is shutting down
case errors.Is(err, errFrozenDetachUnsupported):
return http.StatusConflict, "frozen_detach_unsupported", false
case errors.Is(err, storage.ErrInvalidFreezeBudget):
return http.StatusBadRequest, "bad_request", false
case errors.Is(err, storage.ErrFrozenTailTooLarge):
return http.StatusConflict, "frozen_tail_too_large", true
// A local window abort cancels its uploads; that cancellation is not
// a remote outage. Keep authority and uncertain-publication precedence.
case errors.Is(err, storage.ErrCutCOWAborted):
@@ -496,13 +521,20 @@ func (s *StatusServer) handleChunkDetach(w http.ResponseWriter, r *http.Request)
return
}
var req struct {
VolumeID string `json:"volumeID"`
TimeoutMs int64 `json:"timeoutMs"`
Plain bool `json:"plain,omitempty"`
VolumeID string `json:"volumeID"`
TimeoutMs int64 `json:"timeoutMs"`
Plain bool `json:"plain,omitempty"`
Frozen bool `json:"frozen,omitempty"`
FreezeStartedAtNs int64 `json:"freezeStartedAtNs,omitempty"`
AllowOverBudget bool `json:"allowOverBudget,omitempty"`
}
if !decodeChunkBody(w, r, &req) {
return
}
if (req.Frozen && (req.Plain || req.FreezeStartedAtNs <= 0 || time.Unix(0, req.FreezeStartedAtNs).After(time.Now()))) || (!req.Frozen && (req.FreezeStartedAtNs != 0 || req.AllowOverBudget)) {
writeChunkErr(w, http.StatusBadRequest, "bad_request", false, "frozen requires a non-future freezeStartedAtNs and cannot combine with plain; allowOverBudget requires frozen")
return
}
ctl := s.chunkTarget(w, req.VolumeID)
if ctl == nil {
return
@@ -511,7 +543,16 @@ func (s *StatusServer) handleChunkDetach(w http.ResponseWriter, r *http.Request)
defer cancel()
var res ChunkDetachResponse
var err error
if req.Plain {
if req.Frozen {
frozen, ok := ctl.(interface {
DetachFrozen(context.Context, string, storage.FrozenDetachOptions) (ChunkDetachResponse, error)
})
if !ok {
writeChunkErr(w, http.StatusConflict, "frozen_detach_unsupported", false, "frozen detach unsupported")
return
}
res, err = frozen.DetachFrozen(ctx, req.VolumeID, storage.FrozenDetachOptions{StartedAt: time.Unix(0, req.FreezeStartedAtNs), AllowOverBudget: req.AllowOverBudget})
} else if req.Plain {
plain, ok := ctl.(interface {
DetachPlain(context.Context, string) (ChunkDetachResponse, error)
})
@@ -543,6 +584,8 @@ type ChunkProvider interface {
DetachVolume(ctx context.Context, volumeID string) (storage.ChunkCutResult, uint64, error)
}
var errFrozenDetachUnsupported = errors.New("frozen detach unsupported by provider")
type chunkControl struct {
p ChunkProvider
cat *chunkstore.Catalog
@@ -560,7 +603,7 @@ func (c *chunkControl) Cut(ctx context.Context, volumeID string, minLSN uint64)
return ChunkCutResponse{}, err
}
return ChunkCutResponse{VolumeID: volumeID, CutLSN: r.H, HeadGen: r.Head.Gen, HeadEpoch: r.Head.Epoch, Holder: r.Head.Holder,
Noop: r.Noop, FullHash: r.FullHash, Stats: cutStatsBody(r.Stats)}, nil
Noop: r.Noop, FullHash: r.FullHash, CandidateTail: r.CandidateTail, Stats: cutStatsBody(r.Stats)}, nil
}
// Snapshot resolves the request against the catalog first (§3.2 step 1):
@@ -626,6 +669,17 @@ func (c *chunkControl) Detach(ctx context.Context, volumeID string) (ChunkDetach
return chunkDetachResponse(volumeID, r, last, err)
}
func (c *chunkControl) DetachFrozen(ctx context.Context, volumeID string, opts storage.FrozenDetachOptions) (ChunkDetachResponse, error) {
p, ok := c.p.(interface {
DetachVolumeFrozen(context.Context, string, storage.FrozenDetachOptions) (storage.ChunkCutResult, uint64, error)
})
if !ok {
return ChunkDetachResponse{}, errFrozenDetachUnsupported
}
r, last, err := p.DetachVolumeFrozen(ctx, volumeID, opts)
return chunkDetachResponse(volumeID, r, last, err)
}
func (c *chunkControl) DetachPlain(ctx context.Context, volumeID string) (ChunkDetachResponse, error) {
p, ok := c.p.(interface {
DetachVolumePlain(context.Context, string) (storage.ChunkCutResult, uint64, error)
@@ -182,6 +182,13 @@ func TestChunkCutStatsBody_MirrorsTheLayerStats(t *testing.T) {
f.SetString("s")
case reflect.Bool:
f.SetBool(true)
case reflect.Struct:
for j := 0; j < f.NumField(); j++ {
if f.Field(j).Kind() != reflect.Int64 {
t.Fatalf("nested field %s.%s is not a duration counter", v.Type().Field(i).Name, f.Type().Field(j).Name)
}
f.Field(j).SetInt(int64(100*(i+1) + j + 1))
}
default:
t.Fatalf("field %s: unhandled kind %s", v.Type().Field(i).Name, f.Kind())
}
@@ -0,0 +1,66 @@
package volume
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/seaweedfs/seaweed-block/core/storage"
"net/http"
"testing"
"time"
)
type frozenDetachProvider struct {
*fakeChunkProvider
opts storage.FrozenDetachOptions
calls int
err error
}
func (p *frozenDetachProvider) DetachVolumeFrozen(_ context.Context, _ string, opts storage.FrozenDetachOptions) (storage.ChunkCutResult, uint64, error) {
p.opts = opts
p.calls++
return p.detach, p.last, p.err
}
func TestChunkFrozenDetachWireContractAndPrecedence(t *testing.T) {
p := &frozenDetachProvider{fakeChunkProvider: &fakeChunkProvider{detach: storage.ChunkCutResult{H: 7, Head: storage.ChunkHead{Gen: 2, Epoch: 1, State: storage.ChunkHeadDetached}}, last: 7}}
s := chunkServer(t, NewChunkControl(p, nil), true)
at := time.Now().Add(-time.Second).UnixNano()
body := fmt.Sprintf(`{"volumeID":"v1","frozen":true,"freezeStartedAtNs":%d,"allowOverBudget":true}`, at)
w := serve(t, s, http.MethodPost, "/chunk/detach", body, "")
if w.Code != 200 || p.calls != 1 || p.opts.StartedAt.UnixNano() != at || !p.opts.AllowOverBudget {
t.Fatalf("frozen wire lost fields: %d %s %+v", w.Code, w.Body, p.opts)
}
for _, invalid := range []string{`{"volumeID":"v1","frozen":true}`, `{"volumeID":"v1","allowOverBudget":true}`, fmt.Sprintf(`{"volumeID":"v1","frozen":true,"freezeStartedAtNs":%d}`, time.Now().Add(time.Hour).UnixNano()), fmt.Sprintf(`{"volumeID":"v1","frozen":true,"plain":true,"freezeStartedAtNs":%d}`, at)} {
before := p.calls
w = serve(t, s, http.MethodPost, "/chunk/detach", invalid, "")
if w.Code != 400 || p.calls != before {
t.Fatalf("invalid request reached provider: %d %s", w.Code, w.Body)
}
}
p.err = storage.ErrFrozenTailTooLarge
w = serve(t, s, http.MethodPost, "/chunk/detach", body, "")
var e chunkErrorBody
_ = json.Unmarshal(w.Body.Bytes(), &e)
if w.Code != 409 || e.Code != "frozen_tail_too_large" || !e.Retryable {
t.Fatalf("wrong frozen refusal: %d %s", w.Code, w.Body)
}
for _, terminal := range []error{storage.ErrChunkLayerClosed, storage.ErrChunkLayerFenced, storage.ErrChunkCASOutcomeUnknown} {
expectedStatus, expectedCode, expectedRetry := chunkErrorCode(terminal)
status, code, retry := chunkErrorCode(errors.Join(terminal, storage.ErrFrozenTailTooLarge))
if status != expectedStatus || code != expectedCode || retry != expectedRetry {
t.Fatalf("frozen refusal hid terminal/unknown cause %v: %d %s %t", terminal, status, code, retry)
}
}
}
func TestChunkCheckpointCarriesCandidateTail(t *testing.T) {
tail := &storage.ChunkCandidateTail{Bytes: 4096, Estimate: time.Second, Known: true, RateSamples: 3, BytesPerSecond: 4096}
p := &fakeChunkProvider{cut: storage.ChunkCutResult{CandidateTail: tail}}
s := chunkServer(t, NewChunkControl(p, nil), true)
w := serve(t, s, http.MethodPost, "/chunk/cut", `{"volumeID":"v1"}`, "")
var body ChunkCutResponse
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || w.Code != 200 || body.CandidateTail == nil || *body.CandidateTail != *tail {
t.Fatalf("cut response lost tail: %d %s %v", w.Code, w.Body, err)
}
}
@@ -0,0 +1,61 @@
package storage
import (
"testing"
"time"
)
func TestCheckpointTailMeasuresWritesAfterItsCut(t *testing.T) {
s, f, l, w := precopyLayer(t, 1024, 0)
for i := 0; i < 3; i++ {
l.precopySamples = append(l.precopySamples, precopySample{at: time.Now(), fixed: time.Millisecond, rate: 2 * float64(ctChunkBytes)})
}
w.write(t, s, 1, 0x11)
f.beforeCAS = func(*fakeChunkRemote) { f.beforeCAS = nil; w.write(t, s, 2, 0x22) }
r, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
tail := r.CandidateTail
if tail == nil || tail.Bytes != ctChunkBytes || !tail.Known || tail.BytesPerSecond <= 0 {
t.Fatalf("missing post-cut dirty tail: %+v", tail)
}
expected := time.Duration(float64(tail.Bytes) / tail.BytesPerSecond * float64(time.Second))
if expected > precopyDuration {
expected = precopyDuration
}
if tail.Estimate != expected {
t.Fatalf("tail and rate sampled inconsistently: %+v want=%s", tail, expected)
}
r, err = l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if r.CandidateTail == nil || r.CandidateTail.Bytes != 0 || !r.CandidateTail.Known || r.CandidateTail.Estimate != 0 {
t.Fatalf("settled checkpoint not clean: %+v", r.CandidateTail)
}
assertEveryHeadIsPrefixImage(t, f, w)
}
func TestCheckpointTailUnknownRateIsNotZeroCost(t *testing.T) {
s, _, l, w := precopyLayer(t, 1024, 0)
w.write(t, s, 1, 0x44)
l.precopySamples = []precopySample{{at: time.Now(), fixed: time.Millisecond, rate: 100}}
tail := l.candidateTail()
if tail.Bytes == 0 || tail.Known || tail.RateSamples != 1 {
t.Fatalf("partial rate window misreported ready: %+v", tail)
}
}
func TestCheckpointTailUsesLiteralLatestThreeConservativeRate(t *testing.T) {
s, _, l, w := precopyLayer(t, 1024, 0)
w.write(t, s, 1, 0x51)
// Old slow rate must be excluded; latest three min is 2 chunks/s,
// conservative divisor is 2 => exactly one chunk/s and one second.
for _, multiplier := range []float64{0.25, 2, 6, 4} {
l.precopySamples = append(l.precopySamples, precopySample{at: time.Now(), fixed: time.Millisecond, rate: multiplier * float64(ctChunkBytes)})
}
tail := l.candidateTail()
if tail.Bytes != ctChunkBytes || !tail.Known || tail.BytesPerSecond != float64(ctChunkBytes) || tail.Estimate != time.Second || tail.RateSamples != 4 {
t.Fatalf("literal latest-three rate/estimate mismatch: %+v", tail)
}
}
@@ -51,6 +51,7 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64,
var once sync.Once
var intent string
var intentErr error
put := l.beginPutRound(len(batch))
err := l.uploadBatch(ctx, len(batch), func(ctx context.Context, i int) error {
c, err := read(ctx, batch[i])
if err != nil {
@@ -69,7 +70,7 @@ func (l *chunkLayerImpl) streamCutPayloads(ctx context.Context, batch []uint64,
return fmt.Errorf("storage: capture intent: %w: %w", errChunkRemoteUnavailable, intentErr)
}
c.intent = intent
if err := l.putCaptured(ctx, c.key, c.data); err != nil {
if err := l.putCapturedWith(ctx, c.key, c.data, func(ctx context.Context) error { return put(ctx, i, c.key, c.data) }); err != nil {
return fmt.Errorf("storage: capture upload: %w", errors.Join(errChunkRemoteUnavailable, errCutUpload, err))
}
}
@@ -0,0 +1,96 @@
package storage
import (
"context"
"reflect"
"testing"
"time"
)
type fixedSpanRemote struct {
*fakeChunkRemote
delay time.Duration
}
func (r *fixedSpanRemote) PrepareManifest(_ context.Context, _ ChunkHead, next ChunkHead, _ uint64) (ChunkHead, []string, error) {
time.Sleep(r.delay)
return next, nil, nil
}
func (r *fixedSpanRemote) CASHead(ctx context.Context, v ChunkHeadVersion, h ChunkHead) (uint64, error) {
time.Sleep(r.delay)
return r.fakeChunkRemote.CASHead(ctx, v, h)
}
func (r *fixedSpanRemote) DeleteIntent(ctx context.Context, id string) error {
time.Sleep(r.delay)
return r.fakeChunkRemote.DeleteIntent(ctx, id)
}
func TestChunkCutFixedSpansAttributeManifestAndCleanup(t *testing.T) {
s, f, l, w := precopyLayer(t, 1024, 0)
delay := 10 * time.Millisecond
l.remote = &fixedSpanRemote{fakeChunkRemote: f, delay: delay}
w.write(t, s, 1, 0x32)
r, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
for _, name := range []string{"ManifestNs", "IntentCleanupNs"} {
v := reflect.ValueOf(r.Stats).FieldByName(name)
if !v.IsValid() || time.Duration(v.Int()) < delay {
t.Fatalf("missing fixed span %s: %+v", name, r.Stats)
}
}
if len(l.precopySamples) == 0 {
t.Fatal("no fixed sample")
}
parts := reflect.ValueOf(l.precopySamples[len(l.precopySamples)-1].parts)
for _, name := range []string{"Manifest", "IntentCleanup"} {
v := parts.FieldByName(name)
if !v.IsValid() || time.Duration(v.Int()) < delay {
t.Fatalf("missing selected fixed part %s", name)
}
}
assertEveryHeadIsPrefixImage(t, f, w)
}
func TestPrecopyLiveBarrierSpansExplainOverage(t *testing.T) {
_, _, l, _ := precopyLayer(t, 1024, 0)
seedFrozenSamples(l, time.Millisecond)
delay := 20 * time.Millisecond
l.testBeforeBarrierLockHook = func() { time.Sleep(delay) }
r, err := l.PrecopyDetach(ctTimeout(t), func() bool { return true })
if err != nil {
t.Fatal(err)
}
if r.Precopy.BarrierOverage <= 0 || r.Precopy.BarrierParts.StoreLock < delay || len(r.Precopy.Rounds) != 1 || r.Precopy.Rounds[0].BarrierParts.StoreLock < delay {
t.Fatalf("live lock overage hidden as retained other: %+v", r.Precopy)
}
}
func TestPrecopyFixedPartsDoNotDoubleCountSyncPhases(t *testing.T) {
st := chunkCutStats{SyncNs: int64(100 * time.Millisecond), SyncPhases: SyncPhaseStats{StoreWaitNs: int64(30 * time.Millisecond), GroupCommitNs: int64(70 * time.Millisecond)}}
p := precopyFixedParts(st, 150*time.Millisecond)
if p.DataSync != 100*time.Millisecond || p.Other != 50*time.Millisecond || p.SyncPhases != st.SyncPhases {
t.Fatalf("nested Sync cost counted twice or dropped: %+v", p)
}
}
func TestCheckpointTailScanIncludedInTotalAndFixedCosts(t *testing.T) {
s, f, l, w := precopyLayer(t, 1024, 0)
l.remote = &fixedSpanRemote{fakeChunkRemote: f, delay: time.Millisecond}
w.write(t, s, 1, 0x6a)
delay := 20 * time.Millisecond
scans := 0
l.testBeforeTailScanHook = func() { scans++; time.Sleep(delay) }
result, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if scans != 1 || result.Stats.CandidateNs < int64(delay) || result.Stats.TotalNs < int64(delay) {
t.Fatalf("scan missing from returned costs: scans=%d stats=%+v", scans, result.Stats)
}
sample := l.precopySamples[len(l.precopySamples)-1]
if sample.fixed < delay || sample.parts.Candidate < delay {
t.Fatalf("scan omitted from fixed observation: %+v", sample)
}
}
@@ -0,0 +1,89 @@
package storage
import (
"context"
"errors"
"fmt"
"time"
)
var ErrFrozenTailTooLarge = errors.New("storage: frozen tail does not fit remaining freeze budget")
var ErrInvalidFreezeBudget = errors.New("storage: invalid guest freeze budget")
// FrozenDetachOptions is supplied by the trusted guest orchestrator. It owns
// the maximum two re-freeze cycles; AllowOverBudget explicitly requests its
// final attempt. It never bypasses authority, lifecycle or CAS settlement.
type FrozenDetachOptions struct {
StartedAt time.Time
AllowOverBudget bool
}
type frozenDetachKey struct{}
func WithFrozenDetach(ctx context.Context, opts FrozenDetachOptions) (context.Context, error) {
now := time.Now()
if opts.StartedAt.IsZero() || opts.StartedAt.Before(time.Unix(0, 1)) || opts.StartedAt.After(now) {
return nil, ErrInvalidFreezeBudget
}
// Convert remote wall time to a local monotonic origin once at admission.
opts.StartedAt = now.Add(-now.Sub(opts.StartedAt))
return context.WithValue(ctx, frozenDetachKey{}, opts), nil
}
func FrozenDetachFromContext(ctx context.Context) (FrozenDetachOptions, bool) {
v, ok := ctx.Value(frozenDetachKey{}).(FrozenDetachOptions)
return v, ok
}
func (r *PrecopyReport) admitFrozen(opts FrozenDetachOptions) bool {
return r.admitFrozenAt(opts, time.Now())
}
func (r *PrecopyReport) admitFrozenAt(opts FrozenDetachOptions, now time.Time) bool {
r.GuestFrozen = true
r.GuestFreezeElapsed = max(time.Duration(0), now.Sub(opts.StartedAt))
r.RemainingFreeze = max(time.Duration(0), precopyFreezeLimit-r.GuestFreezeElapsed)
known := r.Reason != "samples_unknown" && r.Estimate > 0
if opts.AllowOverBudget {
r.Reason = "over_budget"
r.OverBudget = true
} else if !known || r.Estimate > r.RemainingFreeze {
r.Reason = "frozen_tail_too_large"
return false
} else {
r.Reason = "fit"
}
r.DeclaredFreeze = r.GuestFreezeElapsed + r.Estimate
if !known {
r.DeclaredFreeze = max(r.DeclaredFreeze, precopyFreezeLimit)
}
return true
}
func frozenRefusal(r PrecopyReport) error {
return fmt.Errorf("%w: reason=%s estimate=%s remaining=%s elapsed=%s", ErrFrozenTailTooLarge, r.Reason, r.Estimate, r.RemainingFreeze, r.GuestFreezeElapsed)
}
// IsReplay distinguishes a replayed applied point from a newly completed freeze.
// The original report remains unchanged on the wire.
func (r PrecopyReport) IsReplay() bool { return r.replayed }
func (l *chunkLayerImpl) admitFrozen(r *PrecopyReport, opts FrozenDetachOptions) bool {
now := time.Now()
if hook := l.testFrozenNow; hook != nil {
now = hook()
}
return r.admitFrozenAt(opts, now)
}
// RememberDetachReport completes the telemetry kept with an applied or still
// pending point. The durable provider calls it after its final settlement spans.
// It changes no publication identity or authority state.
func (l *chunkLayerImpl) RememberDetachReport(report PrecopyReport) {
if report.IsReplay() {
return
}
l.stMu.Lock()
defer l.stMu.Unlock()
if l.detached != nil {
l.detached.Precopy = report
}
if l.pendingDetach {
l.pendingCut.Precopy = report
}
}
@@ -0,0 +1,171 @@
package storage
import (
"bytes"
"context"
"errors"
"reflect"
"testing"
"time"
)
func frozenContext(t *testing.T, elapsed time.Duration, force bool) context.Context {
t.Helper()
ctx, err := WithFrozenDetach(ctTimeout(t), FrozenDetachOptions{StartedAt: time.Now().Add(-elapsed), AllowOverBudget: force})
if err != nil {
t.Fatal(err)
}
return ctx
}
func seedFrozenSamples(l *chunkLayerImpl, fixed time.Duration) {
l.precopySamples = nil
for i := 0; i < 3; i++ {
l.precopySamples = append(l.precopySamples, precopySample{at: time.Now(), fixed: fixed, rate: 20 * float64(ctChunkBytes)})
}
}
func TestFrozenDetachRejectsBeforeStagingOrUpload(t *testing.T) {
s, f, l, w := precopyLayer(t, 1, 0)
w.write(t, s, 1, 0x12)
seedFrozenSamples(l, 1300*time.Millisecond)
before := f.stats()
l.testBeforeBarrierLockHook = func() { t.Fatal("preflight rejection reached capture") }
r, err := l.PrecopyDetach(frozenContext(t, 4*time.Second, false), func() bool { t.Fatal("over-budget attempt stopped backend"); return true })
after := f.stats()
if !errors.Is(err, ErrFrozenTailTooLarge) || r.Precopy.Frozen || r.Precopy.Reason != "frozen_tail_too_large" || after.puts != before.puts || after.cas != before.cas || after.head.Gen != before.head.Gen {
t.Fatalf("over-budget frozen cut did work: %+v %v before=%+v after=%+v", r.Precopy, err, before, after)
}
l.testBeforeBarrierLockHook = nil
r, err = l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(f.imageOf(t, r.Head)[ctBlockSize:2*ctBlockSize], makeBlock(ctBlockSize, 0x12)) {
t.Fatal("refusal dropped dirty bytes")
}
}
func TestFrozenDetachRechecksBudgetAtBarrierWithoutUpload(t *testing.T) {
s, f, l, w := precopyLayer(t, 1, 3)
w.write(t, s, 1, 0x24)
seedFrozenSamples(l, time.Millisecond)
before := f.stats()
reached := false
l.testBeforeBarrierLockHook = func() { reached = true; seedFrozenSamples(l, 6*time.Second) }
r, err := l.PrecopyDetach(frozenContext(t, 0, false), func() bool { t.Fatal("authoritative refusal stopped backend"); return true })
after := f.stats()
if !reached || !errors.Is(err, ErrFrozenTailTooLarge) || r.Precopy.Frozen || len(r.Precopy.Rounds) != 1 || after.puts != before.puts || after.cas != before.cas || after.head.Gen != before.head.Gen {
t.Fatalf("barrier rejection uploaded or rolled: %+v %v", r.Precopy, err)
}
l.testBeforeBarrierLockHook = nil
r, err = l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
assertEveryHeadIsPrefixImage(t, f, w)
}
func TestFrozenDetachForcedFinalCommitsSamePoint(t *testing.T) {
s, f, l, w := precopyLayer(t, 1, 0)
w.write(t, s, 1, 0x36)
seedFrozenSamples(l, 6*time.Second)
stops := 0
r, err := l.PrecopyDetach(frozenContext(t, 6*time.Second, true), func() bool { stops++; return true })
if err != nil || !r.Precopy.OverBudget || !r.Precopy.GuestFrozen || !r.Precopy.Frozen || r.Precopy.Reason != "over_budget" || len(r.Precopy.Rounds) != 1 || stops != 1 || r.Head.State != ChunkHeadDetached {
t.Fatalf("explicit final did not commit once: %+v %v", r, err)
}
if !r.Precopy.LatencyGateFailed || r.Precopy.FreezeElapsed < 6*time.Second {
t.Fatalf("external elapsed hidden: %+v", r.Precopy)
}
assertEveryHeadIsPrefixImage(t, f, w)
r2, err := l.PrecopyDetach(frozenContext(t, 7*time.Second, false), func() bool { t.Fatal("applied retry stopped again"); return true })
want := r.Precopy
want.replayed = true
if err != nil || r2.Head.Gen != r.Head.Gen || !reflect.DeepEqual(r2.Precopy, want) {
t.Fatalf("applied retry budget-refused: %+v %v", r2, err)
}
}
func TestFrozenBudgetInputValidation(t *testing.T) {
for _, at := range []time.Time{{}, time.Now().Add(time.Hour)} {
if _, err := WithFrozenDetach(context.Background(), FrozenDetachOptions{StartedAt: at}); !errors.Is(err, ErrInvalidFreezeBudget) {
t.Fatalf("invalid origin accepted: %v", err)
}
}
}
func TestFrozenFinalOverrideIsVisibleEvenWhenEstimateFits(t *testing.T) {
r := PrecopyReport{Estimate: time.Second, Reason: "fit"}
if !r.admitFrozen(FrozenDetachOptions{StartedAt: time.Now(), AllowOverBudget: true}) || !r.OverBudget || r.Reason != "over_budget" {
t.Fatalf("explicit override hidden: %+v", r)
}
}
func TestFrozenFinalOverrideKeepsAuthorityAndCloseGuards(t *testing.T) {
for _, closed := range []bool{false, true} {
t.Run(map[bool]string{false: "fenced", true: "closed"}[closed], func(t *testing.T) {
s, f, l, w := precopyLayer(t, 1, 0)
w.write(t, s, 1, 0x4a)
before := f.stats()
want := ErrChunkLayerFenced
if closed {
if err := l.Close(); err != nil {
t.Fatal(err)
}
want = ErrChunkLayerClosed
} else {
l.cfg.CaptureAllowed = func() error { return ErrChunkLayerFenced }
}
_, err := l.PrecopyDetach(frozenContext(t, time.Minute, true), func() bool { t.Fatal("override bypassed gate"); return true })
after := f.stats()
if !errors.Is(err, want) || after.puts != before.puts || after.cas != before.cas {
t.Fatalf("override bypassed %v: %v", want, err)
}
})
}
}
func TestFrozenRetryDoesNotHideUnknownPublication(t *testing.T) {
s, f, l, w := precopyLayer(t, 1, 0)
w.write(t, s, 1, 0x5b)
seedFrozenSamples(l, time.Millisecond)
f.casModes = []fakeCASMode{casAppliedLost}
f.afterCAS = func(f *fakeChunkRemote) { f.failGet = errFakeRemoteDown }
r, err := l.PrecopyDetach(frozenContext(t, 0, true), func() bool { return true })
if !r.Precopy.Frozen || !errors.Is(err, ErrChunkCASOutcomeUnknown) {
t.Fatalf("missing unknown publication: %+v %v", r.Precopy, err)
}
before := f.stats()
_, err = l.PrecopyDetach(frozenContext(t, time.Minute, false), func() bool { t.Fatal("unknown retry stopped again"); return true })
if !errors.Is(err, ErrChunkCASOutcomeUnknown) || errors.Is(err, ErrFrozenTailTooLarge) || f.stats().puts != before.puts {
t.Fatalf("budget hid uncertainty: %v", err)
}
f.failGet = nil
r, err = l.PrecopyDetach(frozenContext(t, time.Minute, false), func() bool { t.Fatal("applied retry stopped again"); return true })
if err != nil || r.Head.Gen != before.head.Gen || r.Head.State != ChunkHeadDetached {
t.Fatalf("applied same-point result budget-refused: %+v %v", r, err)
}
assertEveryHeadIsPrefixImage(t, f, w)
}
func TestFrozenBarrierConsumesElapsedWithoutNewAllowance(t *testing.T) {
s, f, l, w := precopyLayer(t, 1, 3)
w.write(t, s, 1, 0x61)
seedFrozenSamples(l, 1300*time.Millisecond)
origin := time.Now()
now := origin
l.testFrozenNow = func() time.Time { return now }
reached := false
l.testBeforeBarrierLockHook = func() { reached = true; now = origin.Add(4 * time.Second) }
before := f.stats()
ctx, err := WithFrozenDetach(ctTimeout(t), FrozenDetachOptions{StartedAt: origin})
if err != nil {
t.Fatal(err)
}
stops := 0
result, err := l.PrecopyDetach(ctx, func() bool { stops++; return true })
after := f.stats()
if !reached || stops != 0 || !errors.Is(err, ErrFrozenTailTooLarge) || result.Precopy.Estimate >= 5*time.Second || result.Precopy.RemainingFreeze > 1100*time.Millisecond || result.Precopy.Estimate <= result.Precopy.RemainingFreeze || after.puts != before.puts || after.cas != before.cas {
t.Fatalf("elapsed barrier budget not enforced without upload: %+v %v", result.Precopy, err)
}
l.testBeforeBarrierLockHook = nil
if _, err := l.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
assertEveryHeadIsPrefixImage(t, f, w)
}
+69 -25
View File
@@ -53,7 +53,7 @@ const defaultReadMissTimeout = 30 * time.Second
type chunkLayerImpl struct {
// capMu serializes pre-copy admission and its recent measurements.
precopyFreeze func(uint64, time.Time) bool
precopyFreeze func(uint64, time.Time, chunkCutStats) bool
precopyPrepare func(context.Context) (func(), error)
precopySamples []precopySample
precopyPause func(time.Duration)
@@ -133,6 +133,8 @@ type chunkLayerImpl struct {
testCOWSave func() error
testPresenceSnapshotHook func() // after a presence snapshot, before it is written
testBaseTransitionBeforeLock func() // test handshake before capMu drain
testBeforeTailScanHook func() // diagnostic tail scan cost witness
testFrozenNow func() time.Time // controlled guest elapsed at admission
testAfterAdmitHook func() // right after a capture is admitted
testAfterStageHook func(round int) // after each pre-copy staging round
testAfterStageReadHook func(idx uint64) // after a staging read, before its result is kept
@@ -669,9 +671,25 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
st.HeadReadbackNs += time.Since(start).Nanoseconds()
return head, err
}
dropCapturedIntents := func(ctx context.Context, ids []string) {
start := time.Now()
l.dropIntents(ctx, ids)
st.IntentCleanupNs += time.Since(start).Nanoseconds()
}
finishCapturedCut := func(head chunkHead, h uint64, changed []uint64, keys map[uint64]string) {
start := time.Now()
l.finishCut(head, h, changed, keys)
st.CommitStateNs += time.Since(start).Nanoseconds()
}
var pauseStart time.Time
var payloadBeforeBarrier int64
defer func() {
var tailBytes uint64
if err == nil {
scanStart := time.Now()
tailBytes = l.candidateTailBytes()
st.CandidateNs += time.Since(scanStart).Nanoseconds()
}
st.TotalNs = time.Since(start).Nanoseconds()
if err == nil {
res.Stats = st
@@ -679,6 +697,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
fixed := time.Since(pauseStart).Nanoseconds() - st.PayloadNs + payloadBeforeBarrier
l.samplePrecopy(st, fixed)
}
res.CandidateTail = l.estimateCandidateTail(tailBytes)
}
if errors.Is(err, errChunkLayerFenced) {
l.stMu.Lock()
@@ -690,7 +709,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
}
l.reusable = nil
l.stMu.Unlock()
l.dropIntents(ctx, ids)
dropCapturedIntents(ctx, ids)
}
if observe := l.precopyPause; observe != nil {
observe(time.Duration(st.BarrierPauseNs))
@@ -742,17 +761,22 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
// Pre-copy large native dirty sets outside the barrier, bounded by the
// remaining COW exposure rather than a fixed candidate count.
stageStart := time.Now()
staged, intents, err := l.stage(ctx, &st)
var staged map[uint64]stagedChunk
var intents []string
_, guestFrozen := FrozenDetachFromContext(ctx)
if !guestFrozen {
staged, intents, err = l.stage(ctx, &st)
}
if st.UploadedBytes > 0 {
st.PayloadNs += time.Since(stageStart).Nanoseconds()
}
if err != nil {
l.dropIntents(ctx, intents)
dropCapturedIntents(ctx, intents)
return chunkCutResult{}, err
}
if cause := context.Cause(ctx); cause != nil {
l.dropIntents(ctx, intents)
dropCapturedIntents(ctx, intents)
return chunkCutResult{}, cause
}
@@ -777,7 +801,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
releasePrecopy()
releasePrecopy = nil
}
l.dropIntents(ctx, intents)
dropCapturedIntents(ctx, intents)
return chunkCutResult{}, cause
}
// Resume rejected tentative admission before any ordinary COW upload.
@@ -794,7 +818,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
l.s.captureMu.Lock()
barrier := time.Now()
st.LockWaitNs = barrier.Sub(pauseStart).Nanoseconds()
h, err := l.s.Sync()
h, err := l.s.syncWithPhases(&st.SyncPhases)
st.SyncNs = time.Since(barrier).Nanoseconds()
if hook := l.testAfterBarrierSyncHook; hook != nil && err == nil {
hook(h)
@@ -802,9 +826,10 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
if err != nil {
unlockCapture()
st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds()
l.dropIntents(ctx, intents) // a clean abort: staged keys are released
dropCapturedIntents(ctx, intents) // a clean abort: staged keys are released
return chunkCutResult{}, fmt.Errorf("storage: capture sync: %w", err)
}
candidateStart := time.Now()
candidates := map[uint64]bool{}
for idx := range l.captureCandidates() {
candidates[idx] = true
@@ -851,12 +876,20 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
// Candidates, mutation versions and births belong to the same barrier.
// Do not sample the owned map after COW writers are admitted again.
births := l.captureBirths(candidates, h)
st.CandidateNs += time.Since(candidateStart).Nanoseconds()
// The authoritative candidate set is fixed with mutation admission closed.
// The owner callback is nonblocking and may stop only an already drained
// frontend; rejected attempts remain ordinary COW cuts.
if freeze := l.precopyFreeze; freeze != nil && context.Cause(ctx) == nil {
tail := uint64(len(candidates)) * uint64(l.blockSize) * l.chunkBlocks
detach = freeze(tail, pauseStart)
detach = freeze(tail, pauseStart, st)
}
if guestFrozen && !detach {
unlockCapture()
st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds()
l.abortCut(all)
dropCapturedIntents(ctx, intents)
return chunkCutResult{}, errors.Join(ErrFrozenTailTooLarge, context.Cause(ctx), l.admit())
}
if h < baseHead.RemoteLSN && !l.supersededBy(baseHead) {
@@ -866,7 +899,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
// reached: publishing would move remote_lsn backwards. Refused
// before any upload. (A HEAD of a newer holder fences below.)
l.abortCut(all)
l.dropIntents(ctx, intents)
dropCapturedIntents(ctx, intents)
return chunkCutResult{}, fmt.Errorf("%w: %w: cut LSN %d, HEAD remote_lsn %d", errChunkCaptureRefused, errChunkLSNBehind, h, baseHead.RemoteLSN)
}
@@ -876,11 +909,13 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
bytesBeforeCopy := st.UploadedBytes
{
var w *cutCOWWindow
windowStart := time.Now()
w, copyErr = l.installCOWWindow(candidates, useStaged, baseHead.Chunks)
if copyErr == nil {
w.budget = budget
}
unlockCapture()
st.WindowSetupNs += time.Since(windowStart).Nanoseconds()
st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds()
copyStart = time.Now()
if copyErr == nil {
@@ -904,11 +939,13 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
st.CopyNs = time.Since(copyStart).Nanoseconds()
if st.UploadedBytes > bytesBeforeCopy {
st.PayloadNs += st.CopyNs
} else {
st.NonPayloadCopyNs += st.CopyNs
}
st.UploadNs = st.CopyNs
if copyErr != nil {
l.abortCut(all)
l.dropIntents(ctx, intents)
dropCapturedIntents(ctx, intents)
return chunkCutResult{}, fmt.Errorf("storage: capture copy: %w", copyErr)
}
if b := l.cfg.BarrierBound; b > 0 && st.BarrierCopyChunks > b {
@@ -916,6 +953,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
}
// Upload only what changed against HEAD.
prepareStart := time.Now()
next := copyHead(baseHead)
next.Epoch, next.Holder, next.RemoteLSN = l.cfg.Epoch, l.cfg.Holder, h
next.State, next.DetachedBy = chunkHeadActive, nil
@@ -965,23 +1003,26 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
id, err := l.remote.PutIntent(ctx, chunkIntent{Gen: baseHead.Gen, Epoch: l.cfg.Epoch, Holder: l.cfg.Holder, Keys: keys})
if err != nil {
l.abortCut(all)
l.dropIntents(ctx, intents)
dropCapturedIntents(ctx, intents)
return chunkCutResult{}, fmt.Errorf("storage: capture intent: %w: %w", errChunkRemoteUnavailable, err)
}
intents = append(intents, id)
}
st.PublishPrepareNs += time.Since(prepareStart).Nanoseconds()
payloadStart := time.Now()
put := l.beginPutRound(len(uploads))
if err := l.uploadBatch(ctx, len(uploads), func(ctx context.Context, i int) error {
u := uploads[i]
return l.putCaptured(ctx, u.key, u.c.data)
return l.putCapturedWith(ctx, u.key, u.c.data, func(ctx context.Context) error { return put(ctx, i, u.key, u.c.data) })
}); err != nil {
l.abortCut(all)
l.dropIntents(ctx, intents)
dropCapturedIntents(ctx, intents)
return chunkCutResult{}, fmt.Errorf("storage: capture upload: %w", errors.Join(errChunkRemoteUnavailable, errCutUpload, err))
}
if len(uploads) > 0 {
st.PayloadNs += time.Since(payloadStart).Nanoseconds()
}
prepareStart = time.Now()
for _, u := range uploads {
next.Chunks[u.c.idx] = chunkRef{Key: u.key, SHA256: u.c.sum, Encoding: "full", BirthLSN: u.c.birth}
newKeys[u.c.idx] = u.key
@@ -989,16 +1030,19 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
st.UploadedChunks++
st.UploadedBytes += int64(max(len(u.c.data), u.c.size))
}
st.PublishPrepareNs += time.Since(prepareStart).Nanoseconds()
upgrade := false
if builder, ok := l.remote.(ChunkManifestBuilder); ok {
upgrade = baseHead.Segments == nil
var ids []string
var err error
manifestStart := time.Now()
next, ids, err = builder.PrepareManifest(ctx, baseHead, next, uint64(l.blockSize)*l.chunkBlocks)
st.ManifestNs += time.Since(manifestStart).Nanoseconds()
intents = append(intents, ids...)
if err != nil {
l.abortCut(all)
l.dropIntents(ctx, intents)
dropCapturedIntents(ctx, intents)
return chunkCutResult{}, err
}
}
@@ -1009,7 +1053,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
cur, err := readCapturedHead()
if err != nil {
l.abortCut(all)
l.dropIntents(ctx, intents)
dropCapturedIntents(ctx, intents)
return chunkCutResult{}, fmt.Errorf("storage: no-op cut authority read: %w: %w", errChunkRemoteUnavailable, err)
}
if cur.Gen != baseHead.Gen || !sameProposal(cur, baseHead) {
@@ -1020,19 +1064,19 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
l.fencePublication(cur)
return chunkCutResult{}, errChunkLayerFenced
}
l.finishCut(baseHead, h, nil, nil) // nothing new: no CAS
finishCapturedCut(baseHead, h, nil, nil) // nothing new: no CAS
persistCapturedMap(capturedVersions)
l.dropIntents(ctx, intents) // superseded staged uploads only
dropCapturedIntents(ctx, intents) // superseded staged uploads only
return chunkCutResult{H: h, Head: copyHead(baseHead), Noop: true, FullHash: all}, nil
}
if err := l.admit(); err != nil { // admission re-checked right before the CAS
l.abortCut(all)
l.dropIntents(ctx, intents)
dropCapturedIntents(ctx, intents)
return chunkCutResult{}, err
}
if l.supersededBy(baseHead) {
l.abortCut(all)
l.dropIntents(ctx, intents)
dropCapturedIntents(ctx, intents)
l.stMu.Lock()
l.fenced = true
l.stMu.Unlock()
@@ -1051,9 +1095,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
}
if casErr == nil {
next.Gen = gen
l.finishCut(next, h, changed, newKeys)
finishCapturedCut(next, h, changed, newKeys)
persistCapturedMap(capturedVersions)
l.dropIntents(ctx, intents)
dropCapturedIntents(ctx, intents)
return l.cutDone(chunkCutResult{H: h, Head: copyHead(next), FullHash: all}, detach), nil
}
// Precondition or unknown outcome: resolve by re-reading HEAD, never by
@@ -1091,14 +1135,14 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
}
if sameProposal(cur, next) {
st.CASResult = "resolved-by-reread"
l.finishCut(cur, h, changed, newKeys)
finishCapturedCut(cur, h, changed, newKeys)
persistCapturedMap(capturedVersions)
l.dropIntents(ctx, intents)
dropCapturedIntents(ctx, intents)
return l.cutDone(chunkCutResult{H: h, Head: copyHead(cur), FullHash: all}, detach), nil
}
// HEAD moved past the CAS's base without it: it can never land.
l.abortCut(all)
l.dropIntents(ctx, intents)
dropCapturedIntents(ctx, intents)
if l.supersededBy(cur) {
l.stMu.Lock()
l.fenced = true
@@ -0,0 +1,29 @@
package storage
import "context"
// ChunkPeriodicCutter is the chunk layer's cut for a periodic timer. The
// timer decides a cut is due from the last successful cut it saw; another
// cut (explicit, snapshot, detach, no-op) may still be running then and
// complete before this one gets the capture lock. That cut restarted the
// timer, so the due cut is not taken.
type ChunkPeriodicCutter interface {
// CutUnlessCutSince cuts unless a cut succeeded after lastCutNs (the
// LastCutNs the timer decided on); skipped reports that it did not cut.
CutUnlessCutSince(ctx context.Context, lastCutNs int64) (r ChunkCutResult, skipped bool, err error)
}
var _ ChunkPeriodicCutter = (*chunkLayerImpl)(nil)
func (l *chunkLayerImpl) CutUnlessCutSince(ctx context.Context, lastCutNs int64) (chunkCutResult, bool, error) {
l.capMu.Lock()
defer l.capMu.Unlock()
l.stMu.Lock()
last := l.stats.LastCutNs
l.stMu.Unlock()
if last > lastCutNs {
return chunkCutResult{}, true, nil
}
r, err := l.captureLocked(ctx, false)
return r, false, err
}
@@ -0,0 +1,36 @@
package storage
import "testing"
// A periodic cut decided before another cut completed is skipped; decided
// after the last cut, it cuts.
func TestChunkPeriodicCut_SkipsAfterANewerCut(t *testing.T) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
layer := mustAttach(t, s, f, ctConfig(1))
pc, ok := layer.(ChunkPeriodicCutter)
if !ok {
t.Fatal("the chunk layer has no periodic cut")
}
w := newWriteLog()
w.write(t, s, 2, 0x22)
decided := layer.Stats().LastCutNs // the timer decides here...
if _, err := layer.Cut(ctTimeout(t)); err != nil { // ...then another cut completes first
t.Fatal(err)
}
w.write(t, s, 9, 0x29)
casBefore := f.stats().cas
if _, skipped, err := pc.CutUnlessCutSince(ctTimeout(t), decided); err != nil || !skipped {
t.Fatalf("periodic cut decided before a newer cut: skipped=%v err=%v; want skipped", skipped, err)
}
if f.stats().cas != casBefore {
t.Fatal("a skipped periodic cut published")
}
r, skipped, err := pc.CutUnlessCutSince(ctTimeout(t), layer.Stats().LastCutNs)
if err != nil || skipped || r.Noop {
t.Fatalf("periodic cut decided after the last cut: skipped=%v noop=%v err=%v; want a cut", skipped, r.Noop, err)
}
if f.stats().cas != casBefore+1 {
t.Fatalf("CAS calls %d -> %d; want one", casBefore, f.stats().cas)
}
}
+113 -13
View File
@@ -25,6 +25,16 @@ const (
// PrecopyFixedParts are disjoint terms of the same retained fixed-cost sample.
type PrecopyFixedParts struct {
// Nested DataSync details, excluded from the additive measured sum.
SyncPhases SyncPhaseStats `json:"syncPhases"`
Candidate time.Duration `json:"candidateNs"`
WindowSetup time.Duration `json:"windowSetupNs"`
PublishPrepare time.Duration `json:"publishPrepareNs"`
Manifest time.Duration `json:"manifestNs"`
CommitState time.Duration `json:"commitStateNs"`
IntentCleanup time.Duration `json:"intentCleanupNs"`
NonPayloadCopy time.Duration `json:"nonPayloadCopyNs"`
Drain time.Duration `json:"drainNs"`
StoreLock time.Duration `json:"storeLockNs"`
DataSync time.Duration `json:"dataSyncNs"`
@@ -35,8 +45,8 @@ type PrecopyFixedParts struct {
}
func precopyFixedParts(st chunkCutStats, fixed time.Duration) PrecopyFixedParts {
p := PrecopyFixedParts{Drain: time.Duration(st.DrainNs), StoreLock: time.Duration(max(int64(0), st.LockWaitNs-st.DrainNs)), DataSync: time.Duration(st.SyncNs), HeadCAS: time.Duration(st.CASWriteNs), HeadReadback: time.Duration(st.HeadReadbackNs), MapPersist: time.Duration(st.MapPersistNs)}
p.Other = max(time.Duration(0), fixed-p.Drain-p.StoreLock-p.DataSync-p.HeadCAS-p.HeadReadback-p.MapPersist)
p := PrecopyFixedParts{SyncPhases: st.SyncPhases, Candidate: time.Duration(st.CandidateNs), WindowSetup: time.Duration(st.WindowSetupNs), PublishPrepare: time.Duration(st.PublishPrepareNs), Manifest: time.Duration(st.ManifestNs), CommitState: time.Duration(st.CommitStateNs), IntentCleanup: time.Duration(st.IntentCleanupNs), NonPayloadCopy: time.Duration(st.NonPayloadCopyNs), Drain: time.Duration(st.DrainNs), StoreLock: time.Duration(max(int64(0), st.LockWaitNs-st.DrainNs)), DataSync: time.Duration(st.SyncNs), HeadCAS: time.Duration(st.CASWriteNs), HeadReadback: time.Duration(st.HeadReadbackNs), MapPersist: time.Duration(st.MapPersistNs)}
p.Other = max(time.Duration(0), fixed-p.measured())
return p
}
@@ -48,6 +58,8 @@ type precopySample struct {
}
type PrecopyAttempt struct {
BarrierParts PrecopyFixedParts `json:"barrierParts"`
BarrierOverage time.Duration `json:"barrierOverageNs"`
// Attempt is the physical round ordinal, including measurement rounds.
Attempt int `json:"attempt"`
Drain time.Duration `json:"drainNs"`
@@ -68,6 +80,15 @@ type PrecopyAttempt struct {
// PrecopyReport records admission estimates, not a worst-case latency proof.
type PrecopyReport struct {
replayed bool // transport-local marker; never replaces the original freeze telemetry.
// Live barrier prefix is diagnostic, not additive to the selected forecast.
BarrierParts PrecopyFixedParts `json:"barrierParts"`
BarrierOverage time.Duration `json:"barrierOverageNs"`
GuestFrozen bool `json:"guestFrozen,omitempty"`
GuestFreezeElapsed time.Duration `json:"guestFreezeElapsedNs,omitempty"`
RemainingFreeze time.Duration `json:"remainingFreezeNs,omitempty"`
OverBudget bool `json:"overBudget,omitempty"`
Rounds []PrecopyAttempt `json:"rounds,omitempty"`
Drain time.Duration `json:"drainNs"`
DrainTimedOut bool `json:"drainTimedOut"`
@@ -103,7 +124,10 @@ func (r *PrecopyReport) Finish(elapsed time.Duration, extraCAS uint64, failed bo
r.CASFailureTimeout = chunkHeadOperationTimeout
r.DeclaredWorst = r.Estimate + time.Duration(extraCAS)*chunkHeadOperationTimeout
limit := precopyAllowance
if r.Reason == "no_progress" || r.Reason == "final_attempt" {
if r.GuestFrozen {
r.DeclaredWorst = r.DeclaredFreeze + time.Duration(extraCAS)*chunkHeadOperationTimeout
limit = precopyFreezeLimit
} else if r.Reason == "no_progress" || r.Reason == "final_attempt" {
limit = min(r.DeclaredFreeze, precopyFreezeLimit)
}
r.LatencyGateFailed = failed || elapsed > limit
@@ -126,7 +150,7 @@ func (l *chunkLayerImpl) PrecopyDetachWithAdmission(ctx context.Context, prepare
return l.precopyDetach(ctx, prepare, stopIO)
}
func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context.Context) (func(), error), stopIO func() bool) (ChunkCutResult, error) {
func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context.Context) (func(), error), stopIO func() bool) (result ChunkCutResult, resultErr error) {
if stopIO == nil {
return ChunkCutResult{}, fmt.Errorf("%w: missing I/O stop", ErrPrecopyUnknown)
}
@@ -136,13 +160,34 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context
return ChunkCutResult{}, err
}
defer l.capMu.Unlock()
defer func() {
if result.Precopy.Frozen && !result.Precopy.IsReplay() {
l.RememberDetachReport(result.Precopy)
}
}()
guestFreeze, externallyFrozen := FrozenDetachFromContext(ctx)
if err := ctx.Err(); err != nil {
return ChunkCutResult{}, err
}
if r, ok := l.storedDetach(); ok {
r.Precopy.Frozen = true
r.Precopy.replayed = true
return r, nil
}
l.stMu.Lock()
pending := l.pending != nil
l.stMu.Unlock()
if externallyFrozen && !pending {
if err := l.admit(); err != nil {
return ChunkCutResult{}, err
}
tail := l.candidateTail()
r := l.precopyEstimate(tail.Bytes, 0)
if !l.admitFrozen(&r, guestFreeze) {
return ChunkCutResult{Precopy: r}, frozenRefusal(r)
}
}
ctx, countCAS := WithChunkCASAccounting(ctx)
var report PrecopyReport
var frozenAt time.Time
@@ -171,7 +216,7 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context
longestPause = pause
}
}
l.precopyFreeze = func(tail uint64, barrierStart time.Time) bool {
l.precopyFreeze = func(tail uint64, barrierStart time.Time, current chunkCutStats) bool {
report = l.precopyEstimate(tail, report.Attempts)
report.Drain = drain
report.DrainTimedOut = errors.Is(drainErr, context.DeadlineExceeded)
@@ -183,8 +228,10 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context
return false
}
spent := time.Since(barrierStart)
report.BarrierParts = precopyFixedParts(current, spent)
if spent > report.Fixed {
extra := spent - report.Fixed
report.BarrierOverage = extra
report.Estimate += extra
report.FixedParts.Other += extra
report.Fixed = spent
@@ -196,10 +243,18 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context
if len(rounds) > 0 {
previous = &rounds[len(rounds)-1]
}
if !report.admitPrecopy(previous, len(rounds)+1 == precopyAttempts) {
admitted := false
if externallyFrozen {
admitted = l.admitFrozen(&report, guestFreeze)
} else {
admitted = report.admitPrecopy(previous, len(rounds)+1 == precopyAttempts)
}
if !admitted {
return false
}
report.DeclaredFreeze = report.Estimate
if !externallyFrozen {
report.DeclaredFreeze = report.Estimate
}
if !stopIO() {
report.Reason = "admitted_io"
return false
@@ -210,7 +265,11 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context
return true
}
defer func() { l.precopyFreeze = nil; l.precopyPause = nil; l.precopyPrepare = nil }()
for attempt := 1; attempt <= precopyAttempts; attempt++ {
maxAttempts := precopyAttempts
if externallyFrozen {
maxAttempts = 1
}
for attempt := 1; attempt <= maxAttempts; attempt++ {
// Measurement rounds still consume the same five-round/60s budget.
// Count an admission attempt only with a warm rate window at entry.
if l.precopyEstimate(0, 0).RateSamples >= 3 {
@@ -227,7 +286,7 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context
r, err := l.captureLocked(ctx, false)
report.SamplesAtStart, report.MeasurementRounds = samplesAtStart, measurementRounds
a := PrecopyAttempt{
Attempt: attempt, Drain: drain, Pause: pauseTotal - pauseBefore,
Attempt: attempt, Drain: drain, Pause: pauseTotal - pauseBefore, BarrierParts: report.BarrierParts, BarrierOverage: report.BarrierOverage,
TailBytes: report.TailBytes, RateSamples: report.RateSamples,
Estimate: report.Estimate, Reason: report.Reason, Frozen: report.Frozen,
Fixed: report.Fixed, FixedParts: report.FixedParts, TailEstimate: report.TailEstimate, DeclaredFreeze: report.DeclaredFreeze, PreviousEstimate: report.PreviousEstimate,
@@ -243,11 +302,13 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context
report.Rounds = rounds
report.TentativePauseTotal, report.LongestTentativePause = pauseTotal, longestPause
r.Precopy = report
if errors.Is(err, ErrFrozenTailTooLarge) {
return r, errors.Join(err, frozenRefusal(report))
}
if errors.Is(err, errChunkLayerDetached) {
if previous, ok := l.storedDetach(); ok {
previous.Precopy = report
previous.Precopy.Frozen = true
previous.Precopy.Reason = "previous_detach_applied"
previous.Precopy.replayed = true
return previous, nil
}
}
@@ -257,7 +318,11 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context
if attempts > 0 {
extra = attempts - 1
}
r.Precopy.Finish(time.Since(frozenAt), extra, err != nil)
elapsed := time.Since(frozenAt)
if externallyFrozen {
elapsed = time.Since(guestFreeze.StartedAt)
}
r.Precopy.Finish(elapsed, extra, err != nil)
return r, err
}
if err != nil {
@@ -370,7 +435,7 @@ func (r *PrecopyReport) admitPrecopy(previous *PrecopyAttempt, final bool) bool
func precopyFixedPartsFromSample(s precopySample) PrecopyFixedParts {
p := s.parts
p.Other = max(time.Duration(0), s.fixed-p.Drain-p.StoreLock-p.DataSync-p.HeadCAS-p.HeadReadback-p.MapPersist)
p.Other = max(time.Duration(0), s.fixed-p.measured())
return p
}
@@ -426,3 +491,38 @@ func comparablePrecopyAttempt(a *PrecopyAttempt) bool {
return false
}
}
func (p PrecopyFixedParts) measured() time.Duration {
return p.Drain + p.StoreLock + p.DataSync + p.HeadCAS + p.HeadReadback + p.MapPersist + p.Candidate + p.WindowSetup + p.PublishPrepare + p.Manifest + p.CommitState + p.IntentCleanup + p.NonPayloadCopy
}
// Candidate count is conservative and advisory while guest writes continue.
// The same immutable rate observation supplies both the estimate and its rate.
func (l *chunkLayerImpl) candidateTail() *ChunkCandidateTail {
return l.estimateCandidateTail(l.candidateTailBytes())
}
func (l *chunkLayerImpl) candidateTailBytes() uint64 {
if hook := l.testBeforeTailScanHook; hook != nil {
hook()
}
candidates := l.captureCandidates()
l.stMu.Lock()
for idx := range l.dirty {
candidates[idx] = true
}
if l.allDirty {
for idx := uint64(0); idx < l.numChunks; idx++ {
if !l.absent[idx] || l.chunkHasLocalLocked(idx) {
candidates[idx] = true
}
}
}
l.stMu.Unlock()
return uint64(len(candidates)) * uint64(l.blockSize) * l.chunkBlocks
}
func (l *chunkLayerImpl) estimateCandidateTail(bytes uint64) *ChunkCandidateTail {
r := l.precopyEstimate(bytes, 0)
return &ChunkCandidateTail{Bytes: bytes, Estimate: r.TailEstimate, BytesPerSecond: r.BytesPerSecond, RateSamples: r.RateSamples, SampleAge: r.SampleAge, Known: bytes == 0 || r.BytesPerSecond > 0}
}
@@ -0,0 +1,37 @@
package storage
import (
"context"
"errors"
)
// ErrChunkPutFinal marks a Put failure no retry can change (for example a
// rejected token): the caller stops retrying the object.
var ErrChunkPutFinal = errors.New("storage: chunk upload refused for good")
// ChunkPutRounds is an optional ChunkRemote capability: the objects of one
// upload round share remote reservations (batch assign) instead of taking
// one each. The round belongs to the cut or staging round that begins it and
// ends with it; it starts no goroutine of its own, so joining the round's
// workers joins every call it made.
type ChunkPutRounds interface {
BeginPutRound(n, objSize int) ChunkPutRound
}
// ChunkPutRound stores object i (0 <= i < n) of its round under key, with
// Put's rules: a bound key is never rebound (ErrChunkKeyExists). A failed Put
// may be retried with the same i and bytes.
type ChunkPutRound interface {
Put(ctx context.Context, i int, key string, data []byte) error
}
// beginPutRound returns the put for a round of n objects: the remote's
// round when it has one, otherwise one Put per object.
func (l *chunkLayerImpl) beginPutRound(n int) func(ctx context.Context, i int, key string, data []byte) error {
if rounds, ok := l.remote.(ChunkPutRounds); ok && n > 0 {
return rounds.BeginPutRound(n, int(uint64(l.blockSize)*l.chunkBlocks)).Put
}
return func(ctx context.Context, _ int, key string, data []byte) error {
return l.remote.Put(ctx, key, data)
}
}
@@ -0,0 +1,335 @@
package storage
import (
"bytes"
"context"
"errors"
"fmt"
"sync"
"testing"
"time"
)
// roundChunkRemote adds upload rounds to the fake remote and records them.
type roundChunkRemote struct {
*fakeChunkRemote
mu sync.Mutex
rounds []int // n of each round begun
puts [][2]int // {round, i} of each round Put
keys []string // key of each round Put
fail func(round, i int, attempt int) error
tries map[[2]int]int
}
type recordedRound struct {
r *roundChunkRemote
id int
}
func (r *roundChunkRemote) BeginPutRound(n, objSize int) ChunkPutRound {
r.mu.Lock()
defer r.mu.Unlock()
r.rounds = append(r.rounds, n)
return recordedRound{r: r, id: len(r.rounds) - 1}
}
func (rr recordedRound) Put(ctx context.Context, i int, key string, data []byte) error {
r := rr.r
r.mu.Lock()
r.puts = append(r.puts, [2]int{rr.id, i})
r.keys = append(r.keys, key)
if r.tries == nil {
r.tries = map[[2]int]int{}
}
r.tries[[2]int{rr.id, i}]++
attempt := r.tries[[2]int{rr.id, i}]
fail := r.fail
r.mu.Unlock()
if fail != nil {
if err := fail(rr.id, i, attempt); err != nil {
return err
}
}
return r.fakeChunkRemote.Put(ctx, key, data)
}
// A cut uploads its changed chunks through one round of the remote, one
// object index per chunk (the round may be sized for more candidates than
// end up changed); a cut with nothing to upload begins none. A retried
// upload keeps its index.
func TestChunkCut_UploadsThroughOneRound(t *testing.T) {
s, _ := newChunkTestStore(t)
f := &roundChunkRemote{fakeChunkRemote: newFakeChunkRemote()}
f.fail = func(round, i, attempt int) error {
if i == 0 && attempt == 1 {
return errors.New("transient upload failure")
}
return nil
}
layer := mustAttach(t, s, f, ctConfig(1))
w := newWriteLog()
w.write(t, s, 2, 0x22)
w.write(t, s, 9, 0x29)
if _, err := layer.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
f.mu.Lock()
rounds, puts := append([]int(nil), f.rounds...), append([][2]int(nil), f.puts...)
f.mu.Unlock()
if len(rounds) != 1 || rounds[0] < 1 {
t.Fatalf("rounds %v; want one round for the cut", rounds)
}
seen := map[int]int{}
for _, p := range puts {
if p[0] != 0 || p[1] < 0 || p[1] >= rounds[0] {
t.Fatalf("round put %v outside round 0 of %d", p, rounds[0])
}
seen[p[1]]++
}
if seen[0] != 2 {
t.Fatalf("object 0 sent %d times; want the failed attempt and its retry on the same index", seen[0])
}
if len(seen) != 2 {
t.Fatalf("round of %d used indexes %v; want one per changed chunk (2)", rounds[0], seen)
}
if _, err := layer.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
f.mu.Lock()
n := len(f.rounds)
f.mu.Unlock()
if n != 1 {
t.Fatalf("a cut with nothing to upload began a round (%d rounds)", n)
}
}
// A round that cannot store an object fails the cut: no HEAD names it.
func TestChunkCut_FailedRoundPublishesNothing(t *testing.T) {
s, _ := newChunkTestStore(t)
f := &roundChunkRemote{fakeChunkRemote: newFakeChunkRemote()}
f.fail = func(int, int, int) error { return ErrChunkKeyExists }
layer := mustAttach(t, s, f, ctConfig(1))
w := newWriteLog()
w.write(t, s, 2, 0x22)
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
if _, err := layer.Cut(ctx); err == nil {
t.Fatal("cut with a refused upload succeeded")
}
if heads := f.installedHeads(); len(heads) != 0 {
t.Fatalf("installed %d HEADs after a failed upload", len(heads))
}
}
// A final upload outcome is not retried: the object is sent once, its
// binding is checked, and the cut fails at once.
func TestChunkCut_FinalUploadIsNotRetried(t *testing.T) {
s, _ := newChunkTestStore(t)
f := &roundChunkRemote{fakeChunkRemote: newFakeChunkRemote()}
f.fail = func(int, int, int) error { return errors.Join(ErrChunkPutFinal, errors.New("token rejected")) }
layer := mustAttach(t, s, f, ctConfig(1))
w := newWriteLog()
w.write(t, s, 2, 0x22)
start := time.Now()
if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, ErrChunkPutFinal) {
t.Fatalf("cut with a final upload refusal: %v", err)
}
if took := time.Since(start); took > 5*time.Second {
t.Fatalf("cut took %v: the final refusal was retried", took)
}
f.mu.Lock()
defer f.mu.Unlock()
for k, n := range f.tries {
if n != 1 {
t.Fatalf("object %v sent %d times; want once", k, n)
}
}
}
// heldRound blocks every round Put until released; cooperative Puts also
// end with their context. It records the bytes of every attempt, and closes
// cancelled when an outstanding Put's context ends.
type heldRound struct {
*fakeChunkRemote
cooperative bool
entered chan struct{}
cancelled chan struct{}
release chan struct{}
once sync.Once
cancelOnce sync.Once
mu sync.Mutex
sent [][]byte
transient int // the first transient attempts fail after being recorded
mutate func()
}
func newHeldRound(cooperative bool) *heldRound {
return &heldRound{fakeChunkRemote: newFakeChunkRemote(), cooperative: cooperative,
entered: make(chan struct{}), cancelled: make(chan struct{}), release: make(chan struct{})}
}
func (h *heldRound) BeginPutRound(n, objSize int) ChunkPutRound { return heldRoundPut{h} }
type heldRoundPut struct{ h *heldRound }
func (p heldRoundPut) Put(ctx context.Context, i int, key string, data []byte) error {
h := p.h
h.mu.Lock()
h.sent = append(h.sent, append([]byte(nil), data...))
attempt := len(h.sent)
mutate := h.mutate
h.mu.Unlock()
h.once.Do(func() { close(h.entered) })
if mutate != nil && attempt == 1 {
mutate()
}
if attempt <= h.transient {
return errors.New("transient upload failure")
}
go func() { // witness: the outstanding call's context ended
select {
case <-ctx.Done():
h.cancelOnce.Do(func() { close(h.cancelled) })
case <-h.release:
}
}()
if h.cooperative {
select {
case <-h.release:
case <-ctx.Done():
return ctx.Err()
}
} else {
<-h.release
}
return h.fakeChunkRemote.Put(ctx, key, data)
}
// waitDone waits for ch, failing t after a bound.
func waitDone(t *testing.T, ch <-chan struct{}, what string) {
t.Helper()
select {
case <-ch:
case <-time.After(10 * time.Second):
t.Fatalf("timed out waiting for %s", what)
}
}
// While a round's upload call is held, guest writes and flushes go on;
// Close cancels the call's context, then joins it: a cooperative call ends
// and Close returns; an uncooperative one is still joined, and Close does
// not return before it does.
func TestChunkCut_HeldRoundCallIsJoined(t *testing.T) {
for _, cooperative := range []bool{true, false} {
t.Run(fmt.Sprintf("cooperative=%v", cooperative), func(t *testing.T) {
s, _ := newChunkTestStore(t)
h := newHeldRound(cooperative)
var releaseOnce sync.Once
release := func() { releaseOnce.Do(func() { close(h.release) }) }
layer := mustAttach(t, s, h, ctConfig(1))
w := newWriteLog()
w.write(t, s, 2, 0x22)
cutDone := make(chan error, 1)
closeDone := make(chan error, 1)
guest := make(chan error, 1)
closeStarted, guestStarted := false, false
t.Cleanup(func() { // release, then join every worker started and not yet joined
release()
for _, c := range []struct {
ch chan error
started bool
}{{cutDone, true}, {closeDone, closeStarted}, {guest, guestStarted}} {
if !c.started {
continue
}
select {
case <-c.ch:
case <-time.After(10 * time.Second):
t.Error("a worker never returned")
}
}
})
go func() { _, err := layer.Cut(context.Background()); cutDone <- err }()
waitDone(t, h.entered, "the cut's upload call")
guestStarted = true
go func() {
if _, err := s.Write(7, makeBlock(ctBlockSize, 0x77)); err != nil {
guest <- err
return
}
_, err := s.Sync()
guest <- err
}()
select {
case err := <-guest:
guestStarted = false // joined
if err != nil {
t.Fatalf("guest write/flush during the held upload: %v", err)
}
case <-time.After(10 * time.Second):
t.Fatal("a guest write or flush waited on the held upload call")
}
closeStarted = true
go func() { closeDone <- layer.Close() }()
// Close has cancelled the layer's calls: it is past cancel, at its join.
waitDone(t, h.cancelled, "Close cancelling the held call")
if !cooperative {
select {
case err := <-closeDone:
closeDone <- err
t.Fatal("Close returned while an uncooperative upload call was still running")
case <-time.After(300 * time.Millisecond):
}
release()
}
select {
case err := <-closeDone:
closeDone <- err
if err != nil {
t.Fatalf("Close: %v", err)
}
case <-time.After(10 * time.Second):
t.Fatal("Close did not return")
}
select {
case err := <-cutDone:
cutDone <- err
if err == nil {
t.Fatal("the cut succeeded across Close")
}
case <-time.After(10 * time.Second):
t.Fatal("the cut did not end with Close")
}
})
}
}
// A retried upload sends the bytes captured for the cut, not the guest's
// newer write to the same block.
func TestChunkCut_RetrySendsTheCapturedBytes(t *testing.T) {
s, _ := newChunkTestStore(t)
h := newHeldRound(true)
h.transient = 1
close(h.release)
w := newWriteLog()
h.mutate = func() { w.write(t, s, 2, 0x99) } // the guest overwrites the block mid-upload
layer := mustAttach(t, s, h, ctConfig(1))
w.write(t, s, 2, 0x22)
if _, err := layer.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
h.mu.Lock()
defer h.mu.Unlock()
if len(h.sent) != 2 {
t.Fatalf("%d upload attempts; want the failed one and its retry", len(h.sent))
}
if !bytes.Equal(h.sent[0], h.sent[1]) {
t.Fatal("the retry sent different bytes than the first attempt")
}
if bytes.Contains(h.sent[1], makeBlock(ctBlockSize, 0x99)) {
t.Fatal("the retry sent the guest's newer write")
}
}
+38 -6
View File
@@ -396,7 +396,25 @@ type chunkLayerConfig struct {
// chunkCutStats describes one cut. The periodic-cut work fills it; a zero
// value means "not measured".
// SyncPhaseStats are nested details of SyncNs; never add them to SyncNs.
type SyncPhaseStats struct {
LifecycleWaitNs int64 `json:"lifecycleWaitNs"`
StoreWaitNs int64 `json:"storeWaitNs"`
GroupCommitNs int64 `json:"groupCommitNs"`
CompletionWaitNs int64 `json:"completionWaitNs"`
}
type chunkCutStats struct {
SyncPhases SyncPhaseStats
// Disjoint non-payload intervals within barrier-to-settlement fixed cost.
CandidateNs int64
WindowSetupNs int64
PublishPrepareNs int64
ManifestNs int64
CommitStateNs int64
IntentCleanupNs int64
NonPayloadCopyNs int64
PayloadNs int64 // disjoint streaming/copy/upload wall intervals
// Local validated WAL attempts and local copy duration, including savers.
@@ -487,13 +505,27 @@ type chunkLayerStats struct {
// the current HEAD when the cut had nothing new (Noop: no CAS).
// - FullHash says the cut compared every chunk by hash (no usable bitmap,
// or the first cut after a BASE install).
//
// ChunkCandidateTail is advisory pending work sampled after a successful cut.
// Bytes and rate/estimate belong to one sampler observation; Known=false must
// never be interpreted as a zero-cost tail. Admission rechecks at its barrier.
type ChunkCandidateTail struct {
Bytes uint64 `json:"bytes"`
Estimate time.Duration `json:"estimateNs"`
BytesPerSecond float64 `json:"bytesPerSecond"`
RateSamples int `json:"rateSamples"`
SampleAge time.Duration `json:"sampleAgeNs"`
Known bool `json:"known"`
}
type chunkCutResult struct {
Precopy PrecopyReport
H uint64
Head chunkHead
Noop bool
FullHash bool
Stats chunkCutStats
CandidateTail *ChunkCandidateTail
Precopy PrecopyReport
H uint64
Head chunkHead
Noop bool
FullHash bool
Stats chunkCutStats
}
// chunkLayer is what the store owner drives.
+10 -1
View File
@@ -14,6 +14,12 @@ import (
// Keep the point and frozen buffer through transient failures until the cut
// context ends (deadline, Close or window abort), never a fresh point.
func (l *chunkLayerImpl) putCaptured(ctx context.Context, key string, data []byte) error {
return l.putCapturedWith(ctx, key, data, func(ctx context.Context) error { return l.remote.Put(ctx, key, data) })
}
// putCapturedWith is putCaptured over put, one object's slot in an upload
// round: every retry sends through the same put.
func (l *chunkLayerImpl) putCapturedWith(ctx context.Context, key string, data []byte, put func(context.Context) error) error {
// The per-object retry deadline also bounds a contextless cut. It retains
// the same point and buffer through a remote outage, never re-reads live data.
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
@@ -24,7 +30,7 @@ func (l *chunkLayerImpl) putCaptured(ctx context.Context, key string, data []byt
if err := ctx.Err(); err != nil {
return errors.Join(lastErr, err)
}
err := l.remote.Put(ctx, key, data)
err := put(ctx)
if err == nil {
return nil
}
@@ -37,6 +43,9 @@ func (l *chunkLayerImpl) putCaptured(ctx context.Context, key string, data []byt
}
return errChunkKeyExists
}
if errors.Is(err, ErrChunkPutFinal) {
return err
}
timer := time.NewTimer(backoff)
select {
case <-ctx.Done():
+34 -1
View File
@@ -752,10 +752,25 @@ func (s *WALStore) readExtentBlock(lba uint32) ([]byte, error) {
// becomes crash-survivable only when a Sync that covers its LSN
// returns nil. Group commit batches concurrent Sync callers into one
// fsync.
func (s *WALStore) Sync() (uint64, error) {
func (s *WALStore) Sync() (uint64, error) { return s.syncWithPhases(nil) }
// Optional capture telemetry leaves the ordinary Sync contract and lock order
// unchanged. Only the requesting goroutine updates these nested phase costs.
func (s *WALStore) syncWithPhases(phases *SyncPhaseStats) (uint64, error) {
var at time.Time
if phases != nil {
at = time.Now()
}
s.lifecycleMu.RLock()
if phases != nil {
phases.LifecycleWaitNs += time.Since(at).Nanoseconds()
at = time.Now()
}
defer s.lifecycleMu.RUnlock()
s.mu.RLock()
if phases != nil {
phases.StoreWaitNs += time.Since(at).Nanoseconds()
}
if s.closed {
s.mu.RUnlock()
return 0, errors.New("storage: Sync after Close")
@@ -778,6 +793,9 @@ func (s *WALStore) Sync() (uint64, error) {
s.mu.RUnlock()
if phases != nil {
at = time.Now()
}
if s.walSyncCovered() {
// Preserve shutdown refusal even when no file I/O is necessary.
select {
@@ -788,6 +806,9 @@ func (s *WALStore) Sync() (uint64, error) {
} else if err := s.syncCache(); err != nil {
return 0, fmt.Errorf("storage: group commit fsync: %w", err)
}
if phases != nil {
phases.GroupCommitNs += time.Since(at).Nanoseconds()
}
s.syncs.Add(1)
{
@@ -797,7 +818,13 @@ func (s *WALStore) Sync() (uint64, error) {
}
// The completion is validated against the recovery generation under
// the leader role: a recovery since the capture refuses the ack.
if phases != nil {
at = time.Now()
}
v.syncMu.Lock()
if phases != nil {
phases.CompletionWaitNs += time.Since(at).Nanoseconds()
}
defer v.syncMu.Unlock()
if v.recoverGen.Load() != targetGen {
return 0, errV3RecoveredMeanwhile
@@ -807,7 +834,13 @@ func (s *WALStore) Sync() (uint64, error) {
}
}
if phases != nil {
at = time.Now()
}
s.mu.Lock()
if phases != nil {
phases.StoreWaitNs += time.Since(at).Nanoseconds()
}
// A fault latched while this Sync waited (another caller's fsync or
// append, or a flusher fsync) refuses it: nothing is acknowledged.
if err := s.stickyIOFault(); err != nil {
+11 -4
View File
@@ -208,9 +208,13 @@ stateDiagram-v2
Admit --> Refused: budget refused, closed, fenced, detached, base install, or lineage or lease invalid
Admit --> PlainStop: plain detach and idle frontend lock acquired
PlainStop --> Quiesce: frontend stopped; ordinary detached cut
Admit --> Stage: budget admitted, earlier unknown CAS settled
Admit --> FrozenForecast: guest already frozen with an explicit origin
FrozenForecast --> Refused: unknown or non-fitting remaining budget
FrozenForecast --> Quiesce: plausible estimate or explicit final override; skip staging
Admit --> Stage: ordinary cut; budget admitted, earlier unknown CAS settled
Stage --> Quiesce: spill-budget remainder reached or no shrink
Quiesce --> FinalFreeze: opt-in measured tail fits after bounded admission drain
Quiesce --> Refused: guest-frozen budget recheck failed; no payload upload
Quiesce --> FinalFreeze: measured admission or explicit frozen final override
FinalFreeze --> OpenWindow: admission stays closed through detached settlement
Quiesce --> OpenWindow: ordinary round; Sync H and D fixed under barrier
OpenWindow --> Copy: release barrier
@@ -241,6 +245,8 @@ stateDiagram-v2
| Pre-copy admission | opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts reopen before ordinary uploads | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-001` |
| Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` |
| Pre-copy detach | at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; a known estimate may use the declared five-second freeze ceiling when it is at least 90% of the previous comparable known estimate or on the final physical round; frozen commands wait up to the five-second cutover budget and resume in FIFO order after a safe abort | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` |
| Guest-frozen detach | `frozen=true` carries a non-future guest freeze origin; forecast before staging, recheck authoritative candidates after Sync, and perform at most one cut. Ordinary frozen refusal issues no staging/payload upload and retains dirty bytes. Explicit `allowOverBudget=true` records `over_budget` and retains authority, drain and CAS settlement checks; actual whole-guest elapsed still reports a five-second violation. | `chunk_frozen_budget.go`; `chunk_precopy.go`; `captureLocked`; `DetachVolumeFrozen`; `/chunk/detach` | `INV-CUT-PRECOPY-001` |
| Checkpoint tail | successful cuts sample remaining candidates and transfer cost from one rate observation after publication; zero bytes is known zero, insufficient history for a nonzero tail is unknown. This is advisory; frozen admission rechecks its own candidates. | `chunk_precopy.go` `candidateTail`; `chunk_control.go` `ChunkCutResponse` | `INV-CUT-PRECOPY-001` |
| Pre-copy host drain | a committed freeze keeps commands held while host storage admission closes; transport teardown cancels held commands before joining the session, without issuing their storage work | `storage_adapter.go` `setOperationalLocked`; `nvme/session.go` `serve` | `INV-CUT-PRECOPY-001` |
| Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt) is read by a bounded upload worker at upload time; a staged copy is reused only if unchanged since staging; native copy occurs after barrier release with pre-publication COW ownership | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001` |
| LSN guard | refuse when H is below HEAD's `RemoteLSN` (`lsn_behind`) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-MONOTONE-001` |
@@ -341,7 +347,7 @@ snapshot lifetime; local persistence does not bypass it.
## Part B. Invariant ledger
117 rows: 98 ACTIVE, 19 STUB; 15 kept from the internal ledger, 102 new.
118 rows: 99 ACTIVE, 19 STUB; 15 kept from the internal ledger, 103 new.
The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger.
@@ -481,7 +487,7 @@ Notes:
| `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE |
| `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE |
| `INV-CUT-PLAIN-DETACH-001` | A plain detach closes the frontend only when no I/O holds its admission lock; no store or remote call occurs while this lock is held. An admitted or entering operation makes the request refuse unchanged. Cost admission alone is bypassed; ordinary detached publication and unknown/fenced/aborted settlement stay enforced. An absent or false field preserves pre-copy policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestPlainDetachSkipsPrecopyCostAdmission`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE |
| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Refusal reopens tentative admission before rolling uploads. A contended freeze fallback never replaces an existing pause or its queue clock. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. Admission fits the allowance, or declares an estimate within five seconds when it is at least 90% of the previous comparable known estimate, or on the final physical round. The fixed input is the maximum of up to the latest five observations younger than fifteen minutes (at least one required); disjoint parts come from the same selected observation. Unknown samples never admit. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample`, `TestPrecopyDetachBusyOwnerExhaustsWithoutStopping`, `TestPrecopyDetachBusyOwnerRetainsSlowFixedCost`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachRefusedFinalCutRetainsSlowFixedCost`, `TestPrecopyDetachRetryResolvesPreviouslyAppliedDetachedCut`, `TestPrecopyDetachAppliedRetryRetainsSlowFixedCost`, `TestPrecopyAttemptDiagnosticsSeparateTimeoutFromFit`, `TestPrecopyAttemptDiagnosticsRetainSlowFixedCost`, `TestPrecopyStopIOReturnTimestampPrecedesFinalPublication`, `TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds`, `TestPrecopyUnknownPreviousCannotClaimProgress`, `TestPrecopyCallerExpiryVersusClose`, `TestPrecopySmokeTraceAmendment4`, `TestPrecopyFixedWindowDecays`, `TestPrecopyFinalAttemptFreezeCeiling`, `TestPrecopyFixedCostSmallTailCommitsBySecondAttempt`, `TestPrecopyLargeTailStillRefusesFixedCostException`, `TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds`, `TestPrecopyFixedPartsStayWithLargestObservation`, `TestPrecopyFixedPartsMeasureCASAndReadbackSeparately`, `TestPrecopyFixedExceptionFinishUsesDeclaredFreeze` (`core/storage/chunk_precopy_fixed_commit_test.go`), `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt` (first eligible allowance or plateau attempt), `TestPrecopyFiftyIOPSSlowMeasuredCostsKeepServing` (retained slow cost, declared admission or refusal, active owner and exact local bytes), `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyFiftyIOPSRoundAccounting` (five total physical rounds, including success and measurement rounds), `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | `PrecopyFixedAdmission.tla` (bounded cost admission only); controlled callers and measured latency are not a model proof | ACTIVE |
| `INV-CUT-PRECOPY-001` | Opt-in final-tail admission closes frontend admission, drains registered I/O before the store lock within a 100 ms caller context, then uses authoritative barrier candidates and measured costs. Ordinary refusal reopens tentative admission before rolling uploads; guest-frozen refusal instead sends no payload. A contended freeze fallback never replaces an existing pause or its queue clock. Final freeze queues without completion for up to five seconds; safe resume is FIFO, host drain preserves the active queue, and transport teardown cancels commands before joining; no queued storage work is issued. Only settled detached publication permits handoff; aborted rounds retain dirty bytes. Warm attempts and measurement rounds are reported separately, with samples at start; both consume the same five-round budget. Admission fits the allowance, or declares an estimate within five seconds when it is at least 90% of the previous comparable known estimate, or on the final physical round. The fixed input is the maximum of up to the latest five observations younger than fifteen minutes (at least one required); disjoint parts come from the same selected observation. Ordinary admission never uses unknown samples. A guest-frozen attempt skips staging, forecasts and rechecks against five seconds minus guest elapsed, and refuses without uploading if it cannot fit. Only an explicit final override can bypass that estimate guard, with over_budget recorded; authority and publication settlement remain mandatory. Checkpoint tails are advisory same-window measurements. Nested Sync phases and live barrier-prefix spans explain fixed cost without double counting. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `chunk_frozen_budget.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestFrozenDetachRejectsBeforeStagingOrUpload`, `TestFrozenDetachRechecksBudgetAtBarrierWithoutUpload`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestCheckpointTailScanIncludedInTotalAndFixedCosts`, `TestCheckpointTailUsesLiteralLatestThreeConservativeRate`, `TestFrozenDetachForcedFinalCommitsSamePoint`, `TestFrozenFinalOverrideKeepsAuthorityAndCloseGuards`, `TestFrozenRetryDoesNotHideUnknownPublication`, `TestFrozenProviderFlagOffRefusesWithoutUploadThenFinalCommits`, `TestChunkFrozenDetachWireContractAndPrecedence`, `TestCheckpointTailMeasuresWritesAfterItsCut`, `TestChunkCutFixedSpansAttributeManifestAndCleanup`, `TestPrecopyLiveBarrierSpansExplainOverage`, `TestPrecopyFixedPartsDoNotDoubleCountSyncPhases`, `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample`, `TestPrecopyDetachBusyOwnerExhaustsWithoutStopping`, `TestPrecopyDetachBusyOwnerRetainsSlowFixedCost`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachRefusedFinalCutRetainsSlowFixedCost`, `TestPrecopyDetachRetryResolvesPreviouslyAppliedDetachedCut`, `TestPrecopyDetachAppliedRetryRetainsSlowFixedCost`, `TestPrecopyAttemptDiagnosticsSeparateTimeoutFromFit`, `TestPrecopyAttemptDiagnosticsRetainSlowFixedCost`, `TestPrecopyStopIOReturnTimestampPrecedesFinalPublication`, `TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds`, `TestPrecopyUnknownPreviousCannotClaimProgress`, `TestPrecopyCallerExpiryVersusClose`, `TestPrecopySmokeTraceAmendment4`, `TestPrecopyFixedWindowDecays`, `TestPrecopyFinalAttemptFreezeCeiling`, `TestPrecopyFixedCostSmallTailCommitsBySecondAttempt`, `TestPrecopyLargeTailStillRefusesFixedCostException`, `TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds`, `TestPrecopyFixedPartsStayWithLargestObservation`, `TestPrecopyFixedPartsMeasureCASAndReadbackSeparately`, `TestPrecopyFixedExceptionFinishUsesDeclaredFreeze` (`core/storage/chunk_precopy_fixed_commit_test.go`), `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt` (first eligible allowance or plateau attempt), `TestPrecopyFiftyIOPSSlowMeasuredCostsKeepServing` (retained slow cost, declared admission or refusal, active owner and exact local bytes), `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyFiftyIOPSRoundAccounting` (five total physical rounds, including success and measurement rounds), `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyQueueResumesInFIFOOrder`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | `PrecopyFixedAdmission.tla` (ordinary admission), `FrozenDetachBudget.tla` (forecast/barrier budget, upload guard, explicit override and stable-authority publicationLine truncated
| `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE |
| `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE |
| `INV-CUT-RECONCILING-001` | ARCHIVED: the legacy bitmap/reconciler is retired. Native owned-map validation and fail-closed attach admission replace its dirty-coverage protection; a provided legacy bitmap is ignored. | M5 native map admission | `core/storage/chunk_layer.go` `AttachChunkLayer` | `TestChunkAttachRefusesAnUnmappedNativeStore`; `TestChunkLayerV3_IgnoresProvidedLegacyBitmap` (`core/storage/chunk_layer_map_only_v3_test.go`) | legacy reconciliation transition retired | ARCHIVED |
@@ -500,6 +506,7 @@ Notes:
| `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE |
| `INV-CUT-HYDRATION-WAIT-001` | A read command shares its arrival deadline across chunks. A timed-out waiter returns typed pending without cancelling a shared fill. Per-layer worker and distinct-flight limits bound remote work; Close wakes waiters and joins issued fills before storage release. Physical/hash errors remain terminal. | M4 Holder (hydration wait) | `core/storage/chunk_hydration.go`; `core/storage/walstore.go` `ReadContext`; `core/frontend/durable/storage_adapter.go` `readStorageBlock`; `core/frontend/nvme/session.go` `handleRead` | `TestDurableHydration_MultipleChunksShareOneDeadline`, `TestDurableHydration_NVMePreservesPhysicalAndHashErrors`, `TestSessionReadBudgetIncludesQueueResidence`, `TestChunkHydration_QueueAndWorkerLimitsAreBounded`, `TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet`, `TestChunkHydration_ContextlessReadAllowsSlowFill`, `TestChunkHydration_NewGenerationDoesNotJoinStaleGet`, `TestChunkHydration_StaleCompletionKeepsReplacement`, `TestDurableHydration_RMWFenceWinsCallerExpiry` | — | ACTIVE |
| `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch, v3 remains dark) | — | ACTIVE |
| `INV-CUT-TIMER-RESTART-001` | A successful cut of any kind (explicit, snapshot, detach, no-op) restarts the periodic timer. A periodic cut the loop decided from an older last cut, while another cut was still running, is skipped under the capture lock once that cut has completed: no automatic cut follows another cut within the interval. | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `chunkLoop`; `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince` | `TestWALStoreChunk_ExplicitCutRestartsTheTimer`, `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`); `TestChunkPeriodicCut_SkipsAfterANewerCut` (`core/storage/chunk_periodic_cut_test.go`) | — | ACTIVE |
A guest read has a cooperative arrival budget; internal contextless readers keep the owned fill timeout (default 30 s). With five immediate host retries, cold fills slower than roughly 20–24 s can still end in guest EIO despite shared work; retry-delay advertisement remains separate. A changed generation replaces its promise without abandoning the old worker. `AllBlocks` returns an error and no partial image on a failed read; the rebuild sender propagates it before sending blocks.
@@ -0,0 +1,56 @@
------------------------ MODULE FrozenDetachBudget ------------------------
\* One externally frozen attempt; physical latency and orchestrator retries
\* are outside this model. Authority is stable during the modeled attempt;
\* mid-cut authority/CAS races remain CutCOW2/publication proof obligations.
EXTENDS Integers, TLC
CONSTANTS OmitElapsed, OmitBarrierGuard, OmitStageGuard,
OmitOverrideRecord, OmitAuthority
Limit == 50
VARIABLES phase, elapsed, estimate, known, force, authority, admitted,
uploaded, published, overBudget, atElapsed, atEstimate, atKnown
vars == <<phase,elapsed,estimate,known,force,authority,admitted,
uploaded,published,overBudget,atElapsed,atEstimate,atKnown>>
Init == /\ phase = "forecast" /\ elapsed \in {0,30,60}
/\ estimate \in {5,30,60} /\ known \in BOOLEAN
/\ force \in BOOLEAN /\ authority \in BOOLEAN
/\ admitted = FALSE /\ uploaded = FALSE /\ published = FALSE
/\ overBudget = FALSE /\ atElapsed = 0 /\ atEstimate = 0
/\ atKnown = FALSE
AuthorityOK == authority \/ OmitAuthority
Fits == known /\ estimate > 0 /\ estimate + (IF OmitElapsed THEN 0 ELSE elapsed) <= Limit
Eligible == AuthorityOK /\ (force \/ Fits)
Forecast == /\ phase = "forecast" /\ Eligible /\ phase' = "stage"
/\ UNCHANGED <<elapsed,estimate,known,force,authority,admitted,
uploaded,published,overBudget,atElapsed,atEstimate,atKnown>>
RefuseForecast == /\ phase = "forecast" /\ ~Eligible /\ phase' = "refused"
/\ UNCHANGED <<elapsed,estimate,known,force,authority,admitted,
uploaded,published,overBudget,atElapsed,atEstimate,atKnown>>
Barrier == /\ phase = "stage" /\ phase' = "barrier"
/\ elapsed' \in {elapsed,elapsed+20}
/\ estimate' \in {estimate,estimate+30} /\ known' \in BOOLEAN
/\ uploaded' = (uploaded \/ OmitStageGuard)
/\ UNCHANGED <<force,authority,admitted,published,overBudget,atElapsed,atEstimate,atKnown>>
Admit == /\ phase = "barrier" /\ (Eligible \/ (OmitBarrierGuard /\ AuthorityOK))
/\ phase' = "admitted" /\ admitted' = TRUE
/\ atElapsed' = elapsed /\ atEstimate' = estimate /\ atKnown' = known
/\ overBudget' = (force /\ ~OmitOverrideRecord)
/\ UNCHANGED <<elapsed,estimate,known,force,authority,uploaded,published>>
RefuseBarrier == /\ phase = "barrier" /\ ~Eligible /\ ~OmitBarrierGuard
/\ phase' = "refused"
/\ UNCHANGED <<elapsed,estimate,known,force,authority,admitted,
uploaded,published,overBudget,atElapsed,atEstimate,atKnown>>
Upload == /\ phase = "admitted" /\ phase' = "uploaded" /\ uploaded' = TRUE
/\ UNCHANGED <<elapsed,estimate,known,force,authority,admitted,
published,overBudget,atElapsed,atEstimate,atKnown>>
Publish == /\ phase = "uploaded" /\ AuthorityOK /\ phase' = "done"
/\ published' = TRUE
/\ UNCHANGED <<elapsed,estimate,known,force,authority,admitted,
uploaded,overBudget,atElapsed,atEstimate,atKnown>>
Done == /\ phase \in {"done","refused"} /\ UNCHANGED vars
Next == Forecast \/ RefuseForecast \/ Barrier \/ Admit \/ RefuseBarrier \/ Upload \/ Publish \/ Done
Spec == Init /\ [][Next]_vars
NoUploadBeforeAdmission == uploaded => admitted
BudgetAtAdmission == admitted /\ ~force => atKnown /\ atEstimate > 0 /\ atElapsed + atEstimate <= Limit
OverrideVisible == admitted /\ force => overBudget
AuthorityAtPublication == published => authority
=============================================================================
+27
View File
@@ -381,3 +381,30 @@ From `docs/spec`, SANY `PlainDetach.tla` exited 0; TLC with
`cfg/PlainDetach_no_idle.cfg` exited 12: `IdleAtStop` fails on
BeginIO -> Plain (7 generated / 5 distinct, depth 3). The negative uses a
distinct `-metadir` to avoid timestamp-directory collisions between short runs.
## Guest-frozen detach admission
`FrozenDetachBudget.tla` models one externally frozen attempt: a forecast,
skipped staging, changed time/estimate/knowledge at the barrier, explicit
admission, upload and publication. Time units are tenths of a second. It checks
`NoUploadBeforeAdmission`, `BudgetAtAdmission`, `OverrideVisible` and
`AuthorityAtPublication`. Authority is stable within this finite model; mid-cut
fencing and CAS races remain covered by the publication/COW contracts. It does
not prove physical latency or the external controller's two-re-freeze limit.
Local run 2026-11-21 02:53 UTC, TLC2.19, tools SHA-256
`936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88`:
```sh
java -Xmx512m -cp /path/to/tla2tools.jar tlc2.TLC -deadlock -config cfg/FrozenDetachBudget.cfg FrozenDetachBudget
```
Positive exited0:667 generated/439 distinct states, queue empty, complete depth6.
The same command with each negative config exited12 at its intended invariant:
`no_elapsed`410/267 depth4; `no_barrier`386/237 depth4;
`staging_upload`151/145 depth3; `hidden_override`367/229 depth4;
`no_authority`951/603 depth6. The first two violate `BudgetAtAdmission`, the
third `NoUploadBeforeAdmission`, the fourth `OverrideVisible`, and the last
`AuthorityAtPublication`. Source tests separately check time/metadata handling,
no-upload refusal, preserved bytes, uncertain outcomes and typed API dispatch.
@@ -0,0 +1,8 @@
SPECIFICATION Spec
CONSTANTS
OmitElapsed = FALSE
OmitBarrierGuard = FALSE
OmitStageGuard = FALSE
OmitOverrideRecord = FALSE
OmitAuthority = FALSE
INVARIANTS NoUploadBeforeAdmission BudgetAtAdmission OverrideVisible AuthorityAtPublication
@@ -0,0 +1,8 @@
SPECIFICATION Spec
CONSTANTS
OmitElapsed = FALSE
OmitBarrierGuard = FALSE
OmitStageGuard = FALSE
OmitOverrideRecord = TRUE
OmitAuthority = FALSE
INVARIANTS NoUploadBeforeAdmission BudgetAtAdmission OverrideVisible AuthorityAtPublication
@@ -0,0 +1,8 @@
SPECIFICATION Spec
CONSTANTS
OmitElapsed = FALSE
OmitBarrierGuard = FALSE
OmitStageGuard = FALSE
OmitOverrideRecord = FALSE
OmitAuthority = TRUE
INVARIANTS NoUploadBeforeAdmission BudgetAtAdmission OverrideVisible AuthorityAtPublication
@@ -0,0 +1,8 @@
SPECIFICATION Spec
CONSTANTS
OmitElapsed = FALSE
OmitBarrierGuard = TRUE
OmitStageGuard = FALSE
OmitOverrideRecord = FALSE
OmitAuthority = FALSE
INVARIANTS NoUploadBeforeAdmission BudgetAtAdmission OverrideVisible AuthorityAtPublication
@@ -0,0 +1,8 @@
SPECIFICATION Spec
CONSTANTS
OmitElapsed = TRUE
OmitBarrierGuard = FALSE
OmitStageGuard = FALSE
OmitOverrideRecord = FALSE
OmitAuthority = FALSE
INVARIANTS NoUploadBeforeAdmission BudgetAtAdmission OverrideVisible AuthorityAtPublication
@@ -0,0 +1,8 @@
SPECIFICATION Spec
CONSTANTS
OmitElapsed = FALSE
OmitBarrierGuard = FALSE
OmitStageGuard = TRUE
OmitOverrideRecord = FALSE
OmitAuthority = FALSE
INVARIANTS NoUploadBeforeAdmission BudgetAtAdmission OverrideVisible AuthorityAtPublication