mount: fail the flush when dirty pages cannot be read back from the swap file (#13198)

* mount: fail the flush when dirty pages cannot be read back from the swap file

Dirty pages that weed mount buffers in the swap file (non-sequential
writes, or when the memory chunks run out) are read back when they
upload. SwapFileChunk.SaveContent ignored the error of that read: an
interval it could not read in full was uploaded short, or not at all,
and flush, fsync and close still succeeded. The writes the application
had been told succeeded became a hole in the stored file, with no error
anywhere. A read error on the cache disk, or a swap file truncated by an
outside cleanup, is enough.

SaveContent now hands the upload a reader that fails with the read
error. The upload fails like any other failed chunk upload: the handle
records it, rejects further writes, and flush, fsync and close return
EIO without publishing the entry. The remaining intervals of that chunk
are not saved, since the handle cannot flush cleanly. The chunk, its
write budget and its swap slot are released as before.

The test in weed/mount cuts the swap file after the write was
acknowledged: on master fsync returns OK and the filer is never told.
The pipeline tests cover a closed and a truncated swap file, and a swap
file cut inside the second of two intervals.

SwapFileChunk.ReadDataAt, which serves reads of pages not yet uploaded,
still logs a read error and returns what it has read so far; that is
left for a follow-up since it needs an error path through the read side.

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

* mount: require a failed fsync to leave the filer entry unchanged

TestFsyncFailsWhenSwapFileCannotBeReadBack accepted any filer entry
backed by stored bytes that left out the lost range, so an entry
published with the readable interval (the original 256 bytes plus the
"A" write) would also have passed. It now records the filer's entry
before the writes and requires the same entry and the same 256 bytes
after the failed fsync.

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:
Yip LeoandClaude Opus 5.5 authored and GitHub committed 2026-11-30 21:55:31 -08:00
1 parent 265b3aae0f
commit de76148f54
3 files changed
+218 -19

No files matched your search

+27 -4
View File
@@ -1,6 +1,7 @@
package page_writer
import (
"fmt"
"io"
"os"
"sync"
@@ -211,13 +212,35 @@ func (sc *SwapFileChunk) SaveContent(saveFn SaveToStorageFunc) {
}
data := mem.Allocate(int(stopOffset - startOffset))
n, _ := sc.swapfile.file.ReadAt(data, startOffset+int64(sc.actualChunkIndex)*sc.swapfile.chunkSize)
if n > 0 {
reader := util.NewBytesReader(data[:n])
saveFn(reader, int64(sc.logicChunkIndex)*sc.swapfile.chunkSize+startOffset, int64(n), tsNs, func() {
n, err := sc.swapfile.file.ReadAt(data, startOffset+int64(sc.actualChunkIndex)*sc.swapfile.chunkSize)
if n < len(data) {
// The bytes were acknowledged to the writer, so uploading less than
// the interval or skipping it would publish a hole. Hand the upload a
// reader that fails, which records the failure on the handle like a
// failed chunk upload, and stop: the handle cannot flush cleanly.
if err == nil || err == io.EOF {
err = io.ErrUnexpectedEOF
}
err = fmt.Errorf("read swap file in %s [%d,%d) of chunk %d: %w", sc.swapfile.dir, startOffset, stopOffset, sc.logicChunkIndex, err)
glog.Errorf("%v", err)
saveFn(&failedReader{err: err}, int64(sc.logicChunkIndex)*sc.swapfile.chunkSize+startOffset, int64(len(data)), tsNs, func() {
})
mem.Free(data)
return
}
reader := util.NewBytesReader(data)
saveFn(reader, int64(sc.logicChunkIndex)*sc.swapfile.chunkSize+startOffset, int64(len(data)), tsNs, func() {
})
mem.Free(data)
}
}
// failedReader fails every read with err.
type failedReader struct {
err error
}
func (r *failedReader) Read([]byte) (int, error) {
return 0, r.err
}
@@ -1,9 +1,15 @@
package page_writer
import (
"errors"
"io"
"os"
"path/filepath"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// When the swap file cannot be created, SaveDataAt must fail the write
@@ -54,3 +60,114 @@ func TestSaveDataAtReportsFailedSwapWrite(t *testing.T) {
t.Fatalf("write through a closed swap file = %d, %v; want 0 and an error", n, err)
}
}
// swapReadBackProbe collects what the pipeline hands to its uploader and the
// errors the uploader meets reading it, the way a chunk upload does.
type swapReadBackProbe struct {
mu sync.Mutex
uploaded map[int64][]byte
errs []error
}
func (p *swapReadBackProbe) save(reader io.Reader, offset int64, size int64, modifiedTsNs int64, cleanupFn func()) {
defer cleanupFn()
body, err := io.ReadAll(reader)
p.mu.Lock()
defer p.mu.Unlock()
if err != nil {
p.errs = append(p.errs, err)
return
}
if p.uploaded == nil {
p.uploaded = make(map[int64][]byte)
}
p.uploaded[offset] = body
}
// Dirty pages in the swap file were acknowledged to the writer. When they
// cannot be read back at upload time the interval must fail the upload, not
// go out short or be skipped, and the chunk must still release its budget.
func TestSwapChunkReadBackFailureFailsTheUpload(t *testing.T) {
for _, tc := range []struct {
name string
breakF func(t *testing.T, f *os.File)
}{
{"closed swap file", func(t *testing.T, f *os.File) {
if err := f.Close(); err != nil {
t.Fatal(err)
}
}},
{"truncated swap file", func(t *testing.T, f *os.File) {
if err := f.Truncate(0); err != nil {
t.Fatal(err)
}
}},
} {
t.Run(tc.name, func(t *testing.T) {
probe := &swapReadBackProbe{}
accountant := NewWriteBufferAccountant(1 << 20)
up := NewUploadPipeline(util.NewLimitedConcurrentExecutor(1), 1024, probe.save, 16, t.TempDir(), accountant)
defer up.Shutdown()
// Not sequential: the chunk goes to the swap file.
if n, err := up.SaveDataAt([]byte("data"), 0, false, 1); err != nil || n != 4 {
t.Fatalf("write = %d, %v", n, err)
}
tc.breakF(t, up.swapFile.file)
up.FlushAll()
probe.mu.Lock()
defer probe.mu.Unlock()
if len(probe.uploaded) != 0 {
t.Errorf("uploaded %v from a swap file that cannot be read", probe.uploaded)
}
if len(probe.errs) != 1 {
t.Fatalf("upload read errors = %v, want exactly one", probe.errs)
}
t.Logf("upload error: %v", probe.errs[0])
waitForBudgetRelease(t, accountant)
})
}
}
// A swap file cut short fails only the intervals it no longer holds, and the
// upload of the first failed interval ends the chunk's save: the handle cannot
// flush cleanly anyway.
func TestSwapChunkReadBackFailureKeepsReadableIntervals(t *testing.T) {
probe := &swapReadBackProbe{}
accountant := NewWriteBufferAccountant(1 << 20)
up := NewUploadPipeline(util.NewLimitedConcurrentExecutor(1), 1024, probe.save, 16, t.TempDir(), accountant)
defer up.Shutdown()
if _, err := up.SaveDataAt([]byte("head"), 0, false, 1); err != nil {
t.Fatal(err)
}
if _, err := up.SaveDataAt([]byte("tail"), 600, false, 2); err != nil {
t.Fatal(err)
}
// The chunk is slot 1 of the swap file: [1024, 2048). Cut it inside the
// second interval.
if err := up.swapFile.file.Truncate(1024 + 602); err != nil {
t.Fatal(err)
}
up.FlushAll()
probe.mu.Lock()
defer probe.mu.Unlock()
if string(probe.uploaded[0]) != "head" || len(probe.uploaded) != 1 {
t.Errorf("uploaded %v, want only the first interval", probe.uploaded)
}
if len(probe.errs) != 1 || !errors.Is(probe.errs[0], io.ErrUnexpectedEOF) {
t.Errorf("upload read errors = %v, want one unexpected EOF", probe.errs)
}
waitForBudgetRelease(t, accountant)
}
func waitForBudgetRelease(t *testing.T, accountant *WriteBufferAccountant) {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
for accountant.Used() != 0 {
if time.Now().After(deadline) {
t.Fatalf("write budget still holds %d bytes after the failed upload", accountant.Used())
}
time.Sleep(5 * time.Millisecond)
}
}
+74 -15
View File
@@ -17,27 +17,18 @@ import (
"google.golang.org/protobuf/proto"
)
// A write the swap file cannot buffer fails, and must not grow the file: the
// next flush would publish that size with a hole where its data should be. A
// write that buffers only its first chunk is a short write of those bytes, or
// an error for kernel writeback, which would drop the rest silently.
func TestFailedWriteDoesNotGrowFile(t *testing.T) {
t.Run("short write", func(t *testing.T) { testFailedWriteDoesNotGrowFile(t, 0) })
t.Run("kernel writeback", func(t *testing.T) { testFailedWriteDoesNotGrowFile(t, fuse.WRITE_CACHE) })
}
func testFailedWriteDoesNotGrowFile(t *testing.T, writeFlags uint32) {
// openSwapWriteHandle opens /dir/file for writing on a WFS with one writable
// chunk slot, so a second chunk is buffered in the swap file under swapDir.
// The file holds 256 'O' bytes on the fake filer.
func openSwapWriteHandle(t *testing.T, swapDir string) (*WFS, *FileHandle, *g6ConditionalPeer, *fuse.OpenOut) {
t.Helper()
base := attributeAppendEntry(1)
base.CommitTsNs = 100
peer := &g6ConditionalPeer{entry: proto.Clone(base).(*filer_pb.Entry)}
peer.blobs = map[string][]byte{base.Chunks[0].GetFileIdString(): bytes.Repeat([]byte{'O'}, 256)}
w := newInvalidateTestWFS(t)
notADir := filepath.Join(t.TempDir(), "file")
if err := os.WriteFile(notADir, nil, 0600); err != nil {
t.Fatal(err)
}
w.option.uniqueCacheDirForWrite = filepath.Join(notADir, "swap")
w.option.uniqueCacheDirForWrite = swapDir
w.option.DefaultPermissions = true
w.posixLocks = NewPosixLockTable()
w.option.ConcurrentWriters = 1
@@ -56,6 +47,25 @@ func testFailedWriteDoesNotGrowFile(t *testing.T, writeFlags uint32) {
fh := w.GetHandle(FileHandleId(out.Fh))
g6AppendUploader(t, fh, 100, peer)
return w, fh, peer, out
}
// A write the swap file cannot buffer fails, and must not grow the file: the
// next flush would publish that size with a hole where its data should be. A
// write that buffers only its first chunk is a short write of those bytes, or
// an error for kernel writeback, which would drop the rest silently.
func TestFailedWriteDoesNotGrowFile(t *testing.T) {
t.Run("short write", func(t *testing.T) { testFailedWriteDoesNotGrowFile(t, 0) })
t.Run("kernel writeback", func(t *testing.T) { testFailedWriteDoesNotGrowFile(t, fuse.WRITE_CACHE) })
}
func testFailedWriteDoesNotGrowFile(t *testing.T, writeFlags uint32) {
notADir := filepath.Join(t.TempDir(), "file")
if err := os.WriteFile(notADir, nil, 0600); err != nil {
t.Fatal(err)
}
w, fh, peer, out := openSwapWriteHandle(t, filepath.Join(notADir, "swap"))
write := func(offset uint64, size int, value byte) (uint32, fuse.Status) {
return w.Write(nil, &fuse.WriteIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: out.Fh, Offset: offset, Size: uint32(size), WriteFlags: writeFlags}, bytes.Repeat([]byte{value}, size))
}
@@ -93,3 +103,52 @@ func testFailedWriteDoesNotGrowFile(t *testing.T, writeFlags uint32) {
t.Fatalf("stored size %d, want 1024 with the original and buffered bytes", peer.entry.Attributes.FileSize)
}
}
// Writes buffered in the swap file were acknowledged to the application. If the
// swap file cannot be read back when they upload, fsync must fail like a failed
// chunk upload and the filer must not get an entry that claims those bytes.
func TestFsyncFailsWhenSwapFileCannotBeReadBack(t *testing.T) {
swapDir := t.TempDir()
w, _, peer, out := openSwapWriteHandle(t, swapDir)
peer.mu.Lock()
before := proto.Clone(peer.entry).(*filer_pb.Entry)
peer.mu.Unlock()
write := func(offset uint64, value byte) (uint32, fuse.Status) {
return w.Write(nil, &fuse.WriteIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: out.Fh, Offset: offset, Size: 256}, bytes.Repeat([]byte{value}, 256))
}
if n, code := write(256, 'A'); n != 256 || code != fuse.OK {
t.Fatalf("buffered write = %d, %v", n, code)
}
// The only writable chunk slot is taken, so this write goes to the swap file.
if n, code := write(4096, 'B'); n != 256 || code != fuse.OK {
t.Fatalf("swap file write = %d, %v", n, code)
}
swapFiles, err := os.ReadDir(swapDir)
if err != nil || len(swapFiles) != 1 {
t.Fatalf("swap dir = %v, %v; want one swap file", swapFiles, err)
}
// An outside cleanup cuts the swap file after the write was acknowledged.
if err := os.Truncate(filepath.Join(swapDir, swapFiles[0].Name()), 0); err != nil {
t.Fatal(err)
}
code := w.Fsync(nil, &fuse.FsyncIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: out.Fh})
if code == fuse.OK {
t.Fatal("fsync succeeded although acknowledged bytes could not be uploaded")
}
t.Logf("fsync = %v", code)
if _, code := write(8192, 'C'); code == fuse.OK {
t.Error("write after the failed upload succeeded; the handle can no longer flush cleanly")
}
peer.mu.Lock()
defer peer.mu.Unlock()
// The failed fsync publishes nothing: the filer keeps the entry and the 256
// bytes it had before the writes.
if !proto.Equal(peer.entry, before) {
t.Fatalf("a failed fsync changed the filer entry:\n got %v\nwant %v", peer.entry, before)
}
if stored := g6StoredBytes(t, peer); !bytes.Equal(stored, bytes.Repeat([]byte{'O'}, 256)) {
t.Fatalf("filer content = %q, want the original 256 bytes", stored)
}
}