diff --git a/internal/chunks/chunk_store.go b/internal/chunks/chunk_store.go index b4a0c95..a715f40 100644 --- a/internal/chunks/chunk_store.go +++ b/internal/chunks/chunk_store.go @@ -144,21 +144,17 @@ func (cs *ChunkStore) Append(ctx context.Context, data []byte, fileOffset int64) // The active chunk is served from the in-memory buffer without a store round-trip. func (cs *ChunkStore) Read(ctx context.Context, chunkID string, chunkOffset, length int64) ([]byte, error) { cs.mu.Lock() - active := cs.activeID - var activeBuf []byte - if chunkID == active { - activeBuf = make([]byte, len(cs.activeBuf)) - copy(activeBuf, cs.activeBuf) - } - cs.mu.Unlock() - - if chunkID == active { - if chunkOffset+length > int64(len(activeBuf)) { + if chunkID == cs.activeID { + defer cs.mu.Unlock() + if chunkOffset+length > int64(len(cs.activeBuf)) { return nil, fmt.Errorf("read out of bounds: chunk %s offset %d length %d size %d", - chunkID, chunkOffset, length, len(activeBuf)) + chunkID, chunkOffset, length, len(cs.activeBuf)) } - return activeBuf[chunkOffset : chunkOffset+length], nil + out := make([]byte, length) + copy(out, cs.activeBuf[chunkOffset:chunkOffset+length]) + return out, nil } + cs.mu.Unlock() // Sealed chunk: serve from local cache if enabled, otherwise fetch directly. if cs.cache != nil { return cs.cache.readRange(ctx, cs.store, chunkID, chunkOffset, length) diff --git a/internal/chunks/chunk_store_test.go b/internal/chunks/chunk_store_test.go index 5118c5b..e82e024 100644 --- a/internal/chunks/chunk_store_test.go +++ b/internal/chunks/chunk_store_test.go @@ -337,3 +337,36 @@ func TestSealAfterFlushActive(t *testing.T) { t.Errorf("sealed chunk: got %q, want %q", got, want) } } + +func TestReadActiveChunkReturnsIndependentCopy(t *testing.T) { + ctx := context.Background() + _, cs := newTestStore(t) + + first, err := cs.Append(ctx, []byte("abcdefghij"), 0) + if err != nil { + t.Fatal(err) + } + got, err := cs.Read(ctx, first.ChunkID, 2, 4) + if err != nil { + t.Fatal(err) + } + if string(got) != "cdef" { + t.Fatalf("got %q, want %q", got, "cdef") + } + + // Sealing reuses the active buffer; a previously returned slice must not change. + if err := cs.Seal(ctx); err != nil { + t.Fatal(err) + } + if _, err := cs.Append(ctx, []byte("ZZZZZZZZZZ"), 0); err != nil { + t.Fatal(err) + } + if string(got) != "cdef" { + t.Errorf("returned slice aliased the active buffer: now %q", got) + } + + if _, err := cs.Read(ctx, cs.ActiveID(), 5, 100); err == nil { + t.Error("want out-of-bounds error reading past the active buffer") + } +} + diff --git a/internal/fuse/fs.go b/internal/fuse/fs.go index c8f8c25..878ca7b 100644 --- a/internal/fuse/fs.go +++ b/internal/fuse/fs.go @@ -30,7 +30,7 @@ type FSIndex interface { GetInode(ino uint64) (index.Inode, bool) Lookup(parentIno uint64, name string) (uint64, bool) Readdir(ino uint64) ([]index.DirEntry, error) - GetExtents(ino uint64) ([]index.Extent, bool) + ExtentsInRange(ino uint64, off, end int64) ([]index.Extent, bool) GetSymlink(ino uint64) (string, bool) GetXattrs(ino uint64) map[string]string GetParentIno(ino uint64) uint64 @@ -476,7 +476,7 @@ func (fh *FileHandle) Read(ctx context.Context, dest []byte, off int64) (gofuse. } need := end - off - exts, ok := fh.f.idx.GetExtents(fh.ino) + exts, ok := fh.f.idx.ExtentsInRange(fh.ino, off, end) if !ok { return gofuse.ReadResultData(nil), 0 } diff --git a/internal/index/extents_test.go b/internal/index/extents_test.go new file mode 100644 index 0000000..7e360ec --- /dev/null +++ b/internal/index/extents_test.go @@ -0,0 +1,210 @@ +package index + +import ( + "fmt" + "math/rand" + "testing" +) + +func newFile(t *testing.T) (*Index, uint64) { + t.Helper() + idx := New(4096) + n := now() + ino, err := idx.CreateInode(Regular, 0o644, 0, 0, 0, n) + if err != nil { + t.Fatal(err) + } + if err := idx.AddDirEntry(RootIno, "f", ino, n); err != nil { + t.Fatal(err) + } + return idx, ino +} + +func TestWriteExtentMergesSequentialWrites(t *testing.T) { + idx, ino := newFile(t) + for i := int64(0); i < 1000; i++ { + ext := Extent{ChunkID: "c0", ChunkOffset: i * 4096, Length: 4096, FileOffset: i * 4096} + if err := idx.WriteExtent(ino, ext, now()); err != nil { + t.Fatal(err) + } + } + exts, _ := idx.GetExtents(ino) + if len(exts) != 1 { + t.Fatalf("got %d extents, want 1: contiguous writes in one chunk should merge", len(exts)) + } + if want := (Extent{ChunkID: "c0", ChunkOffset: 0, Length: 1000 * 4096, FileOffset: 0}); exts[0] != want { + t.Errorf("got %+v, want %+v", exts[0], want) + } + checkInvariants(t, idx) +} + +func TestWriteExtentDoesNotMergeAcrossChunksOrGaps(t *testing.T) { + idx, ino := newFile(t) + writes := []Extent{ + {ChunkID: "c0", ChunkOffset: 0, Length: 10, FileOffset: 0}, + {ChunkID: "c1", ChunkOffset: 0, Length: 10, FileOffset: 10}, // different chunk + {ChunkID: "c1", ChunkOffset: 50, Length: 10, FileOffset: 20}, // chunk-offset gap + {ChunkID: "c1", ChunkOffset: 60, Length: 10, FileOffset: 40}, // file gap + } + for _, w := range writes { + if err := idx.WriteExtent(ino, w, now()); err != nil { + t.Fatal(err) + } + } + exts, _ := idx.GetExtents(ino) + if len(exts) != len(writes) { + t.Fatalf("got %d extents, want %d: %+v", len(exts), len(writes), exts) + } +} + +func TestWriteExtentOverwriteMiddleSplitsExtent(t *testing.T) { + idx, ino := newFile(t) + idx.WriteExtent(ino, Extent{ChunkID: "c0", ChunkOffset: 0, Length: 100, FileOffset: 0}, now()) + idx.WriteExtent(ino, Extent{ChunkID: "c1", ChunkOffset: 500, Length: 20, FileOffset: 40}, now()) + + want := []Extent{ + {ChunkID: "c0", ChunkOffset: 0, Length: 40, FileOffset: 0}, + {ChunkID: "c1", ChunkOffset: 500, Length: 20, FileOffset: 40}, + {ChunkID: "c0", ChunkOffset: 60, Length: 40, FileOffset: 60}, + } + got, _ := idx.GetExtents(ino) + if fmt.Sprint(got) != fmt.Sprint(want) { + t.Errorf("got %+v, want %+v", got, want) + } +} + +func TestExtentsInRange(t *testing.T) { + idx, ino := newFile(t) + for i := int64(0); i < 10; i++ { + // Distinct chunks so nothing merges: file bytes [i*10, i*10+10). + idx.WriteExtent(ino, Extent{ChunkID: fmt.Sprintf("c%d", i), Length: 10, FileOffset: i * 10}, now()) + } + cases := []struct { + off, end int64 + first int64 + count int + }{ + {0, 100, 0, 10}, + {0, 1, 0, 1}, + {9, 11, 0, 2}, + {10, 20, 1, 1}, + {95, 100, 9, 1}, + {100, 200, 0, 0}, + {35, 36, 3, 1}, + } + for _, c := range cases { + got, ok := idx.ExtentsInRange(ino, c.off, c.end) + if !ok { + t.Fatalf("[%d,%d): no extents", c.off, c.end) + } + if len(got) != c.count { + t.Errorf("[%d,%d): got %d extents, want %d: %+v", c.off, c.end, len(got), c.count, got) + continue + } + if c.count > 0 && got[0].FileOffset != c.first*10 { + t.Errorf("[%d,%d): first extent at %d, want %d", c.off, c.end, got[0].FileOffset, c.first*10) + } + } + if _, ok := idx.ExtentsInRange(9999, 0, 1); ok { + t.Error("unknown inode: want ok=false") + } +} + +// TestWriteExtentRandomAgainstModel applies random overlapping writes and +// checks the extent list against a byte-by-byte model, plus the sorted / +// non-overlapping invariant that ExtentsInRange depends on. +func TestWriteExtentRandomAgainstModel(t *testing.T) { + type loc struct { + chunk string + off int64 + } + const fileSize = 512 + rng := rand.New(rand.NewSource(1)) + idx, ino := newFile(t) + model := map[int64]loc{} + + for i := 0; i < 2000; i++ { + fileOff := rng.Int63n(fileSize) + length := 1 + rng.Int63n(40) + chunk := fmt.Sprintf("c%d", rng.Intn(3)) + chunkOff := rng.Int63n(4) * 8 + if rng.Intn(2) == 0 && len(model) > 0 { + // Often continue the previous write so merging is exercised. + chunkOff = 1000 + int64(i)*100 + } + for b := int64(0); b < length; b++ { + model[fileOff+b] = loc{chunk, chunkOff + b} + } + if err := idx.WriteExtent(ino, Extent{ChunkID: chunk, ChunkOffset: chunkOff, Length: length, FileOffset: fileOff}, now()); err != nil { + t.Fatal(err) + } + + exts, _ := idx.GetExtents(ino) + var prevEnd int64 = -1 + got := map[int64]loc{} + for _, e := range exts { + if e.Length <= 0 { + t.Fatalf("step %d: non-positive extent %+v", i, e) + } + if e.FileOffset < prevEnd { + t.Fatalf("step %d: extents unsorted or overlapping at %+v (prevEnd %d)", i, e, prevEnd) + } + prevEnd = e.FileOffset + e.Length + for b := int64(0); b < e.Length; b++ { + got[e.FileOffset+b] = loc{e.ChunkID, e.ChunkOffset + b} + } + } + if len(got) != len(model) { + t.Fatalf("step %d: extents cover %d bytes, model %d", i, len(got), len(model)) + } + for k, v := range model { + if got[k] != v { + t.Fatalf("step %d: byte %d maps to %+v, want %+v", i, k, got[k], v) + } + } + } +} + +func TestSnapshotRoundTripBeyondDefaultCBORLimits(t *testing.T) { + idx, ino := newFile(t) + // Alternate chunks so extents cannot merge: > 131072 extents in one file. + const n = 140000 + idx.mu.Lock() + exts := make([]Extent, n) + for i := range exts { + exts[i] = Extent{ChunkID: fmt.Sprintf("chunk-%08d", i%2), ChunkOffset: int64(i) * 10, Length: 10, FileOffset: int64(i) * 10} + } + idx.extents[ino] = exts + idx.inodes[ino].Size = n * 10 + idx.mu.Unlock() + + data, err := Marshal(idx) + if err != nil { + t.Fatal(err) + } + restored, err := Unmarshal(data, 4096) + if err != nil { + t.Fatalf("Unmarshal of an index with %d extents: %v", n, err) + } + got, _ := restored.GetExtents(ino) + if len(got) != n { + t.Errorf("restored %d extents, want %d", len(got), n) + } +} + +func TestFromSnapshotSortsLegacyExtentOrder(t *testing.T) { + snap := &Snapshot{ + Inodes: map[uint64]*Inode{RootIno: {Ino: RootIno, FileType: Directory}, 2: {Ino: 2, FileType: Regular, Size: 30}}, + ExtentMap: map[uint64][]Extent{2: { + {ChunkID: "c0", Length: 10, FileOffset: 20}, + {ChunkID: "c0", Length: 10, FileOffset: 0}, + {ChunkID: "c0", Length: 10, FileOffset: 10}, + }}, + NextIno: 3, + } + idx := FromSnapshot(snap, 4096) + got, ok := idx.ExtentsInRange(2, 10, 20) + if !ok || len(got) != 1 || got[0].FileOffset != 10 { + t.Errorf("got %+v, want the single extent at offset 10", got) + } +} diff --git a/internal/index/index.go b/internal/index/index.go index 38af279..f5fd9b6 100644 --- a/internal/index/index.go +++ b/internal/index/index.go @@ -6,6 +6,7 @@ package index import ( "fmt" + "sort" "sync" "time" ) @@ -86,6 +87,14 @@ func FromSnapshot(snap *Snapshot, blockSize int32) *Index { if idx.xattrs == nil { idx.xattrs = map[uint64]map[string]string{} } + // Snapshots written before extents were kept sorted may be out of order. + for ino, exts := range idx.extents { + byOffset := func(i, j int) bool { return exts[i].FileOffset < exts[j].FileOffset } + if !sort.SliceIsSorted(exts, byOffset) { + sort.SliceStable(exts, byOffset) + idx.extents[ino] = exts + } + } // Rebuild dirIndex from the flat DirEntry slice. for _, e := range snap.DirEntries { if idx.dirIndex[e.ParentIno] == nil { @@ -248,6 +257,23 @@ func (idx *Index) GetExtents(ino uint64) ([]Extent, bool) { return cp, true } +// ExtentsInRange returns, in file-offset order, only the extents of ino that +// overlap [off, end). It relies on the per-file extent list being sorted and +// non-overlapping, so the lookup is O(log n + k) and copies just k extents. +func (idx *Index) ExtentsInRange(ino uint64, off, end int64) ([]Extent, bool) { + idx.mu.RLock() + defer idx.mu.RUnlock() + exts, ok := idx.extents[ino] + if !ok { + return nil, false + } + lo := sort.Search(len(exts), func(i int) bool { return exts[i].FileOffset+exts[i].Length > off }) + hi := lo + sort.Search(len(exts)-lo, func(i int) bool { return exts[lo+i].FileOffset >= end }) + cp := make([]Extent, hi-lo) + copy(cp, exts[lo:hi]) + return cp, true +} + // GetSymlink returns the target of a symlink inode. func (idx *Index) GetSymlink(ino uint64) (string, bool) { idx.mu.RLock() @@ -655,35 +681,7 @@ func (idx *Index) WriteExtent(ino uint64, ext Extent, now int64) error { } end := ext.FileOffset + ext.Length - surviving := idx.extents[ino][:0] - for _, e := range idx.extents[ino] { - eEnd := e.FileOffset + e.Length - if eEnd <= ext.FileOffset || e.FileOffset >= end { - // No overlap: keep as-is. - surviving = append(surviving, e) - continue - } - // Trim head portion that precedes the write. - if e.FileOffset < ext.FileOffset { - surviving = append(surviving, Extent{ - ChunkID: e.ChunkID, - ChunkOffset: e.ChunkOffset, - Length: ext.FileOffset - e.FileOffset, - FileOffset: e.FileOffset, - }) - } - // Trim tail portion that follows the write. - if eEnd > end { - surviving = append(surviving, Extent{ - ChunkID: e.ChunkID, - ChunkOffset: e.ChunkOffset + (end - e.FileOffset), - Length: eEnd - end, - FileOffset: end, - }) - } - } - surviving = append(surviving, ext) - idx.extents[ino] = surviving + idx.extents[ino] = spliceExtent(idx.extents[ino], ext) if end > inode.Size { inode.Size = end @@ -696,6 +694,64 @@ func (idx *Index) WriteExtent(ino uint64, ext Extent, now int64) error { return nil } +// extentsAdjacent reports whether b continues a both in the file and in the +// same chunk, so the two can be stored as one extent. +func extentsAdjacent(a, b Extent) bool { + return a.ChunkID == b.ChunkID && + a.ChunkOffset+a.Length == b.ChunkOffset && + a.FileOffset+a.Length == b.FileOffset +} + +// spliceExtent inserts ext into exts (sorted by FileOffset, non-overlapping), +// trimming or dropping the extents it overlaps, and merges it with a +// contiguous neighbour. Merging matters because a file written with many small +// write() calls would otherwise carry one extent per call. +func spliceExtent(exts []Extent, ext Extent) []Extent { + end := ext.FileOffset + ext.Length + lo := sort.Search(len(exts), func(i int) bool { return exts[i].FileOffset+exts[i].Length > ext.FileOffset }) + hi := lo + sort.Search(len(exts)-lo, func(i int) bool { return exts[lo+i].FileOffset >= end }) + + mid := make([]Extent, 0, 3) + headTrimmed, tailTrimmed := false, false + if lo < hi { + if f := exts[lo]; f.FileOffset < ext.FileOffset { + f.Length = ext.FileOffset - f.FileOffset + mid = append(mid, f) + headTrimmed = true + } + } + mid = append(mid, ext) + if lo < hi { + if l := exts[hi-1]; l.FileOffset+l.Length > end { + cut := end - l.FileOffset + mid = append(mid, Extent{ChunkID: l.ChunkID, ChunkOffset: l.ChunkOffset + cut, Length: l.Length - cut, FileOffset: end}) + tailTrimmed = true + } + } + + if !headTrimmed && lo > 0 && extentsAdjacent(exts[lo-1], mid[0]) { + lo-- + mid[0] = Extent{ChunkID: exts[lo].ChunkID, ChunkOffset: exts[lo].ChunkOffset, Length: exts[lo].Length + mid[0].Length, FileOffset: exts[lo].FileOffset} + } + if !tailTrimmed && hi < len(exts) && extentsAdjacent(mid[len(mid)-1], exts[hi]) { + mid[len(mid)-1].Length += exts[hi].Length + hi++ + } + + switch { + case hi-lo == len(mid): + copy(exts[lo:hi], mid) + return exts + case hi == len(exts): + return append(exts[:lo], mid...) + } + out := make([]Extent, 0, len(exts)-(hi-lo)+len(mid)) + out = append(out, exts[:lo]...) + out = append(out, mid...) + out = append(out, exts[hi:]...) + return out +} + // SetSymlink records the target for a symlink inode and sets its size. func (idx *Index) SetSymlink(ino uint64, target string, now int64) error { idx.mu.Lock() diff --git a/internal/index/persist.go b/internal/index/persist.go index cae3385..527aedc 100644 --- a/internal/index/persist.go +++ b/internal/index/persist.go @@ -12,6 +12,16 @@ import ( const snapshotFile = "index.cbor" const chunkIDPrefix = "chunk-" +// The library defaults (131072) cap arrays and maps; a real index exceeds them +// (e.g. a checkout with >131k files, or one file with >131k extents). +var snapshotDecMode = func() cbor.DecMode { + dm, err := cbor.DecOptions{MaxArrayElements: 1 << 30, MaxMapPairs: 1 << 30}.DecMode() + if err != nil { + panic(err) + } + return dm +}() + // --- Private CBOR wire types --- // // Integer map keys (keyasint) eliminate per-record field-name overhead. @@ -185,7 +195,7 @@ func Load(dir string, blockSize int32) (*Index, error) { return nil, err // caller checks os.IsNotExist } var ws cborSnapshot - if err := cbor.Unmarshal(data, &ws); err != nil { + if err := snapshotDecMode.Unmarshal(data, &ws); err != nil { return nil, fmt.Errorf("unmarshal snapshot: %w", err) } return FromSnapshot(fromWireSnapshot(ws), blockSize), nil @@ -208,7 +218,7 @@ func Marshal(idx *Index) ([]byte, error) { // Unmarshal restores an Index from the CBOR bytes produced by Marshal. func Unmarshal(data []byte, blockSize int32) (*Index, error) { var ws cborSnapshot - if err := cbor.Unmarshal(data, &ws); err != nil { + if err := snapshotDecMode.Unmarshal(data, &ws); err != nil { return nil, fmt.Errorf("unmarshal snapshot: %w", err) } return FromSnapshot(fromWireSnapshot(ws), blockSize), nil