mergerfs/tests/TEST_readdir_cor_cookie_replay

201 lines
5.8 KiB
Text
Raw Normal View History

fix: keep readdir listings stable under fill errors - func.readdir=cor appended entries in whichever order branch workers finished. Directory offsets are positions in that list, so a reader reopening an unchanged directory and seeking to a previously issued cookie (NFS does this) could see a duplicate and miss a later entry. Read branches concurrently into their own buffers, then merge and deduplicate them in configured branch order. The merge mutex is gone. - Growing a dirents buffer overwrote the only pointer with realloc's result while recording the new capacity, so an allocation failure leaked the buffer and the next fill wrote through NULL. Grow both vectors without changing pointer, length or capacity until the allocation succeeds, and return ENOMEM. - seq and cosr ignored that failure and served a listing with entries missing. Every policy now returns the error, and libfuse resets the handle's buffer whenever a fill fails, so a later request at a nonzero offset re-enumerates instead of serving a partial or stale listing as success. cosr closes the directories its workers opened when it gives up early. - Document the fill-error contract, which doesn't promise that every branch was read: seq and cosr can treat a branch read error as the end of the directory. Document cor's memory use, and refer to func.getattr, not fuse.getattr. - TEST_readdir_cor_cookie_replay compares cor listings, offsets and inodes with seq and replays cookies on fresh handles. TEST_dirents_allocation injects allocation failures into the dirents code. TEST_readdir_cor_enomem fails one allocation in a mounted daemon for cor and seq and checks the same handle then serves the exact suffix. Performance: cor copies each entry twice and merges serially after the parallel reads. Listing 100,000 entries over 4 tmpfs branches took the same time before and after (81-83 ms per listing for cor:4 and seq). Peak daemon memory for cor:4 dropped from 27.4 MB to 18.7 MB.
2026-05-13 10:58:01 -05:00
#!/usr/bin/env python3
import ctypes
import os
import sys
from posix_parity import fail
from posix_parity import mergerfs_mount
from posix_parity import mount_mergerfs
from posix_parity import unmount_mergerfs
if not sys.platform.startswith("linux"):
print("This Linux dirent ABI test is unsupported on " + sys.platform)
raise SystemExit(77)
class Dirent(ctypes.Structure):
_fields_ = [
("d_ino", ctypes.c_ulong),
("d_off", ctypes.c_long),
("d_reclen", ctypes.c_ushort),
("d_type", ctypes.c_ubyte),
("d_name", ctypes.c_char * 256),
]
libc = ctypes.CDLL(None, use_errno=True)
libc.opendir.argtypes = [ctypes.c_char_p]
libc.opendir.restype = ctypes.c_void_p
libc.readdir.argtypes = [ctypes.c_void_p]
libc.readdir.restype = ctypes.POINTER(Dirent)
libc.seekdir.argtypes = [ctypes.c_void_p, ctypes.c_long]
libc.seekdir.restype = None
libc.closedir.argtypes = [ctypes.c_void_p]
libc.closedir.restype = ctypes.c_int
def opendir_or_raise(path):
ctypes.set_errno(0)
dp = libc.opendir(os.fsencode(path))
if not dp:
err = ctypes.get_errno()
raise OSError(err, os.strerror(err), path)
return dp
def snapshot(ent):
name = bytes(ent.d_name).split(b"\0", 1)[0]
return (
os.fsdecode(name),
int(ent.d_type),
int(ent.d_ino),
int(ent.d_off),
)
def read_one(dp):
ctypes.set_errno(0)
entp = libc.readdir(dp)
if entp:
return snapshot(entp.contents)
err = ctypes.get_errno()
if err:
raise OSError(err, os.strerror(err))
return None
def read_all(dp):
entries = []
while True:
entry = read_one(dp)
if entry is None:
return entries
entries.append(entry)
def close_dir(dp):
if libc.closedir(dp) != 0:
err = ctypes.get_errno()
raise OSError(err, os.strerror(err))
def read_listing(path):
dp = opendir_or_raise(path)
try:
return read_all(dp)
finally:
close_dir(dp)
def replay_cookie(path, prefix_length):
dp = opendir_or_raise(path)
try:
prefix = [read_one(dp) for _ in range(prefix_length)]
if any(entry is None for entry in prefix):
raise RuntimeError("directory ended before the requested replay prefix")
cookie = prefix[-1][3]
finally:
close_dir(dp)
dp = opendir_or_raise(path)
try:
ctypes.set_errno(0)
libc.seekdir(dp, cookie)
err = ctypes.get_errno()
if err:
raise OSError(err, os.strerror(err))
suffix = read_all(dp)
finally:
close_dir(dp)
return prefix, cookie, suffix
def first_difference(actual, expected):
for index, (got, want) in enumerate(zip(actual, expected)):
if got != want:
return f"entry {index}: got {got!r}, expected {want!r}"
if len(actual) != len(expected):
return f"entry count {len(actual)}, expected {len(expected)}"
return "unknown difference"
def make_name(prefix, index):
return f"{prefix}_{index:05d}_" + "x" * 64
def populate(branches):
shared = [make_name("shared", index) for index in range(16)]
counts = [4000, 7, 5, 3]
for branch_index, (branch, count) in enumerate(zip(branches, counts)):
dirpath = os.path.join(branch, "dir")
os.mkdir(dirpath)
names = shared + [make_name(f"branch{branch_index}", index) for index in range(count)]
for name in names:
with open(os.path.join(dirpath, name), "wb") as stream:
stream.write(f"branch{branch_index}\n".encode("ascii"))
return shared
def main():
options = "defaults,use_ino,category.create=mfs,cache.readdir=false"
try:
with mergerfs_mount(
num_branches=4,
options=options + ",func.readdir=seq",
) as (mount, branches):
shared = populate(branches)
dirpath = os.path.join(mount, "dir")
expected = read_listing(dirpath)
expected_unique = 2 + 16 + 4000 + 7 + 5 + 3
if len(expected) != expected_unique:
return fail(
f"seq fixture has {len(expected)} entries, expected {expected_unique}"
)
if len({entry[0] for entry in expected}) != len(expected):
return fail("seq fixture contains duplicate names")
with open(os.path.join(dirpath, shared[0]), "rb") as stream:
if stream.read() != b"branch0\n":
return fail("duplicate name does not resolve to the first branch")
unmount_mergerfs(mount)
mount_mergerfs(branches, mount, options + ",func.readdir=cor:4")
for attempt in range(4):
actual = read_listing(dirpath)
if actual != expected:
return fail(
f"cor listing {attempt} differs from seq: "
+ first_difference(actual, expected)
)
split_points = [1, 2, 3, 17, 64, 255, 511, 1024, 1536, 2048, 3072]
split_points += [len(expected) - 1, len(expected)]
for prefix_length in split_points:
prefix, cookie, suffix = replay_cookie(dirpath, prefix_length)
resumed = prefix + suffix
if resumed != expected:
return fail(
f"fresh-handle replay at cookie {cookie} after "
f"{prefix_length} entries differs: "
+ first_difference(resumed, expected)
)
return 0
except RuntimeError as exc:
if "binary not found" in str(exc) or "fusermount" in str(exc):
print(str(exc), end="")
return 77
return fail(str(exc))
except OSError as exc:
return fail(f"readdir COR cookie replay failed: {exc}")
if __name__ == "__main__":
raise SystemExit(main())