Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 22 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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`
Expand Down
36 changes: 36 additions & 0 deletions STATUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
22 changes: 19 additions & 3 deletions docs/developers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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

Expand Down
18 changes: 18 additions & 0 deletions docs/guides/pipelines.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
57 changes: 57 additions & 0 deletions docs/reference/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ Run `adata <command> --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)

---
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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 |
|---|---|---|---|
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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`,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions docs/reference/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading