Files
seaweedfs/weed/mount/flush_fold_test.go
T
Chris LuandClaude Opus 5.5 46b10efcce mount: refuse a stale truncate over a peer's chunks and keep later times when merging a flush (#13100)
* mount: refuse a merge whose local truncate cuts chunks a peer wrote

A flush refused by IF_ENTRY_EQUAL replays the handle's truncate onto the
stored entry. The truncate was made over the handle's base, so a chunk a
peer committed after that base was dropped or clipped silently, losing
data the peer had already fsynced. Like a stale whole-file rewrite over a
peer's chunk change, it now fails the merge. A base chunk the peer only
shortened carries no peer data and is still cut.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: keep the later mtime and ctime when merging a delayed flush

The merge took every attribute the handle changed from the handle, so a
flush that waited behind a peer's commit moved mtime and ctime back to
the handle's older write. Each time is now merged as one value (seconds
and nanoseconds were merged field by field, so a moved second could take
the peer's nanoseconds): the handle's time stands unless a peer moved it
too and later.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: let a truncate merge pass the handle's own committed chunks

A flush whose commit answer was lost finds its own chunks in the stored
entry while its base is still the older one. Those chunks are the
handle's writes, not a peer's, so they do not refuse the merge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: do not keep a stored copy of a chunk the merge re-adds from the handle

A stored chunk the base lacks but the handle holds is the handle's own
commit whose answer was lost. The merge appends the handle's chunks after
the stored ones, so keeping the stored copy referenced the chunk twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: take the manifests of a failed flush's fold for the handle's own chunks

A flush can commit its folded manifests and lose the answer. The handle
reverts to the member chunks and keeps its old base, so the next merge
found the stored manifest, knew neither its file id nor its key, and
refused it as a peer write across the handle's truncate.

The handle now remembers the folds of flushes that failed over its base,
and a merge unfolds them in the stored entry before comparing, so the
members match the handle's chunks. A peer's manifest is still refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: take a retried flush's own stored fold for its own chunks

The client retries a request whose connection dropped, and the first try
may have stored the flush's folded manifests. The retry is then refused
over them before the fold is recorded as failed, and the merge took the
manifest for a peer's write across the handle's truncate. The merge now
unfolds the flush's own fold in the stored entry as well; the condition
still names the entry as stored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: keep every fold the filer may hold instead of the last four

Dropping the oldest of four could forget the fold the filer committed,
and the merge then refused that manifest again. A fold is now kept only
when the flush failed without the filer's answer, or when the refusal
lookup shows it stored, so a refused flush no longer adds one, and the
list ends with the base.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: keep a flush's fold when its first request may have been stored

A precondition verdict on a retried send does not prove the first send
stored nothing, and a failed refusal lookup then hid that it had. The
create now counts the sends of the request that carries the fold and
keeps the fold whenever the flush fails and that request was sent more
than once or never got the filer's answer. That covers both flush paths,
so revert is back to only restoring the chunks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: drop the failed folds a refused create shows were not stored

A refusal means the stored entry moved off the handle's base, so no
request guarded by that base can store another fold. After the refusal
lookup the handle keeps only the folds whose manifests the stored entry
holds, at most one, which bounds the list over a base.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: bound the failed folds a handle keeps over one base

Flushes that keep failing with no filer answer each saved a new fold the
filer may hold, so the list grew for as long as the outage lasted. Once a
handle keeps maxFailedFolds folds over its base, its flushes send their
chunks unfolded for the filer to fold, and no kept fold is dropped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: keep the failed folds a refusal lookup does not show

The refusal comes from the file's write owner, but the lookup after it can
read a filer that lags behind and still shows the base. Pruning the folds
against that read forgot a fold the owner had stored, and once its manifest
showed up a pending truncate took it for a peer's chunk on every flush. The
maxFailedFolds limit bounds the list, so the folds stay until the base moves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: drop the chunks a failed flush sent that the handle has cut since

A flush that commits with its answer lost, then a truncate of the handle,
left the next merge with the handle's own committed chunks in the stored
entry, outside both base and the handle. The truncate check took them for
a peer's writes and refused every later flush over the base. A failed
flush now records the file ids of the chunks it sent that base lacks, and
the merge drops those the handle no longer holds: it cut or replaced them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: copy the failed flush's sent set with a loop

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: keep folding past maxFailedFolds instead of sending chunks unfolded

The filer folds a flat chunk list itself, into manifests the handle does
not know: a lost answer then left one of them across a pending truncate,
and an acknowledged one gave the handle flat chunks under a folded base.
Flushes fold as before, and the handle stops keeping folds past the limit
while it still records the chunks they sent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: read the stored manifests a refused merge cannot name

A fold changes no content, but a manifest the handle does not know sat in
the stored entry as one chunk: across a pending truncate it refused the
merge, though it can hold the handle's own chunks (a fold it did not keep,
or one the filer made). When the merge is refused, the flush reads those
manifests, replaces them with the chunks they hold and merges again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: hold the chunks the filer stored after a plain acknowledged flush

