Skip to content

Opt-in direct-I/O reader for HDF5 inputs (--io, ADATA_IO) - #150

Merged
Claptar merged 6 commits into
direct-iofrom
feat/direct-io
Dec 4, 2026
Merged

Claptar merged 6 commits into
direct-iofrom
feat/direct-io

Conversation

@Claptar

@Claptar Claptar commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Why

The December Lustre probe (benchmarks/lustre/, Performance on cluster storage) found every library — h5py, zarr over HDF5 chunks, DuckDB h5db, obstore — held to 260-500 MB/s on an uncompressed h5ad, because each fetches one 164-415 KB chunk at a time through the page cache. Plain byte ranges of the same file, read with O_DIRECT in 16 MiB requests with 16-32 in flight from Python threads, reached 4-5 GB/s at a third of the CPU on every node. This PR adds that reader.

Opt-in. --io h5py stays the default, and nothing changes unless --io direct|auto or ADATA_IO asks. auto becomes the default on Lustre and NFS only after farm measurements of this build (a later step, another session).

Design

storage/fsinfo.py

  • filesystem(path): the fstype of the longest mount-point prefix of the path's realpath, from /proc/self/mountinfo.
    • Octal escapes (\040) are decoded.
    • On one mount point, the later line wins (NFS over an automounter's autofs).
    • A path that doesn't exist yet uses its nearest existing parent.
    • Off Linux it returns "unknown".
  • io_profile(fstype) → frozen IOProfile(direct, request_bytes, in_flight, buffer_bytes), or None for h5py.
    • lustre: O_DIRECT, 16 MiB requests, 16 in flight, 256 MiB buffer.
    • nfs/nfs4: buffered, 4 MiB, 32 in flight, 128 MiB (provisional).
    • Everything else: None.

storage/rawio.py

  • ChunkMap is built once per dataset, cached per open file. It holds runs of chunks that lie one after another in the file, 24 bytes each. Its size follows how the file was written, not the dataset's size: a dataset that was never written has no runs. All open files' maps share a 64 MiB MAP_BYTES cap, and a dataset whose map wouldn't fit goes to h5py. The map applies only to:

    • a file opened "r" with the sec2 driver and no userblock;
    • a dataset with no filters, kind b/i/u/f, no fields, and a file type equal to py_create(dtype). That last check excludes int24s, custom floats and non-bool enums, where HDF5 converts on read;
    • a contiguous (get_offset) or chunked (chunk_iter) layout, with 1 or 2 dimensions.

    Unallocated chunks read as the fill value. Anything else raises Unsupported, and h5py reads it.

  • Reading. DirectDataset.__getitem__ sends a step-1 row slice with every other axis whole (ds[a:b], ds[a:b, ...], ds[a:b, :], ds[:], ds[...], ds[()]) to read_rows, the one entry point. Everything else goes to super().

    • One run of the file: contiguous datasets, 1-D chunks in order, and 2-D full-width chunks are read straight into the result buffer, with no copy.
    • Everything else (tiles, chunks out of order, gaps): only the rows of each chunk that the block covers are read. They're read in segments of at most a request, grouped into pieces that read through gaps of up to 256 KiB, which covers the 2.6 KB B-tree nodes HDF5 puts between every ~58 chunks. Each segment is copied into place on the I/O thread as its piece arrives. No scratch buffer is larger than a request, whatever the chunk size.
    • Requests run on a persistent module-level pool with os.preadv, into 4 KiB-aligned buffers at 4 KiB-aligned offsets and lengths.
    • Short reads are retried. Reading past EOF is fine as long as the bytes that were asked for arrived.
    • If O_DIRECT is missing (macOS), refused at open, or refused on read (EINVAL), the same requests go through a buffered descriptor.
    • A worker's OSError reaches the caller, with the path and offset, once every request it started has finished.
    • The result matches h5py: dtype, byte order (= for native order, as h5py has it), shape and values. A result at an unaligned file offset is copied, so the array comes back aligned.
  • Read-ahead. After consecutive slices [a,b) then [b,c), the reader reads [c, c+(c-b)) in the background. The next call is served from it when it falls inside, and discarded otherwise. A closed file waits for its read-ahead to finish.

  • Budget. The reader's own memory is one budget for the process, ADATA_IO_BUFFER: reads in flight, pieces waiting for their copy, and read-ahead. It doesn't depend on the input's size.

    • Read-ahead takes room only when some is free, and at most half the budget.
    • No read takes more than half, and nothing waits while holding room that only it can give back, so reads cannot deadlock.
    • The block the caller asked for comes on top of the budget, as it does with h5py.

Descriptors. Buffered reads go through HDF5's own descriptor (preadv doesn't move its offset). The reader opens a descriptor only for O_DIRECT, and checks it against HDF5's for the same inode. concat holds up to 64 inputs, a quarter of macOS's limit.

Wiring (no call-site changes)

  • open_store(path, "r") returns a DirectFile (an h5py.File subclass) when the reader applies.
  • Its _get (behind __getitem__, get, values, items and visititems) wraps members as DirectGroup or DirectDataset. isinstance(x, h5py.Dataset) still holds.
  • New storage.open_hdf5(path) does the same for converter sources. The bulk-read opens in tenx, visium, xenium, cellbender, loom and hdf5 now use it. Sniffers keep plain h5py.File. mudata had none: it reads through open_store. tenx's _CheckedIndices and _Widened stay on h5py.
  • While the reader is on, subset's sparse block floor rises to max(TARGET_READ_BYTES, buffer_bytes // 2) (rawio.block_bytes).

Knobs

  • --io auto|direct|h5py: a shared _io_option with envvar="ADATA_IO", on subset, split, concat, convert, recast, every export and every import. view doesn't get it because it reads no data.
  • ADATA_IO_BUFFER (256M, 1G…, at least 1M) overrides buffer_bytes. Requests are capped at half of it.
  • When the reader is used, stderr gets one escaped status line: Reading HDF5 with adata's direct reader: O_DIRECT, 16 MiB requests, 16 in flight, 256 MiB buffer (filesystem: lustre).

Tests

  • tests/test_rawio.py (117 tests) compares against h5py byte for byte, with dtype and byte order:
    • contiguous and chunked layouts, 11 dtypes (big-endian, bool and float16 included), and chunks of 1,001 elements (never a whole number of pages);
    • edge chunks, unwritten chunks with a fill value (1-D and 2-D), and 2-D tiles with ragged edges, chunks wider or taller than the array;
    • chunks stored in reverse at odd addresses, data at an unaligned offset, zero-column datasets, and random slice boundaries;
    • every slice form that should reach the reader, and every one that shouldn't;
    • fallbacks to h5py: gzip, shuffle, lzf, fletcher32, vlen strings, fixed bytes, compound, complex, enum, 3-D, scalar, empty, unwritten, r+, a userblock;
    • failure paths: no O_DIRECT, O_DIRECT refused at open and on read, partial preadv returns, a file truncated under the reader, an OSError on a worker, an error while placing a chunk;
    • read-ahead hit, miss and partial hit, read-ahead held within half the buffer, close waiting for read-ahead, and the budget never above ADATA_IO_BUFFER;
    • from review: a (10**12,) fill-only dataset maps to no runs; a map over MAP_BYTES falls back to h5py; with a 1 MiB buffer, 2 MiB tiles and out-of-order chunks are read with no allocation above 512 KiB.
  • tests/test_fsinfo.py (30 tests): mountinfo with escapes, nested mounts, autofs with nfs4 over it, Lustre, prefix-not-folder, symlinks, paths that don't exist yet, off-Linux, an unreadable table, and the io_profile table.
  • tests/test_direct_io_cli.py (45 tests) runs each command with ADATA_IO=direct and with h5py on h5ad, Zarr v2 and Zarr v3 inputs: subset --obs/--var, split, convert to Zarr and to a 10x .h5, export sparse, export dataframe obs, concat, and recast csc/float64/dense. Outputs are identical between the two readers and equal to anndata's result. Blocks are kept small so matrices span several blocks and read-ahead is used. It also checks the status line, auto on ext4 vs Lustre, --io over ADATA_IO, and malformed values refused before anything is written.
  • tests/perf_counters.py hooks rawio.read_rows, counted as reads like h5py's, and rawio._read_request, giving direct_requests and direct_request_bytes.
  • Perf guards. The existing guards pin ADATA_IO=h5py. Three new ones check that:
    • each dataset's chunk map is built once, flat in n_obs;
    • a block's requests stay within ceil((block + 2 chunks) / request_bytes) for one run of the file, and pieces of whole chunks otherwise;
    • h5py never reads X/data, X/indices or a dense layer while the reader is on.

The request guard caught tiles being asked for one run at a time across HDF5's B-tree nodes; that's fixed by reading through small gaps.

Local results (macOS, so the buffered path):

  • pytest -m "not integration": 4247 passed, 11 skipped.
  • -m perf: 212 passed, on the final code (5db0476).
  • -m "not integration and not perf" --cov=adata --cov-fail-under=90: 4041 passed at 95.80% total, on the final code. rawio.py is at 97.44% and fsinfo.py at 96.88%.
  • The new tests also pass on this branch merged with main's 0.17.9: 805 passed, including 0.17.9's test_zarr_safety.py.

