mergerfs/tests/TEST_readdir_cor_enomem
Antonio SJ Musumeci eea1c1bc09 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-11-29 23:11:07 -05:00

183 lines
6.8 KiB
Python
Executable file

#!/usr/bin/env python3
"""Mounted ENOMEM regression for func.readdir=cor and func.readdir=seq.
The dirents-level failures are covered by TEST_dirents_allocation; this
test drives the real daemon, once per policy. A fill that fails partway
must be reported as ENOMEM and leave no partial or stale listing cached,
so the next read on the SAME handle re-enumerates and serves the exact
reference suffix from the requested cookie. Helpers come from the
tracked cookie-replay regression via runpy. Only the daemon gets an
LD_PRELOAD failing one realloc: old pointer nonnull (not an initial
reservation), new size 64KiB (the second 32KiB data quantum of the
handle's dirents buffer), on the 'fuse.read' thread, and only while a
marker file exists, armed after a clean reference listing and consumed
on fire so the recovery fill succeeds. seq is targeted by the same
injector because read-thread-count=1 with process-thread-count=-1 runs
every request synchronously on 'fuse.read', where seq performs its
whole fill and grows the handle buffer in the same 32KiB quanta (its
branch scratch buffer is posix_memalign'ed, so it cannot steal the
realloc); cor merges into the same buffer there, while its branch
scratch buffers grow on 'readdir.cor' workers. Fails (not skips) if the
injector never fires or the errno is not ENOMEM.
Exit codes: 0 pass, 1 fail, 77 skip.
"""
import errno
import os
import runpy
import shutil
import subprocess
import sys
import tempfile
SKIP = 77
HERE = os.path.dirname(os.path.realpath(__file__))
_cookie = runpy.run_path(os.path.join(HERE, "TEST_readdir_cor_cookie_replay"))
(close_dir, fail, first_difference, libc, mergerfs_mount,
opendir_or_raise, populate, read_all, read_one, read_listing) = (
_cookie[name] for name in ("close_dir", "fail", "first_difference",
"libc", "mergerfs_mount", "opendir_or_raise",
"populate", "read_all", "read_one",
"read_listing"))
# Synchronous read thread: both policies grow the handle's shared
# dirents buffer there. seq fills it directly on the request thread;
# cor merges into it there, not on the readdir.cor branch workers.
OPTIONS_TEMPLATE = ("defaults,use_ino,category.create=mfs,cache.readdir=false,"
"read-thread-count=1,process-thread-count=-1,"
"func.readdir={policy}")
PRELOAD_C = r"""
#define _GNU_SOURCE
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
extern void *__libc_realloc(void *,size_t);
/* The open directory handle's dirents buffer grows in 32KiB quanta on
the synchronous read thread; its 64KiB growth carries a non-NULL old
pointer, unlike the opendir-time init reservation. Both policies
grow it there: seq fills it directly, cor merges into it. */
#define MERGED_GROWTH ((size_t)(64 * 1024))
void *
realloc(void *ptr_,size_t size_)
{
if((ptr_ != NULL) && (size_ == MERGED_GROWTH))
{
const char *marker = getenv("MERGERFS_TEST_COR_ENOMEM_MARKER");
char name[16];
if((marker != NULL) &&
(pthread_getname_np(pthread_self(),name,sizeof(name)) == 0) &&
(strcmp(name,"fuse.read") == 0) &&
(access(marker,F_OK) == 0))
{
unlink(marker);
return NULL;
}
}
return __libc_realloc(ptr_,size_);
}
"""
def main():
if not sys.platform.startswith("linux"):
print("Linux-only cor ENOMEM regression; skipping on " + sys.platform)
return SKIP
if not hasattr(libc, "__libc_realloc"):
print("glibc is required for the daemon allocator hook")
return SKIP
compiler = shutil.which("cc") or shutil.which("gcc")
if compiler is None:
print("no C compiler for the preload; skipping")
return SKIP
tmp_parent = os.path.join(HERE, ".test_tmp")
os.makedirs(tmp_parent, exist_ok=True)
tmpdir = tempfile.mkdtemp(prefix="mergerfs_cor_enomem_", dir=tmp_parent)
preload = os.path.join(tmpdir, "cor_enomem_preload.so")
marker = os.path.join(tmpdir, "cor_enomem_armed")
preload_env = os.environ.get("LD_PRELOAD")
try:
src = os.path.join(tmpdir, "cor_enomem_preload.c")
with open(src, "w", encoding="ascii") as stream:
stream.write(PRELOAD_C)
built = subprocess.run(
[compiler, "-O2", "-fPIC", "-shared", src, "-o", preload],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
if built.returncode != 0:
return fail("preload compilation failed:\n" + built.stdout)
os.environ["LD_PRELOAD"] = preload
os.environ["MERGERFS_TEST_COR_ENOMEM_MARKER"] = marker
try:
for policy in ("cor:4", "seq"):
rv = injected_run(marker, policy)
if rv != 0:
return rv
return 0
except RuntimeError as exc:
if ("binary not found" in str(exc)) or ("fusermount" in str(exc)):
print(str(exc), end="")
return SKIP
return fail(str(exc))
except OSError as exc:
return fail("cor ENOMEM regression failed: %s" % exc)
finally:
if preload_env is None:
os.environ.pop("LD_PRELOAD", None)
else:
os.environ["LD_PRELOAD"] = preload_env
os.environ.pop("MERGERFS_TEST_COR_ENOMEM_MARKER", None)
shutil.rmtree(tmpdir, ignore_errors=True)
def injected_run(marker, policy):
options = OPTIONS_TEMPLATE.format(policy=policy)
with mergerfs_mount(num_branches=4, options=options) as (mount, branches):
dirpath = os.path.join(mount, "dir")
populate(branches)
truth = read_listing(dirpath)
if len(truth) < 4:
return fail("reference listing has only %d entries" % len(truth))
if len({entry[0] for entry in truth}) != len(truth):
return fail("reference listing contains duplicate names")
mid = len(truth) // 2
cookie = truth[mid][3]
expected_suffix = truth[(mid + 1):]
with open(marker, "w", encoding="ascii"):
pass
dp = opendir_or_raise(dirpath)
try:
libc.seekdir(dp, cookie)
try:
first = read_one(dp)
except OSError as exc:
if exc.errno != errno.ENOMEM:
return fail("injected failure reported errno %s, "
"expected ENOMEM" % exc.errno)
else:
return fail("injector never fired: the seeked readdir "
"returned %r" % (first,))
suffix = read_all(dp)
finally:
close_dir(dp)
if suffix != expected_suffix:
return fail("after ENOMEM the same handle served a wrong "
"suffix: " + first_difference(suffix, expected_suffix))
return 0
if __name__ == "__main__":
raise SystemExit(main())