diff --git a/AGENTS.md b/AGENTS.md index 095e1b8..276fa4f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -81,8 +81,10 @@ uses `elements/` (the spec, `strings`, and the readers and writers that - Commands parse options, validate cheap things such as `--zarr-format`, call into `commands/`, and turn exceptions into `Error:` plus exit code 1. - Shared options are defined once and reused: `_chunk_option` gives every - `--chunk` its `min=1`, and `_space_check_option` is `--no-space-check`. - A new command that takes either uses these, not its own `typer.Option`. + `--chunk` its `min=1`, `_space_check_option` is `--no-space-check`, and + `_io_option` is `--io` (with `ADATA_IO`). A new command that takes any + of them uses these, not its own `typer.Option`; one that reads a store + takes `--io` and calls `_use_io` first. - `console` writes to **stderr**. Only `out_console` and data go to stdout, so output pipes cleanly. Rich asks each stream whether it is a terminal: off one, as in a log file or a pipe, it writes no colour, cursor or @@ -127,6 +129,19 @@ uses `elements/` (the spec, `strings`, and the readers and writers that Without that, anndata reads a stale index and new members look missing. - Use the `is_group`/`is_dataset`/`create_dataset`/`copy_tree` helpers here rather than branching on the backend yourself. + - `rawio.py` is the opt-in direct-I/O reader for HDF5 inputs (`--io`, + `ADATA_IO`, default `h5py`). Opened `"r"` by `open_store`, or by + `open_hdf5` in a converter, an HDF5 file is then a `DirectFile`: an + `h5py.File` whose groups hand out `DirectDataset`s, which send a step-1 + slice of rows (every other axis whole) of an uncompressed numeric + dataset to `read_rows`. That maps the dataset's chunks once + (`ChunkMap`), reads them in `request_bytes` requests on a module-level + thread pool with `os.preadv` (O_DIRECT where the system allows), reads + the next block ahead, and holds at most `ADATA_IO_BUFFER` of its own. + Anything else goes to h5py. + - `fsinfo.py`: `filesystem(path)` from `/proc/self/mountinfo`, and + `io_profile(fstype)`, the reader's settings for Lustre and NFS (None, + h5py, for the rest). `--io auto` uses them. - **`conversion/`**: `adata convert`. AnnData is the hub, so each format has an importer, an exporter, or both, and there are no converters between pairs of other formats. To add a format: @@ -236,6 +251,11 @@ These are easy to break without any test noticing straight away: Changing them is `recast`'s job, or that of an explicit flag. Zarr v3 shards are kept too: `fit_chunks` clamps them with the chunk, and given `itemsize` cuts a unit too large to hold along its rows. +- **Read HDF5 datasets in bulk as `ds[a:b]`, from a file `open_store` or + `open_hdf5` opened.** With `--io` on, that is what goes through the + direct reader; a fancy index, a step, a column slice, `read_direct` or + `np.asarray(ds)` goes to h5py a chunk at a time. Open a source with + `h5py.File(path, "r")` yourself only to sniff it. - **Write a streamed output through `storage.RowWriter`**, and `flush()` it after the last block. A write to part of a Zarr shard rewrites the whole shard, and to part of a chunk Zarr keeps no cache, so writing a `--chunk` diff --git a/STATUS.md b/STATUS.md index 68a6c42..adb8e54 100644 --- a/STATUS.md +++ b/STATUS.md @@ -33,6 +33,42 @@ batches) finished with 0.17.6; the sub-issues (#88–#103) are all done and ticked in #87. The batch names in the follow-ups below (B1 to B10) are theirs. +### Direct-I/O reader for HDF5 inputs (branch `feat/direct-io`) + +The Lustre probe (0.17.8) found every library held to 260-500 MB/s on an +uncompressed h5ad, fetching one chunk 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. Decisions: + +- Our own reader (`storage/rawio.py`), not another library's; h5py stays + for everything it does not handle (filters, text, compound, fancy + indexing), so outputs are the same either way. +- Opt-in: `--io auto|direct|h5py` and `ADATA_IO`, default `h5py`. + `auto` (Lustre and NFS by `/proc/self/mountinfo`, `storage/fsinfo.py`) + becomes the default only after farm measurements of this build; the NFS + settings are provisional until then. +- Memory is one fixed budget, `ADATA_IO_BUFFER` (256M), read-ahead + included; the sparse block floor rises to half of it while the reader is + on. + +Steps: + +- [x] `fsinfo.py`, `rawio.py` (chunk map, coalesced requests on a thread + pool, O_DIRECT with a buffered fallback, read-ahead, budget) +- [x] Wired through `open_store("r")` and `open_hdf5` (converters); `--io` + on every command that reads a store; status line +- [x] Tests against h5py byte for byte, CLI outputs both ways against + anndata, cost guards (maps built once, whole requests, no h5py read + of X) +- [x] Docs: commands reference, pipelines guide, developers/AGENTS +- [x] PR #150, into its own branch `direct-io` (cut from `main` at + 0.17.10), kept apart from `dev` while the audit work lands there +- [x] Review fixes (chunk maps and assembly buffers bounded), green CI +- [ ] Farm measurements of this build against h5py (another session); + nothing has timed it yet +- [ ] Then decide where it lands (`dev` after the audit, or a release of + its own) and whether `auto` becomes the default on Lustre and NFS + ## Follow-ups noticed - From the Lustre probe (0.17.8; docs/reference/cluster-storage.md), what diff --git a/docs/developers.md b/docs/developers.md index 259a020..19af906 100644 --- a/docs/developers.md +++ b/docs/developers.md @@ -69,9 +69,10 @@ element faithfully). given and raises `SystemExit` for the caller; run as the command, a failed run ends the process at once. For the run it turns off numpy's requests for huge pages, which stall on a node with fragmented memory, unless - `NUMPY_MADVISE_HUGEPAGE` is set. `--chunk` and `--no-space-check` are - defined once, as `_chunk_option` and `_space_check_option`; a new command - reuses them. + `NUMPY_MADVISE_HUGEPAGE` is set. `--chunk`, `--no-space-check` and `--io` + are defined once, as `_chunk_option`, `_space_check_option` and + `_io_option`; a new command reuses them, and one that reads a store takes + `--io` and calls `_use_io` first. - **`commands/`** orchestrates one command: what to read, what to refuse, what to write where, and which Zarr version. - **`core/`** holds the algorithms that stream. `subset.py`'s writer serves @@ -88,6 +89,15 @@ element faithfully). returns a `Store`; use its `is_group`, `is_dataset`, `create_dataset` and `copy_tree` rather than branching on h5py or zarr. +`storage/rawio.py` is the opt-in direct-I/O reader for HDF5 inputs (`--io`, +`ADATA_IO`). Opened `"r"` through `open_store`, or through `open_hdf5` by a +converter, an HDF5 file is then a `DirectFile`, an `h5py.File` whose +datasets read a slice of rows of an uncompressed numeric dataset in large +requests on a pool of threads, with O_DIRECT where the system has it, and +leave everything else to h5py. Its memory is one budget for the process, +`ADATA_IO_BUFFER`. `storage/fsinfo.py` says which filesystem a path is on, +from `/proc/self/mountinfo`, and which settings (`IOProfile`) suit it. + ### Adding a format to `convert` AnnData is the hub, so a format needs an importer, an exporter or both, never @@ -172,6 +182,12 @@ before changing anything that writes: defined once in `cli.py` (`_chunk_option`, with `min=1`); reuse it. - **A writable Zarr store rewrites its consolidated metadata on close.** anndata trusts that index, and new members are invisible without it. +- **Read HDF5 datasets in bulk as `ds[a:b]`, from a file `open_store` or + `open_hdf5` opened.** When `--io` turns the direct reader on, a step-1 + slice of rows with every other axis whole (`ds[a:b]`, `ds[a:b, ...]`, + `ds[:]`) goes through it; a fancy index, a step, a column slice, + `read_direct` or `np.asarray(ds)` goes to h5py, a chunk at a time. Open a + source with `h5py.File` yourself only to sniff it. ## Tests diff --git a/docs/guides/pipelines.md b/docs/guides/pipelines.md index 7598157..1262a27 100644 --- a/docs/guides/pipelines.md +++ b/docs/guides/pipelines.md @@ -173,6 +173,24 @@ allocation wait while it tries to free a huge page, and a step that takes seconds can take hours, nearly all of it system time. adata turns the request off for its run. To keep it, set `NUMPY_MADVISE_HUGEPAGE=1`. +## Reading on Lustre and NFS + +`ADATA_IO=auto` reads `.h5ad` inputs on Lustre and NFS with adata's own +direct-I/O reader, in large requests many at once, instead of h5py's one +chunk at a time; elsewhere it keeps h5py. `ADATA_IO=direct` uses the reader +on any filesystem. Set either once for a pipeline's environment, or give +`--io` to one command. The output is the same whichever reads it. + +```bash +export ADATA_IO=auto +export ADATA_IO_BUFFER=512M # the reader's own memory; 256M by default +``` + +Its memory is the fixed budget `ADATA_IO_BUFFER`, whatever the size of the +input, on top of the blocks `--chunk` sets; give a job that much more. It +is opt-in, and `h5py` the default, until it has been measured on the farm. +See [Reading HDF5 inputs](../reference/commands.md#reading-hdf5-inputs). + ## Exit codes and output streams | Exit code | Meaning | diff --git a/docs/reference/commands.md b/docs/reference/commands.md index ce88b37..560d510 100644 --- a/docs/reference/commands.md +++ b/docs/reference/commands.md @@ -34,6 +34,7 @@ Run `adata --help` for the authoritative flag list. Each format - [import](#import) - [Query expressions](query.md), on their own page - [Writing outputs](#writing-outputs): what every command that writes checks +- [Reading HDF5 inputs](#reading-hdf5-inputs): `--io`, `ADATA_IO` and `ADATA_IO_BUFFER` - [Zarr format selection](#zarr-format-selection) --- @@ -96,6 +97,7 @@ adata subset data.h5ad --inplace --obs barcodes.txt | `--chunk`, `-C` | Rows per block, of a dense or a sparse matrix (at least 1) | | `--zarr-format` | Zarr version to write; defaults to the source's | | `--no-space-check` | Write even if the disk looks too small; see [Writing outputs](#writing-outputs) | +| `--io` | How to read HDF5 inputs: `h5py` (default), `direct` or `auto`; see [Reading HDF5 inputs](#reading-hdf5-inputs) | `raw/` is carried over and matched against its **own** var axis, which usually holds more genes than the main object. @@ -166,6 +168,7 @@ adata convert multiome.h5ad -o multiome.h5mu | `--overwrite` | Replace an existing output | | `--force` | Convert despite a lossy, inflating or placeholder result | | `--no-space-check` | Write even if the disk looks too small; see [Writing outputs](#writing-outputs) | +| `--io` | How to read HDF5 inputs: `h5py` (default), `direct` or `auto`; see [Reading HDF5 inputs](#reading-hdf5-inputs) | | Format | Extension | Read | Write | |---|---|---|---| @@ -234,6 +237,7 @@ adata recast data.h5ad layers/counts -o out.h5ad --layout dense --force | `--chunk`, `-C` | Row chunk size for dense matrices (at least 1) | | `--zarr-format` | Zarr version to write; defaults to the source's | | `--no-space-check` | Write even if the disk looks too small; see [Writing outputs](#writing-outputs) | +| `--io` | How to read HDF5 inputs: `h5py` (default), `direct` or `auto`; see [Reading HDF5 inputs](#reading-hdf5-inputs) | Two things are refused before anything is written. A cast that would not round-trip -- checked by casting every value and casting it back, not by @@ -297,6 +301,7 @@ adata split data.h5ad --by cluster -o out/ --min-size 50 | `--chunk`, `-C` | Rows per block, of a dense or a sparse matrix (at least 1) | | `--zarr-format` | Zarr version to write; defaults to the source's | | `--no-space-check` | Write even if the disk looks too small; see [Writing outputs](#writing-outputs) | +| `--io` | How to read HDF5 inputs: `h5py` (default), `direct` or `auto`; see [Reading HDF5 inputs](#reading-hdf5-inputs) | Labels are sanitised for use as filenames, and a label that is a safe filename already keeps it. Collisions get a numeric suffix, and so do labels @@ -340,6 +345,7 @@ adata concat a.h5ad b.h5ad -o m.h5ad --keys a,b --index-unique - --uns-merge sam | `--chunk`, `-C` | Row chunk size while streaming (at least 1) | | `--zarr-format` | Zarr version to write; defaults to the inputs' when they agree, otherwise v3 | | `--no-space-check` | Write even if the disk looks too small; see [Writing outputs](#writing-outputs) | +| `--io` | How to read HDF5 inputs: `h5py` (default), `direct` or `auto`; see [Reading HDF5 inputs](#reading-hdf5-inputs) | Inputs are matched by var name, so each input's var names must be unique. Repeated names are refused before anything is written, and the error names @@ -474,6 +480,7 @@ adata export dict data.h5ad uns -o metadata.json | `--max-elements` | `dict` | Refuse an array larger than this (100,000 elements) | | `--include-attrs` | `dict` | Write the elements' attributes too | | `--scale` | `image` | Stretch the values onto 0-255 (below) | +| `--io` | all | How to read an HDF5 input: `h5py` (default), `direct` or `auto`; see [Reading HDF5 inputs](#reading-hdf5-inputs) | Omit `--output` to write to stdout; `export image` writes PNG there, and otherwise takes its format from the output's extension. `export dataframe`, @@ -547,6 +554,7 @@ adata import image data.h5ad uns/spatial/hires tissue.png --inplace | `--categorical` | `dataframe` | Comma separated columns to read as text and make categoricals | | `--auto-categorical / --no-auto-categorical` | `dataframe` | Make text columns that repeat a value categoricals (default on) | | `--chunk`, `-C` | `array` | Elements a block (below) | +| `--io` | all | How to read an HDF5 source: `h5py` (default), `direct` or `auto`; see [Reading HDF5 inputs](#reading-hdf5-inputs) | Dimensions are validated against the existing obs/var where the path implies an axis. For `array` and `sparse` that is done from the file's header, @@ -701,6 +709,55 @@ whole one at a time: CSC matrix holding more, a gene expressed in every cell, is read in parts. - A Zarr v3 shard's index is read once per command, not once a read. +## Reading HDF5 inputs + +Every command that reads a store (`subset`, `split`, `concat`, `convert`, +`recast`, `export` and `import`) takes `--io`, which chooses how it reads an +`.h5ad`, or another HDF5 input of `convert`. The environment variable +`ADATA_IO` sets it too, for every command of a pipeline; `--io` on the +command line wins. + +| `--io` | Reads HDF5 inputs with | +|---|---| +| `h5py` | h5py, a chunk at a time through the page cache. The default | +| `direct` | adata's direct reader, with the settings measured on Lustre, wherever the input is | +| `auto` | adata's direct reader on Lustre and NFS; h5py on any other filesystem | + +```bash +adata subset data.h5ad -o out.h5ad --obs barcodes.txt --io auto +adata convert data.h5ad -o data.zarr --io direct +``` + +The direct reader reads the bytes of an uncompressed numeric dataset itself. +Where each of the dataset's chunks lies in the file is looked up once, and +a block of rows is then read in large requests (16 MiB on Lustre), sixteen +at once, past the page cache (O_DIRECT), rather than one chunk of a few +hundred kilobytes at a time. On Lustre that one-chunk-at-a-time pattern is +what holds every library to a few hundred MB/s, where plain reads of the +same file reach 4-5 GB/s ([Performance on cluster +storage](cluster-storage.md)). A compressed dataset, text, and anything else +it does not handle are read by h5py as they always were, and the output is +the same either way. It is opt-in until it has been measured on the farm; +`auto` is meant to become the default then. + +Its memory is one budget for the run, `ADATA_IO_BUFFER`: 256M by default, +or 128M on NFS, given in bytes or with `K`, `M` or `G` (at least `1M`). +Reads in flight, chunks waiting to be put in place, and the next block read +ahead all fit in it together, whatever the size of the input; where each +chunk lies takes at most 64 MiB more, for every input together (a dataset +that would need more is read by h5py). The block a +command asks for is on top, as with h5py; while the reader is on, a block +of a sparse matrix holds at least half the buffer, so that each keeps its +requests in flight. A command that reads through it says so once, on +stderr: + +```text +Reading HDF5 with adata's direct reader: O_DIRECT, 16 MiB requests, 16 in flight, 256 MiB buffer (filesystem: lustre) +``` + +Where there is no O_DIRECT (macOS), or the filesystem refuses it, the same +requests go through the page cache, and the line says `buffered`. + ## Zarr format selection New Zarr stores follow the source store's version, so a v2 input is not diff --git a/docs/reference/testing.md b/docs/reference/testing.md index 2a3155c..1a777f7 100644 --- a/docs/reference/testing.md +++ b/docs/reference/testing.md @@ -60,6 +60,9 @@ inside every release before PyPI has it. | `test_elements.py` | The element layer — encodings, string dtypes, readers and writers — run against HDF5, Zarr v2 and Zarr v3 | | `test_storage.py` | Backend detection, copying, Zarr versions, consolidated metadata | | `test_storage_root_attrs.py` | The root's AnnData attributes: written when a store is opened for writing, and a warning on reading a store that lacks them, though not for anndata 0.7's layout, which never had them | +| `test_rawio.py` | The direct-I/O reader (`--io direct`) against h5py byte for byte, dtype and byte order included: contiguous and chunked layouts, chunks not a whole number of pages, edge chunks, unwritten chunks read as the fill value, 2-D tiles with ragged edges, chunks out of file order, random slices; what goes to h5py instead (filters, text, compound, fancy indexing, a file opened `"r+"`); no O_DIRECT, short reads, an error on a reader thread, read-ahead hit and miss, its memory budget | +| `test_fsinfo.py` | `storage/fsinfo.py`: mount tables with escapes, nested mounts, NFS over an automounter's placeholder, Lustre; and which filesystems the direct reader is used on | +| `test_direct_io_cli.py` | `subset`, `split`, `convert` to Zarr and to a 10x matrix, `export sparse`, `export dataframe`, `concat` and `recast`, each run with `ADATA_IO=direct` and with h5py on HDF5, Zarr v2 and Zarr v3 inputs: the same output both ways, and the one anndata computes | | `test_staging.py` | `util/staging.py` on its own: write beside and rename into place, several outputs together, a failed swap put back, leftovers refused rather than deleted | | `test_write_safety.py` | Every way a command used to destroy or corrupt a store while reporting success, or leave a half-written one: outputs that alias the input, failed selections, `--inplace`, failed closes, a full disk, two runs on one output, SIGTERM | | `test_formats.py` | `.npy`, `.mtx`, image and JSON export/import, including their failure modes | @@ -169,6 +172,12 @@ h5py 3.16.0 and zarr 3.4.1: | `zarr.Array.__setitem__`, `zarr.Group.create_array` | Zarr writes (bytes only) | | `zarr.storage.LocalStore.get` | chunk and metadata fetches | | `LocalStore.set` / `.delete` | write storms | +| `adata.storage.rawio.read_rows` | the direct-I/O reader's reads (`--io direct`), counted as reads like h5py's | +| `adata.storage.rawio._read_request` | that reader's requests of the file (`direct_requests`, `direct_request_bytes`) | + +The guards above the direct reader's own measure h5py's path: the file pins +`ADATA_IO=h5py` for each test (`_h5py_reader`), so they keep measuring it +whatever the run's environment says. Both write seams are needed. `create_dataset(name, data=...)` writes its payload during creation and never touches `__setitem__`, so hooking only the latter leaves @@ -407,6 +416,7 @@ should scale with, scale only that, and hold everything else fixed. | sparse `subset` | n_obs; CSR, CSC, a gene in every cell | the **largest read** about `--chunk` rows of entries | | `convert` of a matrix chunked (n_obs, 8) | n_obs | the **largest read** a tile within the budget | | `split` | 128 against 512 groups | **resident memory** flat past 128 outputs a pass | +| `subset` through the direct reader (`--io direct`) | n_obs | each dataset's chunks **mapped once**; a block asked for in **whole requests**, at most ceil((block + 2 chunks) / request); **no h5py read** of `X/data`, `X/indices` or a dense layer | The `slow` marker is on the guards that build a 65,536-row store or run `peak_rss`; they still gate merges, and `-m "not slow"` skips them locally. `perf` is on diff --git a/src/adata/cli.py b/src/adata/cli.py index b2a0354..b3a559d 100644 --- a/src/adata/cli.py +++ b/src/adata/cli.py @@ -1,5 +1,6 @@ """CLI for AnnData stores (.h5ad / .zarr) with export and import subcommands.""" +from enum import Enum from pathlib import Path from typing import Any, List, Optional, Sequence @@ -26,6 +27,7 @@ ) from adata.commands import export_image as export_image_cmd +from adata.storage import rawio from adata.util.markup import literal # Help text is Rich markup on every typer the floor allows: typer 0.21 made @@ -100,6 +102,41 @@ def _chunk_option(default: int, help: str, *aliases: str, hidden: bool = False): ) +class IOChoice(str, Enum): + """How `--io` reads HDF5 inputs.""" + + auto = "auto" + direct = "direct" + h5py = "h5py" + + +def _io_option(): + """`--io`, for every command that reads a store, and `ADATA_IO`.""" + return typer.Option( + IOChoice.h5py, + "--io", + envvar="ADATA_IO", + case_sensitive=False, + help="How to read HDF5 inputs: h5py; adata's direct reader (direct); " + "or the direct reader on Lustre and NFS only (auto). Its buffer is " + "ADATA_IO_BUFFER, 256M by default", + ) + + +def _use_io(choice: IOChoice) -> None: + """Read this run's HDF5 inputs as `--io` says; refuse a malformed + `ADATA_IO_BUFFER` before anything is opened.""" + try: + rawio.set_mode(choice.name) + rawio.buffer_override() + except ValueError as error: + raise _fail(error) + + +def _report_io(message: str) -> None: + console.print(f"[dim]{literal(message)}[/]") + + def _space_check_option(): """`--no-space-check`, for the commands that check free space first.""" return typer.Option( @@ -121,6 +158,11 @@ def _root( ), ) -> None: """Streaming CLI for huge AnnData .h5ad and .zarr stores.""" + # Each run starts from ADATA_IO alone: `--io`, where a command takes + # it, sets it again (`_use_io`). The reader says once a run that it is + # in use. + rawio.set_mode(None) + rawio.set_reporter(_report_io) # ============================================================================ @@ -383,6 +425,7 @@ def subset( help="Zarr spec version to write (defaults to the source store's)", ), no_space_check: bool = _space_check_option(), + io_engine: IOChoice = _io_option(), ) -> None: """ Subset an AnnData store by obs and/or var. @@ -397,6 +440,7 @@ def subset( adata subset data.h5ad -o out.h5ad -q "n_counts > 1000 and cluster in A,B" adata subset data.h5ad -o out.h5ad --var-query "highly_variable == True" """ + _use_io(io_engine) if zarr_format is not None and zarr_format not in (2, 3): console.print("[bold red]Error:[/] --zarr-format must be 2 or 3.") raise typer.Exit(code=1) @@ -485,6 +529,7 @@ def concat( help="Zarr spec version to write (defaults to the inputs' when they agree)", ), no_space_check: bool = _space_check_option(), + io_engine: IOChoice = _io_option(), ) -> None: """ Concatenate stores along the obs axis. @@ -498,6 +543,7 @@ def concat( adata concat *.h5ad -o merged.h5ad --join outer --label sample adata concat a.h5ad b.h5ad -o m.h5ad --keys a,b --index-unique - --uns-merge same """ + _use_io(io_engine) if zarr_format is not None and zarr_format not in (2, 3): console.print("[bold red]Error:[/] --zarr-format must be 2 or 3.") raise typer.Exit(code=1) @@ -862,6 +908,7 @@ def convert( in_memory: bool = typer.Option(False, "--in-memory", hidden=True), chunk_rows: int = _chunk_option(1024, "Row chunk size", hidden=True), no_space_check: bool = _space_check_option(), + io_engine: IOChoice = _io_option(), ) -> None: """ Convert a store to another format. @@ -932,6 +979,7 @@ def convert( adata convert scenicplus.h5mu -o rna.h5ad --mod scRNA_counts adata convert multiome.h5ad -o multiome.h5mu """ + _use_io(io_engine) entries = list(ctx.args) try: @@ -1109,6 +1157,7 @@ def recast( help="Zarr spec version to write (defaults to the source store's)", ), no_space_check: bool = _space_check_option(), + io_engine: IOChoice = _io_option(), ) -> None: """ Change a matrix's dtype, layout or density. @@ -1130,6 +1179,7 @@ def recast( adata recast data.h5ad X --inplace --dtype float32 --indices-dtype int32 adata recast data.h5ad --all -o out.h5ad --dtype float32 """ + _use_io(io_engine) if layout is not None and layout not in LAYOUTS: console.print( f"[bold red]Error:[/] --layout must be one of: {', '.join(LAYOUTS)}." @@ -1204,6 +1254,7 @@ def split( help="Zarr spec version to write (defaults to the source store's)", ), no_space_check: bool = _space_check_option(), + io_engine: IOChoice = _io_option(), ) -> None: """ Split a store into one file per distinct value of a column. @@ -1215,6 +1266,7 @@ def split( adata split data.h5ad --by cell_type -o clusters/ --dry-run adata split data.h5ad --by cluster -o out/ --min-size 50 """ + _use_io(io_engine) if axis not in ("obs", "var"): console.print("[bold red]Error:[/] --axis must be 'obs' or 'var'.") raise typer.Exit(code=1) @@ -1273,6 +1325,7 @@ def export_dataframe( head: Optional[int] = typer.Option( None, "--head", "-n", help="Output only the first n entries" ), + io_engine: IOChoice = _io_option(), ) -> None: """ Export any dataframe-encoded group to CSV. @@ -1285,6 +1338,7 @@ def export_dataframe( adata export dataframe data.h5ad var --columns gene_id,mean adata export dataframe data.h5ad raw/var --head 100 """ + _use_io(io_engine) col_list: Optional[List[str]] = None if columns: @@ -1327,6 +1381,7 @@ def export_array( chunk_elements: int = _chunk_option( 100_000, "Number of elements to read per chunk" ), + io_engine: IOChoice = _io_option(), ) -> None: """ Export a dense array or matrix to NumPy .npy format. @@ -1339,6 +1394,7 @@ def export_array( adata export array data.h5ad X -o matrix.npy adata export array data.h5ad obsm/X_umap > umap.npy """ + _use_io(io_engine) try: export_npy( @@ -1385,6 +1441,7 @@ def export_sparse( "-m", help="Load the entire sparse matrix into memory before exporting (may be faster for small matrices)", ), + io_engine: IOChoice = _io_option(), ) -> None: """ Export a sparse matrix (CSR/CSC) to Matrix Market (.mtx) format. @@ -1394,6 +1451,7 @@ def export_sparse( adata export sparse data.h5ad layers/counts -o counts.mtx adata export sparse data.h5ad X --head 100 """ + _use_io(io_engine) try: export_mtx( @@ -1434,6 +1492,7 @@ def export_dict( include_attrs: bool = typer.Option( False, "--include-attrs", help="Include the elements' attributes in the JSON" ), + io_engine: IOChoice = _io_option(), ) -> None: """ Export a dict/group or scalar to JSON format. @@ -1442,6 +1501,7 @@ def export_dict( adata export dict data.h5ad uns metadata.json adata export dict data.h5ad uns/colors colors.json """ + _use_io(io_engine) try: out_path = output if output is not None else output_arg @@ -1480,6 +1540,7 @@ def export_image( help="Stretch the values onto 0-255 (smallest to 0, largest to 255), " "for values an image cannot keep as they are", ), + io_engine: IOChoice = _io_option(), ) -> None: """ Export an image-like array to PNG/JPG/TIFF format. @@ -1495,6 +1556,7 @@ def export_image( adata export image data.h5ad uns/spatial/image > tissue.png adata export image data.h5ad uns/spatial/morphology -o morphology.png --scale """ + _use_io(io_engine) try: export_image_cmd(file=file, obj=entry, out=output, console=console, scale=scale) @@ -1552,6 +1614,7 @@ def import_dataframe( "--auto-categorical/--no-auto-categorical", help="Make text columns that repeat a value categoricals, as anndata does", ), + io_engine: IOChoice = _io_option(), ) -> None: """ Import a CSV file as a dataframe. @@ -1566,6 +1629,7 @@ def import_dataframe( adata import dataframe data.h5ad var genes.csv --inplace -i gene_id adata import dataframe data.h5ad obs cells.csv --inplace --categorical batch """ + _use_io(io_engine) from adata.commands.import_data import _import_csv, import_into try: @@ -1628,6 +1692,7 @@ def import_array( IMPORT_CHUNK_ELEMENTS, "Number of elements to copy per chunk" ), no_space_check: bool = _space_check_option(), + io_engine: IOChoice = _io_option(), ) -> None: """ Import a NumPy .npy file as a dense array. @@ -1638,6 +1703,7 @@ def import_array( adata import array data.h5ad obsm/X_pca pca.npy -o output.h5ad adata import array data.h5ad X matrix.npy --inplace """ + _use_io(io_engine) from adata.commands.import_data import _import_npy, import_into try: @@ -1688,6 +1754,7 @@ def import_sparse( help="Replace the source; the new store is written beside it first", ), no_space_check: bool = _space_check_option(), + io_engine: IOChoice = _io_option(), ) -> None: """ Import a Matrix Market (.mtx) file as a CSR sparse matrix. @@ -1698,6 +1765,7 @@ def import_sparse( adata import sparse data.h5ad X matrix.mtx -o output.h5ad adata import sparse data.h5ad layers/counts counts.mtx --inplace """ + _use_io(io_engine) from adata.commands.import_data import _import_mtx, import_into try: @@ -1746,6 +1814,7 @@ def import_dict( help="Replace the source; the new store is written beside it first", ), no_space_check: bool = _space_check_option(), + io_engine: IOChoice = _io_option(), ) -> None: """ Import a JSON file into uns or other dict-like groups. @@ -1754,6 +1823,7 @@ def import_dict( adata import dict data.h5ad uns/metadata config.json -o output.h5ad adata import dict data.h5ad uns settings.json --inplace """ + _use_io(io_engine) from adata.commands.import_data import _import_json, import_into try: @@ -1798,6 +1868,7 @@ def import_image_cmd( False, "--inplace", help="Replace the source; the new store is written beside it first" ), no_space_check: bool = _space_check_option(), + io_engine: IOChoice = _io_option(), ) -> None: """ Import an image file as a dense array. @@ -1805,6 +1876,7 @@ def import_image_cmd( Examples: adata import image data.h5ad uns/spatial/hires tissue.png --inplace """ + _use_io(io_engine) from adata.commands.import_data import _import_image, import_into try: diff --git a/src/adata/conversion/cellbender.py b/src/adata/conversion/cellbender.py index eba4d0a..9aa9124 100644 --- a/src/adata/conversion/cellbender.py +++ b/src/adata/conversion/cellbender.py @@ -62,7 +62,7 @@ write_string_array, ) from adata.formats.mtx import EntryMap, iter_matrix_entries -from adata.storage import create_dataset, open_store +from adata.storage import create_dataset, open_hdf5, open_store from adata.util.markup import literal #: Datasets of a 0.2 matrix group that are the matrix, not a latent. @@ -289,7 +289,7 @@ def _plan_raw( f"--raw {path.name} is not a 10x HDF5 matrix; it must be the " "raw_feature_bc_matrix.h5 CellBender was run on." ) - with h5py.File(path, "r") as handle: + with open_hdf5(path) as handle: raw = tenx._read_matrix(handle, options.genome) same = ( raw.n_features == matrix.n_features @@ -365,7 +365,7 @@ def _write_raw( )] for t, root in enumerate(roots) ] - with h5py.File(raw.path, "r") as handle: + with open_hdf5(raw.path) as handle: group = handle[raw.group] source = Matrix( tenx._AsCsr(group, (raw.n_barcodes, n_features)), spec.CSR_MATRIX, @@ -454,7 +454,7 @@ def plan( dst_format: str, options: Options, ) -> ConversionPlan: - with h5py.File(source, "r") as handle: + with open_hdf5(source) as handle: if not _has_latents(handle): # Named with --from: without latents it is a plain 10x # matrix, and calling it CellBender's would invent a result. @@ -536,7 +536,7 @@ def write( matrix, latents, out_rows = detail.matrix, detail.latents, detail.out_rows n_out = matrix.n_barcodes if out_rows is None else out_rows.size - with h5py.File(plan.source, "r") as handle, ExitStack() as stack: + with open_hdf5(plan.source) as handle, ExitStack() as stack: group = handle[matrix.group] roots = [ stack.enter_context( diff --git a/src/adata/conversion/hdf5.py b/src/adata/conversion/hdf5.py index ea13459..360240f 100644 --- a/src/adata/conversion/hdf5.py +++ b/src/adata/conversion/hdf5.py @@ -29,7 +29,7 @@ from adata.conversion.dense import write_dense_matrix from adata.conversion.features import STRING_STEP, Target, write_obs_index, write_var from adata.elements.write import ensure_anndata_skeleton, set_column_order, write_mapping, write_scalar -from adata.storage import COMPRESSIONS, open_store +from adata.storage import COMPRESSIONS, open_hdf5, open_store from adata.util.markup import literal from adata.util.names import count_duplicates, make_index_unique @@ -118,7 +118,7 @@ def plan( ) name = Path(source).name warnings: List[str] = [] - with h5py.File(source, "r") as handle: + with open_hdf5(source) as handle: key = options.key if key is None: raise ValueError( @@ -212,7 +212,7 @@ def write( self, plan: ConversionPlan, staged: Sequence[Path], console: Console ) -> None: detail: _Import = plan.detail - with h5py.File(plan.source, "r") as handle, open_store( + with open_hdf5(plan.source) as handle, open_store( staged[0], "w", zarr_format=detail.zarr_format ) as store: root = store.root diff --git a/src/adata/conversion/loom.py b/src/adata/conversion/loom.py index f43b7e4..24c253a 100644 --- a/src/adata/conversion/loom.py +++ b/src/adata/conversion/loom.py @@ -94,6 +94,7 @@ is_group, is_legacy_categorical, is_zarr_group, + open_hdf5, open_store, ) from adata.util.markup import literal @@ -281,7 +282,7 @@ def plan( f"{dst_format}; use one of: {', '.join(COMPRESSIONS[backend])}." ) warnings: List[str] = [] - with h5py.File(source, "r") as handle: + with open_hdf5(source) as handle: matrix = handle["matrix"] n_genes, n_cells = matrix.shape layers = handle["layers"] if isinstance(handle.get("layers"), h5py.Group) else {} @@ -449,7 +450,7 @@ def write( self, plan: ConversionPlan, staged: Sequence[Path], console: Console ) -> None: detail: _Import = plan.detail - with h5py.File(plan.source, "r") as handle, ExitStack() as stack: + with open_hdf5(plan.source) as handle, ExitStack() as stack: root = stack.enter_context( open_store(staged[0], "w", zarr_format=detail.zarr_format) ).root diff --git a/src/adata/conversion/tenx.py b/src/adata/conversion/tenx.py index 02ec6af..3ffb0cd 100644 --- a/src/adata/conversion/tenx.py +++ b/src/adata/conversion/tenx.py @@ -72,6 +72,7 @@ copy_dataset, has_valid_anndata_root_attrs, is_dataset, + open_hdf5, open_store, ) from adata.util.markup import literal @@ -408,7 +409,7 @@ def plan( dst_format: str, options: Options, ) -> ConversionPlan: - with h5py.File(source, "r") as handle: + with open_hdf5(source) as handle: matrix, outputs, targets, warnings = plan_matrix_import( handle, output, options ) @@ -439,7 +440,7 @@ def write( matrix: _Matrix = detail["matrix"] targets: List[Target] = detail["targets"] - with h5py.File(plan.source, "r") as handle, ExitStack() as stack: + with open_hdf5(plan.source) as handle, ExitStack() as stack: group = handle[matrix.group] roots = [ stack.enter_context( diff --git a/src/adata/conversion/visium.py b/src/adata/conversion/visium.py index 47c39cc..b781705 100644 --- a/src/adata/conversion/visium.py +++ b/src/adata/conversion/visium.py @@ -81,7 +81,7 @@ from adata.formats.parquet import ParquetTable, open_table, require_pyarrow from adata.formats.table import TableScan, column_values, create_columns, scan_table from adata.formats.textio import open_binary -from adata.storage import create_dataset, is_zarr_path, open_store +from adata.storage import create_dataset, is_zarr_path, open_hdf5, open_store from adata.elements import spec from adata.util.markup import literal @@ -380,7 +380,7 @@ def plan( if lacking: raise ValueError(f"{outs} has no {' and no '.join(lacking)} beside the matrix.") - with h5py.File(matrix_path, "r") as handle: + with open_hdf5(matrix_path) as handle: if not tenx.sniff(matrix_path): raise ValueError(f"{matrix_path.name} is not a 10x HDF5 matrix.") matrix, outputs, targets, warnings = tenx.plan_matrix_import(handle, output, options) @@ -469,7 +469,7 @@ def _plan_cells( "gives the cells' areas in µm²." ) - with h5py.File(matrix_path, "r") as handle: + with open_hdf5(matrix_path) as handle: if not tenx.sniff(matrix_path): raise ValueError(f"{matrix_path.name} is not a 10x HDF5 matrix.") matrix, outputs, targets, warnings = tenx.plan_matrix_import(handle, output, options) @@ -530,7 +530,7 @@ def write(self, plan: ConversionPlan, staged: Sequence[Path], console: Console) detail: _Plan = plan.detail matrix = detail.matrix - with h5py.File(detail.matrix_path, "r") as handle, ExitStack() as stack: + with open_hdf5(detail.matrix_path) as handle, ExitStack() as stack: group = handle[matrix.group] roots = [ stack.enter_context(open_store(path, "w", zarr_format=detail.zarr_format)).root diff --git a/src/adata/conversion/xenium.py b/src/adata/conversion/xenium.py index e8bbaff..5920828 100644 --- a/src/adata/conversion/xenium.py +++ b/src/adata/conversion/xenium.py @@ -61,7 +61,7 @@ from adata.elements.read import decode_str_array from adata.elements.write import ensure_anndata_skeleton, set_column_order from adata.formats.table import column_values, create_columns, drop_unused -from adata.storage import create_dataset, is_zarr_path, open_store +from adata.storage import create_dataset, is_zarr_path, open_hdf5, open_store _CENTROIDS = ("x_centroid", "y_centroid") _CELL_TABLES = ("cells.csv.gz", "cells.csv") @@ -168,7 +168,7 @@ def plan( analysis = Path(unpacked.name) packed_but_empty = not any(analysis.rglob("*.csv")) warnings: List[str] = [] - with h5py.File(matrix_path, "r") as handle: + with open_hdf5(matrix_path) as handle: if not tenx.sniff(matrix_path): raise ValueError(f"{matrix_path.name} is not a 10x HDF5 matrix.") matrix, outputs, targets, warnings = tenx.plan_matrix_import(handle, output, options) @@ -219,7 +219,7 @@ def write(self, plan: ConversionPlan, staged: Sequence[Path], console: Console) detail: _Plan = plan.detail matrix = detail.matrix - with h5py.File(detail.matrix_path, "r") as handle, ExitStack() as stack: + with open_hdf5(detail.matrix_path) as handle, ExitStack() as stack: group = handle[matrix.group] roots = [ stack.enter_context(open_store(path, "w", zarr_format=detail.zarr_format)).root diff --git a/src/adata/core/subset.py b/src/adata/core/subset.py index 40ae3ea..5ccfb83 100644 --- a/src/adata/core/subset.py +++ b/src/adata/core/subset.py @@ -29,6 +29,7 @@ read_str_chunk, resolve_index, ) +from adata.storage import rawio from adata.storage import ( TARGET_READ_BYTES, WRITE_UNIT_BYTES, @@ -670,15 +671,19 @@ def subset_sparse_matrix_group( #: The least a block of a sparse matrix reads, `data` and `indices` together: -#: the read budget (`sparse_block_entries`). +#: the read budget (`sparse_block_entries`). Read through the direct-I/O +#: reader, half its buffer, if that is more (`rawio.block_bytes`). SPARSE_BLOCK_BYTES = TARGET_READ_BYTES -def sparse_block_entries(n_rows: int, nnz: int, chunk_rows: int, *, entry_bytes: int) -> int: +def sparse_block_entries( + n_rows: int, nnz: int, chunk_rows: int, *, entry_bytes: int, + floor_bytes: Optional[int] = None, +) -> int: """Entries a block of a sparse matrix holds: as many as `chunk_rows` rows hold on average, in either layout, and never fewer than fill - `SPARSE_BLOCK_BYTES` of `data` and `indices` together, `entry_bytes` - an entry. + `floor_bytes` (by default `SPARSE_BLOCK_BYTES`) of `data` and + `indices` together, `entry_bytes` an entry. Blocks were 4,096 majors, whatever --chunk said. Of a CSC matrix that is 4,096 genes across every cell, a block growing with n_obs: 270M entries, @@ -692,7 +697,8 @@ def sparse_block_entries(n_rows: int, nnz: int, chunk_rows: int, *, entry_bytes: is copied in reads of the same size (`_chunk_step`). """ per_row = -(-int(nnz) // max(1, int(n_rows))) if nnz else 1 - floor = SPARSE_BLOCK_BYTES // max(1, int(entry_bytes)) + floor_bytes = SPARSE_BLOCK_BYTES if floor_bytes is None else int(floor_bytes) + floor = floor_bytes // max(1, int(entry_bytes)) return max(1, int(chunk_rows) * max(1, per_row), floor) @@ -822,6 +828,8 @@ def fan_out_sparse_matrix( budget = sparse_block_entries( n_rows, int(indptr[-1]) if indptr.size else 0, chunk_rows, entry_bytes=np.dtype(data_ds.dtype).itemsize + np.dtype(indices_ds.dtype).itemsize, + # The direct-I/O reader keeps more requests in flight a block. + floor_bytes=rawio.block_bytes(data_ds, SPARSE_BLOCK_BYTES), ) for first, stop, lo, hi in _sparse_blocks( indptr, budget, [out.selection for out in outputs] diff --git a/src/adata/storage/__init__.py b/src/adata/storage/__init__.py index e5d78c4..7cbd7ea 100644 --- a/src/adata/storage/__init__.py +++ b/src/adata/storage/__init__.py @@ -16,6 +16,7 @@ import numpy as np from adata.elements import spec +from adata.storage import rawio from adata.util.path import is_zarr_path # noqa: F401 - re-exported @@ -285,7 +286,12 @@ def open_store( zarr_format=zarr_format_of(root), consolidate=writable, ) - root = h5py.File(path, mode, rdcc_nbytes=chunk_cache) + if mode == "r": + # Read through the direct-I/O reader when `--io` asks for it and it + # applies; otherwise, and for any other mode, h5py as it is. + root = rawio.open_file(path, rdcc_nbytes=chunk_cache) + else: + root = h5py.File(path, mode, rdcc_nbytes=chunk_cache) if mode not in ("w", "w-", "x"): # Anything opened for its contents, read or appended to (--inplace). try: @@ -300,6 +306,14 @@ def open_store( return Store(backend="hdf5", root=root, path=path) +def open_hdf5(path: Path, **kwargs: Any) -> h5py.File: + """An HDF5 file opened `"r"` for its datasets to be read in bulk, as + `h5py.File(path, "r")`: through the direct-I/O reader (`rawio`) when + `--io` asks for it and it applies to the file. For converters that read + a source which is not an AnnData store.""" + return rawio.open_file(path, **kwargs) + + class ExternalDataError(ValueError): """An HDF5 file holds a dataset or link whose data lives in another file.""" diff --git a/src/adata/storage/fsinfo.py b/src/adata/storage/fsinfo.py new file mode 100644 index 0000000..a997d0a --- /dev/null +++ b/src/adata/storage/fsinfo.py @@ -0,0 +1,150 @@ +"""Which filesystem a path is on, and how to read from it. + +The direct-I/O reader (`rawio`) pays off where every read is a network +round trip: on Lustre, h5py and every other library read an uncompressed +h5ad at 260-500 MB/s, one chunk at a time through the page cache, while +plain byte ranges of the same file, read with O_DIRECT in 16 MiB requests, +16 to 32 at once, reached 4-5 GB/s on every node measured +(`docs/reference/cluster-storage.md`). On a local disk the page cache is +already fast, and h5py is kept. + +`filesystem` reads the kernel's own mount table, so it needs no tool and no +privilege; `io_profile` maps a filesystem type to the settings to read it +with, or to None for h5py. +""" + +from __future__ import annotations + +import os +import re +import sys +from dataclasses import dataclass +from pathlib import Path +from typing import List, Optional, Tuple + +MOUNTINFO = "/proc/self/mountinfo" + +MiB = 1 << 20 + + +@dataclass(frozen=True) +class IOProfile: + """How the direct-I/O reader reads a filesystem. + + `direct` opens files with O_DIRECT, past the page cache; `request_bytes` + is the size of one read, `in_flight` how many run at once, and + `buffer_bytes` the most the reader holds of its own at any time: reads + in flight, chunks waiting to be put in place, and read-ahead. + """ + + direct: bool + request_bytes: int + in_flight: int + buffer_bytes: int + + +#: Measured on Lustre in December 2026 (`benchmarks/lustre/`): 16 MiB +#: requests, 16 in flight, past the page cache, reached 4-5 GB/s. +LUSTRE = IOProfile(direct=True, request_bytes=16 * MiB, in_flight=16, buffer_bytes=256 * MiB) + +#: Provisional, until NFS is measured: through the page cache (NFS clients +#: differ in what they allow with O_DIRECT), smaller requests, more of them. +NFS = IOProfile(direct=False, request_bytes=4 * MiB, in_flight=32, buffer_bytes=128 * MiB) + +_PROFILES = { + "lustre": LUSTRE, + "nfs": NFS, + "nfs4": NFS, +} + + +def io_profile(fstype: str) -> Optional[IOProfile]: + """The settings to read a filesystem of `fstype` with, or None for h5py. + + Local filesystems (ext4, xfs, btrfs, tmpfs, overlay, squashfs, apfs), + FUSE mounts and anything unknown keep h5py: the page cache already + serves them well, or nothing has been measured there. + """ + return _PROFILES.get(str(fstype)) + + +_ESCAPE = re.compile(r"\\([0-7]{3})") + + +def _unescape(field: str) -> str: + """A mountinfo field with the kernel's octal escapes (`\\040` for a + space, `\\011` tab, `\\012` newline, `\\134` backslash) decoded.""" + return _ESCAPE.sub(lambda match: chr(int(match.group(1), 8)), field) + + +def parse_mountinfo(text: str) -> List[Tuple[str, str]]: + """`(mount point, fstype)` for each line of /proc/self/mountinfo, in + order. + + A line is `id parent major:minor root mount-point options + [optional fields...] - fstype source super-options`: the optional fields + vary in number, so the fstype is found after the lone `-`. + """ + mounts = [] + for line in text.splitlines(): + fields = line.split(" ") + try: + separator = fields.index("-", 6) + except ValueError: + continue + if len(fields) <= separator + 1 or len(fields) < 5: + continue + mounts.append((_unescape(fields[4]), fields[separator + 1])) + return mounts + + +def _within(path: str, mount_point: str) -> bool: + if mount_point == "/": + return path.startswith("/") + return path == mount_point or path.startswith(mount_point.rstrip("/") + "/") + + +def _existing(path: Path) -> Path: + """`path` resolved, or its nearest parent that exists, resolved: an + output that is about to be written is on its folder's filesystem.""" + path = Path(os.path.abspath(path)) + for candidate in (path, *path.parents): + if candidate.exists(): + return Path(os.path.realpath(candidate)) + return Path("/") + + +def filesystem(path: os.PathLike, mountinfo: Optional[str] = None) -> str: + """The type of the filesystem `path` is on (`lustre`, `nfs4`, `ext4`...). + + The mount whose mount point is the longest prefix of the path's real + path, as /proc/self/mountinfo lists it; where two are mounted on the + same point the later one, which hides the earlier (an NFS share an + automounter has mounted over its `autofs` placeholder). A path that + does not exist yet is taken by its nearest parent that does. Off Linux, + or where the table cannot be read, `"unknown"`. + + `mountinfo` is the table's text, for tests. + """ + if mountinfo is None: + if not sys.platform.startswith("linux"): + return "unknown" + try: + with open(MOUNTINFO, encoding="utf-8", errors="surrogateescape") as handle: + mountinfo = handle.read() + except OSError: + return "unknown" + return fstype_at(str(_existing(Path(path))), mountinfo) + + +def fstype_at(real_path: str, mountinfo: str) -> str: + """The type of the mount holding `real_path`, an absolute path with no + symbolic links, by the table `mountinfo` (`filesystem`).""" + best: Optional[Tuple[int, str]] = None + for mount_point, fstype in parse_mountinfo(mountinfo): + if not _within(real_path, mount_point): + continue + length = len(mount_point.rstrip("/")) + if best is None or length >= best[0]: + best = (length, fstype) + return best[1] if best is not None else "unknown" diff --git a/src/adata/storage/rawio.py b/src/adata/storage/rawio.py new file mode 100644 index 0000000..08d0b2d --- /dev/null +++ b/src/adata/storage/rawio.py @@ -0,0 +1,1052 @@ +"""A direct-I/O reader for uncompressed HDF5 datasets, opt-in. + +On Lustre every library measured -- h5py, zarr over HDF5 chunks, DuckDB, +obstore -- reads an uncompressed h5ad at 260-500 MB/s, because each fetches +one chunk of a few hundred kilobytes at a time through the page cache. +Plain byte ranges of the same file, read past the page cache (O_DIRECT) in +16 MiB requests with 16 to 32 in flight from Python threads, reached 4-5 +GB/s on every node, at a third of the CPU (`docs/reference/cluster-storage.md`). +This module reads that way. + +What it reads, and what it leaves to h5py +----------------------------------------- +A dataset qualifies when its bytes on disk are its values as numpy holds +them: a dtype of kind `b`, `i`, `u` or `f` whose file type is the one numpy +would write (big-endian included), no filters, contiguous or chunked, one or +two dimensions, in a file opened `"r"` with HDF5's default driver and no +userblock. The file positions of its chunks are mapped once per dataset +(`ChunkMap`, from `chunk_iter` or `get_offset`), as runs of chunks that lie +one after another in the file, within `MAP_BYTES` for every open file +together; a chunk never written reads as the dataset's fill value. +Anything else raises `Unsupported`, and h5py reads it as before. + +How it reads +------------ +`DirectDataset.__getitem__` sends a step-1 slice along the first axis, taking +the remaining axes whole, to `read_rows`, the one entry point. The chunks the +rows lie in are coalesced into runs of adjacent file bytes, the runs cut into +`request_bytes` requests, and the requests read by a module-level pool of +`in_flight` threads with `os.preadv`, into buffers aligned to 4 KiB at file +offsets and lengths aligned to 4 KiB, as O_DIRECT needs. Where the rows are +one run in order (a contiguous dataset, a 1-D chunked one written in order, +a 2-D one chunked across its full width), the buffer is the result and +nothing is copied; otherwise the rows of each chunk the block holds are +read in segments of at most a request, and copied into place as they +arrive. Without O_DIRECT (macOS, or a filesystem that refuses it) the same +requests go through the page cache. + +Memory +------ +The reader's own memory is one fixed budget for the process, +`buffer_bytes` (256 MiB on Lustre, `ADATA_IO_BUFFER` to change it): reads in +flight, chunks waiting to be copied into place, and read-ahead waiting to be +used, together, whatever the size of the input; no buffer of its own is +larger than a request. The chunk maps are apart, within `MAP_BYTES`. The +block a command asked for is on top of both, as it is with h5py. + +Read-ahead +---------- +A dataset read in consecutive slices, `[a, b)` then `[b, c)`, has +`[c, c + (c - b))` read in the background, within half the budget, and the +next call served from it when it asks for those rows. + +When it is used +--------------- +Off by default (`--io h5py`). `--io auto` (or `ADATA_IO=auto`) uses it on +the filesystems `fsinfo.io_profile` names, Lustre and NFS; `--io direct` +uses it with Lustre's settings wherever the input is. +""" + +from __future__ import annotations + +import errno +import os +import re +import threading +import weakref +from concurrent.futures import Future, ThreadPoolExecutor, wait +from dataclasses import replace +from pathlib import Path +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple + +import h5py +import numpy as np + +from adata.storage.fsinfo import LUSTRE, IOProfile, MiB, filesystem, io_profile + +#: The alignment O_DIRECT needs of a read's buffer, file offset and length: +#: a page, and a 4K sector, on every system we run on. +ALIGN = 4096 + +#: The `--io` choices. +MODES = ("auto", "direct", "h5py") + +#: The least `ADATA_IO_BUFFER` may be: two of the smallest requests. +MIN_BUFFER_BYTES = 1 * MiB + +#: The most bytes between two chunks that a read goes through rather than +#: asking for each apart. HDF5 puts a node of its chunk index (2.6 KB for a +#: 2-D dataset) after every few dozen chunks; on Lustre another request +#: costs far more than reading past one. +GAP_BYTES = 256 * 1024 + +#: The most bytes the chunk maps of every open file hold together. A map +#: keeps one run (`RUN_BYTES`) for each stretch of chunks that lie one +#: after another in the file, so what it holds follows how the file was +#: written, not how large the dataset is: a dataset written in order is a +#: few runs, one of chunks never written none. A dataset whose map would +#: not fit is left to h5py. +MAP_BYTES = 64 * 1024 * 1024 +RUN_BYTES = 24 +_MAPS = {"bytes": 0} +_MAP_LOCK = threading.Lock() + +#: Threads that run read-ahead. Each waits on the I/O pool, so they are +#: kept apart from it: an I/O thread never waits on another. +AHEAD_THREADS = 4 + + +class Unsupported(Exception): + """A dataset or file the reader does not handle: h5py reads it.""" + + +# --------------------------------------------------------------------------- +# Settings + + +_SETTINGS: Dict[str, Any] = {"mode": None, "report": None} +_ANNOUNCED: set = set() + + +def set_mode(mode: Optional[str]) -> None: + """Choose the reader for stores opened from now on: one of `MODES`, or + None to follow `ADATA_IO` (h5py when it is unset).""" + _SETTINGS["mode"] = None if mode is None else _checked_mode(mode, "--io") + + +def set_reporter(report: Optional[Callable[[str], None]]) -> None: + """Where to say, once a run, that the reader is in use (the CLI's + stderr); None to say nothing.""" + _SETTINGS["report"] = report + _ANNOUNCED.clear() + + +def _checked_mode(mode: str, where: str) -> str: + value = str(mode).strip().lower() + if value not in MODES: + raise ValueError(f"{where} must be one of auto, direct or h5py, not '{mode}'.") + return value + + +def io_mode() -> str: + """The reader chosen: `set_mode`'s, else `ADATA_IO`'s, else h5py.""" + if _SETTINGS["mode"] is not None: + return _SETTINGS["mode"] + value = os.environ.get("ADATA_IO", "").strip() + return _checked_mode(value, "ADATA_IO") if value else "h5py" + + +_SIZE = re.compile(r"^\s*(\d+)\s*([kmgt]?)(i?b)?\s*$", re.IGNORECASE) +_UNITS = {"": 1, "k": 1 << 10, "m": 1 << 20, "g": 1 << 30, "t": 1 << 40} + + +def parse_size(text: str) -> int: + """Bytes in a size such as `256M`, `1G`, `512KiB` or `1048576`; a unit + is a power of 1024.""" + match = _SIZE.match(str(text)) + if not match: + raise ValueError(f"not a size: '{text}'") + return int(match.group(1)) * _UNITS[match.group(2).lower()] + + +def buffer_override() -> Optional[int]: + """`ADATA_IO_BUFFER` in bytes, or None when it is unset.""" + text = os.environ.get("ADATA_IO_BUFFER", "").strip() + if not text: + return None + try: + size = parse_size(text) + except ValueError: + raise ValueError( + f"ADATA_IO_BUFFER must be a size such as 256M or 1G, not '{text}'." + ) from None + if size < MIN_BUFFER_BYTES: + raise ValueError(f"ADATA_IO_BUFFER must be at least 1M, not '{text}'.") + return size + + +def fit(profile: IOProfile) -> IOProfile: + """`profile` with its request cut to half its buffer, in whole pages, + so that a request always fits beside the read-ahead (`_Budget`).""" + half = max(ALIGN, profile.buffer_bytes // 2 // ALIGN * ALIGN) + request = max(ALIGN, min(profile.request_bytes, half) // ALIGN * ALIGN) + return replace(profile, request_bytes=request, in_flight=max(1, int(profile.in_flight))) + + +def profile_for(path: os.PathLike) -> Tuple[Optional[IOProfile], str]: + """How to read the file at `path`: `(profile, fstype)`, the profile None + for h5py.""" + mode = io_mode() + if mode == "h5py": + return None, "" + fstype = filesystem(path) + profile = LUSTRE if mode == "direct" else io_profile(fstype) + if profile is None: + return None, fstype + buffer = buffer_override() + if buffer is not None: + profile = replace(profile, buffer_bytes=buffer) + return fit(profile), fstype + + +def size_text(nbytes: int) -> str: + for unit, scale in (("GiB", 1 << 30), ("MiB", 1 << 20), ("KiB", 1 << 10)): + if nbytes >= scale and nbytes % scale == 0: + return f"{nbytes // scale} {unit}" + return f"{nbytes} B" + + +def describe(engine: "Engine") -> str: + """The status line: the reader and its settings.""" + p = engine.profile + how = "O_DIRECT" if engine.source.direct else "buffered" + return ( + f"Reading HDF5 with adata's direct reader: {how}, " + f"{size_text(p.request_bytes)} requests, {p.in_flight} in flight, " + f"{size_text(p.buffer_bytes)} buffer (filesystem: {engine.fstype or 'unknown'})" + ) + + +def _announce(message: str) -> None: + report = _SETTINGS["report"] + if report is not None and message not in _ANNOUNCED: + _ANNOUNCED.add(message) + report(message) + + +# --------------------------------------------------------------------------- +# The budget and the threads, one of each for the process + + +class _Budget: + """The bytes the reader holds of its own, against `limit`. + + Reads in flight and chunks awaiting their copy take what they need + (`acquire`, waiting for room) and give it back when done; read-ahead + takes room only if there is some, within half the limit (`try_ahead`), + until its rows are used or dropped. A taker never waits while holding + anything that only it can give back, and none takes more than half the + limit, so the reads always make room for each other. + """ + + def __init__(self) -> None: + self.limit = LUSTRE.buffer_bytes + self.used = 0 + self.ahead = 0 + self._cond = threading.Condition() + + def set_limit(self, limit: int) -> None: + with self._cond: + self.limit = int(limit) + self._cond.notify_all() + + def acquire(self, nbytes: int) -> int: + """Wait for room for `nbytes` (at most half the limit); the bytes + held, to give back to `release`.""" + with self._cond: + held = max(1, min(int(nbytes), self.limit // 2)) + while self.used and self.used + held > self.limit: + self._cond.wait() + self.used += held + return held + + def try_ahead(self, nbytes: int) -> bool: + """Take room for `nbytes` of read-ahead, if there is some now.""" + with self._cond: + if self.ahead + nbytes > self.limit // 2 or self.used + nbytes > self.limit: + return False + self.used += nbytes + self.ahead += nbytes + return True + + def release(self, nbytes: int, *, ahead: bool = False) -> None: + with self._cond: + self.used -= nbytes + if ahead: + self.ahead -= nbytes + self._cond.notify_all() + + +_BUDGET = _Budget() +_POOLS: Dict[str, Any] = {"io": None, "io_size": 0, "ahead": None} +_POOL_LOCK = threading.Lock() + + +def _io_pool(threads: int) -> ThreadPoolExecutor: + """The pool reads run on: at least `threads` threads, kept for the + process.""" + with _POOL_LOCK: + if _POOLS["io"] is None or _POOLS["io_size"] < threads: + old = _POOLS["io"] + _POOLS["io"] = ThreadPoolExecutor(threads, thread_name_prefix="adata-io") + _POOLS["io_size"] = threads + if old is not None: + old.shutdown(wait=False) + return _POOLS["io"] + + +def _ahead_pool() -> ThreadPoolExecutor: + with _POOL_LOCK: + if _POOLS["ahead"] is None: + _POOLS["ahead"] = ThreadPoolExecutor( + AHEAD_THREADS, thread_name_prefix="adata-readahead" + ) + return _POOLS["ahead"] + + +# --------------------------------------------------------------------------- +# Byte ranges + + +def _open_direct(path: str) -> Optional[int]: + """A descriptor of `path` opened with O_DIRECT, or None where there is no + O_DIRECT (macOS) or the filesystem refuses it (EINVAL on tmpfs).""" + flag = getattr(os, "O_DIRECT", None) + if flag is None: + return None + try: + return os.open(path, os.O_RDONLY | flag | getattr(os, "O_CLOEXEC", 0)) + except OSError: + return None + + +def _close_all(fds: List[int]) -> None: + for fd in fds: + try: + os.close(fd) + except OSError: # pragma: no cover - already closed + pass + + +class _Source: + """The descriptors one file is read through: HDF5's own, through the page + cache, and one past it when the profile asks and the system allows. + + `os.preadv` leaves a descriptor's offset alone, so reads share HDF5's + with HDF5: a run holding many inputs open (`concat` holds up to 64) + spends no more descriptors on the reader than O_DIRECT takes. + """ + + def __init__(self, path: str, profile: IOProfile, buffered: int) -> None: + self.path = path + self.profile = profile + self.buffered = buffered + owned: List[int] = [] + self._finalizer = weakref.finalize(self, _close_all, owned) + self.direct_fd = _open_direct(path) if profile.direct else None + if self.direct_fd is not None: + owned.append(self.direct_fd) + mine, theirs = os.fstat(self.direct_fd), os.fstat(buffered) + if (mine.st_dev, mine.st_ino) != (theirs.st_dev, theirs.st_ino): + self.close() + raise Unsupported(f"'{path}' is no longer the file HDF5 opened") + self.use_direct = self.direct_fd is not None + + @property + def direct(self) -> bool: + return self.use_direct + + def fd_for(self, offset: int, view: np.ndarray) -> int: + """The descriptor to read `view` at `offset` with: O_DIRECT while the + offset, the address and the length are all aligned.""" + if ( + self.use_direct + and offset % ALIGN == 0 + and view.nbytes % ALIGN == 0 + and view.ctypes.data % ALIGN == 0 + ): + return self.direct_fd + return self.buffered + + def refuse_direct(self) -> None: + """Read through the page cache from now on: the filesystem took + O_DIRECT at open but refuses it on read.""" + self.use_direct = False + + def close(self) -> None: + """Close what the reader opened; HDF5 closes its own.""" + self._finalizer() + + +def _aligned(nbytes: int) -> np.ndarray: + """`nbytes` of uninitialised memory starting on a 4 KiB boundary.""" + raw = np.empty(int(nbytes) + ALIGN, dtype=np.uint8) + shift = (-raw.ctypes.data) % ALIGN + return raw[shift : shift + int(nbytes)] + + +def _read_request(source: _Source, view: np.ndarray, offset: int, need: int) -> int: + """Fill `view` from the file at `offset`; the bytes read. + + A short read is retried for the rest. The file may end before the view + does -- its length is rounded up to a page -- but not before `need` + bytes. An O_DIRECT read past the end returns what there was, unaligned, + and the rest is asked of the page cache, which says the file has ended. + """ + total = int(view.nbytes) + got = 0 + while got < total: + part = view[got:] + at = offset + got + fd = source.fd_for(at, part) + try: + n = os.preadv(fd, [part], at) + except OSError as error: + if fd == source.direct_fd and error.errno == errno.EINVAL: + source.refuse_direct() + continue + raise OSError( + error.errno, f"Could not read '{source.path}' at byte {at}: {error.strerror}" + ) from error + if n <= 0: + break + got += n + if got < need: + raise OSError( + errno.EIO, + f"Could not read '{source.path}': it ends at byte {offset + got}, " + f"before byte {offset + need}", + ) + return got + + +def _request(source: _Source, view: np.ndarray, offset: int, need: int, held: int) -> None: + try: + _read_request(source, view, offset, need) + finally: + if held: + _BUDGET.release(held) + + +class _Latch: + """Runs `done` once every request of a run has arrived, then gives the + run's bytes back to the budget.""" + + def __init__(self, count: int, done: Callable[[], None], held: int) -> None: + self.count = count + self.done = done + self.held = held + self.failed = False + self._lock = threading.Lock() + + def arrive(self, ok: bool) -> None: + with self._lock: + self.count -= 1 + self.failed = self.failed or not ok + last = self.count == 0 + if not last: + return + try: + if not self.failed: + self.done() + finally: + self.done = None + _BUDGET.release(self.held) + + +def _latched(source: _Source, view: np.ndarray, offset: int, need: int, latch: _Latch) -> None: + ok = False + try: + _read_request(source, view, offset, need) + ok = True + finally: + latch.arrive(ok) + + +def read_runs( + source: _Source, + runs: Sequence[Tuple[int, int]], + *, + on_run: Optional[Callable[[int, np.ndarray], None]] = None, + reserved: bool = False, +) -> Optional[List[np.ndarray]]: + """Read byte ranges `[start, end)` of a file, `request_bytes` at a time + on the I/O pool. + + Without `on_run`, the bytes of each run, one buffer each: the caller's, + each request holding room in the budget while it is in flight (none + when `reserved`, for read-ahead, which holds room for all of it). + With `on_run`, `on_run(i, bytes)` is called on an I/O thread once run + `i` has arrived, and its buffer is dropped: the run holds room until + then. An error in any request is raised here, once every request + started has finished. + """ + profile = source.profile + step = profile.request_bytes + pool = _io_pool(profile.in_flight) + results: Optional[List[np.ndarray]] = [] if on_run is None else None + futures: List[Future] = [] + try: + for index, (start, end) in enumerate(runs): + start, end = int(start), int(end) + first = start - start % ALIGN + last = -(-end // ALIGN) * ALIGN + buffer = _aligned(last - first) + wanted = buffer[start - first : end - first] + pieces = [(at, min(at + step, last)) for at in range(first, last, step)] + if on_run is None: + results.append(wanted) + for at, stop in pieces: + held = 0 if reserved else _BUDGET.acquire(stop - at) + futures.append(pool.submit( + _request, source, buffer[at - first : stop - first], at, + min(stop, end) - at, held, + )) + continue + held = _BUDGET.acquire(last - first) + latch = _Latch( + len(pieces), + (lambda i=index, w=wanted: on_run(i, w)), + held, + ) + for at, stop in pieces: + futures.append(pool.submit( + _latched, source, buffer[at - first : stop - first], at, + min(stop, end) - at, latch, + )) + finally: + wait(futures) + for future in futures: + error = future.exception() + if error is not None: + raise error + return results + + +# --------------------------------------------------------------------------- +# Datasets + + +def _prod(values: Sequence[int]) -> int: + total = 1 + for value in values: + total *= int(value) + return total + + +class ChunkMap: + """Where a dataset's rows lie in its file, built once per dataset. + + Raises `Unsupported` for a dataset the reader leaves to h5py. + """ + + def __init__(self, ds: h5py.Dataset, engine: "Engine") -> None: + self.engine = engine + self.name = ds.name + shape = ds.shape + if shape is None or len(shape) not in (1, 2): + raise Unsupported("not one or two dimensions") + dtype = ds.dtype + if dtype.names is not None or dtype.subdtype is not None or dtype.kind not in "biuf": + raise Unsupported(f"dtype {dtype}") + if h5py.check_vlen_dtype(dtype) is not None: + raise Unsupported("variable length") # pragma: no cover - kind O + ftype = ds.id.get_type() + if ftype.get_size() != dtype.itemsize or ftype != h5py.h5t.py_create(dtype): + # HDF5 converts on read: an int24, a custom float, an enum + # other than bool. The bytes are not numpy's. + raise Unsupported("file type is not numpy's") + plist = ds.id.get_create_plist() + if plist.get_nfilters(): + raise Unsupported("filtered") + if plist.get_external_count(): + raise Unsupported("external storage") + self.shape = tuple(int(n) for n in shape) + # As h5py's arrays spell it: a native byte order is `=`, where + # h5py's own dtype says `<`. + self.dtype = np.dtype(dtype.str) + self.itemsize = int(dtype.itemsize) + self.rows = self.shape[0] + self.row_bytes = _prod(self.shape[1:]) * self.itemsize + layout = plist.get_layout() + if layout == h5py.h5d.CONTIGUOUS: + offset = ds.id.get_offset() + if offset is None: + raise Unsupported("never written") + if ds.id.get_storage_size() < self.rows * self.row_bytes: + raise Unsupported("storage smaller than the data") # pragma: no cover + self.contiguous = True + self.offset = int(offset) + elif layout == h5py.h5d.CHUNKED: + self.contiguous = False + self._map_chunks(ds) + else: + raise Unsupported("compact or virtual layout") + + def _map_chunks(self, ds: h5py.Dataset) -> None: + """Runs of chunks adjacent in the file: `(first, address, count)`, + `first` a chunk's index in the grid read row by row.""" + chunks = tuple(int(c) for c in ds.chunks) + grid = tuple(-(-n // c) for n, c in zip(self.shape, chunks)) + chunk_bytes = _prod(chunks) * self.itemsize + across = grid[1] if len(grid) > 1 else 1 + with _MAP_LOCK: + room = (MAP_BYTES - _MAPS["bytes"]) // RUN_BYTES + runs = np.empty((min(max(room, 1), 1024), 3), dtype=np.int64) + state = {"n": 0, "first": -1, "at": -1, "count": 0, "refused": None} + + def flush() -> bool: + n = state["n"] + if state["count"] == 0: + return True + if n >= room: + state["refused"] = "its chunk map would not fit in MAP_BYTES" + return False + nonlocal runs + if n == runs.shape[0]: + runs = np.concatenate([runs, np.empty_like(runs)])[: min(2 * n, room)] + runs[n] = (state["first"], state["at"], state["count"]) + state["n"] = n + 1 + return True + + def visit(info: Any) -> Optional[bool]: + if info.size != chunk_bytes or info.filter_mask: + state["refused"] = "a chunk of an unexpected size" + return True + index = tuple(o // c for o, c in zip(info.chunk_offset, chunks)) + if not all(i < g for i, g in zip(index, grid)): + return None # beyond the dataset's extent + linear = index[0] * across + (index[1] if len(index) > 1 else 0) + count = state["count"] + if ( + count + and linear == state["first"] + count + and info.byte_offset == state["at"] + count * chunk_bytes + ): + state["count"] = count + 1 + return None + if not flush(): + return True + state.update(first=linear, at=info.byte_offset, count=1) + return None + + if all(grid): + ds.id.chunk_iter(visit) + if state["refused"] is None: + flush() + if state["refused"] is not None: + raise Unsupported(state["refused"]) + runs = runs[: state["n"]] + runs = runs[np.argsort(runs[:, 0], kind="stable")].copy() + with _MAP_LOCK: + if _MAPS["bytes"] + runs.nbytes > MAP_BYTES: + raise Unsupported("its chunk map would not fit in MAP_BYTES") + _MAPS["bytes"] += runs.nbytes + self.map_bytes = runs.nbytes + self.runs = runs + self.chunks = chunks + self.grid = grid + self.across = across + self.chunk_bytes = chunk_bytes + self.fill = ds.fillvalue + # Rows run on from one chunk into the next only where a chunk is + # the full width of the array. + self.full_width = len(chunks) == 1 or chunks[1] == self.shape[1] + + def addresses(self, first: int, last: int) -> np.ndarray: + """The file address of each chunk `first` to `last - 1`, in the + grid read row by row; -1 for one never written.""" + out = np.full(max(0, last - first), -1, dtype=np.int64) + if not self.runs.size or last <= first: + return out + starts = self.runs[:, 0] + i0 = max(0, int(np.searchsorted(starts, first, side="right")) - 1) + i1 = int(np.searchsorted(starts, last, side="left")) + for begin, at, count in self.runs[i0:i1].tolist(): + lo, hi = max(begin, first), min(begin + count, last) + if hi > lo: + out[lo - first : hi - first] = at + (np.arange(lo, hi) - begin) * self.chunk_bytes + return out + + def release(self) -> None: + """Give the map's bytes back to `MAP_BYTES`.""" + with _MAP_LOCK: + _MAPS["bytes"] -= getattr(self, "map_bytes", 0) + self.map_bytes = 0 + + def result_bytes(self, start: int, stop: int) -> int: + return max(0, stop - start) * self.row_bytes + + def fetch(self, start: int, stop: int, *, ahead: bool = False) -> np.ndarray: + """Rows `[start, stop)`, as h5py would return them.""" + n = max(0, stop - start) + shape = (n,) + self.shape[1:] + if n == 0 or self.row_bytes == 0: + return np.empty(shape, dtype=self.dtype) + if self.contiguous: + begin = self.offset + start * self.row_bytes + return self._one_run(begin, begin + n * self.row_bytes, shape, ahead) + height = self.chunks[0] + k0, k1 = start // height, (stop - 1) // height + if self.full_width: + run = self.addresses(k0, k1 + 1) + if (run >= 0).all() and (run.size == 1 or (np.diff(run) == self.chunk_bytes).all()): + row_bytes = self.chunks[1] * self.itemsize if len(self.chunks) > 1 else self.itemsize + begin = int(run[0]) + (start - k0 * height) * row_bytes + return self._one_run(begin, begin + n * row_bytes, shape, ahead) + return self._assemble(start, stop, shape, k0, k1) + + def _one_run(self, begin: int, end: int, shape: tuple, ahead: bool) -> np.ndarray: + """Rows that are one run of the file, in order: read into the result.""" + buffer = read_runs(self.engine.source, [(begin, end)], reserved=ahead)[0] + values = buffer.view(self.dtype).reshape(shape) + # HDF5 does not align a dataset's bytes in its file; numpy, and + # what it hands them to, expects them aligned in memory. + return values if values.flags.aligned else values.copy() + + def _assemble(self, start: int, stop: int, shape: tuple, k0: int, k1: int) -> np.ndarray: + """Rows from chunks out of order, or tiles: each chunk's part copied + into place as its bytes arrive. + + Only the rows of each chunk that the block holds are read, a + contiguous stretch of it, in segments of at most a request, and + segments near each other in the file are read together. No buffer + is larger than a request, whatever the size of a chunk, so what + the budget counts is what is held. + """ + out = np.empty(shape, dtype=self.dtype) + height = self.chunks[0] + width = self.chunks[1] if len(self.chunks) > 1 else 1 + span = self.engine.profile.request_bytes - 2 * ALIGN + most = max(1, span // self.itemsize) # elements a segment + block = self.addresses(k0 * self.across, (k1 + 1) * self.across).reshape(-1, self.across) + segments = [] + for (i, kc), where in np.ndenumerate(block): + kr = k0 + i + lo, hi = max(start, kr * height), min(stop, (kr + 1) * height) + if where < 0: + rows = slice(lo - start, hi - start) + if len(self.chunks) == 1: + out[rows] = self.fill + else: + out[rows, kc * width : min(self.shape[1], (kc + 1) * width)] = self.fill + continue + first, last = (lo - kr * height) * width, (hi - kr * height) * width + for a in range(first, last, most): + b = min(a + most, last) + where = int(where) + segments.append((where + a * self.itemsize, where + b * self.itemsize, kr, kc, a)) + segments.sort() + # Pieces of segments in file order, spanning at most a request, + # reading through any gap of up to `GAP_BYTES` between them. + pieces: List[List[tuple]] = [] + for segment in segments: + piece = pieces[-1] if pieces else None + if ( + piece is not None + and segment[0] - piece[-1][1] <= GAP_BYTES + and segment[1] - piece[0][0] <= span + ): + piece.append(segment) + else: + pieces.append([segment]) + + def place(index: int, data: np.ndarray) -> None: + piece = pieces[index] + origin = piece[0][0] + for begin, end, kr, kc, element in piece: + values = data[begin - origin : end - origin].view(self.dtype) + self._put(out, values, kr, kc, element, start) + + if pieces: + read_runs( + self.engine.source, [(p[0][0], p[-1][1]) for p in pieces], on_run=place + ) + return out + + def _put( + self, out: np.ndarray, values: np.ndarray, kr: int, kc: int, element: int, start: int + ) -> None: + """Put `values`, a chunk's elements from `element` on in the order + they are stored, where they belong in `out`, whose first row is + `start`.""" + height = self.chunks[0] + base = kr * height - start + if len(self.chunks) == 1: + out[base + element : base + element + values.size] = values + return + width = self.chunks[1] + left = kc * width + valid = min(self.shape[1], left + width) - left + row, column = divmod(element, width) + at = 0 + if column: + # The rest of a row a segment before began. + part = values[: width - column] + hi = min(column + part.size, valid) + if hi > column: + out[base + row, left + column : left + hi] = part[: hi - column] + at, row = part.size, row + 1 + whole = (values.size - at) // width + if whole: + tile = values[at : at + whole * width].reshape(whole, width) + out[base + row : base + row + whole, left : left + valid] = tile[:, :valid] + at, row = at + whole * width, row + whole + if at < values.size: + part = values[at:] + hi = min(part.size, valid) + out[base + row, left : left + hi] = part[:hi] + + +class _Stream: + """A dataset's read-ahead: where the last read ended, and the rows read + ahead of the next.""" + + def __init__(self) -> None: + self.end: Optional[int] = None + self.pending: Optional[Tuple[int, int, Future, int]] = None + + def take(self, start: int, stop: int, stats: dict) -> Optional[np.ndarray]: + """The rows `[start, stop)` from the read-ahead, or None.""" + pending, self.pending = self.pending, None + if pending is None: + return None + first, last, future, held = pending + if first <= start and stop <= last: + try: + rows = future.result() + finally: + _BUDGET.release(held, ahead=True) + stats["hits"] += 1 + if (first, last) == (start, stop): + return rows + return rows[start - first : stop - first].copy() + stats["misses"] += 1 + future.add_done_callback(lambda _: _BUDGET.release(held, ahead=True)) + return None + + def read_ahead(self, cmap: ChunkMap, start: int, stop: int) -> Optional[Future]: + """Start reading rows `[start, stop)`, if the budget has room.""" + held = cmap.result_bytes(start, stop) + if held <= 0 or not _BUDGET.try_ahead(held): + return None + try: + future = _ahead_pool().submit(cmap.fetch, start, stop, ahead=True) + except BaseException: # pragma: no cover - a pool shut down at exit + _BUDGET.release(held, ahead=True) + raise + self.pending = (start, stop, future, held) + return future + + def drop(self) -> None: + pending, self.pending = self.pending, None + if pending is not None: + wait([pending[2]]) + _BUDGET.release(pending[3], ahead=True) + + +class Engine: + """The reader for one open file: its descriptors, its datasets' chunk + maps, and their read-ahead.""" + + def __init__(self, handle: h5py.File, path: str, profile: IOProfile, fstype: str) -> None: + if not hasattr(os, "preadv"): # pragma: no cover - Windows + raise Unsupported("no os.preadv") + if handle.mode != "r": + raise Unsupported("not opened read-only") + if handle.driver != "sec2": + raise Unsupported(f"HDF5 driver {handle.driver}") + if handle.userblock_size: + raise Unsupported("a userblock") + try: + fd = int(handle.id.get_vfd_handle()) + except Exception as error: # pragma: no cover - a driver without one + raise Unsupported("no file descriptor") from error + self.path = path + self.profile = profile + self.fstype = fstype + self.source = _Source(path, profile, fd) + self.maps: Dict[Any, Optional[ChunkMap]] = {} + self.streams: Dict[ChunkMap, _Stream] = {} + self.stats = {"hits": 0, "misses": 0} + #: Read-ahead still running, used or not: waited for on close, so + #: none reads a descriptor that has been closed. + self.outstanding: set = set() + self._lock = threading.Lock() + _BUDGET.set_limit(profile.buffer_bytes) + + def chunk_map(self, ds: h5py.Dataset) -> Optional[ChunkMap]: + """`ds`'s chunk map, built the first time it is read; None for a + dataset the reader leaves to h5py (`Unsupported`), which is not + asked again.""" + key = ds.id + if key not in self.maps: + try: + self.maps[key] = ChunkMap(ds, self) + except Unsupported: + self.maps[key] = None + return self.maps[key] + + def read(self, cmap: ChunkMap, start: int, stop: int) -> np.ndarray: + with self._lock: + stream = self.streams.setdefault(cmap, _Stream()) + rows = stream.take(start, stop, self.stats) + if rows is None: + rows = cmap.fetch(start, stop) + if start == stream.end and start < stop < cmap.rows: + future = stream.read_ahead(cmap, stop, min(cmap.rows, stop + (stop - start))) + if future is not None: + self.outstanding.add(future) + future.add_done_callback(self.outstanding.discard) + stream.end = stop + return rows + + def close(self) -> None: + with self._lock: + for stream in self.streams.values(): + stream.drop() + wait(list(self.outstanding)) + self.outstanding.clear() + self.streams.clear() + for cmap in self.maps.values(): + if cmap is not None: + cmap.release() + self.maps.clear() + self.source.close() + + +def read_rows(cmap: ChunkMap, start: int, stop: int) -> np.ndarray: + """Rows `[start, stop)` of a dataset, exactly as `ds[start:stop]` + returns them: the one entry point of every read the engine makes for a + caller (`tests/perf_counters.py` counts it).""" + return cmap.engine.read(cmap, int(start), int(stop)) + + +def _row_range(args: Any, shape: Optional[tuple]) -> Optional[Tuple[int, int]]: + """`(start, stop)` if `args` selects rows `[start, stop)` along the first + axis, step 1, and every other axis whole; otherwise None.""" + if not shape: + return None + keys = args if isinstance(args, tuple) else (args,) + if not keys: + return 0, int(shape[0]) + first, rest = keys[0], keys[1:] + if first is Ellipsis: + return (0, int(shape[0])) if not rest else None + if not isinstance(first, slice) or first.step not in (None, 1): + return None + named = [k for k in rest if k is not Ellipsis] + if len(named) > len(shape) - 1 or sum(k is Ellipsis for k in rest) > 1: + return None + for key, extent in zip(named, shape[1:]): + if not isinstance(key, slice) or key.indices(int(extent)) != (0, int(extent), 1): + return None + try: + start, stop, _ = first.indices(int(shape[0])) + except TypeError: + return None + return start, max(start, stop) + + +# --------------------------------------------------------------------------- +# h5py objects that read through the engine + + +def _wrap(obj: Any, engine: Engine) -> Any: + if type(obj) is h5py.Dataset: + wrapped = DirectDataset(obj.id) + elif type(obj) is h5py.Group: + wrapped = DirectGroup(obj.id) + else: + return obj + wrapped._adata_engine = engine + return wrapped + + +class _Wrapping: + """Hands out members as the classes below, bound to the same engine: + by `group[name]` and `group.get(name)` alike, and so by `values()`, + `items()` and `visititems()`, which h5py builds on them.""" + + _adata_engine: Engine + + def _get(self, name: Any, lapl: Any = None) -> Any: + return _wrap(super()._get(name, lapl), self._adata_engine) + + def __getitem__(self, name: Any) -> Any: + return _wrap(super().__getitem__(name), self._adata_engine) + + +class DirectGroup(_Wrapping, h5py.Group): + """An h5py group whose datasets read through the engine.""" + + +class DirectDataset(h5py.Dataset): + """An h5py dataset whose row slices read through the engine. + + `ds[a:b]`, `ds[a:b, :]`, `ds[a:b, ...]`, `ds[:]`, `ds[...]` and `ds[()]` + go to `read_rows`; anything else -- fancy indexing, a step, a column + slice, a field, `astype` -- and every dataset the engine refuses goes to + h5py. + """ + + _adata_engine: Engine + + def __getitem__(self, args: Any, new_dtype: Any = None) -> Any: + if new_dtype is None: + rows = _row_range(args, self.shape) + if rows is not None: + cmap = self._adata_engine.chunk_map(self) + if cmap is not None: + return read_rows(cmap, *rows) + return super().__getitem__(args) + return super().__getitem__(args, new_dtype) + + +class DirectFile(_Wrapping, h5py.File): + """An HDF5 file opened `"r"`, its datasets read through the engine.""" + + def close(self) -> None: + engine = self.__dict__.get("_adata_engine") + try: + if engine is not None: + engine.close() + finally: + super().close() + + +def engine_of(obj: Any) -> Optional[Engine]: + """The engine `obj` reads through, or None for h5py.""" + return getattr(obj, "_adata_engine", None) + + +def block_bytes(obj: Any, default: int) -> int: + """The least a streamed block of `obj` should read: `default`, raised to + half the engine's buffer when the engine reads it, so that each block + keeps its requests in flight.""" + engine = engine_of(obj) + if engine is None: + return default + return max(default, engine.profile.buffer_bytes // 2) + + +def open_file(path: os.PathLike, **kwargs: Any) -> h5py.File: + """`h5py.File(path, "r", **kwargs)`, read through the engine when the + chosen reader (`io_mode`) applies to the file: a `DirectFile` then, + else a plain `h5py.File`.""" + profile, fstype = profile_for(path) + handle = h5py.File(path, "r", **kwargs) + if profile is None: + return handle + try: + engine = Engine(handle, str(Path(path)), profile, fstype) + except (Unsupported, OSError): + # Whatever stops the reader leaves h5py, which opened the file. + return handle + except BaseException: + handle.close() + raise + direct = DirectFile(handle.id) + direct._adata_engine = engine + _announce(describe(engine)) + return direct diff --git a/tests/conftest.py b/tests/conftest.py index 221cf3f..2a49f18 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -14,6 +14,18 @@ import numpy as np +@pytest.fixture(autouse=True) +def _reader_left_as_found(): + """Each test starts with no `--io` chosen. The CLI chooses the reader + for the process (`rawio.set_mode`), and CliRunner runs commands in + this one, so a choice would otherwise outlive the test that made it.""" + yield + from adata.storage import rawio + + rawio.set_mode(None) + rawio.set_reporter(None) + + @pytest.fixture def temp_dir(): """Create a temporary directory for test files.""" diff --git a/tests/perf_counters.py b/tests/perf_counters.py index b94cff8..bb2b680 100644 --- a/tests/perf_counters.py +++ b/tests/perf_counters.py @@ -93,6 +93,15 @@ class IOCounts: store_set: int = 0 store_set_bytes: int = 0 store_delete: int = 0 + #: Reads the direct-I/O reader served (`rawio.read_rows`), and the + #: elements they returned: counted in `elements` and `calls` beside + #: h5py's, since they stand in for h5py's reads. + direct_calls: int = 0 + direct_elements: int = 0 + #: Requests that reader made of the file (`rawio._read_request`, on its + #: threads), and the bytes they asked for. + direct_requests: int = 0 + direct_request_bytes: int = 0 #: Bytes the reads handed back, through either backend. read_bytes: int = 0 @@ -112,6 +121,9 @@ class IOCounts: #: The largest read per dataset, in bytes and in elements. largest_by_name: Dict[str, int] = field(default_factory=dict) largest_elements_by_name: Dict[str, int] = field(default_factory=dict) + #: Elements h5py itself read, per dataset: what the direct reader left + #: to it. + h5_by_name: Dict[str, int] = field(default_factory=dict) #: Bytes written, and whole units encoded, per array: a writer's own #: output apart from its scratch. written_by_name: Dict[str, int] = field(default_factory=dict) @@ -120,11 +132,11 @@ class IOCounts: @property def elements(self) -> int: """Elements read through either backend's array interface.""" - return self.h5_elements + self.zarr_elements + return self.h5_elements + self.zarr_elements + self.direct_elements @property def calls(self) -> int: - return self.h5_calls + self.zarr_calls + return self.h5_calls + self.zarr_calls + self.direct_calls @property def writes(self) -> int: @@ -365,8 +377,14 @@ def count_io() -> Iterator[IOCounts]: ``zarr.Group.create_array`` Zarr writes made at creation ``zarr.storage.LocalStore.get`` chunk and metadata fetches ``LocalStore.set`` / ``.delete`` write storms + ``adata.storage.rawio.read_rows`` the direct-I/O reader's reads + ``adata.storage.rawio._read_request`` its requests of the file ====================================== ================================= + The direct reader (`--io direct`) reads uncompressed HDF5 datasets + without h5py: what it hands back counts as a read like h5py's, whole + (nothing is decoded), and its requests are counted apart. + Both HDF5 write seams are needed: `create_dataset(name, data=...)` writes its payload during creation and never touches `__setitem__`, so hooking only the latter leaves `import` and `create` measuring zero. Zarr's array @@ -379,13 +397,18 @@ def count_io() -> Iterator[IOCounts]: The `LocalStore` methods are coroutines and are wrapped as coroutines. """ + import threading + import h5py import zarr from zarr.core.indexing import OIndex from zarr.storage import LocalStore + from adata.storage import rawio + counts = IOCounts() cache = _ChunkCache() + requests_lock = threading.Lock() h5_get = h5py.Dataset.__getitem__ h5_set = h5py.Dataset.__setitem__ @@ -397,6 +420,8 @@ def count_io() -> Iterator[IOCounts]: store_get = LocalStore.get store_set = LocalStore.set store_delete = LocalStore.delete + direct_get = rawio.read_rows + direct_request = rawio._read_request def _record(name: str, n: int) -> None: counts.by_name[name] = counts.by_name.get(name, 0) + n @@ -427,9 +452,35 @@ def _write(array: Any, key: Any, value: Any) -> None: def h5_wrapper(self: Any, key: Any) -> Any: result = h5_get(self, key) counts.h5_calls += 1 - counts.h5_elements += _read(self, key, result, getattr(self, "name", "?")) + name = getattr(self, "name", "?") + n = _read(self, key, result, name) + counts.h5_elements += n + counts.h5_by_name[name] = counts.h5_by_name.get(name, 0) + n return result + def direct_wrapper(cmap: Any, start: int, stop: int) -> Any: + result = direct_get(cmap, start, stop) + name = str(cmap.name) + n = _size(result) + returned = _nbytes(result) + counts.direct_calls += 1 + counts.direct_elements += n + counts.read_bytes += returned + counts.decoded_bytes += returned # unfiltered: read as it is + counts.largest_read = max(counts.largest_read, returned) + counts.largest_by_name[name] = max(counts.largest_by_name.get(name, 0), returned) + counts.largest_elements_by_name[name] = max( + counts.largest_elements_by_name.get(name, 0), n + ) + _record(name, n) + return result + + def request_wrapper(source: Any, view: Any, offset: int, need: int) -> int: + with requests_lock: + counts.direct_requests += 1 + counts.direct_request_bytes += int(view.nbytes) + return direct_request(source, view, offset, need) + def zarr_wrapper(self: Any, key: Any) -> Any: result = zarr_get(self, key) counts.zarr_calls += 1 @@ -506,6 +557,8 @@ async def delete_wrapper(self: Any, *args: Any, **kwargs: Any) -> Any: (LocalStore, "get", store_get, get_wrapper), (LocalStore, "set", store_set, set_wrapper), (LocalStore, "delete", store_delete, delete_wrapper), + (rawio, "read_rows", direct_get, direct_wrapper), + (rawio, "_read_request", direct_request, request_wrapper), ] for owner, name, _, wrapper in patched: setattr(owner, name, wrapper) diff --git a/tests/test_direct_io_cli.py b/tests/test_direct_io_cli.py new file mode 100644 index 0000000..dc8e7c4 --- /dev/null +++ b/tests/test_direct_io_cli.py @@ -0,0 +1,283 @@ +"""Every command that reads a store gives the same output through the +direct-I/O reader (`ADATA_IO=direct`) as through h5py (`--io h5py`), and +both are what anndata computes. + +The reader serves only HDF5 inputs; on Zarr inputs `--io direct` must +change nothing, which the same test bodies check. Blocks are kept small +(`SPARSE_BLOCK_BYTES`, `ADATA_IO_BUFFER`), so a matrix is read in several +and read-ahead is used. +""" + +from __future__ import annotations + +import re +from pathlib import Path +from typing import Any, Dict + +import h5py +import numpy as np +import pytest +from typer.testing import CliRunner + +from adata.cli import app +from adata.core import subset as subset_module +from tests.conftest import backend_path, backend_zarr_format + +ad = pytest.importorskip("anndata") +pd = pytest.importorskip("pandas") +sparse = pytest.importorskip("scipy.sparse") +mmread = pytest.importorskip("scipy.io").mmread + +runner = CliRunner() +_ANSI = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]") +MODES = ("direct", "h5py") +STATUS = "direct reader" + + +def _out(result) -> str: + text = result.stdout + (result.stderr or "") + return " ".join(_ANSI.sub("", text).split()) + + +@pytest.fixture(autouse=True) +def _small_blocks(monkeypatch): + monkeypatch.setattr(subset_module, "SPARSE_BLOCK_BYTES", 1) + monkeypatch.setenv("ADATA_IO_BUFFER", "1M") + + +def run(mode: str, *args: Any): + """`adata *args` with the reader `mode`, which must succeed.""" + result = runner.invoke(app, [str(a) for a in args], env={"ADATA_IO": mode}) + assert result.exit_code == 0, _out(result) + return result + + +def _object(n_obs: int = 3000, n_var: int = 400, seed: int = 0, prefix: str = "c") -> Any: + rng = np.random.default_rng(seed) + counts = sparse.random( + n_obs, n_var, density=0.08, format="csr", random_state=seed, + data_rvs=lambda k: rng.integers(1, 50, k), + ).astype(np.float32) + obj = ad.AnnData( + X=counts, + obs=pd.DataFrame( + { + "cluster": pd.Categorical(rng.choice(["A", "B", "C"], n_obs)), + "n_counts": np.asarray(counts.sum(axis=1)).ravel(), + "label": [f"cell {i} [x]" for i in range(n_obs)], + }, + index=[f"{prefix}{i}" for i in range(n_obs)], + ), + var=pd.DataFrame( + { + "gene_ids": [f"ENSG{i:05d}" for i in range(n_var)], + "feature_types": ["Gene Expression"] * n_var, + "highly_variable": rng.random(n_var) > 0.5, + }, + index=[f"g{i}" for i in range(n_var)], + ), + ) + obj.layers["counts"] = sparse.csr_matrix(counts.astype(np.int32)) + obj.layers["dense"] = counts.toarray()[:, :50].repeat(8, axis=1).astype(">f8") + obj.obsm["X_pca"] = rng.random((n_obs, 6)) + return obj + + +def _write(obj: Any, tmp_path: Path, backend: str, stem: str = "src") -> Path: + path = backend_path(tmp_path, backend, stem) + if backend == "h5ad": + obj.write_h5ad(path) + else: + with ad.settings.override(zarr_write_format=backend_zarr_format(backend)): + obj.write_zarr(path) + return path + + +def _read(path: Path) -> Any: + return ad.read_zarr(path) if path.suffix == ".zarr" else ad.read_h5ad(path) + + +def _same_matrix(got: Any, want: Any) -> None: + assert got.shape == want.shape + # Zarr v3 writes big-endian values little-endian; the values are what + # count here (`test_rawio` holds HDF5 reads to the byte order). + assert np.dtype(got.dtype).str[1:] == np.dtype(want.dtype).str[1:] + if sparse.issparse(want): + assert sparse.issparse(got) and got.format == want.format + assert (got != want).nnz == 0 + else: + assert np.array_equal(np.asarray(got), np.asarray(want)) + + +def _same(got: Any, want: Any) -> None: + assert list(got.obs_names) == list(want.obs_names) + assert list(got.var_names) == list(want.var_names) + _same_matrix(got.X, want.X) + assert set(got.layers) == set(want.layers) + for key in want.layers: + _same_matrix(got.layers[key], want.layers[key]) + for key in want.obsm: + _same_matrix(got.obsm[key], want.obsm[key]) + pd.testing.assert_frame_equal(got.obs, want.obs, check_categorical=False) + pd.testing.assert_frame_equal(got.var, want.var, check_categorical=False) + + +def _both(tmp_path: Path, backend: str, name: str, *args: Any) -> Dict[str, Path]: + """Run `args` once per reader, output `name` in a folder of its own; + the outputs by reader.""" + outputs = {} + for mode in MODES: + folder = tmp_path / mode + folder.mkdir(exist_ok=True) + out = folder / name + result = run(mode, *[out if a == "{out}" else a for a in args]) + hdf5_input = any(str(a).endswith((".h5ad", ".h5")) and Path(str(a)).exists() for a in args) + assert (STATUS in _out(result)) == (mode == "direct" and hdf5_input) + outputs[mode] = out + return outputs + + +@pytest.fixture +def source(tmp_path, backend): + obj = _object() + return obj, _write(obj, tmp_path, backend) + + +def test_subset_by_obs_is_the_same_through_either_reader(tmp_path, source, backend): + obj, path = source + names = tmp_path / "names.txt" + names.write_text("\n".join(obj.obs_names[::3])) + want = obj[obj.obs_names.isin(obj.obs_names[::3])].copy() + ext = path.suffix + for out in _both(tmp_path, backend, f"out{ext}", "subset", path, "-o", "{out}", "--obs", names).values(): + _same(_read(out), want) + + +def test_subset_by_var_is_the_same_through_either_reader(tmp_path, source, backend): + obj, path = source + names = tmp_path / "names.txt" + names.write_text("\n".join(obj.var_names[1::2])) + want = obj[:, obj.var_names.isin(obj.var_names[1::2])].copy() + for out in _both(tmp_path, backend, f"out{path.suffix}", "subset", path, "-o", "{out}", + "--var", names).values(): + _same(_read(out), want) + + +def test_split_is_the_same_through_either_reader(tmp_path, source, backend): + obj, path = source + for folder in _both(tmp_path, backend, "parts", "split", path, "--by", "cluster", + "-o", "{out}").values(): + for label in ("A", "B", "C"): + want = obj[obj.obs["cluster"] == label].copy() + _same(_read(folder / f"{label}{path.suffix}"), want) + + +def test_convert_to_zarr_is_the_same_through_either_reader(tmp_path, source, backend): + obj, path = source + for out in _both(tmp_path, backend, "out.zarr", "convert", path, "-o", "{out}").values(): + _same(_read(out), obj) + + +def test_convert_to_a_10x_matrix_is_the_same_through_either_reader(tmp_path, source, backend): + obj, path = source + outputs = _both(tmp_path, backend, "out.h5", "convert", path, "-o", "{out}", "--layer", "counts") + with h5py.File(outputs["direct"], "r") as a, h5py.File(outputs["h5py"], "r") as b: + for name in ("data", "indices", "indptr", "shape", "barcodes", "features/id"): + assert np.array_equal(a[f"matrix/{name}"][...], b[f"matrix/{name}"][...]), name + n_features, n_barcodes = a["matrix/shape"][...] + x = sparse.csc_matrix( + (a["matrix/data"][...], a["matrix/indices"][...], a["matrix/indptr"][...]), + shape=(n_features, n_barcodes), + ) + assert (x.T.tocsr() != obj.layers["counts"]).nnz == 0 + + +def test_export_sparse_is_the_same_through_either_reader(tmp_path, source, backend): + obj, path = source + outputs = _both(tmp_path, backend, "x.mtx", "export", "sparse", path, "X", "-o", "{out}") + assert outputs["direct"].read_bytes() == outputs["h5py"].read_bytes() + assert (sparse.csr_matrix(mmread(outputs["direct"])) != obj.X).nnz == 0 + + +def test_export_dataframe_is_the_same_through_either_reader(tmp_path, source, backend): + obj, path = source + outputs = _both(tmp_path, backend, "obs.csv", "export", "dataframe", path, "obs", "-o", "{out}") + assert outputs["direct"].read_bytes() == outputs["h5py"].read_bytes() + got = pd.read_csv(outputs["direct"], index_col=0) + assert list(got.index) == list(obj.obs_names) + assert list(got["label"]) == list(obj.obs["label"]) + assert np.allclose(got["n_counts"], obj.obs["n_counts"]) + + +def test_concat_is_the_same_through_either_reader(tmp_path, source, backend): + obj, path = source + other = _object(n_obs=1700, seed=1, prefix="d") + second = _write(other, tmp_path, backend, "second") + want = ad.concat([obj, other]) + for out in _both(tmp_path, backend, f"out{path.suffix}", "concat", path, second, + "-o", "{out}").values(): + got = _read(out) + assert list(got.obs_names) == list(want.obs_names) + _same_matrix(got.X, want.X) + for key in want.layers: + _same_matrix(got.layers[key], want.layers[key]) + _same_matrix(got.obsm["X_pca"], want.obsm["X_pca"]) + + +@pytest.mark.parametrize( + "flags", [("--layout", "csc"), ("--dtype", "float64"), ("--layout", "dense", "--force")] +) +def test_recast_is_the_same_through_either_reader(tmp_path, source, backend, flags): + obj, path = source + want = { + "csc": lambda x: x.tocsc(), + "float64": lambda x: x.astype(np.float64), + "dense": lambda x: x.toarray(), + }[flags[1]](obj.X) + for out in _both(tmp_path, backend, f"out{path.suffix}", "recast", path, "X", "-o", "{out}", + *flags).values(): + _same_matrix(_read(out).X, want) + + +def test_the_reader_is_named_once_a_run_on_stderr(tmp_path, source, backend): + obj, path = source + if backend != "h5ad": + pytest.skip("the reader serves HDF5 inputs only") + result = run("direct", "export", "sparse", path, "X") + assert result.stdout.count(STATUS) == 0 + assert result.stderr.count(STATUS) == 1 + assert "16 in flight, 1 MiB buffer" in _out(result) + + +def test_auto_leaves_a_local_disk_to_h5py(tmp_path, source, backend, monkeypatch): + obj, path = source + monkeypatch.setattr("adata.storage.rawio.filesystem", lambda p: "ext4") + result = run("auto", "export", "sparse", path, "X", "-o", tmp_path / "x.mtx") + assert STATUS not in _out(result) + monkeypatch.setattr("adata.storage.rawio.filesystem", lambda p: "lustre") + result = run("auto", "export", "sparse", path, "X", "-o", tmp_path / "y.mtx") + assert (STATUS in _out(result)) == (backend == "h5ad") + assert (tmp_path / "x.mtx").read_bytes() == (tmp_path / "y.mtx").read_bytes() + + +def test_the_option_overrides_the_environment(tmp_path, source, backend): + obj, path = source + result = runner.invoke( + app, ["export", "sparse", str(path), "X", "--io", "h5py"], env={"ADATA_IO": "direct"} + ) + assert result.exit_code == 0, _out(result) + assert STATUS not in _out(result) + + +def test_a_misspelt_reader_or_buffer_is_refused_before_anything_is_written(tmp_path, source): + obj, path = source + out = tmp_path / "x.mtx" + result = runner.invoke(app, ["export", "sparse", str(path), "X", "-o", str(out), "--io", "fast"]) + assert result.exit_code == 2 and "fast" in _out(result) + result = runner.invoke( + app, ["export", "sparse", str(path), "X", "-o", str(out)], + env={"ADATA_IO": "direct", "ADATA_IO_BUFFER": "lots"}, + ) + assert result.exit_code == 1 + assert "Error: ADATA_IO_BUFFER must be a size such as 256M or 1G, not 'lots'." in _out(result) + assert not out.exists() diff --git a/tests/test_fsinfo.py b/tests/test_fsinfo.py new file mode 100644 index 0000000..9d500e7 --- /dev/null +++ b/tests/test_fsinfo.py @@ -0,0 +1,145 @@ +"""Which filesystem a path is on (`storage.fsinfo`), and how the direct-I/O +reader reads it. + +The mount table is the kernel's own text, so it is given here as text: +the tests run the same on a laptop and on CI, and on no Lustre at all. +""" + +from __future__ import annotations + +import os + +import pytest + +from adata.storage import fsinfo +from adata.storage.fsinfo import LUSTRE, NFS, IOProfile, filesystem, fstype_at, io_profile + + +def _line(mount_id: int, mount_point: str, fstype: str, *, optional: str = "shared:1") -> str: + """A /proc/self/mountinfo line, `optional` its optional fields.""" + fields = [str(mount_id), "1", "0:1", "/", mount_point, "rw,relatime"] + if optional: + fields += optional.split() + return " ".join(fields + ["-", fstype, "source", "rw"]) + + +MOUNTS = "\n".join([ + _line(21, "/", "ext4"), + _line(22, "/proc", "proc", optional=""), + _line(23, "/lustre", "lustre", optional="shared:7 master:3"), + _line(24, "/lustre/scratch126", "lustre"), + _line(25, "/nfs", "autofs"), + _line(26, "/nfs/users", "autofs"), + # The automounter's placeholder, then the share mounted over it. + _line(27, "/nfs/users/nfs_a", "autofs"), + _line(28, "/nfs/users/nfs_a", "nfs4"), + _line(29, "/mnt/My\\040Drive", "fuse.sshfs"), + _line(30, "/tmp", "tmpfs"), + "a line the kernel never writes", +]) + + +@pytest.mark.parametrize( + "path, expected", + [ + ("/lustre/scratch126/cellgeni/data.h5ad", "lustre"), + ("/lustre/other/data.h5ad", "lustre"), + ("/nfs/users/nfs_a/data.h5ad", "nfs4"), + ("/nfs/users/nfs_b/data.h5ad", "autofs"), + ("/mnt/My Drive/data.h5ad", "fuse.sshfs"), + ("/tmp/x.h5ad", "tmpfs"), + ("/home/me/data.h5ad", "ext4"), + ("/", "ext4"), + ], +) +def test_the_longest_mount_point_that_holds_a_path_names_its_filesystem(path, expected): + assert fstype_at(path, MOUNTS) == expected + + +def test_a_mount_point_is_matched_by_whole_folders_not_by_prefix(): + """/lustre2 is not inside /lustre.""" + mounts = "\n".join([_line(1, "/", "xfs"), _line(2, "/lustre", "lustre")]) + assert fstype_at("/lustre2/data.h5ad", mounts) == "xfs" + assert fstype_at("/lustre", mounts) == "lustre" + + +def test_a_mount_point_with_a_space_is_decoded(): + mounts = fsinfo.parse_mountinfo(_line(1, "/mnt/a\\040b\\011c\\134d", "nfs")) + assert mounts == [("/mnt/a b\tc\\d", "nfs")] + + +def test_the_fstype_is_found_after_any_number_of_optional_fields(): + for optional in ("", "shared:1", "shared:1 master:2 propagate_from:3 unbindable"): + line = _line(1, "/data", "lustre", optional=optional) + assert fsinfo.parse_mountinfo(line) == [("/data", "lustre")] + + +def test_a_table_with_no_mount_for_a_path_says_unknown(): + assert fstype_at("/data/x.h5ad", _line(1, "/data2", "xfs")) == "unknown" + assert fstype_at("/data/x.h5ad", "") == "unknown" + + +def test_a_path_that_does_not_exist_yet_is_on_its_nearest_parents_filesystem(tmp_path): + real = os.path.realpath(tmp_path) + mounts = "\n".join([_line(1, "/", "ext4"), _line(2, real, "lustre")]) + out = tmp_path / "not" / "yet" / "out.h5ad" + assert filesystem(out, mountinfo=mounts) == "lustre" + + +def test_a_symlinked_path_is_on_its_targets_filesystem(tmp_path): + (tmp_path / "real").mkdir() + (tmp_path / "link").symlink_to(tmp_path / "real") + real = os.path.realpath(tmp_path / "real") + mounts = "\n".join([_line(1, "/", "ext4"), _line(2, real, "lustre")]) + assert filesystem(tmp_path / "link" / "x.h5ad", mountinfo=mounts) == "lustre" + + +def test_off_linux_the_filesystem_is_unknown(monkeypatch, tmp_path): + monkeypatch.setattr(fsinfo.sys, "platform", "darwin") + assert filesystem(tmp_path) == "unknown" + + +def test_an_unreadable_mount_table_says_unknown(monkeypatch, tmp_path): + monkeypatch.setattr(fsinfo.sys, "platform", "linux") + monkeypatch.setattr(fsinfo, "MOUNTINFO", str(tmp_path / "no-such-mountinfo")) + assert filesystem(tmp_path) == "unknown" + + +def test_the_mount_table_is_read_from_proc_on_linux(monkeypatch, tmp_path): + table = tmp_path / "mountinfo" + table.write_text("\n".join([_line(1, "/", "ext4"), _line(2, os.path.realpath(tmp_path), "nfs")])) + monkeypatch.setattr(fsinfo.sys, "platform", "linux") + monkeypatch.setattr(fsinfo, "MOUNTINFO", str(table)) + assert filesystem(tmp_path / "x.h5ad") == "nfs" + + +@pytest.mark.parametrize( + "fstype, expected", + [ + ("lustre", LUSTRE), + ("nfs", NFS), + ("nfs4", NFS), + ("ext4", None), + ("xfs", None), + ("btrfs", None), + ("tmpfs", None), + ("overlay", None), + ("squashfs", None), + ("fuse.sshfs", None), + ("apfs", None), + ("unknown", None), + ], +) +def test_lustre_and_nfs_have_a_profile_and_everything_else_keeps_h5py(fstype, expected): + assert io_profile(fstype) == expected + + +def test_the_profiles_start_where_the_lustre_probe_measured(): + assert LUSTRE == IOProfile( + direct=True, request_bytes=16 << 20, in_flight=16, buffer_bytes=256 << 20 + ) + assert NFS == IOProfile( + direct=False, request_bytes=4 << 20, in_flight=32, buffer_bytes=128 << 20 + ) + with pytest.raises(Exception): + LUSTRE.in_flight = 8 # frozen diff --git a/tests/test_performance.py b/tests/test_performance.py index 8b702ea..55808fe 100644 --- a/tests/test_performance.py +++ b/tests/test_performance.py @@ -77,6 +77,14 @@ QUIET = Console(quiet=True) + +@pytest.fixture(autouse=True) +def _h5py_reader(monkeypatch): + """The guards measure h5py's path, whatever `ADATA_IO` the run was + given: the direct reader (`--io direct`) has guards of its own, at the + end of this file, and they ask for it.""" + monkeypatch.setenv("ADATA_IO", "h5py") + #: Only Python executed inside the package counts towards the CPU proxy. SOURCE_PREFIX = str(pathlib.Path(__file__).resolve().parent.parent / "src" / "adata") @@ -3052,3 +3060,166 @@ def measure(groups: int) -> int: f"split into 320 groups added {many / 1e6:.0f} MB of RSS against " f"{few / 1e6:.0f} MB into 128: memory follows the number of groups" ) + + +# --------------------------------------------------------------------------- +# The direct-I/O reader (`--io direct`, `storage/rawio.py`) +# +# What it costs is requests of the file rather than elements: each block is +# asked for in requests of `request_bytes`, not a chunk at a time, and each +# dataset's chunks are mapped once. + + +def _direct_store(path: Path, n_obs: int, n_var: int = 64, density: float = 0.25) -> Path: + """A CSR X as anndata writes it (chunked `data` and `indices`), and a + dense layer of tiles narrower than the matrix.""" + import h5py + + x = sparse.random(n_obs, n_var, density=density, format="csr", dtype=np.float32, + random_state=0) + obj = ad.AnnData( + X=x, + obs=pd.DataFrame(index=[f"c{i}" for i in range(n_obs)]), + var=pd.DataFrame(index=[f"g{i}" for i in range(n_var)]), + ) + obj.write_h5ad(path) + with h5py.File(path, "a") as f: + dense = f["layers"].create_dataset("dense", data=x.toarray(), chunks=(64, 16)) + dense.attrs.update({"encoding-type": "array", "encoding-version": "0.2.0"}) + return path + + +def _keep_every_other(tmp_path: Path, n_obs: int) -> Path: + keep = tmp_path / f"keep{n_obs}.txt" + keep.write_text("\n".join(f"c{i}" for i in range(0, n_obs, 2)) + "\n") + return keep + + +def _direct(monkeypatch, buffer: str = "1M") -> None: + from adata.core import subset as subset_module + + monkeypatch.setenv("ADATA_IO", "direct") + monkeypatch.setenv("ADATA_IO_BUFFER", buffer) + monkeypatch.setattr(subset_module, "SPARSE_BLOCK_BYTES", 1) + + +def test_the_direct_reader_maps_each_dataset_once(tmp_path, monkeypatch): + """A chunk map walks the dataset's whole chunk index: built once a + block, it would cost as much as the reads it saves.""" + from adata.storage import rawio + + _direct(monkeypatch) + built: List[tuple] = [] + real = rawio.ChunkMap.__init__ + + def init(self, ds, engine): + real(self, ds, engine) + built.append((id(engine), ds.name)) + + monkeypatch.setattr(rawio.ChunkMap, "__init__", init) + + def measure(n: int) -> int: + source = _direct_store(tmp_path / f"m{n}.h5ad", n_obs=n) + built.clear() + with count_io() as io: + subset_h5ad(source, tmp_path / f"om{n}.h5ad", _keep_every_other(tmp_path, n), + None, console=QUIET) + assert len(built) == len(set(built)), f"a chunk map was built twice: {built}" + assert {"/X/data", "/X/indices", "/layers/dense"} <= {name for _, name in built} + assert io.direct_calls > len(built), "the store was not read in blocks" + return len(built) + + assert_independent_of(measure, what="chunk maps built", axis="n_obs", + sizes=(20_000, 80_000), tolerance=1.0) + + +def test_a_block_read_directly_is_asked_for_in_whole_requests(tmp_path, monkeypatch): + """Each block is read in requests of `request_bytes`, never a chunk at a + time, which is what held every library to 260-500 MB/s on Lustre. Rows + that are one run of the file (sparse `data` and `indices`) take at most + ceil((block + 2 chunks) / request). Anything else -- tiles narrower than + the matrix, chunks with HDF5's index between them -- is read in pieces + of the rows each chunk holds, each over `request - chunk - GAP_BYTES` + bytes (less two pages of alignment) but the last, within the file span + of the block's chunks.""" + import math + import threading + + from adata.storage import rawio + + _direct(monkeypatch) + monkeypatch.setattr("adata.core.subset.SPARSE_BLOCK_BYTES", 4 << 20) + # Read-ahead off, so the requests made during a read are its own. + monkeypatch.setattr(rawio._Stream, "read_ahead", lambda self, cmap, start, stop: None) + lock = threading.Lock() + requests = [0] + blocks: List[tuple] = [] + real_request, real_rows = rawio._read_request, rawio.read_rows + + def request(*args): + with lock: + requests[0] += 1 + return real_request(*args) + + def rows(cmap, start, stop): + before = requests[0] + result = real_rows(cmap, start, stop) + blocks.append((cmap, start, stop, result.nbytes, requests[0] - before)) + return result + + monkeypatch.setattr(rawio, "_read_request", request) + monkeypatch.setattr(rawio, "read_rows", rows) + + n = 100_000 + source = _direct_store(tmp_path / "r.h5ad", n_obs=n) + subset_h5ad(source, tmp_path / "out.h5ad", _keep_every_other(tmp_path, n), None, + console=QUIET) + + step = 512 << 10 # half of ADATA_IO_BUFFER + assert {cmap.name for cmap, *_ in blocks} >= {"/X/data", "/X/indices", "/layers/dense"} + many = 0 + for cmap, start, stop, nbytes, made in blocks: + assert cmap.engine.profile.request_bytes == step + if not nbytes: + continue + assert made >= math.ceil(nbytes / step), f"{cmap.name}: requests were not counted" + chunk = 0 if cmap.contiguous else cmap.chunk_bytes + if not cmap.contiguous: + height = cmap.chunks[0] + at = cmap.addresses(start // height * cmap.across, + ((stop - 1) // height + 1) * cmap.across) + one_run = cmap.full_width and (np.diff(at) == chunk).all() + if cmap.contiguous or one_run: + bound = math.ceil((nbytes + 2 * chunk) / step) + else: + span = int(at.max()) + chunk - int(at.min()) + piece = step - 2 * rawio.ALIGN - chunk - rawio.GAP_BYTES + bound = math.ceil(span / piece) + assert made <= bound, ( + f"{cmap.name}[{start}:{stop}]: {nbytes} bytes in {made} requests, " + f"more than {bound} of {step} bytes" + ) + many += made > 2 + assert many, "no block was large enough to take several requests" + + +def test_no_read_of_x_reaches_h5py_when_the_direct_reader_is_on(tmp_path, monkeypatch): + def x_reads(mode: str) -> tuple: + monkeypatch.setenv("ADATA_IO", mode) + source = _direct_store(tmp_path / f"{mode}.h5ad", n_obs=20_000) + with count_io() as io: + subset_h5ad(source, tmp_path / f"o{mode}.h5ad", + _keep_every_other(tmp_path, 20_000), None, console=QUIET) + return io + + _direct(monkeypatch) + io = x_reads("direct") + for name in ("/X/data", "/X/indices", "/layers/dense"): + assert name not in io.h5_by_name, f"h5py read {io.h5_by_name.get(name)} of {name}" + assert io.by_name.get(name), f"nothing read {name}" + assert io.direct_requests and io.direct_request_bytes >= io.largest_by_name["/X/data"] + + # And the probe sees h5py's reads where the reader is off. + io = x_reads("h5py") + assert io.h5_by_name.get("/X/data") and not io.direct_calls + diff --git a/tests/test_rawio.py b/tests/test_rawio.py new file mode 100644 index 0000000..ea648d4 --- /dev/null +++ b/tests/test_rawio.py @@ -0,0 +1,787 @@ +"""The direct-I/O reader (`storage.rawio`) against h5py, byte for byte. + +Every read it serves must be exactly what `ds[a:b]` returns from h5py: +the same dtype (byte order included), shape and bytes. Every dataset it +does not handle must go to h5py untouched. On Linux CI the reads go +through O_DIRECT; on macOS, which has none, through the page cache. +""" + +from __future__ import annotations + +import errno +import os +from contextlib import contextmanager +from pathlib import Path +from typing import Iterator + +import h5py +import numpy as np +import pytest + +from adata.storage import open_hdf5, open_store, rawio +from adata.storage.fsinfo import LUSTRE, NFS +from adata.storage.rawio import DirectDataset, DirectFile, DirectGroup + +KiB = 1 << 10 +MiB = 1 << 20 + + +@contextmanager +def direct(path: Path, **kwargs) -> Iterator[h5py.File]: + """`path` opened through the reader, forced on.""" + rawio.set_mode("direct") + handle = rawio.open_file(path, **kwargs) + try: + assert isinstance(handle, DirectFile) + yield handle + finally: + handle.close() + + +def same(got: np.ndarray, want: np.ndarray) -> None: + got, want = np.asarray(got), np.asarray(want) + assert got.dtype == want.dtype + assert got.dtype.byteorder == want.dtype.byteorder + assert got.shape == want.shape + if got.dtype.hasobject: + assert got.tolist() == want.tolist() + else: + assert got.tobytes() == want.tobytes() + + +def check_slices(path: Path, name: str, *, seed: int = 0, count: int = 40) -> None: + """Random row slices of `name`, read both ways, compared.""" + rng = np.random.default_rng(seed) + with h5py.File(path, "r") as ref, direct(path) as handle: + want, got = ref[name], handle[name] + assert isinstance(got, DirectDataset) + n = want.shape[0] + bounds = [(0, n), (0, 0), (n, n), (n - 1, n), (0, 1), (-5, n + 10), (n // 2, n // 2 + 1)] + for _ in range(count): + a = int(rng.integers(0, n + 1)) + bounds.append((a, int(rng.integers(a, n + 3)))) + for a, b in bounds: + same(got[a:b], want[a:b]) + assert handle._adata_engine.chunk_map(got) is not None + + +DTYPES = ["int64", "float64", "int32", "float32", "int8", "uint16", "float16", "bool", ">f8", ">i4", ">u8"] + + +def _values(dtype: str, shape, seed: int = 0) -> np.ndarray: + rng = np.random.default_rng(seed) + if dtype == "bool": + return rng.random(shape) > 0.5 + return (rng.random(shape) * 1000).astype(dtype) + + +@pytest.mark.parametrize("dtype", DTYPES) +def test_contiguous_rows_match_h5py_byte_for_byte(tmp_path, dtype): + path = tmp_path / "a.h5" + with h5py.File(path, "w") as f: + f.create_dataset("v", data=_values(dtype, 20011)) + f.create_dataset("m", data=_values(dtype, (3001, 7))) + check_slices(path, "v") + check_slices(path, "m") + + +@pytest.mark.parametrize("dtype", DTYPES) +def test_chunked_rows_match_h5py_byte_for_byte(tmp_path, dtype): + """Chunks of 1,001 elements: a chunk is never a whole number of pages, + and the last one is cut short by the end of the array.""" + path = tmp_path / "a.h5" + with h5py.File(path, "w") as f: + f.create_dataset("v", data=_values(dtype, 20011), chunks=(1001,)) + check_slices(path, "v") + + +@pytest.mark.parametrize("dtype", ["float32", ">f8", "bool", "int16"]) +def test_two_dimensional_tiles_with_ragged_edges_match_h5py(tmp_path, dtype): + path = tmp_path / "a.h5" + with h5py.File(path, "w") as f: + f.create_dataset("tiles", data=_values(dtype, (5003, 77)), chunks=(97, 13)) + f.create_dataset("wide", data=_values(dtype, (5003, 77)), chunks=(97, 77)) + f.create_dataset("wider", data=_values(dtype, (503, 50)), chunks=(64, 64), maxshape=(None, None)) + f.create_dataset("tall", data=_values(dtype, (50, 9)), chunks=(64, 4), maxshape=(None, 9)) + for name in ("tiles", "wide", "wider", "tall"): + check_slices(path, name) + + +def test_unwritten_chunks_read_as_the_fill_value(tmp_path): + path = tmp_path / "a.h5" + with h5py.File(path, "w") as f: + v = f.create_dataset("v", shape=(50000,), dtype="i8", chunks=(1000,), fillvalue=-5) + v[3000:7000] = 3 + v[48500:] = 9 + m = f.create_dataset("m", shape=(500, 300), dtype=">f8", chunks=(64, 64), fillvalue=1.5) + m[100:200, 64:200] = 2 + f.create_dataset("none", shape=(4000,), dtype="f4", chunks=(100,), fillvalue=7) + for name in ("v", "m"): + check_slices(path, name) + with h5py.File(path, "r") as ref, direct(path) as handle: + same(handle["none"][10:3900], ref["none"][10:3900]) + + +def test_rows_of_no_columns_match_h5py(tmp_path): + path = tmp_path / "a.h5" + with h5py.File(path, "w") as f: + f.create_dataset("c", shape=(100, 0), dtype="f4") + f.create_dataset("k", shape=(100, 0), dtype="f4", chunks=(10, 1), maxshape=(None, None)) + with h5py.File(path, "r") as ref, direct(path) as handle: + for name in ("c", "k"): + same(handle[name][5:50], ref[name][5:50]) + + +def test_chunks_stored_out_of_order_are_put_in_place(tmp_path): + """A dataset written from its end: its chunks lie in the file in the + reverse of their order, at addresses that are not even aligned.""" + path = tmp_path / "a.h5" + with h5py.File(path, "w") as f: + f.create_dataset("pad", data=np.zeros(3, "u1")) + v = f.create_dataset("v", shape=(10000,), dtype="i4", chunks=(1000,)) + for k in range(9, -1, -1): + v[k * 1000 : (k + 1) * 1000] = np.arange(k * 1000, (k + 1) * 1000) + check_slices(path, "v") + + +def test_a_chunk_map_holds_runs_of_the_file_not_every_possible_chunk(tmp_path): + """The 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 of it.""" + path = tmp_path / "a.h5" + with h5py.File(path, "w") as f: + huge = f.create_dataset("huge", shape=(10**12,), dtype="f4", chunks=(1000,), fillvalue=2) + huge[5_000_000_000 : 5_000_002_500] = 7 + f.create_dataset("v", data=np.arange(400_000, dtype="i4"), chunks=(1000,)) + with h5py.File(path, "r") as ref, direct(path) as handle: + cmap = handle._adata_engine.chunk_map(handle["huge"]) + assert cmap.runs.nbytes <= 2 * rawio.RUN_BYTES + for a, b in ((0, 10), (4_999_999_000, 5_000_003_000), (10**12 - 5, 10**12)): + same(handle["huge"][a:b], ref["huge"][a:b]) + # 400 chunks written in order: a handful of runs, not 400. + cmap = handle._adata_engine.chunk_map(handle["v"]) + assert len(cmap.runs) < 40 + check_slices(path, "v") + assert rawio._MAPS["bytes"] == 0 + + +def test_a_dataset_whose_chunk_map_would_not_fit_is_left_to_h5py(tmp_path, monkeypatch): + path = tmp_path / "a.h5" + with h5py.File(path, "w") as f: + v = f.create_dataset("v", shape=(10000,), dtype="i4", chunks=(1000,)) + for k in range(9, -1, -1): # ten runs of one chunk + v[k * 1000 : (k + 1) * 1000] = np.arange(k * 1000, (k + 1) * 1000) + f.create_dataset("w", data=np.arange(10000, dtype="i4"), chunks=(1000,)) + monkeypatch.setattr(rawio, "MAP_BYTES", 5 * rawio.RUN_BYTES) + with h5py.File(path, "r") as ref, direct(path) as handle: + engine = handle._adata_engine + assert engine.chunk_map(handle["v"]) is None + same(handle["v"][3:9000], ref["v"][3:9000]) + assert engine.chunk_map(handle["w"]) is not None + assert rawio._MAPS["bytes"] == engine.chunk_map(handle["w"]).runs.nbytes + assert rawio._MAPS["bytes"] == 0 + + +@pytest.mark.parametrize("layout", ["tiles", "reversed"]) +def test_a_chunk_larger_than_a_request_is_read_in_parts(tmp_path, monkeypatch, layout): + """A chunk was 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.""" + path = tmp_path / "a.h5" + values = np.arange(2000 * 1500, dtype="f8").reshape(2000, 1500) + with h5py.File(path, "w") as f: + if layout == "tiles": + f.create_dataset("m", data=values, chunks=(512, 512)) + else: + m = f.create_dataset("m", shape=(2000, 1500), dtype="f8", chunks=(200, 1500)) + for k in range(9, -1, -1): + m[k * 200 : (k + 1) * 200] = values[k * 200 : (k + 1) * 200] + monkeypatch.setenv("ADATA_IO_BUFFER", "1M") + sizes, asked = [], [] + real_aligned, real_request = rawio._aligned, rawio._read_request + monkeypatch.setattr(rawio, "_aligned", lambda n: sizes.append(n) or real_aligned(n)) + monkeypatch.setattr( + rawio, "_read_request", lambda source, view, *a: asked.append(view.nbytes) + or real_request(source, view, *a) + ) + with h5py.File(path, "r") as ref, direct(path) as handle: + assert handle._adata_engine.profile.request_bytes == 512 * KiB + same(handle["m"][10:12], ref["m"][10:12]) + # Two rows of three tiles, not three 2 MiB tiles. + assert sum(asked) <= 3 * 2 * 512 * 8 + 6 * rawio.ALIGN or layout != "tiles" + for a, b in ((0, 2000), (37, 1203), (1999, 2000), (400, 401)): + same(handle["m"][a:b], ref["m"][a:b]) + assert sizes and max(sizes) <= 512 * KiB + + +def test_values_at_an_unaligned_file_offset_come_back_aligned(tmp_path): + """HDF5 put this dataset at byte 2051; numpy, and what it hands arrays + to, expects float64 on an 8-byte boundary.""" + path = tmp_path / "a.h5" + with h5py.File(path, "w") as f: + f.create_dataset("pad", data=np.zeros(3, "u1")) + f.create_dataset("x", data=np.arange(1000, dtype="f8")) + with h5py.File(path, "r") as ref, direct(path) as handle: + assert ref["x"].id.get_offset() % 8 + values = handle["x"][1:999] + assert values.flags.aligned and values.flags.c_contiguous + same(values, ref["x"][1:999]) + + +def test_rows_that_are_one_run_of_the_file_are_read_into_the_result(tmp_path, monkeypatch): + """A contiguous dataset, a 1-D chunked one written in order, and a 2-D + one chunked across its width need no copy chunk by chunk.""" + path = tmp_path / "a.h5" + with h5py.File(path, "w") as f: + f.create_dataset("c", data=np.arange(5000, dtype="f4")) + f.create_dataset("k", data=np.arange(5000, dtype="f4"), chunks=(100,)) + f.create_dataset("w", data=np.ones((500, 8), "i4"), chunks=(64, 8)) + + def no_copy(*args, **kwargs): + raise AssertionError("assembled chunk by chunk") + + monkeypatch.setattr(rawio.ChunkMap, "_assemble", no_copy) + with h5py.File(path, "r") as ref, direct(path) as handle: + for name in ("c", "k", "w"): + same(handle[name][17:433], ref[name][17:433]) + + +@pytest.mark.parametrize( + "key", + [ + slice(None), slice(5, 90), slice(-30, None), slice(5, 90, 1), Ellipsis, (), + (slice(5, 90),), (slice(5, 90), slice(None)), (slice(5, 90), Ellipsis), + (slice(5, 90), slice(0, 6)), (slice(5, 90), slice(None), Ellipsis), + slice(np.int64(3), np.int64(50)), + ], +) +def test_row_slices_read_through_the_reader(tmp_path, monkeypatch, key): + path = tmp_path / "a.h5" + with h5py.File(path, "w") as f: + f.create_dataset("m", data=np.arange(600, dtype="f8").reshape(100, 6), chunks=(10, 6)) + calls = [] + real = rawio.read_rows + monkeypatch.setattr(rawio, "read_rows", lambda *a: calls.append(a) or real(*a)) + with h5py.File(path, "r") as ref, direct(path) as handle: + same(handle["m"][key], ref["m"][key]) + assert len(calls) == 1 + + +@pytest.mark.parametrize( + "key", + [ + 5, -1, slice(None, None, 2), slice(5, 90, 3), [1, 5, 9], np.array([0, 3]), + (slice(5, 90), slice(1, 3)), (slice(5, 90), 2), (Ellipsis, slice(1, 3)), + (slice(None), [0, 2]), np.arange(100) % 3 == 0, (slice(5, 90), slice(None, None, 2)), + ], +) +def test_other_selections_go_to_h5py(tmp_path, monkeypatch, key): + path = tmp_path / "a.h5" + with h5py.File(path, "w") as f: + f.create_dataset("m", data=np.arange(600, dtype="f8").reshape(100, 6), chunks=(10, 6)) + monkeypatch.setattr(rawio, "read_rows", lambda *a: pytest.fail("read by the reader")) + with h5py.File(path, "r") as ref, direct(path) as handle: + same(handle["m"][key], ref["m"][key]) + + +def test_a_read_with_a_new_dtype_goes_to_h5py(tmp_path, monkeypatch): + path = tmp_path / "a.h5" + with h5py.File(path, "w") as f: + f.create_dataset("v", data=np.arange(100, dtype="i4")) + monkeypatch.setattr(rawio, "read_rows", lambda *a: pytest.fail("read by the reader")) + with direct(path) as handle: + same(handle["v"].astype("f8")[3:9], np.arange(3, 9, dtype="f8")) + + +def _refused(f: h5py.File) -> None: + rng = np.random.default_rng(1) + values = rng.random(5000) + f.create_dataset("gzip", data=values, chunks=(500,), compression="gzip") + f.create_dataset("shuffle", data=values, chunks=(500,), shuffle=True) + f.create_dataset("lzf", data=values, chunks=(500,), compression="lzf") + f.create_dataset("fletcher32", data=values, chunks=(500,), fletcher32=True) + f.create_dataset("text", data=np.array([f"cell{i}" for i in range(5000)], dtype=object), + dtype=h5py.string_dtype()) + f.create_dataset("bytes", data=np.array([b"ab", b"cd"] * 2500)) + f.create_dataset("compound", data=np.array( + [(i, i / 2) for i in range(5000)], dtype=[("a", "i4"), ("b", "f8")])) + f.create_dataset("complex", data=values.astype("c16")) + f.create_dataset("enum", data=np.arange(5000) % 3, + dtype=h5py.enum_dtype({"a": 0, "b": 1, "c": 2}, basetype="i1")) + f.create_dataset("three_d", data=values[:4992].reshape(16, 312, 1)) + f.create_dataset("compact", data=np.arange(10, dtype="i4"), + **({"compact": True} if False else {})) + f.create_dataset("scalar", data=3.5) + f.create_dataset("empty", shape=(0,), dtype="f8") + f.create_dataset("unwritten", shape=(5000,), dtype="f8") + + +@pytest.mark.parametrize( + "name", + ["gzip", "shuffle", "lzf", "fletcher32", "text", "bytes", "compound", "complex", + "enum", "three_d", "scalar", "empty", "unwritten"], +) +def test_datasets_the_reader_does_not_handle_go_to_h5py(tmp_path, monkeypatch, name): + path = tmp_path / "a.h5" + with h5py.File(path, "w") as f: + _refused(f) + monkeypatch.setattr(rawio, "read_rows", lambda *a: pytest.fail("read by the reader")) + with h5py.File(path, "r") as ref, direct(path) as handle: + got, want = handle[name], ref[name] + assert handle._adata_engine.chunk_map(got) is None + if want.shape: + same(got[: want.shape[0] // 2], want[: want.shape[0] // 2]) + same(got[...], want[...]) + else: + assert got[()] == want[()] + + +def test_a_refused_dataset_is_examined_once(tmp_path, monkeypatch): + path = tmp_path / "a.h5" + with h5py.File(path, "w") as f: + f.create_dataset("g", data=np.arange(1000.0), chunks=(100,), compression="gzip") + built = [] + real = rawio.ChunkMap.__init__ + monkeypatch.setattr(rawio.ChunkMap, "__init__", lambda self, *a: built.append(1) or real(self, *a)) + with direct(path) as handle: + for start in range(0, 1000, 100): + handle["g"][start : start + 100] + assert len(built) == 1 + + +def test_a_file_opened_for_writing_is_left_to_h5py(tmp_path): + path = tmp_path / "a.h5ad" + with h5py.File(path, "w") as f: + f.create_dataset("v", data=np.arange(100)) + rawio.set_mode("direct") + with open_store(path, "r+", require_anndata=False) as store: + assert type(store.root) is h5py.File + assert type(store.root["v"]) is h5py.Dataset + with h5py.File(path, "r+") as handle, pytest.raises(rawio.Unsupported): + rawio.Engine(handle, str(path), LUSTRE, "lustre") + with open_store(path, "r", require_anndata=False) as store: + assert isinstance(store.root, DirectFile) + + +def test_a_file_with_a_userblock_is_left_to_h5py(tmp_path): + path = tmp_path / "a.h5mu" + with h5py.File(path, "w", userblock_size=512) as f: + f.create_dataset("v", data=np.arange(100)) + rawio.set_mode("direct") + with rawio.open_file(path) as handle: + assert type(handle) is h5py.File + + +def _open_descriptors() -> int: + return len(os.listdir("/dev/fd")) + + +def test_the_reader_reads_through_hdf5s_own_descriptor(tmp_path, monkeypatch): + """`concat` holds up to 64 inputs open, a quarter of macOS's limit: the + reader adds a descriptor only for O_DIRECT.""" + path = tmp_path / "a.h5" + with h5py.File(path, "w") as f: + f.create_dataset("v", data=np.arange(100.0)) + with h5py.File(path, "r"): + plain = _open_descriptors() + monkeypatch.setattr(rawio, "_open_direct", lambda p: None) + with direct(path) as handle: + same(handle["v"][3:9], np.arange(3.0, 9.0)) + assert _open_descriptors() == plain + monkeypatch.setattr(rawio, "_open_direct", lambda p: os.open(p, os.O_RDONLY)) + with direct(path) as handle: + assert _open_descriptors() == plain + 1 + after = _open_descriptors() + assert after <= plain - 1 # every descriptor of both closed + + +def test_a_file_replaced_before_the_reader_opens_it_is_left_to_h5py(tmp_path, monkeypatch): + path, other = tmp_path / "a.h5", tmp_path / "b.h5" + for target in (path, other): + with h5py.File(target, "w") as f: + f.create_dataset("v", data=np.arange(100.0)) + monkeypatch.setattr(rawio, "_open_direct", lambda p: os.open(other, os.O_RDONLY)) + rawio.set_mode("direct") + before = _open_descriptors() + with rawio.open_file(path) as handle: + assert type(handle) is h5py.File + assert _open_descriptors() == before + + +def test_members_keep_their_h5py_types(tmp_path): + path = tmp_path / "a.h5" + with h5py.File(path, "w") as f: + f.create_group("X").create_dataset("data", data=np.arange(10.0)) + with direct(path) as handle: + group = handle["X"] + assert isinstance(group, DirectGroup) and isinstance(group, h5py.Group) + assert isinstance(group["data"], DirectDataset) and isinstance(group["data"], h5py.Dataset) + assert isinstance(handle["X/data"], DirectDataset) + assert isinstance(handle.get("X"), DirectGroup) + assert isinstance(dict(group.items())["data"], DirectDataset) + seen = {} + handle.visititems(lambda name, obj: seen.update({name: type(obj)})) + assert seen["X/data"] is DirectDataset and seen["X"] is DirectGroup + + +def test_open_hdf5_reads_through_the_reader_only_when_asked(tmp_path): + path = tmp_path / "a.h5" + with h5py.File(path, "w") as f: + f.create_dataset("v", data=np.arange(10.0)) + with open_hdf5(path) as handle: + assert type(handle) is h5py.File + rawio.set_mode("direct") + with open_hdf5(path) as handle: + assert isinstance(handle, DirectFile) + same(handle["v"][2:5], np.arange(2.0, 5.0)) + + +# --------------------------------------------------------------------------- +# Failure paths + + +def _big(path: Path, n: int = 600_000, chunks=(30_001,)) -> np.ndarray: + values = np.arange(n, dtype="f8") + with h5py.File(path, "w") as f: + f.create_dataset("c", data=values) + f.create_dataset("k", data=values, chunks=chunks) + return values + + +@pytest.mark.skipif(not hasattr(os, "O_DIRECT"), reason="no O_DIRECT here (macOS)") +def test_on_linux_requests_go_past_the_page_cache(tmp_path, monkeypatch): + """What CI's Linux runners check: aligned requests are read with + O_DIRECT, and give what h5py gives.""" + path = tmp_path / "a.h5" + values = _big(path) + probe = rawio._open_direct(str(path)) + if probe is None: + pytest.skip(f"{tmp_path} refuses O_DIRECT") + os.close(probe) + real = os.preadv + used = [] + + def preadv(fd, buffers, offset): + used.append(fd) + return real(fd, buffers, offset) + + monkeypatch.setattr(rawio.os, "preadv", preadv) + with direct(path) as handle: + source = handle._adata_engine.source + assert source.direct + same(handle["c"][5:599_000], values[5:599_000]) + same(handle["k"][5:599_000], values[5:599_000]) + assert source.direct, "the filesystem refused O_DIRECT on read" + assert used.count(source.direct_fd) >= 2 + + +def test_without_o_direct_the_reader_reads_through_the_page_cache(tmp_path, monkeypatch): + values = _big(tmp_path / "a.h5") + monkeypatch.delattr(os, "O_DIRECT", raising=False) + with direct(tmp_path / "a.h5") as handle: + assert not handle._adata_engine.source.direct + same(handle["c"][7:500_001], values[7:500_001]) + same(handle["k"][7:500_001], values[7:500_001]) + + +def test_a_filesystem_that_refuses_o_direct_at_open_is_read_through_the_page_cache( + tmp_path, monkeypatch +): + values = _big(tmp_path / "a.h5") + monkeypatch.setattr(rawio.os, "O_DIRECT", 0o40000, raising=False) + real_open = os.open + + def refuse(path, flags, *args): + if flags & 0o40000: + raise OSError(errno.EINVAL, "Invalid argument") + return real_open(path, flags, *args) + + monkeypatch.setattr(rawio.os, "open", refuse) + with direct(tmp_path / "a.h5") as handle: + assert not handle._adata_engine.source.direct + same(handle["k"][3:400_000], values[3:400_000]) + + +def test_a_filesystem_that_refuses_o_direct_on_read_is_read_through_the_page_cache( + tmp_path, monkeypatch +): + """Some filesystems open with O_DIRECT and then refuse the read.""" + path = tmp_path / "a.h5" + values = _big(path) + monkeypatch.setattr(rawio, "_open_direct", lambda p: os.open(p, os.O_RDONLY)) + real = os.preadv + refused = [] + + def preadv(fd, buffers, offset): + if fd == handle._adata_engine.source.direct_fd: + refused.append(offset) + raise OSError(errno.EINVAL, "Invalid argument") + return real(fd, buffers, offset) + + with direct(path, rdcc_nbytes=0) as handle: + assert handle._adata_engine.source.direct + monkeypatch.setattr(rawio.os, "preadv", preadv) + same(handle["c"][0:600_000], values) + assert refused and not handle._adata_engine.source.direct + + +def test_short_reads_are_retried_until_each_request_is_whole(tmp_path, monkeypatch): + path = tmp_path / "a.h5" + values = _big(path) + real = os.preadv + calls = [] + + def short(fd, buffers, offset): + calls.append(offset) + view = memoryview(buffers[0]) + return real(fd, [view[: min(len(view), 10_000)]], offset) + + monkeypatch.setattr(rawio.os, "preadv", short) + with direct(path) as handle: + same(handle["c"][11:599_990], values[11:599_990]) + same(handle["k"][11:599_990], values[11:599_990]) + assert len(calls) > 2 * 4_800_000 // 10_000 + + +def test_a_read_past_the_end_of_the_file_is_fine_on_its_last_chunk(tmp_path): + """The last request is rounded up to a whole page, past the end of the + file: what the file holds is enough.""" + path = tmp_path / "a.h5" + with h5py.File(path, "w") as f: + f.create_dataset("v", data=np.arange(4097, dtype="u1")) + size = os.path.getsize(path) + with h5py.File(path, "r") as ref, direct(path) as handle: + # The data ends the file, part way through a page. + assert handle["v"].id.get_offset() + 4097 == size and size % rawio.ALIGN + same(handle["v"][1:4097], ref["v"][1:4097]) + + +def test_a_file_that_ends_before_its_data_is_an_error(tmp_path): + path = tmp_path / "a.h5" + with h5py.File(path, "w") as f: + f.create_dataset("v", data=np.arange(100_000, dtype="f8")) + with direct(path) as handle: + ds = handle["v"] + end = ds.id.get_offset() + 50_000 * 8 + os.truncate(path, end) + with pytest.raises(OSError, match="ends at byte"): + ds[0:100_000] + assert rawio._BUDGET.used == 0 + + +def test_an_error_on_a_reader_thread_reaches_the_caller(tmp_path, monkeypatch): + path = tmp_path / "a.h5" + _big(path) + monkeypatch.setenv("ADATA_IO_BUFFER", "2M") # requests of 1 MiB + real = os.preadv + + def fail(fd, buffers, offset): + if offset > 1 << 20: + raise OSError(errno.EIO, "Input/output error") + return real(fd, buffers, offset) + + monkeypatch.setattr(rawio.os, "preadv", fail) + with direct(path) as handle: + with pytest.raises(OSError, match="Could not read .* Input/output error") as raised: + handle["c"][0:600_000] + assert raised.value.errno == errno.EIO + with pytest.raises(OSError, match="Input/output error"): + handle["k"][0:600_000] + assert rawio._BUDGET.used == 0 + + +def test_an_error_placing_a_chunk_reaches_the_caller(tmp_path, monkeypatch): + path = tmp_path / "a.h5" + with h5py.File(path, "w") as f: + f.create_dataset("m", data=np.ones((1000, 50)), chunks=(100, 10)) + with direct(path) as handle: + cmap = handle._adata_engine.chunk_map(handle["m"]) + + def broken(*args): + raise ValueError("could not place it") + + monkeypatch.setattr(cmap, "_put", broken) + with pytest.raises(ValueError, match="could not place it"): + handle["m"][0:1000] + assert rawio._BUDGET.used == 0 + + +# --------------------------------------------------------------------------- +# Read-ahead and the budget + + +def test_consecutive_reads_are_served_from_read_ahead(tmp_path): + path = tmp_path / "a.h5" + values = _big(path) + with direct(path) as handle: + ds = handle["k"] + for start in range(0, 600_000, 50_000): + same(ds[start : start + 50_000], values[start : start + 50_000]) + stats = handle._adata_engine.stats + # The first two reads show the pattern; each one after is ready. + assert stats == {"hits": 10, "misses": 0} + assert rawio._BUDGET.used == 0 + + +def test_read_ahead_that_is_not_used_is_dropped(tmp_path): + path = tmp_path / "a.h5" + values = _big(path) + with direct(path) as handle: + ds = handle["c"] + ds[0:1000] + ds[1000:2000] # reads 2000:3000 ahead + same(ds[500_000:500_100], values[500_000:500_100]) + ds[2000:2500] + assert handle._adata_engine.stats == {"hits": 0, "misses": 1} + ds[2500:3000] # reads 3000:3500 ahead + same(ds[3000:3200], values[3000:3200]) # within it + assert handle._adata_engine.stats == {"hits": 1, "misses": 1} + assert rawio._BUDGET.used == 0 and rawio._BUDGET.ahead == 0 + + +def test_read_ahead_stays_within_half_the_buffer(tmp_path, monkeypatch): + path = tmp_path / "a.h5" + values = _big(path) + monkeypatch.setenv("ADATA_IO_BUFFER", "1M") + with direct(path) as handle: + ds = handle["c"] + # 800 KB blocks: one read ahead would be more than half of 1 MiB. + for start in range(0, 600_000, 100_000): + same(ds[start : start + 100_000], values[start : start + 100_000]) + assert handle._adata_engine.stats == {"hits": 0, "misses": 0} + # 400 KB blocks fit. + for start in range(0, 600_000, 50_000): + ds[start : start + 50_000] + assert handle._adata_engine.stats["hits"] > 0 + + +def test_closing_a_file_waits_for_its_read_ahead(tmp_path): + path = tmp_path / "a.h5" + _big(path) + with direct(path) as handle: + engine = handle._adata_engine + handle["c"][0:100_000] + handle["c"][100_000:200_000] + handle["c"][300_000:300_001] # drops what was read ahead + assert not engine.outstanding and not engine.streams + assert rawio._BUDGET.used == 0 and rawio._BUDGET.ahead == 0 + + +def test_the_reader_never_holds_more_than_its_buffer(tmp_path, monkeypatch): + """In flight, awaiting a copy, and read ahead, together.""" + path = tmp_path / "a.h5" + values = np.arange(2_000_000, dtype="f8") + with h5py.File(path, "w") as f: + f.create_dataset("k", data=values, chunks=(5_000,)) + f.create_dataset("m", data=values.reshape(20_000, 100), chunks=(500, 30)) + monkeypatch.setenv("ADATA_IO_BUFFER", "2M") + peak = [0] + budget = rawio._BUDGET + real_acquire, real_ahead = budget.acquire, budget.try_ahead + + def acquire(nbytes): + held = real_acquire(nbytes) + peak[0] = max(peak[0], budget.used) + return held + + def try_ahead(nbytes): + taken = real_ahead(nbytes) + peak[0] = max(peak[0], budget.used) + return taken + + monkeypatch.setattr(budget, "acquire", acquire) + monkeypatch.setattr(budget, "try_ahead", try_ahead) + with direct(path) as handle: + assert handle._adata_engine.profile.request_bytes == 1 * MiB + for start in range(0, 2_000_000, 100_000): + same(handle["k"][start : start + 100_000], values[start : start + 100_000]) + for start in range(0, 20_000, 1_000): + same(handle["m"][start : start + 1_000], values.reshape(20_000, 100)[start : start + 1_000]) + assert handle._adata_engine.stats["hits"] > 0 + assert 0 < peak[0] <= 2 * MiB + assert budget.used == 0 + + +# --------------------------------------------------------------------------- +# Settings + + +def test_the_reader_is_off_unless_asked_for(tmp_path, monkeypatch): + monkeypatch.delenv("ADATA_IO", raising=False) + assert rawio.io_mode() == "h5py" + assert rawio.profile_for(tmp_path) == (None, "") + monkeypatch.setenv("ADATA_IO", " Direct ") + assert rawio.io_mode() == "direct" + rawio.set_mode("h5py") + assert rawio.io_mode() == "h5py" + + +def test_a_misspelt_reader_is_refused(monkeypatch): + monkeypatch.setenv("ADATA_IO", "fast") + with pytest.raises(ValueError, match="ADATA_IO must be one of auto, direct or h5py, not 'fast'"): + rawio.io_mode() + with pytest.raises(ValueError, match="--io must be one of"): + rawio.set_mode("fast") + + +def test_auto_reads_lustre_and_nfs_directly_and_leaves_the_rest(tmp_path, monkeypatch): + rawio.set_mode("auto") + for fstype, expected in (("lustre", LUSTRE), ("nfs4", NFS), ("ext4", None), ("unknown", None)): + monkeypatch.setattr(rawio, "filesystem", lambda path, f=fstype: f) + assert rawio.profile_for(tmp_path) == (expected, fstype) + + +def test_direct_reads_any_filesystem_with_lustres_settings(tmp_path, monkeypatch): + rawio.set_mode("direct") + monkeypatch.setattr(rawio, "filesystem", lambda path: "apfs") + assert rawio.profile_for(tmp_path) == (LUSTRE, "apfs") + + +@pytest.mark.parametrize( + "text, expected", + [("256M", 256 * MiB), ("1G", 1 << 30), ("2048KiB", 2048 * KiB), ("64mb", 64 * MiB), + ("1048576", MiB), (" 2 G ", 2 << 30), ("1T", 1 << 40)], +) +def test_the_buffer_is_set_in_bytes_or_with_a_unit(monkeypatch, text, expected): + monkeypatch.setenv("ADATA_IO_BUFFER", text) + assert rawio.buffer_override() == expected + + +@pytest.mark.parametrize("text", ["lots", "1.5G", "-1M", "256Q", "512K", "0"]) +def test_a_buffer_that_is_not_a_size_or_too_small_is_refused(monkeypatch, text): + monkeypatch.setenv("ADATA_IO_BUFFER", text) + with pytest.raises(ValueError, match="ADATA_IO_BUFFER must be"): + rawio.buffer_override() + + +def test_a_small_buffer_cuts_the_requests_to_half_of_it(tmp_path, monkeypatch): + rawio.set_mode("direct") + monkeypatch.setenv("ADATA_IO_BUFFER", "6M") + profile, _ = rawio.profile_for(tmp_path) + assert profile.buffer_bytes == 6 * MiB + assert profile.request_bytes == 3 * MiB + monkeypatch.setenv("ADATA_IO_BUFFER", "1G") + assert rawio.profile_for(tmp_path)[0].request_bytes == 16 * MiB + + +def test_the_status_line_names_the_reader_and_its_settings(tmp_path, monkeypatch): + path = tmp_path / "a.h5" + with h5py.File(path, "w") as f: + f.create_dataset("v", data=np.arange(10)) + said = [] + rawio.set_reporter(said.append) + monkeypatch.setattr(rawio, "filesystem", lambda path: "lustre") + with direct(path) as handle: + how = "O_DIRECT" if handle._adata_engine.source.direct else "buffered" + with direct(path): + pass # said once a run + assert said == [ + f"Reading HDF5 with adata's direct reader: {how}, 16 MiB requests, " + "16 in flight, 256 MiB buffer (filesystem: lustre)" + ] + + +@pytest.mark.parametrize( + "nbytes, text", [(16 * MiB, "16 MiB"), (1 << 30, "1 GiB"), (512 * KiB, "512 KiB"), (1000, "1000 B")] +) +def test_sizes_are_said_in_their_largest_whole_unit(nbytes, text): + assert rawio.size_text(nbytes) == text