From e8fef6bdfd7ef369ff27167920aca075c8fed180 Mon Sep 17 00:00:00 2001 From: Yip Leo Date: Wed, 2 Dec 2026 03:58:05 +0800 Subject: [PATCH] mount: fail a read of dirty pages that cannot be read back from the swap file (#13215) Dirty pages that weed mount buffers in the swap file (non-sequential writes, or when the memory chunks run out) also serve reads until they upload. SwapFileChunk.ReadDataAt logged a read error and stopped, returning only how far it had read; UploadPipeline.MaybeReadDataAt and DirtyPages.ReadDirtyDataAt passed that offset up. The mount read path then served the rest of the range from the stored chunks or from zeros, and the read returned OK. A read error on the cache disk, or a swap file truncated by an outside cleanup, is enough: the application reads back bytes it was told were written and gets other bytes, with no error anywhere. This is the read-side twin of #13198, which made the upload of those bytes fail. PageChunk.ReadDataAt, UploadPipeline.MaybeReadDataAt and DirtyPages.ReadDirtyDataAt now return an error besides the offset. A swap chunk that cannot read back an interval overlapping the requested range returns it, wrapping the new ErrDirtyDataUnreadable and the read error (a short read is io.ErrUnexpectedEOF). Intervals outside the range are not read, so a read that does not touch the lost bytes still succeeds. MemChunk cannot fail. The read handler and copy_file_range turn the error into EIO. Read does not refresh the filer entry and retry for this error, since the entry has no say over bytes that only exist in the swap file. A failed read does not mark the handle failed. Reads of other ranges and writes keep working, and the upload path already records the failure when it cannot read the same bytes, so flush, fsync and close return EIO. Co-authored-by: Claude Opus 5.5 --- weed/mount/dirty_pages_chunked.go | 2 +- weed/mount/filehandle_read.go | 5 +- weed/mount/page_writer.go | 8 +- weed/mount/page_writer/dirty_pages.go | 2 +- weed/mount/page_writer/page_chunk.go | 11 +- weed/mount/page_writer/page_chunk_mem.go | 2 +- weed/mount/page_writer/page_chunk_swapfile.go | 17 ++- weed/mount/page_writer/upload_pipeline.go | 16 ++- .../upload_pipeline_read_swap_test.go | 111 ++++++++++++++++++ .../upload_pipeline_reseal_test.go | 16 +-- weed/mount/page_writer_test.go | 8 +- weed/mount/weedfs_file_mkrm_test.go | 4 +- weed/mount/weedfs_file_read.go | 20 +++- weed/mount/weedfs_file_read_swap_test.go | 86 ++++++++++++++ weed/mount/weedfs_unpublished_create_test.go | 4 +- 15 files changed, 275 insertions(+), 37 deletions(-) create mode 100644 weed/mount/page_writer/upload_pipeline_read_swap_test.go create mode 100644 weed/mount/weedfs_file_read_swap_test.go diff --git a/weed/mount/dirty_pages_chunked.go b/weed/mount/dirty_pages_chunked.go index 3d97589f19..403304998c 100644 --- a/weed/mount/dirty_pages_chunked.go +++ b/weed/mount/dirty_pages_chunked.go @@ -102,7 +102,7 @@ func (pages *ChunkedDirtyPages) setLastError(err error) { } } -func (pages *ChunkedDirtyPages) ReadDirtyDataAt(data []byte, startOffset int64, tsNs int64) (maxStop int64) { +func (pages *ChunkedDirtyPages) ReadDirtyDataAt(data []byte, startOffset int64, tsNs int64) (maxStop int64, err error) { if !pages.hasWrites { return } diff --git a/weed/mount/filehandle_read.go b/weed/mount/filehandle_read.go index 32783e26aa..c13cd212df 100644 --- a/weed/mount/filehandle_read.go +++ b/weed/mount/filehandle_read.go @@ -23,9 +23,8 @@ func (fh *FileHandle) unlockForRead(startOffset int64, size int) { fh.dirtyPages.UnlockForRead(startOffset, startOffset+int64(size)) } -func (fh *FileHandle) readFromDirtyPages(buff []byte, startOffset int64, tsNs int64) (maxStop int64) { - maxStop = fh.dirtyPages.ReadDirtyDataAt(buff, startOffset, tsNs) - return +func (fh *FileHandle) readFromDirtyPages(buff []byte, startOffset int64, tsNs int64) (maxStop int64, err error) { + return fh.dirtyPages.ReadDirtyDataAt(buff, startOffset, tsNs) } func (fh *FileHandle) readFromChunks(buff []byte, offset int64) (int64, int64, error) { diff --git a/weed/mount/page_writer.go b/weed/mount/page_writer.go index 665e783c4d..315d133cce 100644 --- a/weed/mount/page_writer.go +++ b/weed/mount/page_writer.go @@ -61,7 +61,7 @@ func (pw *PageWriter) HasPendingUploads() bool { return pw.randomWriter.HasPendingUploads() } -func (pw *PageWriter) ReadDirtyDataAt(data []byte, offset int64, tsNs int64) (maxStop int64) { +func (pw *PageWriter) ReadDirtyDataAt(data []byte, offset int64, tsNs int64) (maxStop int64, err error) { glog.V(4).Infof("ReadDirtyDataAt %v [%d, %d)", pw.fh.inode, offset, offset+int64(len(data))) chunkIndex := offset / pw.chunkSize @@ -70,7 +70,11 @@ func (pw *PageWriter) ReadDirtyDataAt(data []byte, offset int64, tsNs int64) (ma // keep the furthest stop across chunks; a clean chunk later in the // range returns 0 and must not hide dirty data read from earlier ones - maxStop = max(maxStop, pw.randomWriter.ReadDirtyDataAt(data[:readSize], offset, tsNs)) + chunkStop, err := pw.randomWriter.ReadDirtyDataAt(data[:readSize], offset, tsNs) + if err != nil { + return maxStop, err + } + maxStop = max(maxStop, chunkStop) offset += readSize data = data[readSize:] diff --git a/weed/mount/page_writer/dirty_pages.go b/weed/mount/page_writer/dirty_pages.go index 42ad62831f..27a55b2f2e 100644 --- a/weed/mount/page_writer/dirty_pages.go +++ b/weed/mount/page_writer/dirty_pages.go @@ -5,7 +5,7 @@ type DirtyPages interface { FlushData() error HasWrites() bool HasPendingUploads() bool - ReadDirtyDataAt(data []byte, startOffset int64, tsNs int64) (maxStop int64) + ReadDirtyDataAt(data []byte, startOffset int64, tsNs int64) (maxStop int64, err error) Destroy() LockForRead(startOffset, stopOffset int64) UnlockForRead(startOffset, stopOffset int64) diff --git a/weed/mount/page_writer/page_chunk.go b/weed/mount/page_writer/page_chunk.go index 7c59db8d8b..9a86b63071 100644 --- a/weed/mount/page_writer/page_chunk.go +++ b/weed/mount/page_writer/page_chunk.go @@ -1,15 +1,24 @@ package page_writer import ( + "errors" "io" ) +// ErrDirtyDataUnreadable marks a read that overlaps dirty data which cannot be +// read back from where it is buffered. +var ErrDirtyDataUnreadable = errors.New("dirty data cannot be read back") + type SaveToStorageFunc func(reader io.Reader, offset int64, size int64, modifiedTsNs int64, cleanupFn func()) type PageChunk interface { FreeResource() WriteDataAt(src []byte, offset int64, tsNs int64) (n int) - ReadDataAt(p []byte, off int64, tsNs int64) (maxStop int64) + // ReadDataAt copies the written bytes that overlap [off, off+len(p)) into p + // and returns the furthest offset it filled. It fails, with an error that + // matches ErrDirtyDataUnreadable, when written bytes in that range cannot + // be read back: serving the range from elsewhere would return other data. + ReadDataAt(p []byte, off int64, tsNs int64) (maxStop int64, err error) IsComplete() bool IsContiguouslyWritten() bool ActivityScore() int64 diff --git a/weed/mount/page_writer/page_chunk_mem.go b/weed/mount/page_writer/page_chunk_mem.go index 9d2b13d5dc..bf5356405c 100644 --- a/weed/mount/page_writer/page_chunk_mem.go +++ b/weed/mount/page_writer/page_chunk_mem.go @@ -56,7 +56,7 @@ func (mc *MemChunk) WriteDataAt(src []byte, offset int64, tsNs int64) (n int) { return } -func (mc *MemChunk) ReadDataAt(p []byte, off int64, tsNs int64) (maxStop int64) { +func (mc *MemChunk) ReadDataAt(p []byte, off int64, tsNs int64) (maxStop int64, err error) { mc.RLock() defer mc.RUnlock() diff --git a/weed/mount/page_writer/page_chunk_swapfile.go b/weed/mount/page_writer/page_chunk_swapfile.go index 2575f8449f..ed490a7f78 100644 --- a/weed/mount/page_writer/page_chunk_swapfile.go +++ b/weed/mount/page_writer/page_chunk_swapfile.go @@ -132,7 +132,7 @@ func (sc *SwapFileChunk) WriteDataAt(src []byte, offset int64, tsNs int64) (n in return } -func (sc *SwapFileChunk) ReadDataAt(p []byte, off int64, tsNs int64) (maxStop int64) { +func (sc *SwapFileChunk) ReadDataAt(p []byte, off int64, tsNs int64) (maxStop int64, err error) { sc.RLock() defer sc.RUnlock() @@ -147,12 +147,17 @@ func (sc *SwapFileChunk) ReadDataAt(p []byte, off int64, tsNs int64) (maxStop in logicStop := min(off+int64(len(p)), chunkStartOffset+t.stopOffset) if logicStart < logicStop { actualStart := logicStart - chunkStartOffset + int64(sc.actualChunkIndex)*sc.swapfile.chunkSize - if n, err := sc.swapfile.file.ReadAt(p[logicStart-off:logicStop-off], actualStart); err != nil { - if err == io.EOF && n == int(logicStop-logicStart) { - err = nil + want := int(logicStop - logicStart) + if n, readErr := sc.swapfile.file.ReadAt(p[logicStart-off:logicStop-off], actualStart); n < want { + // The bytes were acknowledged to the writer, so a read that + // serves this range from stored chunks or zeros returns data + // the application did not write: fail it instead. + if readErr == nil || readErr == io.EOF { + readErr = io.ErrUnexpectedEOF } - glog.Errorf("failed to reading swap file %s: %v", sc.swapfile.file.Name(), err) - break + err = fmt.Errorf("%w: read swap file in %s [%d,%d) of chunk %d: %w", ErrDirtyDataUnreadable, sc.swapfile.dir, logicStart, logicStop, sc.logicChunkIndex, readErr) + glog.Errorf("%v", err) + return maxStop, err } maxStop = max(maxStop, logicStop) } diff --git a/weed/mount/page_writer/upload_pipeline.go b/weed/mount/page_writer/upload_pipeline.go index 85797453f4..979f9d138d 100644 --- a/weed/mount/page_writer/upload_pipeline.go +++ b/weed/mount/page_writer/upload_pipeline.go @@ -172,7 +172,11 @@ func (up *UploadPipeline) SaveDataAt(p []byte, off int64, isSequential bool, tsN return } -func (up *UploadPipeline) MaybeReadDataAt(p []byte, off int64, tsNs int64) (maxStop int64) { +// MaybeReadDataAt copies the dirty bytes of [off, off+len(p)) the pipeline +// holds into p and returns the furthest offset it filled. It fails when dirty +// bytes in the range cannot be read back, since the caller would otherwise +// serve the range from stored chunks or zeros. +func (up *UploadPipeline) MaybeReadDataAt(p []byte, off int64, tsNs int64) (maxStop int64, err error) { logicChunkIndex := LogicChunkIndex(off / up.ChunkSize) up.chunksLock.Lock() @@ -181,7 +185,10 @@ func (up *UploadPipeline) MaybeReadDataAt(p []byte, off int64, tsNs int64) (maxS // read from sealed chunks first sealedChunk, found := up.sealedChunks[logicChunkIndex] if found { - maxStop = sealedChunk.chunk.ReadDataAt(p, off, tsNs) + maxStop, err = sealedChunk.chunk.ReadDataAt(p, off, tsNs) + if err != nil { + return maxStop, err + } glog.V(4).Infof("%s read sealed memchunk [%d,%d)", up.filepath, off, maxStop) } @@ -190,7 +197,10 @@ func (up *UploadPipeline) MaybeReadDataAt(p []byte, off int64, tsNs int64) (maxS if !found { return } - writableMaxStop := writableChunk.ReadDataAt(p, off, tsNs) + writableMaxStop, err := writableChunk.ReadDataAt(p, off, tsNs) + if err != nil { + return maxStop, err + } glog.V(4).Infof("%s read writable memchunk [%d,%d)", up.filepath, off, writableMaxStop) maxStop = max(maxStop, writableMaxStop) diff --git a/weed/mount/page_writer/upload_pipeline_read_swap_test.go b/weed/mount/page_writer/upload_pipeline_read_swap_test.go new file mode 100644 index 0000000000..36dbc9da23 --- /dev/null +++ b/weed/mount/page_writer/upload_pipeline_read_swap_test.go @@ -0,0 +1,111 @@ +package page_writer + +import ( + "bytes" + "errors" + "io" + "os" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/util" +) + +func discardSave(reader io.Reader, offset int64, size int64, modifiedTsNs int64, cleanupFn func()) { + io.Copy(io.Discard, reader) +} + +// A read must fail when it overlaps dirty bytes in the swap file that cannot +// be read back, and only then: a range that holds no dirty bytes, or bytes the +// swap file still has, reads as before. +func TestMaybeReadDataAtFailsWhenSwapFileCannotBeRead(t *testing.T) { + up := NewUploadPipeline(util.NewLimitedConcurrentExecutor(1), 1024, discardSave, 16, t.TempDir(), nil) + defer up.Shutdown() + // Not sequential: the chunk goes to the swap file, slot 1 = [1024, 2048). + 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) + } + + p := make([]byte, 1024) + if maxStop, err := up.MaybeReadDataAt(p, 0, 0); err != nil || maxStop != 604 || string(p[:4]) != "head" || string(p[600:604]) != "tail" { + t.Fatalf("healthy read = %d, %v, %q ... %q; want 604, nil, head ... tail", maxStop, err, p[:4], p[600:604]) + } + + // The swap file is cut inside the second interval. + if err := up.swapFile.file.Truncate(1024 + 602); err != nil { + t.Fatal(err) + } + + p = make([]byte, 4) + if maxStop, err := up.MaybeReadDataAt(p, 0, 0); err != nil || maxStop != 4 || string(p) != "head" { + t.Errorf("read of the interval the swap file still holds = %d, %v, %q; want 4, nil, head", maxStop, err, p) + } + p = make([]byte, 100) + if maxStop, err := up.MaybeReadDataAt(p, 100, 0); err != nil || maxStop != 0 || !bytes.Equal(p, make([]byte, 100)) { + t.Errorf("read of a range without dirty bytes = %d, %v; want 0, nil and p untouched", maxStop, err) + } + for _, tc := range []struct { + name string + off int64 + size int + }{ + {"exactly the lost interval", 600, 4}, + {"part of the lost interval", 602, 1}, + {"a range spanning both intervals", 0, 1024}, + } { + p = make([]byte, tc.size) + _, err := up.MaybeReadDataAt(p, tc.off, 0) + if !errors.Is(err, ErrDirtyDataUnreadable) || !errors.Is(err, io.ErrUnexpectedEOF) { + t.Errorf("%s: err = %v; want ErrDirtyDataUnreadable wrapping io.ErrUnexpectedEOF", tc.name, err) + } + } +} + +// A closed swap file fails the read with the file's own error. +func TestMaybeReadDataAtFailsWhenSwapFileIsClosed(t *testing.T) { + up := NewUploadPipeline(util.NewLimitedConcurrentExecutor(1), 1024, discardSave, 16, t.TempDir(), nil) + defer up.Shutdown() + if _, err := up.SaveDataAt([]byte("data"), 0, false, 1); err != nil { + t.Fatal(err) + } + if err := up.swapFile.file.Close(); err != nil { + t.Fatal(err) + } + if _, err := up.MaybeReadDataAt(make([]byte, 4), 0, 0); !errors.Is(err, ErrDirtyDataUnreadable) || !errors.Is(err, os.ErrClosed) { + t.Fatalf("err = %v; want ErrDirtyDataUnreadable wrapping os.ErrClosed", err) + } +} + +// A chunk sealed for upload stays readable until its readers leave. A reader +// holds the chunk here, so it is still indexed after its upload finished; a +// failure reading it back fails the read like one of a writable chunk. +func TestMaybeReadDataAtFailsForSealedSwapChunk(t *testing.T) { + up := NewUploadPipeline(util.NewLimitedConcurrentExecutor(1), 1024, discardSave, 16, t.TempDir(), nil) + defer up.Shutdown() + if _, err := up.SaveDataAt([]byte("data"), 0, false, 1); err != nil { + t.Fatal(err) + } + up.LockForRead(0, 1024) + defer up.UnlockForRead(0, 1024) + up.FlushAll() + + up.chunksLock.Lock() + _, sealed := up.sealedChunks[0] + _, writable := up.writableChunks[0] + up.chunksLock.Unlock() + if !sealed || writable { + t.Fatalf("chunk 0 sealed = %v, writable = %v; want sealed only", sealed, writable) + } + p := make([]byte, 4) + if maxStop, err := up.MaybeReadDataAt(p, 0, 0); err != nil || maxStop != 4 || string(p) != "data" { + t.Fatalf("healthy read of the sealed chunk = %d, %v, %q", maxStop, err, p) + } + if err := up.swapFile.file.Truncate(0); err != nil { + t.Fatal(err) + } + if _, err := up.MaybeReadDataAt(make([]byte, 4), 0, 0); !errors.Is(err, ErrDirtyDataUnreadable) { + t.Fatalf("err = %v; want ErrDirtyDataUnreadable", err) + } +} diff --git a/weed/mount/page_writer/upload_pipeline_reseal_test.go b/weed/mount/page_writer/upload_pipeline_reseal_test.go index 41d78ef0b4..24c40b9aea 100644 --- a/weed/mount/page_writer/upload_pipeline_reseal_test.go +++ b/weed/mount/page_writer/upload_pipeline_reseal_test.go @@ -24,14 +24,14 @@ func newGatedChunk() *gatedChunk { } } -func (c *gatedChunk) FreeResource() { c.freeCount.Add(1) } -func (c *gatedChunk) WriteDataAt([]byte, int64, int64) int { return 0 } -func (c *gatedChunk) ReadDataAt([]byte, int64, int64) int64 { return 0 } -func (c *gatedChunk) IsComplete() bool { return false } -func (c *gatedChunk) IsContiguouslyWritten() bool { return true } -func (c *gatedChunk) ActivityScore() int64 { return 0 } -func (c *gatedChunk) WrittenSize() int64 { return 0 } -func (c *gatedChunk) LastWriteTsNs() int64 { return 0 } +func (c *gatedChunk) FreeResource() { c.freeCount.Add(1) } +func (c *gatedChunk) WriteDataAt([]byte, int64, int64) int { return 0 } +func (c *gatedChunk) ReadDataAt([]byte, int64, int64) (int64, error) { return 0, nil } +func (c *gatedChunk) IsComplete() bool { return false } +func (c *gatedChunk) IsContiguouslyWritten() bool { return true } +func (c *gatedChunk) ActivityScore() int64 { return 0 } +func (c *gatedChunk) WrittenSize() int64 { return 0 } +func (c *gatedChunk) LastWriteTsNs() int64 { return 0 } func (c *gatedChunk) SaveContent(saveFn SaveToStorageFunc) { <-c.gate c.freedBefore = c.freeCount.Load() > 0 diff --git a/weed/mount/page_writer_test.go b/weed/mount/page_writer_test.go index 5020164f1b..200c28dd6a 100644 --- a/weed/mount/page_writer_test.go +++ b/weed/mount/page_writer_test.go @@ -14,14 +14,14 @@ type stubDirtyPages struct { dirty map[int64]bool } -func (s *stubDirtyPages) ReadDirtyDataAt(data []byte, startOffset int64, tsNs int64) (maxStop int64) { +func (s *stubDirtyPages) ReadDirtyDataAt(data []byte, startOffset int64, tsNs int64) (maxStop int64, err error) { if !s.dirty[startOffset/s.chunkSize] { - return 0 + return 0, nil } for i := range data { data[i] = 'x' } - return startOffset + int64(len(data)) + return startOffset + int64(len(data)), nil } func TestPageWriterReadDirtyDataAtAcrossChunks(t *testing.T) { @@ -47,7 +47,7 @@ func TestPageWriterReadDirtyDataAtAcrossChunks(t *testing.T) { chunkSize: chunkSize, randomWriter: &stubDirtyPages{chunkSize: chunkSize, dirty: tt.dirty}, } - if got := pw.ReadDirtyDataAt(make([]byte, tt.size), tt.offset, 0); got != tt.want { + if got, err := pw.ReadDirtyDataAt(make([]byte, tt.size), tt.offset, 0); err != nil || got != tt.want { t.Errorf("ReadDirtyDataAt(offset=%d, size=%d) = %d, want %d", tt.offset, tt.size, got, tt.want) } }) diff --git a/weed/mount/weedfs_file_mkrm_test.go b/weed/mount/weedfs_file_mkrm_test.go index 3837851243..805b18191f 100644 --- a/weed/mount/weedfs_file_mkrm_test.go +++ b/weed/mount/weedfs_file_mkrm_test.go @@ -313,8 +313,8 @@ func TestTruncateEntryClearsDirtyPagesForOpenHandle(t *testing.T) { t.Fatalf("file handle size = %d, want 0", got) } buf := make([]byte, 5) - if maxStop := fh.dirtyPages.ReadDirtyDataAt(buf, 0, time.Now().UnixNano()); maxStop != 0 { - t.Fatalf("dirty pages maxStop = %d, want 0 after truncate", maxStop) + if maxStop, err := fh.dirtyPages.ReadDirtyDataAt(buf, 0, time.Now().UnixNano()); err != nil || maxStop != 0 { + t.Fatalf("dirty pages maxStop = %d, err %v, want 0 after truncate", maxStop, err) } } diff --git a/weed/mount/weedfs_file_read.go b/weed/mount/weedfs_file_read.go index a7f078d55d..a20bc875ae 100644 --- a/weed/mount/weedfs_file_read.go +++ b/weed/mount/weedfs_file_read.go @@ -3,9 +3,11 @@ package mount import ( "bytes" "context" + "errors" "fmt" "io" + "github.com/seaweedfs/seaweedfs/weed/mount/page_writer" "github.com/seaweedfs/seaweedfs/weed/util" "github.com/seaweedfs/go-fuse/v2/fuse" @@ -52,7 +54,9 @@ func (wfs *WFS) Read(cancel <-chan struct{}, in *fuse.ReadIn, buff []byte) (fuse offset := int64(in.Offset) totalRead, err := readDataByFileHandleWithContext(ctx, buff, fh, offset) - if err != nil && err != errNativeSSERead && err != errSSES3Permission && ctx.Err() == nil { + // A failed read of buffered dirty data is not retried after a refresh: the + // filer entry has no say over bytes that are only in the swap file. + if err != nil && err != errNativeSSERead && err != errSSES3Permission && !errors.Is(err, page_writer.ErrDirtyDataUnreadable) && ctx.Err() == nil { // The chunk views a read resolves can name data a concurrent overwrite // already replaced: the filer queues replaced file ids for deletion at // commit while this handle only learns the new list when the metadata @@ -112,7 +116,12 @@ func readDataByFileHandle(buff []byte, fhIn *FileHandle, offset int64) (int64, e n, tsNs, err := fhIn.readFromChunks(buff, offset) if err == nil || err == io.EOF { - maxStop := fhIn.readFromDirtyPages(buff, offset, tsNs) + maxStop, dirtyErr := fhIn.readFromDirtyPages(buff, offset, tsNs) + if dirtyErr != nil { + // Buffered bytes of this range cannot be read back: the read + // must fail rather than return the stored chunks or zeros. + return 0, dirtyErr + } n = max(maxStop-offset, n) } if err == io.EOF { @@ -129,7 +138,12 @@ func readDataByFileHandleWithContext(ctx context.Context, buff []byte, fhIn *Fil n, tsNs, err := fhIn.readFromChunksWithContext(ctx, buff, offset) if err == nil || err == io.EOF { - maxStop := fhIn.readFromDirtyPages(buff, offset, tsNs) + maxStop, dirtyErr := fhIn.readFromDirtyPages(buff, offset, tsNs) + if dirtyErr != nil { + // Buffered bytes of this range cannot be read back: the read + // must fail rather than return the stored chunks or zeros. + return 0, dirtyErr + } n = max(maxStop-offset, n) } if err == io.EOF { diff --git a/weed/mount/weedfs_file_read_swap_test.go b/weed/mount/weedfs_file_read_swap_test.go new file mode 100644 index 0000000000..83a196119f --- /dev/null +++ b/weed/mount/weedfs_file_read_swap_test.go @@ -0,0 +1,86 @@ +//go:build !freebsd + +package mount + +import ( + "bytes" + "errors" + "os" + "path/filepath" + "testing" + + "github.com/seaweedfs/go-fuse/v2/fuse" + "github.com/seaweedfs/seaweedfs/weed/mount/page_writer" +) + +// A read of bytes that were acknowledged to the writer but sit in a swap file +// that can no longer be read must fail. Serving the range from the stored +// chunks or from zeros returns data the application did not write, with no +// error anywhere. +func TestReadFailsWhenBufferedBytesCannotBeReadFromSwapFile(t *testing.T) { + swapDir := t.TempDir() + w, fh, _, out := openSwapWriteHandle(t, swapDir) + 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)) + } + read := func(offset uint64, size uint32) ([]byte, fuse.Status) { + buf := make([]byte, size) + res, code := w.Read(nil, &fuse.ReadIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: out.Fh, Offset: offset, Size: size}, buf) + if code != fuse.OK { + return nil, code + } + got, status := res.Bytes(buf) + if status != fuse.OK { + t.Fatalf("read result bytes: %v", status) + } + return append([]byte(nil), got...), code + } + 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) + } + wantB := bytes.Repeat([]byte{'B'}, 256) + if got, code := read(4096, 256); code != fuse.OK || !bytes.Equal(got, wantB) { + t.Fatalf("read of the swap-buffered range before the cut = %v, %q; want OK and 256 'B'", code, got) + } + + // 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) + } + + if got, code := read(4096, 256); code != fuse.EIO { + t.Fatalf("read of the swap-buffered range after the cut = %v, %q; want EIO", code, got) + } + // A read that merely reaches into the swap-buffered range fails too, even + // when it starts in a chunk without dirty data. + if got, code := read(3584, 1024); code != fuse.EIO { + t.Fatalf("read across the chunk boundary into the swap-buffered range = %v, %q; want EIO", code, got) + } + // copy_file_range reads its source through the same path. + if n, err := readDataByFileHandle(make([]byte, 256), fh, 4096); err == nil || !errors.Is(err, page_writer.ErrDirtyDataUnreadable) { + t.Fatalf("readDataByFileHandle of the swap-buffered range = %d, %v; want ErrDirtyDataUnreadable", n, err) + } + + // The failure belongs to that read: the handle is not poisoned. A range the + // swap file does not hold still reads, and a write still goes through. + wantA := bytes.Repeat([]byte{'A'}, 256) + if got, code := read(256, 256); code != fuse.OK || !bytes.Equal(got, wantA) { + t.Fatalf("read of the memory-buffered range = %v, %q; want OK and 256 'A'", code, got) + } + if n, code := write(512, 'C'); n != 256 || code != fuse.OK { + t.Fatalf("write after the failed read = %d, %v; want OK", n, code) + } + // The upload path still reports the loss: the unreadable bytes can never be + // flushed. + if code := w.Fsync(nil, &fuse.FsyncIn{InHeader: fuse.InHeader{NodeId: 42}, Fh: out.Fh}); code == fuse.OK { + t.Fatal("fsync succeeded although acknowledged bytes could not be uploaded") + } +} diff --git a/weed/mount/weedfs_unpublished_create_test.go b/weed/mount/weedfs_unpublished_create_test.go index 7fc1f9b688..dafa159366 100644 --- a/weed/mount/weedfs_unpublished_create_test.go +++ b/weed/mount/weedfs_unpublished_create_test.go @@ -52,8 +52,8 @@ func requireWritesKept(t *testing.T, fh *FileHandle, pages *PageWriter, data []b t.Fatal("the handle's unflushed writes were discarded") } buf := make([]byte, len(data)) - if maxStop := fh.dirtyPages.ReadDirtyDataAt(buf, 0, time.Now().UnixNano()); maxStop != int64(len(data)) || !bytes.Equal(buf, data) { - t.Fatalf("dirty data = %q (maxStop %d), want %q", buf, maxStop, data) + if maxStop, err := fh.dirtyPages.ReadDirtyDataAt(buf, 0, time.Now().UnixNano()); err != nil || maxStop != int64(len(data)) || !bytes.Equal(buf, data) { + t.Fatalf("dirty data = %q (maxStop %d, err %v), want %q", buf, maxStop, err, data) } if fh.baseEntry.Load() != nil { t.Fatal("the handle took the peer's entry as its base")