The filer folds a flat chunk list (the mount's own fold failed), and the
acknowledgement makes the stored entry the base while the handle kept the
flat chunks. A later merge took them for writes of the handle, which can
bring back chunks a peer's truncate removed. As after a merge, the handle
now takes the stored chunks, keeping those attached since the request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: keep a bounded record per failed flush instead of a growing set

The set of chunk ids failed flushes sent grew with every overwrite while
commits failed, and each failure copied it whole. Each failed flush the
filer may have stored (a send got no verdict) now keeps one record, its
fold and the ids it sent, built once and at most maxFailedFlushes over a
base. Past that, a merge refuses the chunks of a flush it did not keep
that the handle has cut since, as a peer's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: register the chunks a rebase or install gives the handle for reads

A handle that takes the stored chunks after a flush (or a peer's, after a
merge) can get manifests the filer made, and resolving them needs the
file's read token. rebaseEntry and installRewrittenChunks now record the
chunks under the file's path before the read view resolves them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: keep every chunk id a failed flush sent, cap only the folds

Past four failed flushes over one base the handle stopped recording what a
later flush sent. If that flush was stored with its answer lost, a truncate
of its chunks was refused as a peer's write and kept failing after the
filer came back. The ids now go into one set shared by the base's marks,
each kept once and never copied, until the base moves. Only the folds stay
capped: a stored manifest past the cap is read when a refused merge cannot
place it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: fail a flush over a peer's chunk change unless -concurrentWriteMerge

A content flush refused because another mount committed first used to
merge the handle's writes onto the stored entry. That merge now runs
only with the new -concurrentWriteMerge mount option (off by default).
By default a stored chunk change that neither the base nor the handle
holds fails the flush with EIO, and a peer's chunk event no longer
rebases a dirty handle. Attribute-only changes and the handle's own
commits (a lost answer, its own truncate) still merge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: recognize the shortened references a failed flush sent

A truncate shrinks a base chunk in place, keeping its file id. A failed
flush that may have stored such a reference recorded only file ids base
lacks, so a later truncate saw its own stored reference as a peer's
change and failed with EIO by default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:34:30 -08:00

618 lines
27 KiB
Go

package mount
import (
"context"
"fmt"
"io"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/go-fuse/v2/fuse"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/wdclient"
)
// foldMergeSaver stands in for wfs.saveDataAsChunk when a test folds chunks:
// each saved manifest gets a fresh file id.
type foldMergeSaver struct{ saved uint64 }
func (s *foldMergeSaver) save(reader io.Reader, name string, offset int64, tsNs int64, expectedDataSize uint64) (*filer_pb.FileChunk, error) {
if _, err := io.Copy(io.Discard, reader); err != nil {
return nil, err
}
s.saved++
return &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 9, FileKey: s.saved, Cookie: 1}, ModifiedTsNs: tsNs}, nil
}
// mergeFoldFile is a file of n small appended chunks (base) whose handle
// appended one more chunk and folded on flush, as flushMetadataToFiler does
// (local, fold).
func mergeFoldFile(t *testing.T, n int) (base, local *filer_pb.Entry, fold *chunkFold) {
t.Helper()
var chunks []*filer_pb.FileChunk
for i := 0; i < n; i++ {
chunks = append(chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 1, FileKey: uint64(i + 1), Cookie: 1}, Offset: int64(i) * 300, Size: 300, ModifiedTsNs: int64(i + 1)})
}
attrs := &filer_pb.FuseAttributes{Inode: 7, FileSize: uint64(n) * 300, FileMode: 0644}
base = &filer_pb.Entry{Name: "progress.jsonl", Attributes: attrs, Chunks: chunks}
appended := &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 1, FileKey: uint64(n + 1), Cookie: 1}, Offset: int64(n) * 300, Size: 300, ModifiedTsNs: int64(n + 1)}
before := append(append([]*filer_pb.FileChunk(nil), chunks...), appended)
saver := &foldMergeSaver{}
after, err := filer.MaybeManifestize(saver.save, nil, before)
require.NoError(t, err)
fold = newChunkFold(before, after)
require.NotNil(t, fold)
localAttrs := proto.Clone(attrs).(*filer_pb.FuseAttributes)
localAttrs.FileSize = uint64(n+1) * 300
local = &filer_pb.Entry{Name: "progress.jsonl", Attributes: localAttrs, Chunks: after}
return base, local, fold
}
func referenceCounts(chunks []*filer_pb.FileChunk) map[string]int {
keys := make(map[string]int, len(chunks))
for _, c := range chunks {
keys[contentChunkKey(c)]++
}
return keys
}
func TestChunkFoldUnfoldsToTheChunksItHolds(t *testing.T) {
base, local, fold := mergeFoldFile(t, filer.SmallChunkManifestBatch+44)
manifests, _ := filer.SeparateManifestChunks(local.Chunks)
require.Len(t, manifests, 1)
require.Len(t, fold.members, filer.SmallChunkManifestBatch)
unfolded := fold.unfoldChunks(local.Chunks)
want := referenceCounts(base.Chunks)
got := referenceCounts(unfolded)
require.Len(t, got, len(want)+1, "the base chunks and the appended one")
for key := range want {
require.Equal(t, 1, got[key], "chunk %s", key)
}
// a list that is missing one of the fold's manifests is left alone
require.Equal(t, base.Chunks, fold.unfoldChunks(base.Chunks))
var nilFold *chunkFold
require.Equal(t, local.Chunks, nilFold.unfoldChunks(local.Chunks))
require.Nil(t, newChunkFold(base.Chunks, base.Chunks))
}
// A peer that folded the same chunks: the merge keeps the peer's manifest and
// does not add the handle's, so each chunk is referenced once.
func TestMergeAfterFoldKeepsThePeersFoldOnly(t *testing.T) {
base, local, fold := mergeFoldFile(t, filer.SmallChunkManifestBatch+44)
peerSaver := &foldMergeSaver{saved: 1000}
peerChunks, err := filer.MaybeManifestize(peerSaver.save, nil, append([]*filer_pb.FileChunk(nil), base.Chunks...))
require.NoError(t, err)
peerManifests, _ := filer.SeparateManifestChunks(peerChunks)
require.Len(t, peerManifests, 1)
stored := proto.Clone(base).(*filer_pb.Entry)
stored.Chunks = peerChunks
merged, ok := mergeContentEntry(stored, base, fold.unfold(local), fold.unfold(local), -1, false)
require.True(t, ok)
manifests, _ := filer.SeparateManifestChunks(merged.Chunks)
require.Len(t, manifests, 1)
require.Equal(t, contentChunkKey(peerManifests[0]), contentChunkKey(manifests[0]))
// without the unfold the handle's manifest of the same chunks is added too
merged, ok = mergeContentEntry(stored, base, local, local, -1, false)
require.True(t, ok)
manifests, _ = filer.SeparateManifestChunks(merged.Chunks)
require.Len(t, manifests, 2)
}
// A peer that rewrote the whole file: the merge must not bring the base
// chunks back inside the handle's manifest, where they would cover the peer's
// rewritten bytes wherever their stamps are newer.
func TestMergeAfterFoldDoesNotRestoreChunksThePeerDropped(t *testing.T) {
base, local, fold := mergeFoldFile(t, filer.SmallChunkManifestBatch+44)
stored := proto.Clone(base).(*filer_pb.Entry)
stored.Chunks = []*filer_pb.FileChunk{{Fid: &filer_pb.FileId{VolumeId: 2, FileKey: 1, Cookie: 1}, Offset: 0, Size: base.Attributes.FileSize, ModifiedTsNs: 1}}
merged, ok := mergeContentEntry(stored, base, fold.unfold(local), fold.unfold(local), -1, false)
require.True(t, ok)
keys := referenceCounts(merged.Chunks)
require.Len(t, keys, 2, "the peer's rewrite and the handle's appended chunk")
for _, c := range merged.Chunks {
require.False(t, c.IsChunkManifest, "no manifest of dropped chunks")
}
for _, c := range base.Chunks {
require.Zero(t, keys[contentChunkKey(c)], "base chunk %s came back", contentChunkKey(c))
}
// without the unfold the manifest of base chunks is added as a local write
merged, ok = mergeContentEntry(stored, base, local, local, -1, false)
require.True(t, ok)
manifests, _ := filer.SeparateManifestChunks(merged.Chunks)
require.Len(t, manifests, 1)
}
// A flush that truncated, folded and committed but lost the answer: the next
// merge finds the fold's manifest stored and takes it for the handle's own
// chunks, not for a peer's write across the truncate.
func TestMergeTakesAFailedFlushsFoldForItsOwn(t *testing.T) {
base := flushConditionEntry(1, 2)
var written []*filer_pb.FileChunk
for i := 0; i < filer.SmallChunkManifestBatch+4; i++ {
written = append(written, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 3, FileKey: uint64(i + 1), Cookie: 1}, Offset: int64(i) * 300, Size: 300, ModifiedTsNs: int64(100 + i)})
}
after, err := filer.MaybeManifestize((&foldMergeSaver{}).save, nil, written)
require.NoError(t, err)
fold := newChunkFold(written, after)
require.NotNil(t, fold)
local := proto.Clone(base).(*filer_pb.Entry)
local.Chunks = written
local.Attributes.FileSize = uint64(len(written)) * 300
stored := proto.Clone(local).(*filer_pb.Entry)
stored.Chunks = after
_, ok := mergeContentEntry(stored, base, local, local, 0, false)
require.False(t, ok, "an unknown manifest across the truncate is a peer's")
fh := &FileHandle{}
fh.baseEntry.Store(base)
fh.noteFailedFlush(fold, nil)
mark := fh.markSince(base)
require.Len(t, mark.folds, 1)
merged, ok := mergeContentEntry(mark.unfoldOwn(stored, local), base, local, local, 0, false)
require.True(t, ok)
require.Equal(t, referenceCounts(written), referenceCounts(merged.Chunks))
require.Equal(t, local.Attributes.FileSize, merged.Attributes.FileSize)
fh.adoptPeerBase(stored)
require.Empty(t, fh.markSince(stored).folds)
}
// foldMergeFiler keeps the stored entry and its IF_ENTRY_EQUAL condition like
// contentFlushConditionFiler, and points AssignVolume at a volume stub, so a
// flush can store the manifests it folds.
type foldMergeFiler struct {
contentFlushConditionFiler
volume string
assigns atomic.Int32
}
func (s *foldMergeFiler) AssignVolume(ctx context.Context, req *filer_pb.AssignVolumeRequest) (*filer_pb.AssignVolumeResponse, error) {
n := s.assigns.Add(1)
return &filer_pb.AssignVolumeResponse{
FileId: fmt.Sprintf("3,%02x637037d6", n),
Count: 1,
Location: &filer_pb.Location{Url: s.volume, PublicUrl: s.volume},
}, nil
}
// A flush that folds the handle's chunks finds the entry rewritten by a peer
// (a bloat merge on another mount: one chunk, stamped older than the bytes it
// replaced). The merged commit carries the peer's rewrite and the handle's own
// append, not a manifest of the base chunks the peer dropped.
func TestFlushMergeAfterFoldLeavesThePeersRewrite(t *testing.T) {
const n = filer.SmallChunkManifestBatch + 44
wfs := newInvalidateTestWFS(t)
wfs.option.ConcurrentWriteMerge = true
wfs.option.ConcurrentWriters = 4
wfs.option.uniqueCacheDirForWrite = t.TempDir()
wfs.concurrentWriters = util.NewLimitedConcurrentExecutor(4)
fake := &foldMergeFiler{volume: newVolumeStub(t)}
startFakeFiler(t, wfs, fake)
wfs.option.VolumeServerAccess = "direct"
wfs.filerClient = wdclient.NewFilerClient(wfs.option.FilerAddresses, wfs.option.GrpcDialOption, "")
attrs := &filer_pb.FuseAttributes{Inode: 42, FileMode: 0644, Uid: 2000, Gid: 20, FileSize: n * 300}
base := &filer_pb.Entry{Name: "file", Attributes: attrs}
for i := 0; i < n; i++ {
base.Chunks = append(base.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 1, FileKey: uint64(i + 1), Cookie: 1}, Offset: int64(i) * 300, Size: 300, ModifiedTsNs: int64(100 + i)})
}
rewrite := &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 2, FileKey: 999, Cookie: 1}, Offset: 0, Size: n * 300, ModifiedTsNs: 1}
peer := proto.Clone(base).(*filer_pb.Entry)
peer.Chunks = []*filer_pb.FileChunk{rewrite}
fake.entry = peer
appended := &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 1, FileKey: n + 1, Cookie: 1}, Offset: n * 300, Size: 300, ModifiedTsNs: 100 + n}
live := proto.Clone(base).(*filer_pb.Entry)
live.Chunks = append(live.Chunks, appended)
live.Attributes.FileSize = (n + 1) * 300
observed := proto.Clone(base).(*filer_pb.Entry)
wfs.mapPbIdFromFilerToLocal(observed)
wfs.mapPbIdFromFilerToLocal(live)
fh := newFileHandle(wfs, 1, 42, live)
t.Cleanup(func() { fh.dirtyPages.Destroy() })
fh.baseEntry.Store(observed)
fh.RememberPath(util.FullPath("/dir/file"))
fh.dirtyMetadata = true
require.Equal(t, fuse.OK, wfs.doFlush(context.Background(), fh, 1000, 20, false, 0))
require.NotZero(t, fake.assigns.Load(), "the flush folded and stored a manifest")
fake.mu.Lock()
defer fake.mu.Unlock()
keys := referenceCounts(fake.entry.Chunks)
require.Len(t, keys, 2, "the peer's rewrite and the handle's append: %v", keys)
require.Equal(t, 1, keys[contentChunkKey(rewrite)])
require.Equal(t, 1, keys[contentChunkKey(appended)])
}
// lostAnswerFiler fails every create without a verdict while stalled, then
// stores the first create and fails it like a dropped
// connection, so the client retries the same request.
type lostAnswerFiler struct {
foldMergeFiler
lost atomic.Bool
failLookups atomic.Int32
stall atomic.Bool
}
func (s *lostAnswerFiler) LookupDirectoryEntry(ctx context.Context, r *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
if s.failLookups.Add(-1) >= 0 {
return nil, status.Error(codes.Internal, "lookup failed")
}
return s.foldMergeFiler.LookupDirectoryEntry(ctx, r)
}
func (s *lostAnswerFiler) CreateEntry(ctx context.Context, r *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
if s.stall.Load() {
return nil, status.Error(codes.Internal, "store stalled")
}
resp, err := s.foldMergeFiler.CreateEntry(ctx, r)
if err == nil && resp.GetError() == "" && s.lost.CompareAndSwap(false, true) {
return nil, status.Error(codes.Unavailable, "connection lost after commit")
}
return resp, err
}
// A flush that truncated and folded its writes commits, loses the answer, and
// retries the same request: the retry is refused over the manifest it stored
// itself, which the merge must take for the flush's own chunks.
func TestFlushRetryAfterLostAnswerTakesItsOwnFold(t *testing.T) {
for _, failLookups := range []int32{0, 1} {
t.Run(fmt.Sprintf("failed lookups %d", failLookups), func(t *testing.T) {
testFlushRetryAfterLostAnswer(t, failLookups)
})
}
}
// With the refusal lookup failing, the flush fails; the next flush must still
// know the stored manifest for its own.
func testFlushRetryAfterLostAnswer(t *testing.T, failLookups int32) {
const n = filer.SmallChunkManifestBatch + 4
wfs := newInvalidateTestWFS(t)
wfs.option.ConcurrentWriters = 4
wfs.option.uniqueCacheDirForWrite = t.TempDir()
wfs.concurrentWriters = util.NewLimitedConcurrentExecutor(4)
fake := &lostAnswerFiler{foldMergeFiler: foldMergeFiler{volume: newVolumeStub(t)}}
startFakeFiler(t, wfs, fake)
wfs.option.VolumeServerAccess = "direct"
wfs.filerClient = wdclient.NewFilerClient(wfs.option.FilerAddresses, wfs.option.GrpcDialOption, "")
base := flushConditionEntry(1, 2)
fake.entry = proto.Clone(base).(*filer_pb.Entry)
live := proto.Clone(base).(*filer_pb.Entry)
live.Chunks = nil
for i := 0; i < n; i++ {
live.Chunks = append(live.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 3, FileKey: uint64(i + 1), Cookie: 1}, Offset: int64(i) * 300, Size: 300, ModifiedTsNs: int64(100 + i)})
}
live.Attributes.FileSize = n * 300
observed := proto.Clone(base).(*filer_pb.Entry)
wfs.mapPbIdFromFilerToLocal(observed)
wfs.mapPbIdFromFilerToLocal(live)
fh := newFileHandle(wfs, 1, 42, live)
t.Cleanup(func() { fh.dirtyPages.Destroy() })
fh.baseEntry.Store(observed)
fh.noteTruncate(0)
fh.RememberPath(util.FullPath("/dir/file"))
fh.dirtyMetadata = true
fake.failLookups.Store(failLookups)
if failLookups > 0 {
require.NotEqual(t, fuse.OK, wfs.doFlush(context.Background(), fh, 1000, 20, false, 0))
require.Len(t, fh.markSince(fh.baseEntry.Load()).folds, 1, "the fold the filer may hold is kept")
}
require.Equal(t, fuse.OK, wfs.doFlush(context.Background(), fh, 1000, 20, false, 0))
require.True(t, fake.lost.Load(), "the first commit's answer was dropped")
fake.mu.Lock()
defer fake.mu.Unlock()
require.Equal(t, referenceCounts(live.Chunks), referenceCounts(fake.entry.Chunks))
}
// A flush commits the handle's appended chunks, loses the answer and fails;
// the handle then truncates them away. The next flush is refused over the
// stored chunks, which are the handle's own cut writes, not a peer's: it must
// publish the truncate instead of refusing the merge.
// When the filer folded the chunks itself, the merge reads its manifest.
// With the handle's folds full from flushes that got no answer, the lost
// flush also sent a chunk none of them did.
func TestFlushAfterLostAnswerTakesItsOwnTruncate(t *testing.T) {
for _, c := range []struct {
n int
filerFolds bool
foldsFull bool
}{{1, false, false}, {filer.SmallChunkManifestBatch + 4, false, false}, {filer.SmallChunkManifestBatch + 4, true, false}, {filer.SmallChunkManifestBatch + 4, false, true}} {
t.Run(fmt.Sprintf("%d appended, filer folds %v, folds full %v", c.n, c.filerFolds, c.foldsFull), func(t *testing.T) {
testFlushAfterLostAnswerTakesItsOwnTruncate(t, c.n, c.filerFolds, c.foldsFull)
})
}
}
// refoldingLostAnswerFiler assigns no volume, so the mount cannot fold, and
// folds a create before lostAnswerFiler stores it.
type refoldingLostAnswerFiler struct {
*lostAnswerFiler
saver foldMergeSaver
}
func (s *refoldingLostAnswerFiler) AssignVolume(ctx context.Context, req *filer_pb.AssignVolumeRequest) (*filer_pb.AssignVolumeResponse, error) {
return &filer_pb.AssignVolumeResponse{Error: "no writable volumes"}, nil
}
func (s *refoldingLostAnswerFiler) CreateEntry(ctx context.Context, r *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
r = proto.Clone(r).(*filer_pb.CreateEntryRequest)
folded, err := filer.MaybeManifestize(s.saver.save, nil, r.Entry.Chunks)
if err != nil {
return nil, err
}
r.Entry.Chunks = folded
return s.lostAnswerFiler.CreateEntry(ctx, r)
}
func testFlushAfterLostAnswerTakesItsOwnTruncate(t *testing.T, n int, filerFolds, foldsFull bool) {
wfs := newInvalidateTestWFS(t)
wfs.option.ConcurrentWriters = 4
wfs.option.uniqueCacheDirForWrite = t.TempDir()
wfs.concurrentWriters = util.NewLimitedConcurrentExecutor(4)
fake := &lostAnswerFiler{foldMergeFiler: foldMergeFiler{volume: newVolumeStub(t)}}
var server filer_pb.SeaweedFilerServer = fake
if filerFolds {
server = &refoldingLostAnswerFiler{lostAnswerFiler: fake, saver: foldMergeSaver{saved: 500}}
}
startFakeFiler(t, wfs, server)
wfs.option.VolumeServerAccess = "direct"
wfs.filerClient = wdclient.NewFilerClient(wfs.option.FilerAddresses, wfs.option.GrpcDialOption, "")
base := flushConditionEntry(1, 2)
fake.entry = proto.Clone(base).(*filer_pb.Entry)
live := proto.Clone(base).(*filer_pb.Entry)
for i := 0; i < n; i++ {
live.Chunks = append(live.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 3, FileKey: uint64(i + 1), Cookie: 1}, Offset: 3 + int64(i)*300, Size: 300, ModifiedTsNs: int64(100 + i)})
}
live.Attributes.FileSize = 3 + uint64(n)*300
observed := proto.Clone(base).(*filer_pb.Entry)
wfs.mapPbIdFromFilerToLocal(observed)
wfs.mapPbIdFromFilerToLocal(live)
fh := newFileHandle(wfs, 1, 42, live)
t.Cleanup(func() { fh.dirtyPages.Destroy() })
fh.baseEntry.Store(observed)
fh.RememberPath(util.FullPath("/dir/file"))
fh.dirtyMetadata = true
if foldsFull {
oldSleep := metadataFlushSleep
metadataFlushSleep = func(context.Context, time.Duration) {}
t.Cleanup(func() { metadataFlushSleep = oldSleep })
fake.stall.Store(true)
failUntilFoldsFull(t, wfs, fh, observed)
fake.stall.Store(false)
fh.UpdateEntry(func(e *filer_pb.Entry) {
e.Chunks = append(e.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 3, FileKey: 999, Cookie: 1}, Offset: int64(e.Attributes.FileSize), Size: 300, ModifiedTsNs: 999})
e.Attributes.FileSize += 300
})
}
if filerFolds || foldsFull {
var written []*filer_pb.FileChunk
fh.UpdateEntry(func(e *filer_pb.Entry) { written = proto.Clone(e).(*filer_pb.Entry).Chunks })
saved := truncateManifestResolver
t.Cleanup(func() { truncateManifestResolver = saved })
truncateManifestResolver = func(ctx context.Context, wfs *WFS, manifest *filer_pb.FileChunk) (held []*filer_pb.FileChunk, err error) {
for _, c := range written {
if c.Offset >= manifest.Offset && chunkSpanEnd(c) <= chunkSpanEnd(manifest) {
held = append(held, proto.Clone(c).(*filer_pb.FileChunk))
}
}
return held, nil
}
}
fake.failLookups.Store(1)
require.NotEqual(t, fuse.OK, wfs.doFlush(context.Background(), fh, 1000, 20, false, 0))
require.True(t, fake.lost.Load(), "the first commit's answer was dropped")
fh.UpdateEntry(func(e *filer_pb.Entry) {
e.Chunks = e.Chunks[:2]
e.Attributes.FileSize = 3
})
fh.noteTruncate(3)
require.Equal(t, fuse.OK, wfs.doFlush(context.Background(), fh, 1000, 20, false, 0))
fake.mu.Lock()
defer fake.mu.Unlock()
require.Equal(t, referenceCounts(base.Chunks), referenceCounts(fake.entry.Chunks))
require.Equal(t, uint64(3), fake.entry.Attributes.FileSize)
}
// noAnswerFiler fails every create without a verdict, as a stalled store
// does: the filer may hold any of them.
type noAnswerFiler struct{ foldMergeFiler }
func (s *noAnswerFiler) CreateEntry(ctx context.Context, r *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
return nil, status.Error(codes.Internal, "store stalled")
}
// Flushes that keep failing without an answer keep at most maxFailedFolds
// folds, and the later ones still fold.
func TestFailedFlushesKeepBoundedFolds(t *testing.T) {
const n = filer.SmallChunkManifestBatch + 4
wfs := newInvalidateTestWFS(t)
wfs.option.ConcurrentWriters = 4
wfs.option.uniqueCacheDirForWrite = t.TempDir()
wfs.concurrentWriters = util.NewLimitedConcurrentExecutor(4)
fake := &noAnswerFiler{foldMergeFiler{volume: newVolumeStub(t)}}
startFakeFiler(t, wfs, fake)
wfs.option.VolumeServerAccess = "direct"
wfs.filerClient = wdclient.NewFilerClient(wfs.option.FilerAddresses, wfs.option.GrpcDialOption, "")
base := flushConditionEntry(1, 2)
fake.entry = proto.Clone(base).(*filer_pb.Entry)
live := proto.Clone(base).(*filer_pb.Entry)
for i := 0; i < n; i++ {
live.Chunks = append(live.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 3, FileKey: uint64(i + 1), Cookie: 1}, Offset: int64(i) * 300, Size: 300, ModifiedTsNs: int64(100 + i)})
}
live.Attributes.FileSize = n * 300
observed := proto.Clone(base).(*filer_pb.Entry)
wfs.mapPbIdFromFilerToLocal(observed)
wfs.mapPbIdFromFilerToLocal(live)
fh := newFileHandle(wfs, 1, 42, live)
t.Cleanup(func() { fh.dirtyPages.Destroy() })
fh.baseEntry.Store(observed)
fh.RememberPath(util.FullPath("/dir/file"))
fh.dirtyMetadata = true
oldSleep := metadataFlushSleep
metadataFlushSleep = func(context.Context, time.Duration) {}
t.Cleanup(func() { metadataFlushSleep = oldSleep })
failUntilFoldsFull(t, wfs, fh, observed)
assigns := fake.assigns.Load()
for i := 0; i < 2; i++ {
require.NotEqual(t, fuse.OK, wfs.doFlush(context.Background(), fh, 1000, 20, false, 0))
}
require.Len(t, fh.markSince(observed).folds, maxFailedFolds)
require.Greater(t, fake.assigns.Load(), assigns)
}
// failUntilFoldsFull fails flushes until the handle keeps maxFailedFolds
// folds over base.
func failUntilFoldsFull(t *testing.T, wfs *WFS, fh *FileHandle, base *filer_pb.Entry) {
for i := 0; i < maxFailedFolds && len(fh.markSince(base).folds) < maxFailedFolds; i++ {
require.NotEqual(t, fuse.OK, wfs.doFlush(context.Background(), fh, 1000, 20, false, 0))
}
require.Len(t, fh.markSince(base).folds, maxFailedFolds)
}
// refoldingFiler folds the small chunks of a create before it stores and
// acknowledges it, as the filer's cleanupChunks does.
type refoldingFiler struct {
foldMergeFiler
saver foldMergeSaver
}
func (s *refoldingFiler) CreateEntry(ctx context.Context, r *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
r = proto.Clone(r).(*filer_pb.CreateEntryRequest)
folded, err := filer.MaybeManifestize(s.saver.save, nil, r.Entry.Chunks)
if err != nil {
return nil, err
}
r.Entry.Chunks = folded
return s.foldMergeFiler.CreateEntry(ctx, r)
}
// A peer's chmod refuses the flush's first commit; the merged retry sends the
// handle's 256 small chunks unfolded and the filer folds them before storing.
// The handle must hold what the filer stored, which is also its base: holding
// the flat chunks against a base that lists a manifest, a later merge would
// take them for writes of its own, after a peer truncated the file too.
func TestFlushMergeInstallsTheEntryTheFilerStored(t *testing.T) {
const n = filer.SmallChunkManifestBatch - 1
wfs := newInvalidateTestWFS(t)
wfs.option.ConcurrentWriters = 4
wfs.option.uniqueCacheDirForWrite = t.TempDir()
wfs.concurrentWriters = util.NewLimitedConcurrentExecutor(4)
fake := &refoldingFiler{foldMergeFiler: foldMergeFiler{volume: newVolumeStub(t)}, saver: foldMergeSaver{saved: 500}}
startFakeFiler(t, wfs, fake)
wfs.option.VolumeServerAccess = "direct"
wfs.filerClient = wdclient.NewFilerClient(wfs.option.FilerAddresses, wfs.option.GrpcDialOption, "")
attrs := &filer_pb.FuseAttributes{Inode: 42, FileMode: 0644, Uid: 2000, Gid: 20, FileSize: n * 300}
base := &filer_pb.Entry{Name: "file", Attributes: attrs}
for i := 0; i < n; i++ {
base.Chunks = append(base.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 1, FileKey: uint64(i + 1), Cookie: 1}, Offset: int64(i) * 300, Size: 300, ModifiedTsNs: int64(100 + i)})
}
peer := proto.Clone(base).(*filer_pb.Entry)
peer.Attributes.FileMode = 0600 // a chmod on another mount
fake.entry = peer
live := proto.Clone(base).(*filer_pb.Entry)
live.Chunks = append(live.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 1, FileKey: n + 1, Cookie: 1}, Offset: n * 300, Size: 300, ModifiedTsNs: 100 + n})
live.Attributes.FileSize = (n + 1) * 300
observed := proto.Clone(base).(*filer_pb.Entry)
wfs.mapPbIdFromFilerToLocal(observed)
wfs.mapPbIdFromFilerToLocal(live)
fh := newFileHandle(wfs, 1, 42, live)
t.Cleanup(func() { fh.dirtyPages.Destroy() })
fh.baseEntry.Store(observed)
fh.RememberPath(util.FullPath("/dir/file"))
fh.dirtyMetadata = true
require.Equal(t, fuse.OK, wfs.doFlush(context.Background(), fh, 1000, 20, false, 0))
fake.mu.Lock()
stored := referenceCounts(fake.entry.Chunks)
fake.mu.Unlock()
manifests, _ := filer.SeparateManifestChunks(fake.entry.Chunks)
require.Len(t, manifests, 1, "the filer folded the merged chunks")
require.Equal(t, stored, referenceCounts(fh.GetEntry().GetEntry().Chunks), "the handle holds what the filer stored")
require.Equal(t, stored, referenceCounts(fh.baseEntry.Load().Chunks), "the base is what the filer stored")
}
// noAssignFiler assigns no volume, so the mount cannot fold, and folds a
// create itself like refoldingFiler.
type noAssignFiler struct{ refoldingFiler }
func (s *noAssignFiler) AssignVolume(ctx context.Context, req *filer_pb.AssignVolumeRequest) (*filer_pb.AssignVolumeResponse, error) {
return &filer_pb.AssignVolumeResponse{Error: "no writable volumes"}, nil
}
// A flush the filer folds and acknowledges leaves the handle holding what the
// filer stored, as after a merge: its flat chunks under the folded base would
// count as writes of its own.
func TestFlushInstallsTheChunksTheFilerFolded(t *testing.T) {
const n = filer.SmallChunkManifestBatch - 1
wfs := newInvalidateTestWFS(t)
wfs.option.ConcurrentWriters = 4
wfs.option.uniqueCacheDirForWrite = t.TempDir()
wfs.concurrentWriters = util.NewLimitedConcurrentExecutor(4)
wfs.readAuth = newReadAuth(wfs)
fake := &noAssignFiler{refoldingFiler{foldMergeFiler: foldMergeFiler{volume: newVolumeStub(t)}, saver: foldMergeSaver{saved: 500}}}
startFakeFiler(t, wfs, fake)
wfs.option.VolumeServerAccess = "direct"
wfs.filerClient = wdclient.NewFilerClient(wfs.option.FilerAddresses, wfs.option.GrpcDialOption, "")
attrs := &filer_pb.FuseAttributes{Inode: 42, FileMode: 0644, Uid: 2000, Gid: 20, FileSize: n * 300}
base := &filer_pb.Entry{Name: "file", Attributes: attrs}
for i := 0; i < n; i++ {
base.Chunks = append(base.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 1, FileKey: uint64(i + 1), Cookie: 1}, Offset: int64(i) * 300, Size: 300, ModifiedTsNs: int64(100 + i)})
}
fake.entry = proto.Clone(base).(*filer_pb.Entry)
live := proto.Clone(base).(*filer_pb.Entry)
live.Chunks = append(live.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 1, FileKey: n + 1, Cookie: 1}, Offset: n * 300, Size: 300, ModifiedTsNs: 100 + n})
live.Attributes.FileSize = (n + 1) * 300
observed := proto.Clone(base).(*filer_pb.Entry)
wfs.mapPbIdFromFilerToLocal(observed)
wfs.mapPbIdFromFilerToLocal(live)
fh := newFileHandle(wfs, 1, 42, live)
t.Cleanup(func() { fh.dirtyPages.Destroy() })
fh.baseEntry.Store(observed)
fh.RememberPath(util.FullPath("/dir/file"))
fh.dirtyMetadata = true
require.Equal(t, fuse.OK, wfs.doFlush(context.Background(), fh, 1000, 20, false, 0))
fake.mu.Lock()
stored := referenceCounts(fake.entry.Chunks)
fake.mu.Unlock()
manifests, _ := filer.SeparateManifestChunks(fake.entry.Chunks)
require.Len(t, manifests, 1, "the filer folded the chunks")
require.Equal(t, stored, referenceCounts(fh.GetEntry().GetEntry().Chunks), "the handle holds what the filer stored")
require.Equal(t, stored, referenceCounts(fh.baseEntry.Load().Chunks), "the base is what the filer stored")
wfs.readAuth.mu.Lock()
defer wfs.readAuth.mu.Unlock()
require.Equal(t, util.FullPath("/dir/file"), wfs.readAuth.paths[manifests[0].GetFileIdString()], "its manifest reads with the file's token")
}