Files
seaweedfs/weed/filer/filer_hardlink_list_test.go
T
Chris LuandClaude Opus 5.5 d49876a7aa filer: every filer store reads KV keys in batches (#13119)
* filer: read KV keys a few at a time for a store without batch reads

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

* abstract_sql: read KV keys with one query

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

* redis: read KV keys in one pipeline

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

* etcd: read KV keys in read-only transactions

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

* mongodb: read KV keys with one query

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

* cassandra: read KV keys concurrently

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

* hbase: read KV keys concurrently

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

* elastic: read KV keys concurrently

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

* arangodb: read KV keys with one request

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

* foundationdb: read KV keys in one transaction

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

* ydb: read KV keys with one query

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

* tarantool: send KV reads before waiting for any

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

* filer: every filer store reads KV keys in batches

KvBatchGet moves from the optional KvBatchReader onto FilerStore. A listing
now reads the hard link records of its waiting entries together from any
store, a path-specific one included.

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

* tikv: count only the record reads of a listing in its test

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

* filer: return every batched key that pads to the same stored row

SQL, MongoDB and YDB pad a short KV key with zero bytes, so "short" and
"short\x00" read the same row. KvBatchGet kept only the last such key.

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

* filer: read keys in a plain loop when KvGetEach runs one at a time

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 23:10:49 -08:00

467 lines
18 KiB
Go

package filer
import (
"context"
"errors"
"fmt"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/stretchr/testify/require"
)
// What a listing reads the store for besides the listing itself: the shared
// record of every hard-linked entry. The store is asked for the records of the
// waiting entries together; the caller of the listing must not be able to tell
// that from a listing that reads each record as its entry arrives, except by
// how long it takes.
// rowListingStore hands over an entry of its own for each name it lists, as a
// store that decodes rows does. It can fail a listing part of the way.
type rowListingStore struct {
*stubFilerStore
failAfter int // fail the listing once it has handed over this many entries
listErr error // with this
// A store may take one more step after its caller ended the listing, as
// TiKV moves its iterator on before it looks at the answer. stopErr is
// that step failing behind the entry numbered failStopAt.
failStopAt int
stopErr error
}
func (s *rowListingStore) list(listed func(each ListEachEntryFunc) (string, error), eachEntryFunc ListEachEntryFunc) (string, error) {
handed, endedAt := 0, 0
lastFileName, err := listed(func(entry *Entry) (bool, error) {
if s.listErr != nil && handed == s.failAfter {
return false, s.listErr
}
handed++
more, err := eachEntryFunc(entry.ShallowClone())
if err == nil && !more {
endedAt = handed
}
return more, err
})
if err == nil && s.stopErr != nil && endedAt == s.failStopAt {
return lastFileName, s.stopErr
}
return lastFileName, err
}
func (s *rowListingStore) ListDirectoryEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc ListEachEntryFunc) (string, error) {
return s.list(func(each ListEachEntryFunc) (string, error) {
return s.stubFilerStore.ListDirectoryEntries(ctx, dirPath, startFileName, includeStartFile, limit, each)
}, eachEntryFunc)
}
func (s *rowListingStore) ListDirectoryPrefixedEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc ListEachEntryFunc) (string, error) {
return s.list(func(each ListEachEntryFunc) (string, error) {
return s.stubFilerStore.ListDirectoryPrefixedEntries(ctx, dirPath, startFileName, includeStartFile, limit, prefix, each)
}, eachEntryFunc)
}
// batchReadingStore also records the batches it is asked for.
type batchReadingStore struct {
*rowListingStore
batches [][]string // the keys of each batch it was asked for
batchErr error
}
func (s *batchReadingStore) KvBatchGet(_ context.Context, keys [][]byte) (map[string][]byte, error) {
s.mu.Lock()
defer s.mu.Unlock()
batch := make([]string, 0, len(keys))
for _, key := range keys {
batch = append(batch, string(key))
}
s.batches = append(s.batches, batch)
if s.batchErr != nil {
return nil, s.batchErr
}
values := make(map[string][]byte)
for _, key := range keys {
if value, found := s.kv[string(key)]; found {
values[string(key)] = append([]byte(nil), value...)
}
}
return values, nil
}
// linkListingStores returns the same directory in two stores, one to list with
// oneAtATime and one that records its batches, each with a count of the single
// reads it serves.
func linkListingStores(t *testing.T, fill func(store *stubFilerStore)) (oneByOne *rowListingStore, oneReads *int, batched *batchReadingStore, batchedReads *int) {
t.Helper()
build := func() (*rowListingStore, *int) {
stub := newStubFilerStore()
fill(stub)
reads := new(int)
stub.kvGetHook = func([]byte) { *reads++ }
return &rowListingStore{stubFilerStore: stub}, reads
}
oneByOne, oneReads = build()
rows, batchedReads := build()
return oneByOne, oneReads, &batchReadingStore{rowListingStore: rows}, batchedReads
}
// linkedName stores name as one more name of a hard-linked file. The row keeps
// what the name was written with; the record, which a listing must answer
// with, has moved on: size bytes and count names.
func linkedName(t *testing.T, store *stubFilerStore, id HardLinkId, name string, size uint64, count int32) {
t.Helper()
store.entries[name] = &Entry{
FullPath: util.FullPath(name),
Attr: Attr{Mode: 0o644, Mtime: time.Unix(1700000000, 0)},
HardLinkId: id,
HardLinkCounter: 1,
}
if size == 0 {
return // a name whose record is gone
}
store.kv[string(id)] = encodeLinkRecord(t, &Entry{
FullPath: util.FullPath(name),
Attr: Attr{Mode: 0o600, Mtime: time.Unix(1700000500, 0), FileSize: size},
HardLinkId: id,
HardLinkCounter: count,
Chunks: []*filer_pb.FileChunk{{FileId: fmt.Sprintf("7,%02x", size), Size: size}},
})
}
// listed is what a caller of a listing can see of an entry.
type listed struct {
Name string
Size uint64
Mode uint32
Links int32
Chunks string
}
func see(entry *Entry) listed {
return listed{
Name: entry.Name(),
Size: entry.FileSize,
Mode: uint32(entry.Mode),
Links: entry.HardLinkCounter,
Chunks: strings.Join(filer_pb.FileIdsString(entry.GetChunks()), " "),
}
}
type lister func(ctx context.Context, dir util.FullPath, startFileName string, limit int64, each ListEachEntryFunc) (string, error)
// throughWrapper lists as the filer does.
func throughWrapper(store FilerStore) lister {
return func(ctx context.Context, dir util.FullPath, startFileName string, limit int64, each ListEachEntryFunc) (string, error) {
return NewFilerStoreWrapper(store).ListDirectoryEntries(ctx, dir, startFileName, false, limit, each)
}
}
// oneAtATime lists reading each record as its entry arrives, and hands the
// entry on before the store lists the next one.
func oneAtATime(store FilerStore) lister {
fsw := NewFilerStoreWrapper(store)
return func(ctx context.Context, dir util.FullPath, startFileName string, limit int64, each ListEachEntryFunc) (string, error) {
return store.ListDirectoryEntries(ctx, dir, startFileName, false, limit, func(entry *Entry) (bool, error) {
fsw.maybeReadHardLink(ctx, entry)
filer_pb.AfterEntryDeserialization(entry.GetChunks())
return each(entry)
})
}
}
func listAll(t *testing.T, list lister, dir string, startFileName string, limit int64) (entries []listed, lastFileName string) {
t.Helper()
lastFileName, err := list(context.Background(), util.FullPath(dir), startFileName, limit, func(entry *Entry) (bool, error) {
entries = append(entries, see(entry))
return true, nil
})
require.NoError(t, err)
return entries, lastFileName
}
func mixedDirectory(t *testing.T) func(store *stubFilerStore) {
x, y, gone := HardLinkId("link-x-0123456789"), HardLinkId("link-y-0123456789"), HardLinkId("link-gone-0123456")
return func(store *stubFilerStore) {
store.entries["/d/a"] = fileAt("/d/a")
linkedName(t, store, x, "/d/b", 11, 2)
store.entries["/d/c"] = fileAt("/d/c")
linkedName(t, store, y, "/d/d", 22, 3)
linkedName(t, store, x, "/d/e", 11, 2)
linkedName(t, store, gone, "/d/f", 0, 0)
store.entries["/d/g"] = fileAt("/d/g")
linkedName(t, store, y, "/elsewhere/y", 22, 3)
}
}
func TestListingReadsHardLinkRecordsTogether(t *testing.T) {
oneByOne, oneReads, batched, batchedReads := linkListingStores(t, mixedDirectory(t))
want, wantLast := listAll(t, oneAtATime(oneByOne), "/d", "", 100)
got, gotLast := listAll(t, throughWrapper(batched), "/d", "", 100)
require.Equal(t, []string{"a", "b", "c", "d", "e", "f", "g"}, namesOf(want))
require.Equal(t, listed{Name: "b", Size: 11, Mode: 0o600, Links: 2, Chunks: "7,0b"}, want[1], "a linked name lists what its record holds")
require.Equal(t, listed{Name: "f", Mode: 0o644, Links: 1}, want[5], "a name whose record is gone lists its row")
require.Equal(t, want, got, "the entries of a listing do not depend on how their records were read")
require.Equal(t, wantLast, gotLast)
require.Equal(t, 4, *oneReads, "one read for each hard-linked name")
require.Zero(t, *batchedReads)
require.Equal(t, [][]string{{"link-x-0123456789", "link-y-0123456789", "link-gone-0123456"}}, batched.batches,
"one read for all of them, each record asked for once")
}
func TestListingWithAPrefixReadsHardLinkRecordsTogether(t *testing.T) {
_, _, batched, batchedReads := linkListingStores(t, func(store *stubFilerStore) {
for i := 0; i < 6; i++ {
linkedName(t, store, HardLinkId(fmt.Sprintf("link-%d-0123456789", i)), fmt.Sprintf("/d/p%d", i), uint64(10+i), 2)
store.entries[fmt.Sprintf("/d/q%d", i)] = fileAt(fmt.Sprintf("/d/q%d", i))
}
})
var got []listed
lastFileName, err := NewFilerStoreWrapper(batched).ListDirectoryPrefixedEntries(context.Background(), "/d", "", false, 100, "p", func(entry *Entry) (bool, error) {
got = append(got, see(entry))
return true, nil
})
require.NoError(t, err)
require.Equal(t, "p5", lastFileName)
require.Equal(t, []string{"p0", "p1", "p2", "p3", "p4", "p5"}, namesOf(got))
require.Equal(t, uint64(13), got[3].Size)
require.Zero(t, *batchedReads)
require.Len(t, batched.batches, 1)
}
// More names than wait at once: the entries still come in the store's order,
// page after page, each once.
func TestListingKeepsItsOrderAcrossBatches(t *testing.T) {
const names = 2*hardLinkBatchSize + 300
oneByOne, _, batched, batchedReads := linkListingStores(t, func(store *stubFilerStore) {
for i := 0; i < names; i++ {
name := fmt.Sprintf("/d/n%05d", i)
if i%3 == 1 {
store.entries[name] = fileAt(name)
continue
}
linkedName(t, store, HardLinkId(fmt.Sprintf("link-%05d-012345", i)), name, uint64(1+i), 2)
}
})
want, _ := listAll(t, oneAtATime(oneByOne), "/d", "", names+1)
got, lastFileName := listAll(t, throughWrapper(batched), "/d", "", names+1)
require.Len(t, got, names)
require.Equal(t, want, got)
require.Equal(t, fmt.Sprintf("n%05d", names-1), lastFileName)
require.Zero(t, *batchedReads)
// the first name is linked, so every hardLinkBatchSize entries wait together
require.Len(t, batched.batches, (names+hardLinkBatchSize-1)/hardLinkBatchSize)
for _, batch := range batched.batches {
require.LessOrEqual(t, len(batch), hardLinkBatchSize)
}
// read in pages, as ListEntries reads a directory
const pageSize = hardLinkBatchSize + 100
var paged []listed
for start := ""; ; {
page, last := listAll(t, throughWrapper(batched), "/d", start, pageSize)
paged = append(paged, page...)
if len(page) < pageSize {
break
}
start = last
}
require.Equal(t, want, paged)
}
// The caller ends a listing at an entry whose record was read with those of
// the entries behind it. The listing ends there for the caller: it gets none
// of the entries behind it, and the listing that continues from the name it
// is given back has every one of them.
func TestListingEndedByItsCallerContinuesFromWhereItEnded(t *testing.T) {
oneByOne, _, batched, _ := linkListingStores(t, mixedDirectory(t))
want, _ := listAll(t, oneAtATime(oneByOne), "/d", "", 100)
for stopAt := 1; stopAt <= len(want); stopAt++ {
var got []listed
lastFileName, err := NewFilerStoreWrapper(batched).ListDirectoryEntries(context.Background(), "/d", "", false, 100, func(entry *Entry) (bool, error) {
got = append(got, see(entry))
return len(got) < stopAt, nil
})
require.NoError(t, err)
require.Equal(t, want[:stopAt], got, "ended at entry %d", stopAt)
require.Equal(t, want[stopAt-1].Name, lastFileName, "ended at entry %d", stopAt)
rest, _ := listAll(t, throughWrapper(batched), "/d", lastFileName, 100)
require.Equal(t, want[stopAt:], append([]listed{}, rest...), "continued after entry %d", stopAt)
}
}
// A caller's error ends the listing with that error, and with nothing handed
// on after it.
func TestListingReturnsItsCallersError(t *testing.T) {
_, _, batched, _ := linkListingStores(t, mixedDirectory(t))
refused := errors.New("refused")
for failAt := 1; failAt <= 7; failAt++ {
handed := 0
_, err := NewFilerStoreWrapper(batched).ListDirectoryEntries(context.Background(), "/d", "", false, 100, func(entry *Entry) (bool, error) {
handed++
if handed == failAt {
return false, refused
}
return true, nil
})
require.ErrorIs(t, err, refused, "failed at entry %d", failAt)
require.Equal(t, failAt, handed, "failed at entry %d", failAt)
}
}
// The records are then read one at a time.
func TestListingReadsRecordsOneByOneWhenTheBatchFails(t *testing.T) {
oneByOne, _, batched, batchedReads := linkListingStores(t, mixedDirectory(t))
batched.batchErr = errors.New("region unavailable")
want, _ := listAll(t, oneAtATime(oneByOne), "/d", "", 100)
got, _ := listAll(t, throughWrapper(batched), "/d", "", 100)
require.Equal(t, want, got)
require.Equal(t, 4, *batchedReads)
}
// A store that fails its listing part of the way has handed some entries over
// already. They reach the caller before the error does, as they do when each
// is handed on as it arrives.
func TestListingHandsOnWhatTheStoreListedBeforeItFailed(t *testing.T) {
oneByOne, _, batched, _ := linkListingStores(t, mixedDirectory(t))
broken := errors.New("iterator closed")
want, _ := listAll(t, oneAtATime(oneByOne), "/d", "", 100)
for failAfter := 0; failAfter <= 6; failAfter++ {
batched.failAfter, batched.listErr = failAfter, broken
var got []listed
_, err := NewFilerStoreWrapper(batched).ListDirectoryEntries(context.Background(), "/d", "", false, 100, func(entry *Entry) (bool, error) {
got = append(got, see(entry))
return true, nil
})
require.ErrorIs(t, err, broken, "failed after %d entries", failAfter)
require.Equal(t, want[:failAfter], append([]listed{}, got...), "failed after %d entries", failAfter)
}
}
// listUntil lists dir and ends the listing at its entry numbered stopAt.
func listUntil(list lister, dir string, stopAt int) (entries []listed, lastFileName string, err error) {
lastFileName, err = list(context.Background(), util.FullPath(dir), "", 100000, func(entry *Entry) (bool, error) {
entries = append(entries, see(entry))
return len(entries) < stopAt, nil
})
return entries, lastFileName, err
}
// The store goes on past the entry its caller ends the listing at, to the
// entries that wait with it, and may fail there. Handed each entry as it
// arrived, the caller would have stopped the store before that: the listing
// ends where the caller ended it, and its own failure is the one it gets.
func TestListingEndedByItsCallerIsNotFailedByWhatTheStoreMetBehind(t *testing.T) {
oneByOne, _, batched, _ := linkListingStores(t, mixedDirectory(t))
want, _ := listAll(t, oneAtATime(oneByOne), "/d", "", 100)
broken := errors.New("iterator closed")
// the store hands over a to e and then fails; b to e wait for their records
oneByOne.failAfter, oneByOne.listErr = 5, broken
batched.failAfter, batched.listErr = 5, broken
for stopAt := 1; stopAt <= 5; stopAt++ {
_, _, err := listUntil(oneAtATime(oneByOne), "/d", stopAt)
require.NoError(t, err, "one at a time, ended at entry %d", stopAt)
got, lastFileName, err := listUntil(throughWrapper(batched), "/d", stopAt)
require.NoError(t, err, "ended at entry %d", stopAt)
require.Equal(t, want[:stopAt], got, "ended at entry %d", stopAt)
require.Equal(t, want[stopAt-1].Name, lastFileName, "ended at entry %d", stopAt)
}
refused := errors.New("refused")
for failAt := 2; failAt <= 5; failAt++ {
handed := 0
_, err := NewFilerStoreWrapper(batched).ListDirectoryEntries(context.Background(), "/d", "", false, 100, func(entry *Entry) (bool, error) {
handed++
if handed == failAt {
return false, refused
}
return true, nil
})
require.ErrorIs(t, err, refused, "failed at entry %d", failAt)
require.NotErrorIs(t, err, broken, "failed at entry %d", failAt)
}
}
// The same for the step a store takes after its caller has ended the listing.
// It fails behind the last entry that waits: a caller that ended the listing
// at an earlier one had stopped the store before, and a caller that ended it
// at that last one gets the failure, as it does from a store that hands each
// entry on as it arrives.
func TestListingEndedByItsCallerIsNotFailedByTheStoresStepBehind(t *testing.T) {
const names = hardLinkBatchSize + 50
oneByOne, _, batched, _ := linkListingStores(t, func(store *stubFilerStore) {
for i := 0; i < names; i++ {
linkedName(t, store, HardLinkId(fmt.Sprintf("link-%05d-012345", i)), fmt.Sprintf("/d/n%05d", i), uint64(1+i), 2)
}
})
broken := errors.New("iterator closed")
oneByOne.failStopAt, oneByOne.stopErr = hardLinkBatchSize, broken
batched.failStopAt, batched.stopErr = hardLinkBatchSize, broken
for _, stopAt := range []int{1, 10, hardLinkBatchSize - 1, hardLinkBatchSize, hardLinkBatchSize + 1, names} {
want, wantLast, wantErr := listUntil(oneAtATime(oneByOne), "/d", stopAt)
got, gotLast, gotErr := listUntil(throughWrapper(batched), "/d", stopAt)
require.Equal(t, stopAt == hardLinkBatchSize, wantErr != nil, "one at a time, ended at entry %d", stopAt)
require.Equal(t, wantErr, gotErr, "ended at entry %d", stopAt)
require.Equal(t, want, got, "ended at entry %d", stopAt)
if wantErr == nil {
require.Equal(t, wantLast, gotLast, "ended at entry %d", stopAt)
}
}
}
// The records are in the default store, and a directory another store lists
// reads them from there together too.
func TestListingOfAPathSpecificStoreReadsRecordsTogether(t *testing.T) {
_, _, batched, batchedReads := linkListingStores(t, mixedDirectory(t))
other := &rowListingStore{stubFilerStore: newStubFilerStore()}
// the store keeps its paths without the prefix it is mounted at
for _, name := range []string{"/d/m", "/d/n"} {
other.entries[name] = &Entry{
FullPath: util.FullPath(name),
Attr: Attr{Mode: 0o644},
HardLinkId: HardLinkId("link-x-0123456789"),
}
}
wrapper := NewFilerStoreWrapper(batched)
wrapper.AddPathSpecificStore("/other/", "other", other)
var got []listed
_, err := wrapper.ListDirectoryEntries(context.Background(), "/other/d", "", false, 100, func(entry *Entry) (bool, error) {
got = append(got, see(entry))
return true, nil
})
require.NoError(t, err)
linked := listed{Size: 11, Mode: 0o600, Links: 2, Chunks: "7,0b"}
m, n := linked, linked
m.Name, n.Name = "m", "n"
require.Equal(t, []listed{m, n}, got)
require.Zero(t, *batchedReads)
require.Equal(t, [][]string{{"link-x-0123456789"}}, batched.batches)
}
func namesOf(entries []listed) (names []string) {
for _, entry := range entries {
names = append(names, entry.Name)
}
return names
}