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>
This commit is contained in:
Chris LuandClaude Opus 5.5 authored and GitHub committed 2026-11-29 12:34:30 -08:00
1 parent a963c1309c
commit 46b10efcce
12 files changed
+779 -28

No files matched your search

+7
View File
@@ -274,6 +274,13 @@ func runFuse(cmd *Command, args []string) bool {
fmt.Fprintf(os.Stderr, "failed to parse 'writebackCache' value %q: %v\n", parameter.value, err)
return false
}
case "concurrentWriteMerge":
if parsed, err := strconv.ParseBool(parameter.value); err == nil {
mountOptions.concurrentWriteMerge = &parsed
} else {
fmt.Fprintf(os.Stderr, "failed to parse 'concurrentWriteMerge' value %q: %v\n", parameter.value, err)
return false
}
case "asyncDio":
if parsed, err := strconv.ParseBool(parameter.value); err == nil {
mountOptions.asyncDio = &parsed
+3 -1
View File
@@ -65,7 +65,8 @@ type MountOptions struct {
// Distributed locking for cross-mount write coordination and POSIX
// advisory locks (flock/fcntl)
distributedLock *bool
distributedLock *bool
concurrentWriteMerge *bool
// POSIX compliance options
posixDirNlink *bool
@@ -163,6 +164,7 @@ func init() {
// Distributed lock for cross-mount write coordination
mountOptions.distributedLock = cmdMount.Flag.Bool("dlm", false, "coordinate writes across mounts (only one mount writes a file at a time) and honor POSIX advisory locks (flock/fcntl) across mounts by routing them to the owner filer")
mountOptions.concurrentWriteMerge = cmdMount.Flag.Bool("concurrentWriteMerge", false, "when another mount wrote a file this mount has unflushed writes to, merge both mounts' writes instead of failing the later flush with EIO")
// POSIX compliance options
mountOptions.posixDirNlink = cmdMount.Flag.Bool("posix.dirNLink", false, "report POSIX-compliant directory nlink (2 + subdirectory count); costs one directory listing per stat")
+1
View File
@@ -253,6 +253,7 @@ func buildSeaweedFileSystem(option *MountOptions, p fileSystemParams) *mount.WFS
MetadataFlushSeconds: *option.metadataFlushSeconds,
DirIdleEvictSec: *option.dirIdleEvictSec,
EnableDistributedLock: option.distributedLock != nil && *option.distributedLock,
ConcurrentWriteMerge: option.concurrentWriteMerge != nil && *option.concurrentWriteMerge,
WritebackCache: option.writebackCache != nil && *option.writebackCache,
NfsExport: option.nfsExport != nil && *option.nfsExport,
EagerFilerCreate: p.eagerFilerCreate,
+86 -11
View File
@@ -88,6 +88,7 @@ func TestContentFlushPreservesPeerChunks(t *testing.T) {
for _, name := range []string{"single-writer", "peer-append", "replaced", "deleted", "deferred-create", "deferred-create-race"} {
t.Run(name, func(t *testing.T) {
wfs := newInvalidateTestWFS(t)
wfs.option.ConcurrentWriteMerge = true
observed := flushConditionEntry(1)
live := flushConditionEntry(1, 3)
live.Chunks[1].Offset = 2
@@ -252,6 +253,7 @@ func chunkFileKeys(e *filer_pb.Entry) (keys []uint64) {
// overwrite a peer's append either.
func TestPeriodicMetadataFlushPreservesPeerChunks(t *testing.T) {
wfs := newInvalidateTestWFS(t)
wfs.option.ConcurrentWriteMerge = true
current := flushConditionEntry(1, 2)
fake := &contentFlushConditionFiler{entry: proto.Clone(current).(*filer_pb.Entry)}
startFakeFiler(t, wfs, fake)
@@ -285,6 +287,7 @@ func TestPeriodicMetadataFlushPreservesPeerChunks(t *testing.T) {
// the peer's chunk is not dropped by the next publication from this handle.
func TestContentFlushMergeThenRepeat(t *testing.T) {
wfs := newInvalidateTestWFS(t)
wfs.option.ConcurrentWriteMerge = true
fake := &contentFlushConditionFiler{entry: flushConditionEntry(1, 2)}
startFakeFiler(t, wfs, fake)
observed := flushConditionEntry(1)
@@ -318,8 +321,8 @@ func TestContentFlushMergeThenRepeat(t *testing.T) {
}
// The merge keeps a peer's attribute and extended changes the handle did not
// make, applies the ones it did, and lets a local truncation clip the peer's
// chunks past the new end.
// make, applies the ones it did, and lets a local truncation clip the base's
// chunks past the new end, but not the chunks a peer wrote since.
func TestMergeContentEntry(t *testing.T) {
base := flushConditionEntry(1, 2)
base.Extended = map[string][]byte{"user.a": []byte("1"), "user.b": []byte("1")}
@@ -352,25 +355,54 @@ func TestMergeContentEntry(t *testing.T) {
truncated := proto.Clone(base).(*filer_pb.Entry)
truncated.Chunks = truncated.Chunks[:1]
truncated.Attributes.FileSize = 1
merged, ok = mergeContentEntry(stored, base, truncated, truncated, -1, false)
if _, ok := mergeContentEntry(stored, base, truncated, truncated, -1, false); ok {
t.Fatal("a stale truncate dropped the chunk a peer wrote")
}
peerChmod := proto.Clone(base).(*filer_pb.Entry)
peerChmod.Attributes.FileMode = 0600
merged, ok = mergeContentEntry(peerChmod, base, truncated, truncated, -1, false)
if !ok {
t.Fatal("truncation not merged")
}
if got := chunkFileKeys(merged); !slices.Equal(got, []uint64{1}) || merged.Attributes.FileSize != 1 {
t.Fatalf("truncated merge kept %v, size %d", got, merged.Attributes.FileSize)
if got := chunkFileKeys(merged); !slices.Equal(got, []uint64{1}) || merged.Attributes.FileSize != 1 || merged.Attributes.FileMode != 0600 {
t.Fatalf("truncated merge kept %v, size %d, mode %o", got, merged.Attributes.FileSize, merged.Attributes.FileMode)
}
// Truncated to 1, then written at 7: the peer chunk at 2 stays cut.
// Truncated to 1, then written at 7: the base chunk at 1 stays cut, and a
// peer chunk inside the truncated size stays.
regrown := proto.Clone(truncated).(*filer_pb.Entry)
regrown.Chunks = append(regrown.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 1, FileKey: 7, Cookie: 1}, Offset: 7, Size: 1, ModifiedTsNs: 7})
regrown.Attributes.FileSize = 8
merged, ok = mergeContentEntry(stored, base, regrown, regrown, 1, false)
peerInside := proto.Clone(base).(*filer_pb.Entry)
peerInside.Chunks = append(peerInside.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 1, FileKey: 9, Cookie: 1}, Offset: 0, Size: 1, ModifiedTsNs: 9})
merged, ok = mergeContentEntry(peerInside, base, regrown, regrown, 1, false)
if !ok {
t.Fatal("truncate then write not merged")
}
if got := chunkFileKeys(merged); !slices.Equal(got, []uint64{1, 7}) || merged.Attributes.FileSize != 8 {
if got := chunkFileKeys(merged); !slices.Equal(got, []uint64{1, 9, 7}) || merged.Attributes.FileSize != 8 {
t.Fatalf("truncate then write kept %v, size %d", got, merged.Attributes.FileSize)
}
if _, ok := mergeContentEntry(stored, base, regrown, regrown, 1, false); ok {
t.Fatal("a stale truncate cut the chunk a peer wrote")
}
// The handle's own commit whose answer was lost is no peer write.
committed := proto.Clone(base).(*filer_pb.Entry)
committed.Chunks = append(committed.Chunks, regrown.Chunks[1])
merged, ok = mergeContentEntry(committed, base, regrown, regrown, 1, false)
if !ok {
t.Fatal("refused the handle's own committed chunk")
}
if got := chunkFileKeys(merged); !slices.Equal(got, []uint64{1, 7}) || merged.Attributes.FileSize != 8 {
t.Fatalf("replayed commit kept %v, size %d", got, merged.Attributes.FileSize)
}
grown := proto.Clone(base).(*filer_pb.Entry)
grown.Chunks = append(grown.Chunks, regrown.Chunks[1])
grown.Attributes.FileSize = 8
committed.Attributes.FileSize = 8
merged, ok = mergeContentEntry(committed, base, grown, grown, -1, false)
if got := chunkFileKeys(merged); !ok || !slices.Equal(got, []uint64{1, 2, 7}) {
t.Fatalf("replayed commit without a truncate kept %v", got)
}
// Shortening a manifest reference leaves its members whole.
peerManifest := proto.Clone(base).(*filer_pb.Entry)
@@ -413,11 +445,19 @@ func TestMergeContentEntry(t *testing.T) {
unstamped.Chunks[0].Size, unstamped.Chunks[0].ModifiedTsNs = 3, 0
shortened := proto.Clone(unstamped).(*filer_pb.Entry)
shortened.Chunks[0].Size, shortened.Attributes.FileSize = 2, 2
peerAppend := proto.Clone(unstamped).(*filer_pb.Entry)
peerAppend.Chunks = append(peerAppend.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 1, FileKey: 9, Cookie: 1}, Offset: 3, Size: 1, ModifiedTsNs: 9})
if _, ok := mergeContentEntry(peerAppend, unstamped, shortened, shortened, 2, false); !ok {
peerWrite := proto.Clone(unstamped).(*filer_pb.Entry)
peerWrite.Chunks = append(peerWrite.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 1, FileKey: 9, Cookie: 1}, Offset: 1, Size: 1, ModifiedTsNs: 9})
if _, ok := mergeContentEntry(peerWrite, unstamped, shortened, shortened, 2, false); !ok {
t.Fatal("refused a truncate that shortened an unstamped base chunk")
}
// A base chunk the peer shortened holds no peer data: the truncate cuts it.
peerShortened := proto.Clone(unstamped).(*filer_pb.Entry)
peerShortened.Chunks[0].Size, peerShortened.Attributes.FileSize = 2, 2
cut := proto.Clone(unstamped).(*filer_pb.Entry)
cut.Chunks[0].Size, cut.Attributes.FileSize = 1, 1
if merged, ok := mergeContentEntry(peerShortened, unstamped, cut, cut, 1, false); !ok || merged.Attributes.FileSize != 1 {
t.Fatal("refused a truncate over a base chunk the peer shortened")
}
noInode := proto.Clone(base).(*filer_pb.Entry)
noInode.Attributes.Inode, noInode.Attributes.Crtime = 0, 5
@@ -444,6 +484,41 @@ func TestMergeContentEntry(t *testing.T) {
}
}
// A delayed flush keeps the later of two moved times, and a time only the
// handle moved, even back.
func TestMergeContentEntryKeepsLaterTime(t *testing.T) {
base := flushConditionEntry(1)
base.Attributes.Mtime, base.Attributes.Ctime = 100, 100
stored := proto.Clone(base).(*filer_pb.Entry)
stored.Chunks = append(stored.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 1, FileKey: 9, Cookie: 1}, Offset: 1, Size: 1, ModifiedTsNs: 9})
stored.Attributes.Mtime, stored.Attributes.MtimeNs = 300, 5
stored.Attributes.Ctime, stored.Attributes.CtimeNs = 300, 5
local := proto.Clone(base).(*filer_pb.Entry)
local.Chunks = append(local.Chunks, &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 1, FileKey: 7, Cookie: 1}, Offset: 2, Size: 1, ModifiedTsNs: 7})
local.Attributes.Mtime, local.Attributes.MtimeNs = 300, 1
local.Attributes.Ctime, local.Attributes.CtimeNs = 200, 0
merged, ok := mergeContentEntry(stored, base, local, local, -1, false)
if !ok {
t.Fatal("not merged")
}
if a := merged.Attributes; a.Mtime != 300 || a.MtimeNs != 5 || a.Ctime != 300 || a.CtimeNs != 5 {
t.Fatalf("delayed flush moved times back: mtime %d.%d ctime %d.%d", a.Mtime, a.MtimeNs, a.Ctime, a.CtimeNs)
}
local.Attributes.Mtime, local.Attributes.MtimeNs = 400, 0
if merged, _ = mergeContentEntry(stored, base, local, local, -1, false); merged.Attributes.Mtime != 400 || merged.Attributes.MtimeNs != 0 {
t.Fatalf("later local mtime not kept: %d.%d", merged.Attributes.Mtime, merged.Attributes.MtimeNs)
}
peerChmod := proto.Clone(base).(*filer_pb.Entry)
peerChmod.Attributes.FileMode = 0600
local.Attributes.Mtime, local.Attributes.MtimeNs = 50, 0
if merged, _ = mergeContentEntry(peerChmod, base, local, local, -1, false); merged.Attributes.Mtime != 50 {
t.Fatalf("mtime only the handle set: %d", merged.Attributes.Mtime)
}
}
// A miss on state no peer changed is republished once against the stored
// entry: a rename while open, or a filer uid the local id mapping cannot
// reproduce (newInvalidateTestWFS maps local 1000 to filer 2000).
+14 -3
View File
@@ -15,7 +15,7 @@ import (
)
// These caller controls measure published bytes; none imports #12608 internals.
func masterAssertPeerMergeOutcome(t *testing.T, periodic bool) {
func masterAssertPeerMergeOutcome(t *testing.T, periodic, merge bool) {
for _, scenario := range []string{"peer-append", "peer-replaced-file", "peer-truncate"} {
t.Run(scenario, func(t *testing.T) {
base := attributeAppendEntry(1)
@@ -46,6 +46,7 @@ func masterAssertPeerMergeOutcome(t *testing.T, periodic bool) {
original := proto.Clone(stored).(*filer_pb.Entry)
peer := &g6ConditionalPeer{entry: proto.Clone(stored).(*filer_pb.Entry), blobs: blobs}
w := newInvalidateTestWFS(t)
w.option.ConcurrentWriteMerge = merge
startFakeFiler(t, w, peer)
w.mapPbIdFromFilerToLocal(base)
w.mapPbIdFromFilerToLocal(pending)
@@ -67,6 +68,12 @@ func masterAssertPeerMergeOutcome(t *testing.T, periodic bool) {
defer peer.mu.Unlock()
actual := g6StoredBytes(t, peer)
t.Logf("scenario=%s status=%v size=%d rejected=%d gap[256,512)-zero=%v", scenario, code, len(actual), peer.rejected, len(actual) >= 512 && bytes.Equal(actual[256:512], make([]byte, 256)))
if !merge {
if code != fuse.EIO || !g6EntryEqual(peer.entry, original) {
t.Fatal("a peer's chunk change must fail the flush without merging")
}
return
}
if scenario == "peer-replaced-file" {
if code != fuse.EIO || !g6EntryEqual(peer.entry, original) || !bytes.Equal(actual, bytes.Repeat([]byte{'R'}, 256)) {
t.Fatal("replacement must be refused without publishing stale content")
@@ -208,5 +215,9 @@ func TestMasterConflictThenAppendCannotPublishGap(t *testing.T) {
}
}
func TestContentGapPeerMerge(t *testing.T) { masterAssertPeerMergeOutcome(t, false) }
func TestContentGapPeriodicPeerMerge(t *testing.T) { masterAssertPeerMergeOutcome(t, true) }
func TestContentGapPeerMerge(t *testing.T) { masterAssertPeerMergeOutcome(t, false, true) }
func TestContentGapPeriodicPeerMerge(t *testing.T) { masterAssertPeerMergeOutcome(t, true, true) }
func TestContentGapPeerConflict(t *testing.T) { masterAssertPeerMergeOutcome(t, false, false) }
func TestContentGapPeriodicPeerConflict(t *testing.T) {
masterAssertPeerMergeOutcome(t, true, false)
}
+43
View File
@@ -598,3 +598,46 @@ func TestLostAnswerToOwnShrinkingFlushIsNotAConflict(t *testing.T) {
t.Fatal("lost answer was not exercised or the overwrite did not land")
}
}
type g6LostLookupFiler struct {
*g6LostAnswerFiler
lookupFails atomic.Bool
}
func (s *g6LostLookupFiler) LookupDirectoryEntry(ctx context.Context, r *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
if s.lookupFails.Load() {
return nil, status.Error(codes.Internal, "lookup failed")
}
return s.g6LostAnswerFiler.LookupDirectoryEntry(ctx, r)
}
func TestTruncateAfterLostTruncateFlushIsNotAConflict(t *testing.T) {
base := attributeAppendEntry(1)
peer := &g6ConditionalPeer{entry: proto.Clone(base).(*filer_pb.Entry)}
w, handle := g6AppendHandle(t, peer, base, 2200)
fake := &g6LostLookupFiler{g6LostAnswerFiler: &g6LostAnswerFiler{g6ConditionalPeer: peer}}
fake.lookupFails.Store(true)
startFakeFiler(t, w, fake)
truncate := func(size uint64) fuse.Status {
return w.SetAttr(nil, &fuse.SetAttrIn{SetAttrInCommon: fuse.SetAttrInCommon{InHeader: fuse.InHeader{NodeId: 42}, Valid: fuse.FATTR_SIZE | fuse.FATTR_FH, Fh: handle, Size: size}}, &fuse.AttrOut{})
}
if code := truncate(200); code == fuse.OK {
t.Fatal("truncate whose answer and lookup were lost reported success")
}
peer.mu.Lock()
committed := peer.entry.Attributes.FileSize
peer.mu.Unlock()
if !fake.lost.Load() || committed != 200 {
t.Fatal("lost answer was not exercised", committed)
}
fake.lookupFails.Store(false)
if code := truncate(100); code != fuse.OK {
t.Fatal("own committed truncate reported as a conflict", code)
}
peer.mu.Lock()
defer peer.mu.Unlock()
chunks := peer.entry.Chunks
if peer.entry.Attributes.FileSize != 100 || len(chunks) != 1 || chunks[0].Fid.FileKey != 1 || chunks[0].Offset != 0 || chunks[0].Size != 100 {
t.Fatal("second truncate did not land", peer.entry.Attributes.FileSize, chunks)
}
}
+104 -4
View File
@@ -230,6 +230,7 @@ func (fh *FileHandle) rebaseEntry(merged, sent *filer_pb.Entry) {
inSent[contentChunkKey(c)] = true
}
merged = proto.Clone(merged).(*filer_pb.Entry)
fh.wfs.readAuth.Track(fh.FullPath(), merged.Chunks)
fh.UpdateEntry(func(e *filer_pb.Entry) {
chunks := merged.Chunks
for _, c := range e.Chunks {
@@ -256,6 +257,7 @@ func (fh *FileHandle) rebaseEntry(merged, sent *filer_pb.Entry) {
// naming them would send reads to needles a vacuum removes. Chunks attached
// after snapshot was taken were not part of the merge and stay.
func (fh *FileHandle) installRewrittenChunks(snapshot, rewritten []*filer_pb.FileChunk) {
fh.wfs.readAuth.Track(fh.FullPath(), rewritten)
fh.UpdateEntry(func(e *filer_pb.Entry) {
chunks := withChunksAttachedSince(snapshot, rewritten, e.Chunks)
e.Chunks = chunks
@@ -267,6 +269,26 @@ func (fh *FileHandle) installRewrittenChunks(snapshot, rewritten []*filer_pb.Fil
})
}
// installStoredChunks gives the handle the chunks an acknowledged create
// stored when they differ from those sent held (the filer folds a flat list):
// they are its base, and a later merge takes the chunks the handle holds that
// its base lacks for writes of its own.
func (fh *FileHandle) installStoredChunks(stored, sent *filer_pb.Entry) {
count := make(map[string]int, len(sent.GetChunks()))
for _, c := range sent.GetChunks() {
count[contentChunkKey(c)]++
}
same := len(stored.GetChunks()) == len(sent.GetChunks())
for _, c := range stored.GetChunks() {
key := contentChunkKey(c)
same = same && count[key] > 0
count[key]--
}
if !same {
fh.installRewrittenChunks(sent.Chunks, stored.Chunks)
}
}
// withChunksAttachedSince returns processed, the chunks a flush made from
// snapshot, followed by the chunks uploads attached to current after snapshot
// was taken: they attach without the handle lock.
@@ -302,7 +324,7 @@ func (fh *FileHandle) mergePeerContent(peer, base *filer_pb.Entry) bool {
local = proto.Clone(e).(*filer_pb.Entry)
})
mark := fh.markSince(base)
merged, ok := mergeContentEntry(peer, base, local, local, mark.truncatedTo, mark.rewrote)
merged, ok := fh.wfs.mergeOwnContent(mark.unfoldOwn(peer, local), base, local, local, mark)
ok = ok && mergeKeepsBuffered(merged, local)
if ok {
fh.rebaseEntry(merged, local)
@@ -318,12 +340,90 @@ func mergeKeepsBuffered(merged, local *filer_pb.Entry) bool {
}
// baseMark records what the handle did over base that its entry does not
// show: the lowest size a truncate set (-1 for none), and a whole-file
// rewrite of its chunks.
// show: the lowest size a truncate set (-1 for none), a whole-file rewrite of
// its chunks, and what the flushes that failed over base sent where the filer
// may have stored one (committed with its answer lost).
type baseMark struct {
base *filer_pb.Entry
truncatedTo int64
rewrote bool
folds []*chunkFold
sent *sentChunks
}
// sentChunks holds what the chunks such flushes sent add over base: the file
// ids base lacks, and the references a truncate shortened from base's files.
// Every copy of a mark over one base shares it, and it only grows until the
// base moves: the filer may hold any of those flushes, and a merge that
// forgot one of its chunks would refuse the handle's own cut write as a
// peer's. Each id is kept once.
type sentChunks struct {
sync.Mutex
ids map[string]bool
}
// maxFailedFolds bounds the folds of failed flushes a handle keeps over one
// base. A stored manifest of a fold past it is read when a refused merge
// cannot place it.
const maxFailedFolds = 4
// noteFailedFlush records a flush that failed over the current base: its
// fold, and the chunks it sent.
func (fh *FileHandle) noteFailedFlush(f *chunkFold, sent []*filer_pb.FileChunk) {
fh.markBase(func(m *baseMark) {
if f != nil && len(m.folds) < maxFailedFolds {
m.folds = append(m.folds[:len(m.folds):len(m.folds)], f)
}
if m.sent == nil {
m.sent = &sentChunks{ids: make(map[string]bool, len(sent))}
}
inBase := make(map[string]bool, 2*len(m.base.GetChunks()))
for _, c := range m.base.GetChunks() {
inBase[contentFileIdKey(c)] = true
inBase[contentChunkKey(c)] = true
}
m.sent.Lock()
defer m.sent.Unlock()
for _, c := range sent {
if key := contentFileIdKey(c); !inBase[key] {
m.sent.ids[key] = true
} else if ref := contentChunkKey(c); !inBase[ref] {
m.sent.ids[ref] = true
}
}
})
}
// unfoldOwn returns stored with the manifests of the handle's failed flushes
// replaced by the chunks they hold, and without the chunks those flushes sent
// that local no longer holds: they are the handle's own writes, which it has
// cut or replaced since, not a peer's.
func (m baseMark) unfoldOwn(stored, local *filer_pb.Entry) *filer_pb.Entry {
for _, f := range m.folds {
stored = f.unfold(stored)
}
if m.sent == nil || stored == nil {
return stored
}
inLocal := make(map[string]bool, len(local.GetChunks()))
for _, c := range local.GetChunks() {
inLocal[contentChunkKey(c)] = true
}
var kept []*filer_pb.FileChunk
m.sent.Lock()
for _, c := range stored.Chunks {
key := contentChunkKey(c)
if !m.sent.ids[contentFileIdKey(c)] && !m.sent.ids[key] || inLocal[key] {
kept = append(kept, c)
}
}
m.sent.Unlock()
if len(kept) == len(stored.Chunks) {
return stored
}
stored = proto.Clone(stored).(*filer_pb.Entry)
stored.Chunks = kept
return stored
}
func (fh *FileHandle) markBase(update func(m *baseMark)) {
@@ -361,7 +461,7 @@ func (fh *FileHandle) adoptPeerBase(base *filer_pb.Entry) {
old := fh.baseEntry.Swap(base)
if m := fh.sinceBase.Load(); m != nil && m.base == old {
moved := *m
moved.base = base
moved.base, moved.folds, moved.sent = base, nil, nil
fh.sinceBase.CompareAndSwap(m, &moved)
}
}
+350
View File
@@ -6,9 +6,12 @@ import (
"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"
@@ -134,6 +137,42 @@ func TestMergeAfterFoldDoesNotRestoreChunksThePeerDropped(t *testing.T) {
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.
@@ -159,6 +198,7 @@ func (s *foldMergeFiler) AssignVolume(ctx context.Context, req *filer_pb.AssignV
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)
@@ -201,6 +241,260 @@ func TestFlushMergeAfterFoldLeavesThePeersRewrite(t *testing.T) {
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 {
@@ -265,3 +559,59 @@ func TestFlushMergeInstallsTheEntryTheFilerStored(t *testing.T) {
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")
}
+4
View File
@@ -117,6 +117,10 @@ type Option struct {
// mounts. Disabled under writeback cache, which implies single-writer.
EnableDistributedLock bool
// ConcurrentWriteMerge merges a handle's writes with chunks another mount
// committed since the handle's base; otherwise its flush fails with EIO.
ConcurrentWriteMerge bool
// WritebackCache enables async flush on close for improved small file write performance.
// When true, Flush() returns immediately and data upload + metadata flush happen in background.
WritebackCache bool
+146 -8
View File
@@ -430,6 +430,8 @@ func (wfs *WFS) flushMetadataToFiler(ctx context.Context, fh *FileHandle, dir, n
merged = wfs.ackedBase(resp, merged)
fh.rebaseEntry(merged, requestEntry)
baseSnapshot = merged
} else {
fh.installStoredChunks(wfs.ackedBase(resp, baseSnapshot), baseSnapshot)
}
event := resp.GetMetadataEvent()
@@ -516,6 +518,20 @@ func (wfs *WFS) createContentEntry(ctx context.Context, fh *FileHandle, request
guard = &filer_pb.WriteCondition_Clause{Kind: filer_pb.WriteCondition_IF_ENTRY_EQUAL, ExpectedEntry: expected}
}
sent := request.Entry
// A failed flush the filer may have stored keeps what it sent, to tell it
// from a peer's chunks. Only the first request carries the flush's fold:
// unless the filer refused its only send, the filer may hold its manifests.
foldSends, foldRefused, mayStore := 0, false, false
defer func() {
if err == nil || !mayStore {
return
}
kept := fold
if foldSends == 1 && foldRefused {
kept = nil
}
fh.noteFailedFlush(kept, fold.unfoldChunks(sent.Chunks))
}()
for attempt := 0; ; attempt++ {
if guardErr := wfs.checkContentPublication(fh, guard.ExpectedEntry); guardErr != nil {
return nil, nil, guardErr
@@ -527,6 +543,11 @@ func (wfs *WFS) createContentEntry(ctx context.Context, fh *FileHandle, request
if errors.Is(callErr, filer_pb.ErrPreconditionFailed) {
publication.refused = true
}
if attempt == 0 {
foldSends++
foldRefused = filer_pb.IsFilerVerdict(callErr)
}
mayStore = mayStore || callErr != nil && !filer_pb.IsFilerVerdict(callErr)
return callErr
})
if err == nil && request.Entry != sent {
@@ -541,9 +562,16 @@ func (wfs *WFS) createContentEntry(ctx context.Context, fh *FileHandle, request
return resp, nil, err
}
mark := fh.markSince(base)
// The flush's own fold is no change of content: merge the chunks.
// The flush's own fold is no change of content: merge the chunks. A
// retried request may have stored it already.
unfoldedLocal := fold.unfold(local)
next, ok := mergeContentEntry(stored, base, unfoldedLocal, fold.unfold(sent), mark.truncatedTo, mark.rewrote)
own := mark.unfoldOwn(fold.unfold(stored), unfoldedLocal)
next, ok := wfs.mergeOwnContent(own, base, unfoldedLocal, fold.unfold(sent), mark)
if !ok && sameContentFile(stored, base) {
if expanded := wfs.expandStoredManifests(ctx, util.FullPath(request.Directory).Child(request.Entry.Name), own, base, unfoldedLocal); expanded != nil {
next, ok = wfs.mergeOwnContent(mark.unfoldOwn(expanded, unfoldedLocal), base, unfoldedLocal, fold.unfold(sent), mark)
}
}
if !ok || buffered && !mergeKeepsBuffered(next, unfoldedLocal) {
return resp, nil, err
}
@@ -568,6 +596,87 @@ func (wfs *WFS) lookupRefusedEntry(ctx context.Context, dir, name string) (store
return stored
}
// expandStoredManifests returns stored with each manifest base and local lack
// replaced by the chunks it holds, or nil when it has none or one cannot be
// read. A fold changes no content, and the handle cannot name every fold of
// its own chunks: one the filer made, or one past maxFailedFolds.
func (wfs *WFS) expandStoredManifests(ctx context.Context, path util.FullPath, stored, base, local *filer_pb.Entry) *filer_pb.Entry {
known := make(map[string]bool, len(base.GetChunks())+len(local.GetChunks()))
for _, e := range []*filer_pb.Entry{base, local} {
for _, c := range e.GetChunks() {
known[contentChunkKey(c)] = true
}
}
var unknown []*filer_pb.FileChunk
for _, c := range stored.GetChunks() {
if c.IsChunkManifest && !known[contentChunkKey(c)] {
unknown = append(unknown, c)
}
}
if len(unknown) == 0 {
return nil
}
wfs.readAuth.Track(path, unknown)
ctx, cancel := context.WithTimeout(ctx, wfs.filerRPCWait())
defer cancel()
resolve := func(manifest *filer_pb.FileChunk) ([]*filer_pb.FileChunk, error) {
return truncateManifestResolver(ctx, wfs, manifest)
}
chunks := make([]*filer_pb.FileChunk, 0, len(stored.Chunks))
for _, c := range stored.Chunks {
if !c.IsChunkManifest || known[contentChunkKey(c)] {
chunks = append(chunks, c)
continue
}
held, err := expandManifestAt(c, -1, resolve, 1)
if err != nil {
glog.V(1).Infof("content flush %s: %v", path, err)
return nil
}
chunks = append(chunks, held...)
}
expanded := proto.Clone(stored).(*filer_pb.Entry)
expanded.Chunks = chunks
return expanded
}
// mergeOwnContent merges as mergeContentEntry does. Without
// ConcurrentWriteMerge a stored chunk change that is neither base's nor the
// handle's is not merged: only attributes, and the handle's own commits, are.
func (wfs *WFS) mergeOwnContent(stored, base, local, sent *filer_pb.Entry, mark baseMark) (*filer_pb.Entry, bool) {
if !wfs.option.ConcurrentWriteMerge && peerChangedChunks(stored, base, local) {
return nil, false
}
return mergeContentEntry(stored, base, local, sent, mark.truncatedTo, mark.rewrote)
}
// peerChangedChunks reports a chunk change in stored that is neither base's
// nor local's: a chunk added beside them, or a base chunk local still holds
// but stored dropped.
func peerChangedChunks(stored, base, local *filer_pb.Entry) bool {
held := make(map[string]bool, len(base.GetChunks())+len(local.GetChunks()))
for _, c := range local.GetChunks() {
held[contentChunkKey(c)] = true
}
inStored := make(map[string]bool, len(stored.GetChunks()))
for _, c := range stored.GetChunks() {
inStored[contentChunkKey(c)] = true
}
for _, c := range base.GetChunks() {
key := contentChunkKey(c)
if held[key] && !inStored[key] {
return true
}
held[key] = true
}
for _, c := range stored.GetChunks() {
if !held[contentChunkKey(c)] {
return true
}
}
return false
}
// maxContentFlushMerges bounds how often one flush rebases onto a moving entry.
const maxContentFlushMerges = 3
@@ -577,12 +686,13 @@ const maxContentFlushMerges = 3
// space). Everything else keeps the stored value. A local truncation keeps
// the handle's size and clips stored chunks at the lowest size truncated to
// (truncatedTo, or -1); otherwise the stored size stands unless the handle
// changed its size or wrote past it.
// changed its size or wrote past it. A time both sides moved keeps the later.
// A different file at the path, inline content changed on both sides,
// inline content next to chunks (reads stop at the inline bytes), a manifest
// across the truncate (its members keep their sizes), or a local
// whole-file rewrite (rewrote) over a peer's chunk change cannot be merged:
// the rewrite carries the handle's stale view.
// across the truncate (its members keep their sizes), a local truncate across
// a chunk a peer wrote since base, or a local whole-file rewrite (rewrote)
// over a peer's chunk change cannot be merged: the truncate and the rewrite
// carry the handle's stale view.
func mergeContentEntry(stored, base, local, sent *filer_pb.Entry, truncatedTo int64, rewrote bool) (*filer_pb.Entry, bool) {
if !sameContentFile(stored, base) {
return nil, false
@@ -597,8 +707,10 @@ func mergeContentEntry(stored, base, local, sent *filer_pb.Entry, truncatedTo in
}
inBase := make(map[string]bool, len(base.Chunks))
baseFiles := make(map[string]bool, len(base.Chunks))
for _, c := range base.Chunks {
inBase[contentChunkKey(c)] = true
baseFiles[contentFileIdKey(c)] = true
}
inLocal := make(map[string]bool, len(local.Chunks))
for _, c := range local.Chunks {
@@ -613,7 +725,10 @@ func mergeContentEntry(stored, base, local, sent *filer_pb.Entry, truncatedTo in
for _, c := range stored.Chunks {
key := contentChunkKey(c)
peerChanged = peerChanged || !inBase[key]
if inBase[key] && !inLocal[key] || truncatedTo >= 0 && c.Offset >= truncatedTo {
if truncatedTo >= 0 && c.Offset+int64(c.Size) > truncatedTo && !baseFiles[contentFileIdKey(c)] && !inLocal[key] {
return nil, false
}
if inBase[key] != inLocal[key] || truncatedTo >= 0 && c.Offset >= truncatedTo {
continue
}
c = proto.Clone(c).(*filer_pb.FileChunk)
@@ -657,7 +772,11 @@ func mergeContentEntry(stored, base, local, sent *filer_pb.Entry, truncatedTo in
fields := m.Descriptor().Fields()
for i := 0; i < fields.Len(); i++ {
fd := fields.Get(i)
if fd.Name() == "file_size" || l.Get(fd).Equal(b.Get(fd)) {
switch fd.Name() {
case "file_size", "mtime", "mtime_ns", "ctime", "ctime_ns":
continue
}
if l.Get(fd).Equal(b.Get(fd)) {
continue
}
if s.Has(fd) {
@@ -667,6 +786,14 @@ func mergeContentEntry(stored, base, local, sent *filer_pb.Entry, truncatedTo in
}
}
sa, sn := stored.GetAttributes(), sent.GetAttributes()
if takesHandleTime(fuseTime(sa.GetMtime(), sa.GetMtimeNs()), fuseTime(baseAttrs.Mtime, baseAttrs.MtimeNs), fuseTime(localAttrs.Mtime, localAttrs.MtimeNs), fuseTime(sn.GetMtime(), sn.GetMtimeNs())) {
merged.Attributes.Mtime, merged.Attributes.MtimeNs = sn.GetMtime(), sn.GetMtimeNs()
}
if takesHandleTime(fuseTime(sa.GetCtime(), sa.GetCtimeNs()), fuseTime(baseAttrs.Ctime, baseAttrs.CtimeNs), fuseTime(localAttrs.Ctime, localAttrs.CtimeNs), fuseTime(sn.GetCtime(), sn.GetCtimeNs())) {
merged.Attributes.Ctime, merged.Attributes.CtimeNs = sn.GetCtime(), sn.GetCtimeNs()
}
for k, v := range local.Extended {
if old, found := base.Extended[k]; !found || !bytes.Equal(old, v) {
if merged.Extended == nil {
@@ -692,6 +819,17 @@ func mergeContentEntry(stored, base, local, sent *filer_pb.Entry, truncatedTo in
return merged, true
}
// takesHandleTime reports whether a merge takes the time the handle sends:
// the handle moved it since base, and no peer moved it later. A delayed flush
// must not move a peer's time back.
func takesHandleTime(stored, base, local, sent time.Time) bool {
return !local.Equal(base) && (stored.Equal(base) || !stored.After(sent))
}
func fuseTime(sec int64, nsec int32) time.Time {
return time.Unix(sec, int64(nsec))
}
// sameContentFile reports whether stored is still the regular file base was:
// the same inode, or for an entry without one, the same creation time. A
// synthesized base with neither cannot tell.
@@ -2087,8 +2087,17 @@ func TestAckFromAnotherFilerIsNotDroppedBehindForeignFence(t *testing.T) {
// A peer's append reaching a dirty handle is merged under the handle's own
// writes: the uploaded chunk and the unflushed pages both survive.
func TestPeerAppendMergesIntoDirtyHandle(t *testing.T) {
func TestPeerAppendMergesIntoDirtyHandle(t *testing.T) { assertPeerAppendIntoDirtyHandle(t, true) }
// Without ConcurrentWriteMerge the handle keeps its writes and base, so its
// flush fails instead of merging.
func TestPeerAppendLeavesDirtyHandleByDefault(t *testing.T) {
assertPeerAppendIntoDirtyHandle(t, false)
}
func assertPeerAppendIntoDirtyHandle(t *testing.T, merge bool) {
wfs := newInvalidateTestWFS(t)
wfs.option.ConcurrentWriteMerge = merge
inode := wfs.inodeToPath.Lookup(util.FullPath("/dir/file"), time.Now().Unix(), false, false, 0, false)
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, flushConditionEntry(1), 0, 0)
@@ -2117,6 +2126,15 @@ func TestPeerAppendMergesIntoDirtyHandle(t *testing.T) {
t.Fatal("dirty pages destroyed by a peer append")
}
entry := fh.GetEntry().GetEntry()
if !merge {
if got := len(entry.Chunks); got != 2 {
t.Fatalf("handle has %d chunks; want only its own", got)
}
if base := fh.baseEntry.Load(); len(base.GetChunks()) != 1 {
t.Fatalf("base %v, want the handle's own base", base)
}
return
}
if got := len(entry.Chunks); got != 3 || entry.Attributes.FileSize != 4 {
t.Fatalf("handle has %d chunks, size %d; want the peer's and its own", got, entry.Attributes.FileSize)
}
+2
View File
@@ -204,6 +204,8 @@ func (wfs *WFS) flushFileMetadata(fh *FileHandle) error {
merged = wfs.ackedBase(resp, merged)
fh.rebaseEntry(merged, requestEntry)
baseSnapshot = merged
} else {
fh.installStoredChunks(wfs.ackedBase(resp, baseSnapshot), baseSnapshot)
}
event := resp.GetMetadataEvent()