On Linux, test_on_linux_requests_go_past_the_page_cache asserts that requests really went through the O_DIRECT descriptor; it skips where O_DIRECT is missing or refused. It passed on every Linux leg of CI (ext4 runners). Docker wasn't available locally, and nothing has run on Lustre yet. macOS covers the buffered path, and the fallback tests force it on Linux too.

Notes

  • Base is direct-io, not dev. direct-io is its own branch, cut from main at 0.17.10. It keeps this work apart from the audit work landing in dev until a farm measurement shows the reader pays off. Nothing has timed it yet; the tests above show correctness and request patterns, not speed. Where it lands after that (dev once the audit settles, or a release of its own) is still to be decided.
  • The head branch is based on main at 0.17.8 (2077928). git merge-tree shows it merges cleanly with main at 0.17.10 and with dev.
  • docs/reference/cluster-storage.md and benchmarks/lustre/ are untouched. The changelog has no Unreleased section, so it's left to the release.
  • Not merged, and not to be merged until it has been measured.

🤖 Generated with Claude Code

Claptar and others added 2 commits December 4, 2026 11:57
The Lustre probe found every library held to 260-500 MB/s on an
uncompressed h5ad, fetching one chunk of a few hundred KB at a time
through the page cache, where plain O_DIRECT reads of the same file in
16 MiB requests, 16-32 in flight, reached 4-5 GB/s.

storage/rawio.py reads those datasets itself: each dataset's chunks are
mapped once (chunk_iter / get_offset), a slice of rows is coalesced into
runs of the file and read in request_bytes requests on a module-level
thread pool with os.preadv, into 4 KiB-aligned buffers, past the page
cache where the system allows (a buffered descriptor otherwise). Rows
that are one run of the file are read into the result; tiles and chunks
out of order are copied into place as they arrive. Consecutive slices
are read ahead. Its own memory, read-ahead included, is one budget for
the process (ADATA_IO_BUFFER, 256M). Anything else - filters, text,
compound, fancy indexing, a file opened r+ - goes to h5py.

storage/fsinfo.py says which filesystem a path is on, from
/proc/self/mountinfo, and the settings for Lustre and NFS.

open_store(path, "r") and the new open_hdf5 (the converters' sources)
return a DirectFile when the reader applies: an h5py.File whose groups
hand out DirectDatasets, so no call site changes. --io auto|direct|h5py
(and ADATA_IO) on every command that reads a store; h5py stays the
default until the reader is measured on the farm. While it is on, a
sparse block reads at least half the buffer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
os.preadv leaves a descriptor's offset alone, so the reader can share
HDF5's: concat holds up to 64 inputs open, a quarter of macOS's limit,
and each input cost the reader one more descriptor than O_DIRECT needs.
The O_DIRECT descriptor is checked against HDF5's for the same file. A
platform without os.preadv is left to h5py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Copilot AI balanced review requested due to automatic review settings December 4, 2026 12:19

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-04T12:21:53.984670Z 282e9bc PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 282e9bc232

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/adata/storage/rawio.py Resolved
Comment thread src/adata/storage/rawio.py Resolved
@github-actions

github-actions Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Test Results (py3.13)

4 097 tests  +256   4 082 ✅ +253   11m 10s ⏱️ + 3m 46s
    1 suites ±  0      15 💤 +  3 
    1 files   ±  0       0 ❌ ±  0 

Results for commit 5db0476. ± Comparison against base commit 1dc3f28.

♻️ This comment has been updated with latest results.

@github-actions

github-actions Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Test Results (py3.12)

4 097 tests  +256   4 082 ✅ +253   11m 42s ⏱️ + 5m 22s
    1 suites ±  0      15 💤 +  3 
    1 files   ±  0       0 ❌ ±  0 

Results for commit 5db0476. ± Comparison against base commit 1dc3f28.

♻️ This comment has been updated with latest results.

Claptar and others added 3 commits December 4, 2026 12:55
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A chunk map held an int64 for every chunk a dataset could have, written
or not: 8 GB for a (10**12,) dataset in chunks of 1,000, to read a few
rows. It now holds runs of chunks that lie one after another in the
file, within MAP_BYTES (64 MiB) for every open file together; a dataset
whose map would not fit is left to h5py.

Chunks out of order, and tiles, were read whole into one buffer: with a
1 MiB buffer and 2 MiB chunks each buffer was 2 MiB while the budget
counted 512 KiB. Only the rows of each chunk a block holds are read now,
in segments of at most a request, so what the budget counts is what is
held.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Claptar
Claptar changed the base branch from dev to direct-io December 4, 2026 13:22
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Claptar
Claptar merged commit 4aa25d3 into direct-io Dec 4, 2026
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

2 participants