From ce8516bb44b8522710b6879cde5223b9765f0cc5 Mon Sep 17 00:00:00 2001 From: Aljes Date: Fri, 30 Oct 2026 14:31:10 +0000 Subject: [PATCH 1/2] B5: element fidelity, legacy stores and HDF5 safety Every element anndata or scanpy writes survives every copy path, read back by anndata (and scanpy for rank_genes_groups): - record arrays copied field by field across backends (F017), and no record fill value handed to h5py (F021) - anndata 0.7 frames nested in raw/obsm/uns keep their references in HDF5 copies (F006), legacy `ordered` read from __categories (F072), no root-attribute warning for the 0.7 layout (F164) - attributes: nested bytes, h5py.Empty, references (F130); vlen numbers and references not taken for text (F126); float32 at its own precision (F125); a carried fill converted with the dtype (F071) - Zarr v2: compressors via the current API, None kept (F134, F135); an untagged empty dataspace not made a null (F136); missing text in pickle tables as a categorical (F133) - hardening for crafted HDF5 inputs (F041, security) - zarr floor 3.2.0 (lock 3.4.1): 3.1 cannot read a v3 record dtype newer zarr writes - fixtures written by anndata 0.7.8, 0.7.8 in the version matrix, every release and oracle pinned exactly (F087); plain-string fixtures under pandas 3 (F090); convert and split/concat read back by each release (F086); spec and testing docs corrected (F154, F156); dead code and duplicated spec constants removed (F163) Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 5 +- docs/developers.md | 6 +- docs/index.md | 5 +- docs/reference/spec-h5ad.md | 60 ++- docs/reference/spec-zarr.md | 73 ++- docs/reference/testing.md | 54 +- docs/troubleshooting.md | 10 + pyproject.toml | 4 +- src/adata/commands/convert.py | 5 + src/adata/elements/__init__.py | 14 +- src/adata/elements/read.py | 31 +- src/adata/elements/spec.py | 8 + src/adata/elements/strings.py | 59 ++- src/adata/elements/write.py | 4 - src/adata/formats/json_data.py | 3 + src/adata/formats/pandas_frame.py | 27 +- src/adata/storage/__init__.py | 491 ++++++++++++++---- tests/fixtures/anndata-0.7.8/reference.h5ad | Bin 0 -> 77704 bytes .../fixtures/anndata-0.7.8/reference.zarr.zip | Bin 0 -> 39050 bytes tests/fixtures/write_reference_store.py | 32 +- tests/reference_stores.py | 122 ++++- tests/test_anndata_roundtrip.py | 49 +- tests/test_anndata_versions.py | 68 ++- tests/test_element_fidelity.py | 476 +++++++++++++++++ tests/test_elements.py | 65 +++ tests/test_external_readers.py | 64 ++- tests/test_legacy_copies.py | 24 + tests/test_pandas_frame.py | 20 + tests/test_storage.py | 219 ++++++++ tests/test_storage_root_attrs.py | 18 + uv.lock | 78 ++- 31 files changed, 1866 insertions(+), 228 deletions(-) create mode 100644 tests/fixtures/anndata-0.7.8/reference.h5ad create mode 100644 tests/fixtures/anndata-0.7.8/reference.zarr.zip create mode 100644 tests/test_element_fidelity.py diff --git a/AGENTS.md b/AGENTS.md index 6d2e203..5f2d20c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -43,8 +43,9 @@ uv run python -m benchmarks.report results.json ``` Test markers: -- `integration` tests build uv environments with real anndata releases (0.8 to - 0.13), scanpy and PyTables, so they need the network on the first run. +- `integration` tests build uv environments with real anndata releases (0.7.8 + to 0.13) and the oracles (scanpy, PyTables and others), all pinned exactly + in `tests/reference_stores.py`, so they need the network on the first run. - `perf` tests are slow, but CI runs them in the main job. CI also installs the package from a fresh resolution, without the lock, diff --git a/docs/developers.md b/docs/developers.md index a8f233e..91d0a6a 100644 --- a/docs/developers.md +++ b/docs/developers.md @@ -149,8 +149,10 @@ before changing anything that writes: parametrised over `h5ad`, `zarr2` and `zarr3`. - **An oracle, not self-consistency.** anndata reads back what is written, scipy checks `recast`, scanpy, loompy and mudata check the conversions. - `test_anndata_versions.py` builds environments with anndata 0.8 to 0.13 and - checks both directions. + `test_anndata_versions.py` builds environments with anndata 0.7.8 to 0.13, + pinned exactly, and checks both directions: each release's store is read, + and from 0.8 the release reads back `subset`, `convert`, `split` and + `concat` outputs. - **Complexity guards that count, not time.** `tests/test_performance.py` counts the elements and bytes read through hooks on h5py and zarr. A change that adds reads per row or per group fails it on any machine. diff --git a/docs/index.md b/docs/index.md index c2eed4c..18ddcaa 100644 --- a/docs/index.md +++ b/docs/index.md @@ -66,8 +66,9 @@ Status goes to stderr and data to stdout, so every command pipes cleanly. - **Every AnnData on-disk layout**, from anndata 0.7 to the current spec, in HDF5 and in Zarr v2 and v3; everything written is in the current spec. CI - checks this against stores written by anndata 0.8 to 0.13, and checks that - each of those releases reads what `adata` writes. + checks this against stores written by anndata 0.7.8 to 0.13, and checks + that each release from 0.8 reads the output of `subset`, `convert`, + `split` and `concat` on the store it wrote. - **Other formats, through `convert`**: 10x Genomics HDF5 and MTX folders (Cell Ranger, STARsolo, velocyto), Visium and Xenium spatial outputs with their coordinates and images, CellBender output, Parse Biosciences runs, diff --git a/docs/reference/spec-h5ad.md b/docs/reference/spec-h5ad.md index a6472fc..57e05d7 100644 --- a/docs/reference/spec-h5ad.md +++ b/docs/reference/spec-h5ad.md @@ -27,7 +27,7 @@ It is intended to be GitHub-renderable Markdown (no Sphinx/MyST directives). - [DataFrame v0.1.0 (legacy: anndata 0.7.x)](#dataframe-v010-legacy-anndata-07x) - [Legacy categorical columns (Series-level)](#legacy-categorical-columns-series-level) - [Mappings](#mappings) - - [Legacy mapping encoding (`dict` v0.1.0)](#legacy-mapping-encoding-dict-v010) + - [The `dict` encoding (v0.1.0)](#the-dict-encoding-v010) - [Scalars](#scalars) - [Categorical arrays](#categorical-arrays) - [String arrays](#string-arrays) @@ -161,6 +161,15 @@ In v0.1.0 DataFrames, a categorical column dataset (e.g. `obs/cell_type`) can be - `categories`: an **HDF5 object reference** pointing to the corresponding `__categories/` dataset. +Whether the categories are ordered is not on the column. It is the +`ordered` attribute of the labels dataset, `__categories/`. + +A reference holds an address in its own file. Copied into another file by +HDF5 without help, it becomes a null reference, so a copy of a 0.1.0 +dataframe either rewrites it as 0.2.0 (`obs` and `var`, and every copy to +Zarr) or has HDF5 repoint the references at the copies (a 0.1.0 dataframe +nested in `raw`, `obsm` or `uns`, copied between HDF5 files). + ## Mappings Mappings are stored as HDF5 **groups** on disk. @@ -169,20 +178,16 @@ Mappings are stored as HDF5 **groups** on disk. - Mappings are distinct from DataFrames and sparse arrays and do not require special mapping-specific attributes. - Mapping semantics are recursive: entries in `uns` can themselves be groups containing additional encoded elements. -> **Legacy compatibility note** -> -> In earlier conventions (commonly seen in older docs and some files), mappings could carry -> `encoding-type: "dict"` and `encoding-version: "0.1.0"`. -> Readers should still accept this legacy metadata when encountered. - -### Legacy mapping encoding (`dict` v0.1.0) +### The `dict` encoding (v0.1.0) -For backward compatibility, older files may encode mappings with explicit mapping metadata: +anndata 0.8 and later tag a mapping group with: - `encoding-type: "dict"` - `encoding-version: "0.1.0"` -This historical convention existed in earlier AnnData docs and files and should still be accepted by readers. +This is the current encoding, not a legacy one: anndata 0.13 writes it, and +so does this tool, on every mapping group. Files from anndata 0.7.x leave +mappings untagged, and readers accept those too. ## Scalars @@ -269,6 +274,20 @@ For elements supporting a `na-value` attribute: Readers should preserve semantics when the runtime model supports it. +## Record arrays + +### `encoding-type: rec-array`, `encoding-version: 0.2.0` + +A numpy record array, as scanpy's `rank_genes_groups` keeps its results in +`uns` (`names`, `scores`, `pvals` and the rest: one field per group). It is a +single dataset with a compound dtype: + +- a text field is variable-length UTF-8, as anndata writes it to HDF5 (Zarr + holds the same field as fixed-width `` array. +- `categories`: a **path string, relative to the dataframe group**, to the corresponding labels: `__categories/`, as anndata 0.7.8 writes it. -(This differs from HDF5, which can store an object reference.) +(This differs from HDF5, which stores an object reference.) + +Whether the categories are ordered is not on the column. It is the +`ordered` attribute of the labels array, `__categories/`. ## Mappings @@ -171,20 +174,16 @@ Mappings are stored as Zarr **groups** on disk. - Mappings are distinct from DataFrames and sparse arrays and do not require special mapping-specific attributes. - Mapping semantics are recursive: entries in `uns` can themselves be groups containing additional encoded elements. -> **Legacy compatibility note** -> -> In earlier conventions (commonly seen in older docs and some files), mappings could carry -> `encoding-type: "dict"` and `encoding-version: "0.1.0"`. -> Readers should still accept this legacy metadata when encountered. - -### Legacy mapping encoding (`dict` v0.1.0) +### The `dict` encoding (v0.1.0) -For backward compatibility, older files may encode mappings with explicit mapping metadata: +anndata 0.8 and later tag a mapping group with: - `encoding-type: "dict"` - `encoding-version: "0.1.0"` -This historical convention existed in earlier AnnData docs and files and should still be accepted by readers. +This is the current encoding, not a legacy one: anndata 0.13 writes it, and +so does this tool, on every mapping group. Files from anndata 0.7.x leave +mappings untagged, and readers accept those too. ## Scalars @@ -201,7 +200,7 @@ These should typically only occur inside `uns` and are commonly used for saved p - String scalars: - `encoding-type: "string"` - `encoding-version: "0.2.0"` - - **Zarr requirement:** fixed-length unicode dtype (e.g. ` **Legacy note** > @@ -271,6 +270,24 @@ For elements supporting a `na-value` attribute: Readers should preserve semantics when the runtime model supports it. +## Record arrays + +### `encoding-type: rec-array`, `encoding-version: 0.2.0` + +A numpy record array, as scanpy's `rank_genes_groups` keeps its results in +`uns` (`names`, `scores`, `pvals` and the rest: one field per group). It is a +single Zarr array with a structured dtype: + +- a text field is fixed-width unicode, `` for the longest value, as + anndata writes it to Zarr (HDF5 holds the same field as variable-length + UTF-8); +- every other field keeps its dtype. + +anndata 0.7.x wrote the same arrays untagged. + +zarr-python warns that a structured dtype has no Zarr v3 specification yet; +anndata writes rec-arrays to v3 regardless, and this tool does too. + ## Awkward arrays (experimental) ### `encoding-type: awkward-array`, `encoding-version: 0.1.0` @@ -309,6 +326,7 @@ and always writes the current spec version shown in each section. | `numeric-scalar` | yes | yes (0.2.0) | | `string` | yes | yes (0.2.0), as a 0-d dataset | | `null` | yes | yes (0.1.0) | +| `rec-array` | yes, tagged or not | copied field by field: text as `=3` | Zarr v3 | -| 0.13.3 | 3.12 | `zarr>=3` | Zarr v3 by default | - -The pins matter: a modern pandas makes string columns a type the older -releases cannot write, and pandas 1.x has no wheels for Python 3.12. To add a -release, append to `RELEASES` in `tests/reference_stores.py`. +| 0.7.8 | 3.10 | pandas 1.3.5, numpy 1.23.5, zarr 2.10.3, h5py 3.7.0 | The legacy layout: no root attributes, categoricals as codes with a reference, `ordered` on `__categories`. Read only: it predates the encoding `adata` writes | +| 0.8.0 | 3.11 | pandas 1.5.3, numpy 1.26.4, zarr 2.18.7 | Introduced `encoding-type`/`encoding-version`; the oldest release that reads what `adata` writes | +| 0.9.2 | 3.11 | pandas 1.5.3, numpy 1.26.4, zarr 2.18.7 | | +| 0.10.9 | 3.12 | pandas 2.3.3, numpy 1.26.4, zarr 2.18.7 | | +| 0.11.4 | 3.12 | pandas 2.3.3, numpy 2.5.4, zarr 2.18.7 | The first that reads a `nullable-string-array` (it still writes text as `string-array`) | +| 0.12.2 | 3.12 | pandas 2.3.3, numpy 2.5.4, zarr 3.4.2 | Zarr v3; the first that reads a `null` | +| 0.13.4 | 3.12 | pandas 3.1.0, numpy 2.5.4, zarr 3.4.2 | Zarr v3 by default; with pandas 3, text as `nullable-string-array` | + +Every release runs on exact versions (scipy and h5py too). A modern pandas +makes string columns a type the older releases cannot write, pandas 1.x has +no wheels for Python 3.12, and a floating pin would change what the job +checks, or turn it red, without a change here. To add a release, append to +`RELEASES` in `tests/reference_stores.py`. The readers +`test_external_readers.py` compares against (scanpy, PyTables, loompy, +mudata, squidpy and the rest) are pinned the same way, in `ORACLES` there. + +The unit suite needs no network to read anndata 0.7's layout: +`tests/fixtures/anndata-0.7.8/` holds the two stores the 0.7.8 environment +wrote (the Zarr one zipped), which `test_element_fidelity.py` copies through +every path. To write them again, run the fixture writer in that environment: + +```bash +uv run --no-project --python 3.10 --with anndata==0.7.8 --with scipy==1.9.3 --with pandas==1.3.5 --with numpy==1.23.5 --with zarr==2.10.3 --with h5py==3.7.0 --with numcodecs==0.13.1 tests/fixtures/write_reference_store.py h5ad +``` + +and the same with `zarr` for the Zarr store. + +Under pandas 3 anndata 0.13 writes every text column as a +`nullable-string-array`, while most files in the wild hold `string-array` +datasets. `test_anndata_roundtrip.py` builds its fixtures both ways, and +concatenates one of each against `anndata.concat`. First run downloads those environments; afterwards `uv` serves them from cache and the suite takes about a minute. To skip it without the marker: diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 6b998fa..cd4efda 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -368,6 +368,16 @@ and anndata read it with its legacy reader. The data is read correctly. If `adata` wrote the store from a current source and anndata still warns, that is a bug: please [report it](https://github.com/cellgeni/adata-cli/issues). +### anndata 0.8 to 0.11 fail with `No read method registered for ... nullable-string-array` (or `null`) + +anndata reads a `nullable-string-array` from 0.11 and a `null` from 0.12. +`adata` writes either only where its input held one: anndata 0.13 under +pandas 3 writes every text column as a `nullable-string-array`, and anndata +0.12 and later write a `None` in `uns` as a `null`. A store derived from such +a file keeps them. To give it to an older anndata, write it again from +anndata 0.13 with `anndata.settings.allow_write_nullable_strings = False`, +and without the `None` values in `uns`. + ### Genes are named by id, not by symbol 10x, MTX, Parse and loom imports name features by gene id, which is unique, diff --git a/pyproject.toml b/pyproject.toml index 660291d..058ce1f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -52,7 +52,9 @@ dependencies = [ "pillow>=13.0.0", "rich>=14.2.0", "typer>=0.20.0,<1", - "zarr>=3.1.5,<4", + # 3.2.0 reads both spellings of a v3 record dtype (scanpy's + # rank_genes_groups); 3.1 cannot open a store newer zarr wrote with one. + "zarr>=3.2.0,<4", ] [project.urls] diff --git a/src/adata/commands/convert.py b/src/adata/commands/convert.py index febcfb6..c172b68 100644 --- a/src/adata/commands/convert.py +++ b/src/adata/commands/convert.py @@ -21,6 +21,7 @@ detect_format, output_format, ) +from adata.storage import check_hdf5_inputs from adata.util.path import check_output, is_zarr_path, same_path from adata.util.staging import check_free_space, disk_size, staged_outputs @@ -57,6 +58,10 @@ def convert_store( dst_format = output_format(output, dst_format) converter = converter_for(src_format, dst_format) check_options(converter, options, src_format, dst_format) + # Most converters read their HDF5 with h5py directly, not open_store. + for source in (file, options.raw): + if source is not None: + check_hdf5_inputs(source) plan = converter.plan(file, output, src_format, dst_format, options) for out in plan.outputs: diff --git a/src/adata/elements/__init__.py b/src/adata/elements/__init__.py index 138687b..ffb2af9 100644 --- a/src/adata/elements/__init__.py +++ b/src/adata/elements/__init__.py @@ -3,8 +3,20 @@ `spec` holds the encoding constants, `read` turns any on-disk layout into usable values, `write` emits the current spec, and `strings` reconciles the two backends' incompatible spellings of text. + +The submodules load on first use rather than here. `spec` imports nothing +else, so `adata.storage` can take its constants from it, while `read`, +`strings` and `write` import `adata.storage`: loading them eagerly with the +package would be an import cycle. """ -from adata.elements import read, spec, strings, write +from importlib import import_module +from typing import Any __all__ = ["read", "spec", "strings", "write"] + + +def __getattr__(name: str) -> Any: + if name in __all__: + return import_module(f"{__name__}.{name}") + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/src/adata/elements/read.py b/src/adata/elements/read.py index 49f5d62..5cd0fc7 100644 --- a/src/adata/elements/read.py +++ b/src/adata/elements/read.py @@ -178,7 +178,8 @@ def categories_dataset(col: Any, parent_group: Any | None = None) -> Any: return cats_grp[col_name] if cats_ref is not None and isinstance(cats_ref, (str, bytes)): - # Legacy Zarr: `categories` is an absolute path within the store. + # Legacy Zarr: `categories` names the labels' array by path, relative + # to the frame (`__categories/`, as anndata 0.7 wrote it). path = spec.decode_attr(cats_ref).lstrip("/") if parent_group is not None and path.split("/")[-1] in parent_group: return parent_group[path.split("/")[-1]] @@ -194,9 +195,22 @@ def read_categories(col: Any, parent_group: Any | None = None) -> np.ndarray: return np.asarray(decode_str_array(categories_dataset(col, parent_group)[...]), dtype=str) -def is_ordered(col: Any) -> bool: - """Whether a categorical column declares an order over its categories.""" - return bool(spec.decode_attr(col.attrs.get("ordered", False))) +def is_ordered(col: Any, parent_group: Any | None = None) -> bool: + """Whether a categorical column declares an order over its categories. + + anndata 0.7 kept a column's `ordered` on its labels, in `__categories`, + not on the codes, so a legacy column (a dataset of codes) is looked up + there too: reading only the codes made every such column unordered. + """ + if spec.decode_attr(col.attrs.get("ordered", False)): + return True + if is_dataset(col) and "categories" in col.attrs: + try: + labels = categories_dataset(col, parent_group) + except KeyError: + return False + return bool(spec.decode_attr(labels.attrs.get("ordered", False))) + return False def read_categorical_column( @@ -222,10 +236,17 @@ def read_categorical_column( def _format_values(values: np.ndarray) -> List[str]: - """Render a numeric or text array as strings without a lossy detour.""" + """Render a numeric or text array as strings without a lossy detour. + + A float32 or float16 is written at its own precision, the shortest text + that reads back as the same value, as pandas writes it: widened to a + Python float first, 0.1 became 0.10000000149011612. + """ arr = np.asarray(values) if arr.dtype.kind in ("O", "S", "U", "T"): return decode_str_array(arr).tolist() + if arr.dtype.kind == "f" and arr.dtype.itemsize < 8: + return [str(v) for v in arr.reshape(-1)] return [str(v) for v in arr.tolist()] diff --git a/src/adata/elements/spec.py b/src/adata/elements/spec.py index a1cbc22..bacea73 100644 --- a/src/adata/elements/spec.py +++ b/src/adata/elements/spec.py @@ -28,6 +28,8 @@ STRING = "string" AWKWARD_ARRAY = "awkward-array" NULL = "null" +#: A numpy record array, as scanpy's `rank_genes_groups` keeps its results. +REC_ARRAY = "rec-array" #: Encoding type -> the version this tool writes. CURRENT_VERSION = { @@ -47,8 +49,14 @@ STRING: "0.2.0", AWKWARD_ARRAY: "0.1.0", NULL: "0.1.0", + REC_ARRAY: "0.2.0", } +#: The dataframe version anndata 0.7 wrote: each categorical a dataset of +#: codes whose `categories` attribute is an object reference into +#: `__categories`, and no encoding attributes at the root. +LEGACY_DATAFRAME_VERSION = "0.1.0" + SPARSE_TYPES = frozenset({CSR_MATRIX, CSC_MATRIX}) NULLABLE_TYPES = frozenset( {NULLABLE_INTEGER, NULLABLE_BOOLEAN, NULLABLE_STRING_ARRAY} diff --git a/src/adata/elements/strings.py b/src/adata/elements/strings.py index 7cafe59..1e47ef4 100644 --- a/src/adata/elements/strings.py +++ b/src/adata/elements/strings.py @@ -24,6 +24,9 @@ def is_string_dtype(dtype: Any) -> bool: Covers h5py vlen-UTF-8 (object), fixed-width bytes ('S'), numpy unicode ('U'), numpy StringDType ('T', what zarr-python 3 reports for both `VariableLengthUTF8` and v2 `VLenUTF8`), and bare object arrays. + + Not h5py's other `object` dtypes, variable-length numbers and object + references: taken for text, they were copied as the strings '[1 2 3]'. """ if dtype is None: return False @@ -32,6 +35,11 @@ def is_string_dtype(dtype: Any) -> bool: try: if h5py.check_string_dtype(dtype) is not None: return True + if ( + h5py.check_vlen_dtype(dtype) is not None + or h5py.check_ref_dtype(dtype) is not None + ): + return False except (TypeError, AttributeError): pass kind = getattr(dtype, "kind", None) @@ -76,15 +84,44 @@ def as_str_array(values: Any) -> np.ndarray: return np.asarray(flat, dtype=object).reshape(arr.shape) -def strip_string_filters(kwargs: dict, target_backend: str, zarr_format: Optional[int]) -> dict: - """Drop codecs that cannot survive the jump to `target_backend`. - - A Zarr v2 string array carries `VLenUTF8` in `filters`; forwarding it to a - v3 array raises `TypeError: Expected an ArrayArrayCodec`. The v3 string - dtype encodes variable length itself, so the filter is simply dropped. - """ - if target_backend != "zarr" or zarr_format != 3: - return kwargs - out = dict(kwargs) - out.pop("filters", None) +def text_field_widths(records: np.ndarray) -> dict: + """The longest value, in characters, of each variable-length text field.""" + widths = {} + for field in records.dtype.names or (): + sub = records.dtype.fields[field][0] + if is_string_dtype(sub) and sub.kind in ("O", "T"): + values = as_str_array(records[field]).reshape(-1) + widths[field] = max((len(v) for v in values), default=0) + return widths + + +def record_dtype(src_dtype: Any, target_backend: str, widths: Optional[dict] = None) -> np.dtype: + """A record dtype the target can create, field by field, as anndata + writes a `rec-array`: text as variable-length str on HDF5, fixed-width + ` np.ndarray: + """Records read from one backend, respelt in `dtype` (`record_dtype`).""" + values = np.asarray(values) + out = np.empty(values.shape, dtype=dtype) + for field in dtype.names: + column = values[field] + target = dtype.fields[field][0] + if is_string_dtype(target) and target.kind != column.dtype.kind or target.kind == "O": + column = as_str_array(column) + out[field] = column return out diff --git a/src/adata/elements/write.py b/src/adata/elements/write.py index 698d465..a2532da 100644 --- a/src/adata/elements/write.py +++ b/src/adata/elements/write.py @@ -17,10 +17,6 @@ from adata.storage import create_dataset, is_zarr_group -def _backend_of(parent: Any) -> str: - return "zarr" if is_zarr_group(parent) else "hdf5" - - def _replace(parent: Any, name: str) -> None: """Remove an existing member so it can be rewritten.""" if name in parent: diff --git a/src/adata/formats/json_data.py b/src/adata/formats/json_data.py index f8d351e..b2627fe 100644 --- a/src/adata/formats/json_data.py +++ b/src/adata/formats/json_data.py @@ -100,6 +100,9 @@ def _pyify(value: Any, max_elements: int) -> Any: raise ValueError( f"Refusing to convert array of size {value.size} (> {max_elements}) to JSON." ) + if value.dtype.names is not None: + # A record array (scanpy's rank_genes_groups): one list per field. + return {f: _pyify(value[f], max_elements) for f in value.dtype.names} if np.issubdtype(value.dtype, np.bytes_) or value.dtype.kind == "O": value = decode_str_array(value) return value.tolist() diff --git a/src/adata/formats/pandas_frame.py b/src/adata/formats/pandas_frame.py index a9486db..8395cb0 100644 --- a/src/adata/formats/pandas_frame.py +++ b/src/adata/formats/pandas_frame.py @@ -9,9 +9,11 @@ order kept; * pandas' nullable integers and booleans as `nullable-integer` and `nullable-boolean`; nullable floats as floats with NaN; -* text as a `string-array`, or a `nullable-string-array` when a value is - missing; in obs and var (`categorize=True`) text with a repeated value - becomes a categorical, as anndata's `strings_to_categoricals` makes it; +* text as a `string-array`, or a categorical when a value is missing (its + code -1), which every anndata release from 0.8 reads, where a + `nullable-string-array` needs 0.11; in obs and var (`categorize=True`) + text with a repeated value becomes a categorical too, as anndata's + `strings_to_categoricals` makes it; * an `object` column by what it holds (`pd.api.types.infer_dtype`): numbers as numbers, text as text, anything mixed as text with a warning; * datetimes as ISO text, with a warning. Anything else is left out, with a @@ -139,18 +141,13 @@ def _missing(value: Any) -> bool: def _text(parent: Any, name: str, values: List[Optional[str]], *, categorize: bool) -> None: present = [v for v in values if v is not None] - if categorize: - categories = natural_sorted(set(present)) - if len(categories) < len(values): - lookup = {c: i for i, c in enumerate(categories)} - write_categorical(parent, name, [lookup.get(v, -1) if v is not None else -1 - for v in values], categories) - return - if len(present) < len(values): - write_masked( - parent, name, np.asarray(["" if v is None else v for v in values], dtype=object), - np.asarray([v is None for v in values], dtype=bool), spec.NULLABLE_STRING_ARRAY, - ) + categories = natural_sorted(set(present)) + # A missing value makes a categorical anywhere: as a nullable-string-array + # it made a converted file anndata 0.8 to 0.10 refuse whole. + if len(present) < len(values) or (categorize and len(categories) < len(values)): + lookup = {c: i for i, c in enumerate(categories)} + write_categorical(parent, name, [lookup.get(v, -1) if v is not None else -1 + for v in values], categories) return write_string_array(parent, name, np.asarray(values, dtype=object)) diff --git a/src/adata/storage/__init__.py b/src/adata/storage/__init__.py index 06bb980..8e04ac3 100644 --- a/src/adata/storage/__init__.py +++ b/src/adata/storage/__init__.py @@ -15,11 +15,12 @@ import numpy as np +from adata.elements import spec from adata.util.path import is_zarr_path # noqa: F401 - re-exported -ROOT_ENCODING_TYPE = "anndata" -ROOT_ENCODING_VERSION = "0.1.0" +ROOT_ENCODING_TYPE = spec.ANNDATA +ROOT_ENCODING_VERSION = spec.CURRENT_VERSION[spec.ANNDATA] @dataclass @@ -163,6 +164,13 @@ def open_store( consolidate=writable, ) root = h5py.File(path, mode) + if mode not in ("w", "w-", "x"): + # Anything opened for its contents, read or appended to (--inplace). + try: + check_hdf5_contents(root, path) + except BaseException: + root.close() + raise if _is_writable_mode(mode): ensure_anndata_root_attrs(root) elif require_anndata: @@ -170,24 +178,118 @@ def open_store( return Store(backend="hdf5", root=root, path=path) +class ExternalDataError(ValueError): + """An HDF5 file holds a dataset or link whose data lives in another file.""" + + +def _outside_data(obj: Any) -> Optional[str]: + """Why reading `obj` would read another file, or None if it would not. + + A dataset with external storage reads its bytes from files named in its + creation properties, and a virtual dataset maps datasets of other files. + h5py follows both on any read, silently, so a copy carries that file's + contents into the output. + """ + if not is_hdf5_dataset(obj): + return None + return _dataset_id_outside(obj.id) + + +def _refuse_outside_data(obj: Any) -> None: + reason = _outside_data(obj) + if reason: + raise ExternalDataError( + f"{obj.name} {reason}. adata reads only data held in the file itself." + ) + + +def _dataset_id_outside(dsid: Any) -> Optional[str]: + plist = dsid.get_create_plist() + if plist.get_layout() == h5py.h5d.VIRTUAL: + return "is a virtual dataset, which maps data held in other files" + if plist.get_external_count() > 0: + return "keeps its data in external files" + return None + + +def check_hdf5_contents(group: Any, path: Any = None) -> None: + """Refuse an HDF5 file, or a group of one, that reads data from elsewhere. + + Every link below `group` is looked at once, without reading any data: + an external link opens another file, and a dataset stored externally or + virtually reads one. None of these is something anndata writes, and + any of them would quietly copy another file's contents into an output, + so the input is refused before anything is read from it. + """ + found: list = [] + + def visit(name: bytes, info: Any) -> None: + if found: + return + where = name.decode("utf-8", "replace") + if info.type == h5py.h5l.TYPE_EXTERNAL: + found.append((where, "is an external link into another file")) + elif info.type == h5py.h5l.TYPE_HARD: + oid = h5py.h5o.open(group.id, name) + if isinstance(oid, h5py.h5d.DatasetID): + reason = _dataset_id_outside(oid) + if reason: + found.append((where, reason)) + elif info.type != h5py.h5l.TYPE_SOFT: + found.append((where, "is a user-defined link")) + + group.id.links.visit(visit, info=True) + if found: + where, reason = found[0] + base = getattr(group, "name", "/") or "/" + element = f"{base.rstrip('/')}/{where}" + source = f"'{path}'" if path is not None else "The input" + raise ExternalDataError( + f"{source} is refused: {element} {reason}. adata reads only " + "data held in the file itself." + ) + + +def check_hdf5_file(path: Path) -> None: + """`check_hdf5_contents` for a file on disk that is not open yet.""" + with h5py.File(path, "r") as handle: + check_hdf5_contents(handle, path) + + +#: Suffixes of the HDF5 files a folder source can hold (Space Ranger's +#: matrices, Xenium's), checked before a converter reads them. +HDF5_SUFFIXES = (".h5", ".hdf5", ".h5ad", ".h5mu", ".loom") + + +def check_hdf5_inputs(path: Path) -> None: + """`check_hdf5_file` for a source that is not opened through + `open_store`: an HDF5 file, or the HDF5 files in a folder of outputs.""" + path = Path(path) + if path.is_file(): + files = [path] + elif path.is_dir() and not is_zarr_path(path): + files = sorted( + p for p in path.rglob("*") if p.suffix in HDF5_SUFFIXES and p.is_file() + ) + else: + return + for file in files: + if h5py.is_hdf5(file): + check_hdf5_file(file) + + def zarr_format_of(obj: Any) -> Optional[int]: """The Zarr spec version (2 or 3) backing `obj`, or None for HDF5.""" return getattr(getattr(obj, "metadata", None), "zarr_format", None) -def _decode_attr(value: Any) -> Any: - if isinstance(value, bytes): - return value.decode("utf-8") - return value - - def _is_writable_mode(mode: str) -> bool: return any(flag in mode for flag in ("w", "a", "+", "x")) def has_valid_anndata_root_attrs(root: Any) -> bool: - enc_type = _decode_attr(root.attrs.get("encoding-type", None)) - enc_ver = _decode_attr(root.attrs.get("encoding-version", None)) + enc_type = spec.decode_attr(root.attrs.get("encoding-type", None)) + enc_ver = spec.decode_attr(root.attrs.get("encoding-version", None)) return enc_type == ROOT_ENCODING_TYPE and enc_ver == ROOT_ENCODING_VERSION @@ -196,12 +298,27 @@ def ensure_anndata_root_attrs(root: Any) -> None: root.attrs["encoding-version"] = ROOT_ENCODING_VERSION +def is_legacy_root(root: Any) -> bool: + """A root as anndata 0.7 wrote it: no attributes of its own, and `obs` + and `var` tagged as that release's dataframes.""" + if spec.encoding_type(root) is not None: + return False + for key in ("obs", "var"): + frame = root[key] if key in root else None + if not is_group(frame) or spec.encoding_of(frame) != ( + spec.DATAFRAME, spec.LEGACY_DATAFRAME_VERSION + ): + return False + return True + + def warn_if_missing_anndata_root_attrs(root: Any, *, path: Path) -> None: - if has_valid_anndata_root_attrs(root): + # anndata 0.7 never stamped the root, so its stores are valid without. + if has_valid_anndata_root_attrs(root) or is_legacy_root(root): return - enc_type = _decode_attr(root.attrs.get("encoding-type", None)) - enc_ver = _decode_attr(root.attrs.get("encoding-version", None)) + enc_type = spec.decode_attr(root.attrs.get("encoding-type", None)) + enc_ver = spec.decode_attr(root.attrs.get("encoding-version", None)) warnings.warn( ( f"Store '{path}' root has missing or invalid AnnData attrs " @@ -213,21 +330,44 @@ def warn_if_missing_anndata_root_attrs(root: Any, *, path: Path) -> None: ) +def _decoded(value: Any) -> Any: + """Bytes as text and numpy values as Python's, at any depth of nesting.""" + if isinstance(value, (bytes, np.bytes_)): + return bytes(value).decode("utf-8") + if isinstance(value, (list, tuple)): + return [_decoded(v) for v in value] + if isinstance(value, np.ndarray): + return _decoded(value.tolist()) + if isinstance(value, np.generic): + return value.item() + return value + + +def _is_reference(value: Any) -> bool: + if isinstance(value, (h5py.Reference, h5py.RegionReference)): + return True + dtype = getattr(value, "dtype", None) + return dtype is not None and h5py.check_ref_dtype(dtype) is not None + + +def _attrs_owner(attrs: Any) -> str: + """The name of the element `attrs` belong to, for a message.""" + oid = getattr(attrs, "_id", None) + try: + return h5py.h5i.get_name(oid).decode("utf-8", "replace") + except Exception: # not an h5py AttributeManager + return "an element" + + def _normalize_attr_value(value: Any, target_backend: str) -> Any: + if isinstance(value, h5py.Empty): + # An attribute with a null dataspace: present, but holding nothing. + return None if target_backend == "zarr" else value if target_backend == "zarr": - if isinstance(value, bytes): - return value.decode("utf-8") - if isinstance(value, (list, tuple)): - return [v.decode("utf-8") if isinstance(v, bytes) else v for v in value] - if isinstance(value, np.ndarray): - if value.dtype.kind in ("S", "O"): - return [ - v.decode("utf-8") if isinstance(v, bytes) else v - for v in value.tolist() - ] - return value.tolist() - if isinstance(value, np.generic): - return value.item() + return _decoded(value) + if value is None: + # JSON's null, from a Zarr attribute; HDF5 spells it as nothing. + return h5py.Empty("f4") return value @@ -239,10 +379,17 @@ def copy_attrs(src_attrs: Any, dst_attrs: Any, *, target_backend: str) -> None: one at a time means a separate round trip per attribute -- slow, and the place a `split` over many groups was observed to wedge in CI. """ - normalized = { - str(k): _normalize_attr_value(v, target_backend) - for k, v in src_attrs.items() - } + normalized = {} + for k, v in src_attrs.items(): + if _is_reference(v): + # It names an object by its address in the source file, which + # means nothing in another: h5py would write a dangling pointer, + # and Zarr has no way to hold one. + raise ValueError( + f"Attribute {k!r} of {_attrs_owner(src_attrs)} is an HDF5 " + "object reference, which cannot be copied out of its file." + ) + normalized[str(k)] = _normalize_attr_value(v, target_backend) if not normalized: return @@ -285,8 +432,9 @@ def dataset_create_kwargs( kw["fletcher32"] = bool(src.fletcher32) if src.scaleoffset is not None: kw["scaleoffset"] = src.scaleoffset - if src.fillvalue is not None: - kw["fillvalue"] = src.fillvalue + fill = _carried_fill(src) + if fill is not None: + kw["fillvalue"] = fill if ( target_backend == "hdf5" and is_zarr_array(src) @@ -302,7 +450,9 @@ def dataset_create_kwargs( kw["compression_opts"] = GZIP_LEVEL if target_backend == "zarr" and is_zarr_array(src): src_zarr_format = getattr(getattr(src, "metadata", None), "zarr_format", None) - target_format = _target_zarr_format(kw_target) + # Unknown means "carry nothing version-specific": guessing 3 once + # forwarded sharding into v2 arrays, which reject it outright. + target_format = kw_target # Only when both versions are known and equal can codecs travel. same_version = ( target_format is not None and src_zarr_format == target_format @@ -313,46 +463,82 @@ def dataset_create_kwargs( # accepts the other's. Across versions the target's default is used # rather than a translation that fails at creation time. if same_version: + # `compressors` on both versions: v2's own `compressor` is + # deprecated, and an error reading it once meant zarr's default + # Blosc. None, or an empty tuple, is "uncompressed", and is + # passed on as such -- left out, it too would mean Blosc. + compressors = tuple(src.compressors or ()) if src_zarr_format == 3: - try: - compressors = getattr(src, "compressors", None) - except Exception: - compressors = None - if compressors is not None: - kw["compressors"] = compressors + kw["compressors"] = compressors else: - try: - compressor = getattr(src, "compressor", None) - except Exception: - compressor = None - if compressor is not None: - kw["compressor"] = compressor - - try: - filters = getattr(src, "filters", None) - except Exception: - filters = None + kw["compressors"] = compressors[0] if compressors else None + + filters = src.filters # A v2 string array carries VLenUTF8 in `filters`; the v3 string # dtype encodes variable length itself and rejects it. if filters and not _is_string_src(src): kw["filters"] = filters - try: - shards = getattr(src, "shards", None) - except Exception: - shards = None + shards = src.shards if shards is not None and target_format == 3: kw["shards"] = shards - try: - fill_value = getattr(src, "fill_value", None) - except Exception: - fill_value = None - if fill_value is not None and not _is_string_src(src): + fill_value = src.fill_value + # A record's fill is a value of its fields, which change type when + # text is respelt for the target. + if ( + fill_value is not None + and not _is_string_src(src) + and src.dtype.names is None + ): kw["fill_value"] = fill_value return kw +def _carried_fill(src: Any) -> Any: + """An HDF5 dataset's fill value, when a copy should keep it. + + Only a number other than zero, HDF5's own default, is worth carrying: + every copy writes every value, so the fill is only what the dataset + reports. A record's fill holds a value for each field, and when a field + is text h5py crashes the process creating a dataset with it. + """ + dtype = src.dtype + if dtype.names is not None or dtype.kind not in "biufc": + return None + fill = src.fillvalue + if fill is None or not np.any(np.asarray(fill) != 0): + return None + return fill + + +def _fill_as(fill: Any, dtype: Any) -> Any: + """`fill` converted to `dtype`, or None when it does not survive that. + + A fill carried over from a source of another dtype -- recast to bool of + a float matrix -- is refused by h5py unless converted, and one that the + conversion would change (NaN for an integer) is better left to HDF5's + default than replaced by an arbitrary value. + """ + if dtype is None: + return fill + try: + target = np.dtype(dtype) + except TypeError: + return None + value = np.asarray(fill) + if value.dtype == target: + return fill + if target.names is not None or target.kind not in "biufc": + return None + with np.errstate(all="ignore"), warnings.catch_warnings(): + warnings.simplefilter("ignore") + converted = value.astype(target) + if not np.array_equal(converted.astype(value.dtype), value, equal_nan=True): + return None + return converted[()] + + def _create_string_dataset( parent: Any, name: str, @@ -420,6 +606,15 @@ def create_dataset( kwargs.pop("compressor", None) kwargs.pop("filters", None) + if "fillvalue" in kwargs and not is_zarr_group(parent): + kwargs = dict(kwargs) + target = dtype if dtype is not None else getattr(data, "dtype", None) + if target is None and data is not None: + target = np.asarray(data).dtype + fill = _fill_as(kwargs.pop("fillvalue"), target) + if fill is not None: + kwargs["fillvalue"] = fill + if is_zarr_group(parent): zarr_format = getattr(getattr(parent, "metadata", None), "zarr_format", None) if zarr_format == 3: @@ -451,10 +646,7 @@ def create_dataset( def _zarr_is_compressed(src: Any) -> bool: """Does this Zarr array carry a compressor? (`compressors` covers v2 too.)""" - try: - return bool(getattr(src, "compressors", None)) - except Exception: - return False + return bool(src.compressors) def fit_chunks(kw: dict, shape: Sequence[int], *, backend: str) -> dict: @@ -566,23 +758,9 @@ def with_compression( def _is_null(src: Any) -> bool: - """Is `src` an explicit null -- `h5py.Empty` on HDF5, or tagged `null`?""" - if is_hdf5_dataset(src) and src.shape is None: - return True - value = src.attrs.get("encoding-type", None) - if isinstance(value, bytes): - value = value.decode("utf-8") - return value == "null" - - -def _target_zarr_format(zarr_format: Optional[int]) -> Optional[int]: - """The destination's Zarr version, or None when the caller did not say. - - Deliberately not defaulting to 3: guessing meant v3-only options such as - sharding were forwarded into v2 arrays, which reject them outright. - Unknown means "carry nothing version-specific". - """ - return zarr_format + """Is `src` anndata's null: tagged `null`, an empty dataspace on HDF5 and + a 0-d bool on Zarr? An empty dataspace without the tag is not one.""" + return spec.encoding_type(src) == spec.NULL def _is_string_src(src: Any) -> bool: @@ -728,6 +906,7 @@ def copy_dataset( from adata.elements.strings import target_dtype target_backend = "zarr" if is_zarr_group(dst_group) else "hdf5" + _refuse_outside_data(src) if _is_null(src): # anndata writes an absent element, `raw` most often, as a null: an # empty dataspace on HDF5 and a 0-d bool on Zarr. Neither can be read @@ -738,6 +917,19 @@ def copy_dataset( ds = write_null(dst_group, name) copy_attrs(src.attrs, ds.attrs, target_backend=target_backend) return ds + if is_hdf5_dataset(src) and src.shape is None: + return _copy_empty(src, dst_group, name, target_backend) + if is_hdf5_dataset(src): + _refuse_beyond_zarr(src, target_backend) + if h5py.check_ref_dtype(src.dtype) is not None: + # References name objects by their address in the source. HDF5's + # own copy brings what they point to along and repoints them. + dst_group.copy(src, dst_group, name, expand_refs=True) + return dst_group[name] + if src.dtype.names is not None: + return _copy_records( + src, dst_group, name, compression=compression, skip_attrs=skip_attrs + ) shape = tuple(src.shape) zformat = zarr_format_of(dst_group) @@ -777,16 +969,123 @@ def copy_dataset( return ds -#: A dataframe as anndata 0.7 wrote it: each categorical a dataset of codes -#: whose `categories` attribute is an object reference into `__categories`. -LEGACY_DATAFRAME_VERSION = "0.1.0" +def _copy_empty(src: Any, dst_group: Any, name: str, target_backend: str) -> Any: + """An HDF5 empty dataspace that is not tagged `null`. + + anndata never writes one; other HDF5 writers leave them. Tagging it + `null` on the way, as once happened, made a store anndata 0.8 to 0.11 + read into one they refuse. HDF5 copies it as it is; Zarr has no empty + dataspace, and any value written in its place would be invented, so it + is left out, and said so. + """ + if target_backend == "hdf5": + ds = dst_group.create_dataset(name, data=h5py.Empty(src.dtype)) + copy_attrs(src.attrs, ds.attrs, target_backend=target_backend) + return ds + warnings.warn( + f"Not copied: {src.name}, an HDF5 empty dataspace with no encoding, " + "which Zarr cannot hold.", + UserWarning, + stacklevel=3, + ) + return None + + +def _refuse_beyond_zarr(src: Any, target_backend: str) -> None: + """Refuse an HDF5 dataset Zarr cannot hold, before anything is written. + + Its dtype is an `object` to numpy, which this layer once took for text: + variable-length numbers came out as the strings '[1 2 3]'. + """ + if target_backend != "zarr": + return + if h5py.check_ref_dtype(src.dtype) is not None: + raise ValueError( + f"{src.name} holds HDF5 object references, which cannot be " + "copied to Zarr." + ) + base = h5py.check_vlen_dtype(src.dtype) + if base is not None and base not in (str, bytes): + raise ValueError( + f"{src.name} holds variable-length sequences of {np.dtype(base)}, " + "which Zarr cannot store." + ) + + +def _copy_records( + src: Any, dst_group: Any, name: str, *, compression: Optional[str] = None, + skip_attrs: Sequence[str] = (), +) -> Any: + """A record array (`rec-array`, scanpy's `rank_genes_groups`), field by + field. + + Each backend spells a text field its own way and refuses the other's: + h5py variable-length str (an `object` to numpy, which Zarr calls + ambiguous), Zarr fixed-width ` np.ndarray: + return np.asarray(src[()] if shape == () else src[block[0]:block[1]]) + + widths: dict = {} + if target_backend == "zarr": + # A fixed width has to be known before the array exists: one pass + # to measure the variable-length fields, a second to copy. + from adata.elements.strings import text_field_widths + + for block in blocks: + for field, width in text_field_widths(read(block)).items(): + widths[field] = max(width, widths.get(field, 1)) + dtype = record_dtype(src.dtype, target_backend, widths) + + kw = dataset_create_kwargs(src, target_backend=target_backend, zarr_format=zformat) + if compression is not None: + kw = with_compression( + kw, compression, shape=shape, dtype=dtype, + backend=target_backend, zarr_format=zformat, + ) + with warnings.catch_warnings(): + # zarr notes, on every write, that Zarr v3 has no specification for a + # record dtype yet. anndata writes rec-arrays to v3 just the same. + warnings.filterwarnings("ignore", message=".*does not have a Zarr V3 specification") + ds = create_dataset( + dst_group, name, shape=shape, dtype=dtype, + **fit_chunks(kw, shape, backend=target_backend), + ) + attrs = src.attrs if not skip_attrs else { + k: v for k, v in src.attrs.items() if k not in skip_attrs + } + copy_attrs(attrs, ds.attrs, target_backend=target_backend) + for block in blocks: + values = as_records(read(block), dtype) + if shape == (): + ds[()] = values + else: + ds[block[0]:block[1]] = values + return ds def is_legacy_dataframe(obj: Any) -> bool: - return ( - is_group(obj) - and _decode_attr(obj.attrs.get("encoding-type", None)) == "dataframe" - and str(_decode_attr(obj.attrs.get("encoding-version", None))) == LEGACY_DATAFRAME_VERSION + """A dataframe as anndata 0.7 wrote it: each categorical a dataset of + codes whose `categories` attribute is an object reference into + `__categories`.""" + return is_group(obj) and spec.encoding_of(obj) == ( + spec.DATAFRAME, spec.LEGACY_DATAFRAME_VERSION ) @@ -807,13 +1106,14 @@ def write_legacy_categorical( file nulls it, and Zarr cannot hold one -- so the column is rewritten in the layout anndata has written since 0.8, which needs none. """ - from adata.elements.read import categories_dataset + from adata.elements.read import categories_dataset, is_ordered target_backend = "zarr" if is_zarr_group(dst_group) else "hdf5" group = dst_group.create_group(name) copy_attrs({ - "encoding-type": "categorical", "encoding-version": "0.2.0", - "ordered": bool(_decode_attr(codes_src.attrs.get("ordered", False))), + "encoding-type": spec.CATEGORICAL, + "encoding-version": spec.CURRENT_VERSION[spec.CATEGORICAL], + "ordered": is_ordered(codes_src, frame), }, group.attrs, target_backend=target_backend) categories = categories_dataset(codes_src, frame) if kept is None: @@ -843,7 +1143,7 @@ def copy_legacy_dataframe( target_backend = "zarr" if is_zarr_group(dst_group) else "hdf5" grp = dst_group.create_group(name) copy_attrs(src.attrs, grp.attrs, target_backend=target_backend) - grp.attrs["encoding-version"] = "0.2.0" + grp.attrs["encoding-version"] = spec.CURRENT_VERSION[spec.DATAFRAME] for key in src.keys(): child = src[key] if key == "__categories": @@ -871,7 +1171,14 @@ def copy_tree( # HDF5's own copy keeps every dataset exactly as it was, which is # what is wanted unless the caller asked for something else. if not exclude and compression is None: - dst_group.copy(src_obj, dst_group, name) + if is_hdf5_group(src_obj): + check_hdf5_contents(src_obj) + else: + _refuse_outside_data(src_obj) + # References below it -- anndata 0.7's categoricals, in a frame + # nested in raw, obsm or uns -- would otherwise come out null: + # with expand_refs HDF5 repoints them at their copies. + dst_group.copy(src_obj, dst_group, name, expand_refs=True) return dst_group[name] if is_dataset(src_obj): return copy_dataset(src_obj, dst_group, name, compression=compression) diff --git a/tests/fixtures/anndata-0.7.8/reference.h5ad b/tests/fixtures/anndata-0.7.8/reference.h5ad new file mode 100644 index 0000000000000000000000000000000000000000..de5d86b6ffb5382260a1fd2eb9f870791b7a9e9c GIT binary patch literal 77704 zcmeHQU2J5@RW92*JI&54c#_?Wce9(hyE{AUB>Uqe6EHtv?(F<*6PCo;-AEQZ*gba7 z*u>K|ZF}NDKpY6rK?yiPMBZpY35g;H5E>*D{D8zh@G$%@2q7c#FcLu;B%(Md0`s)g zsdK)*_g44q>u$R}-96`8?o;Pf-TL|JRMojvb#Hw-fBxeA_dR@{p(~d&_n1NF#Lt^@ zRi5i}BJl8^6bJhnQxSfnpB;UM{)`zC`7w##5BJJT7cLmnZxBDI+-7baV%I1H-(^P# zUTIGwkiT$tj0$)|N;xicY?~c@=1@Y<21UDK_mbYZDL?%C4x>{M})=)zLjI2|N; zwf`e#7uU-l`tW&b8#xIZ46p-Qo)>;b@{yNtYu`?W+Z2B5J1mDDZx@r{ZhxHl+|M%| zW@2uCCK+z~Rptj@V~TRU@s(t_9pQ(*#_~J$i~a-y*^Ff5sA0tV%=eoIEXu{w)co{p z>B=)p*B1zyhx+rSj~G^R^>2U!pE%=M@(OVtkD;^Kk=Yt|gzFx59 z4KA!Kl#7c_4c{jIqBiDiX=(P-{PgwUTw#HLJud#h-LEI~A4nJVB*SF2{uZa^%S9X4 z!(M!s%SBsx#g!$Izg;Nmr!+A&zg${ce8jtNxinv%E|!baB7fBLpDNDHIi(Q!JA?v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`s*%$*j0qoZ9A79AtexO+2)!x%)?+Lgm2j)?K#2M&qkpq_eux!9qQl9Dh&_J(2bY<18tD_SE=2kiiar4$?yx@;y;&WjV~k5F#Z@98>gziy@r54 zzVK6+op15x;Yx+8MS25u(H;aq4z${EkAM^=7MIGir7MW0P@0%6Eg4goxI8ysShDoe z{QMm8bF+(9URu6-iC%~;6&II^)5eqwrH@TqDOz^oN_l>Hf!~si@;8Qv_eg8|@#OQW zyiR982h6I&=xtUI*tE~?GW~kbx6jMHS#7l5z0o`YS6MW_^d~ZYgkH`9kFU>iKOVhL z7(5M)s2?7AUwO81xcYbZu5>SYMV7>F_3Bt~LN?t5=6KE=|Af64dWAKqG?eSz8|hWQ UtI$ZVzAJi#8b_=F91ZFJ1CuX!rvLx| literal 0 HcmV?d00001 diff --git a/tests/fixtures/anndata-0.7.8/reference.zarr.zip b/tests/fixtures/anndata-0.7.8/reference.zarr.zip new file mode 100644 index 0000000000000000000000000000000000000000..612114153a77128a0e6d60bb20cb73b0c1fccf4e GIT binary patch literal 39050 zcmdsg30zHE`+ud9iUvtEI3X%ir6}Y!h?3GEw~*$dc}}J@A|i7sLn%Ysil!UKhts(()2;c*e~1 z=KsL|p#;8TgMx!%gCYZhhR*eijUDE~`j^#&|8kUnTr^{b_Ti)-8sKljk0#5Ep>soG zqY|R$$@9SI3m@wf92Fbk7vFaj&qRI!I|=<*00W{TBZC6sXD7~%pB)s(pa{$nj6vWR zgJC`o41n2@fwKc}Ajq~HUve3*m+dS8e=?JlkT7W<5MQ=_$q6g1yQLW^+kGrdyR0yTs1PvdwQmJ;O>eD+VvcF>PSXL!6>UfwI;O>%zrl?tkrKu z#q{TGmS^$`?gm(Co(WZby4qGst4HRvI-R8^ajb4wlo+2^We z_`o8g<1z0fm2-8?Pz%B!jm482jzij`d^)tp%{IY*6%Sc&^K8#qeY^TR-)K{lfDFTj z#~rSXD7a#nT=nVyiaq}Iyzq_=U=`Y;_|6PPhnb@vG)HZQIga4TGAsa~3kEcO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R_xa$tME`wA39gEc_9~;buyDIkgs_Fffcd30D>@K$WQdC><%C z9ZBR}41t6N#s)SdmU|fLyJd8vS8`+F4o6}UJ+;=Jvu$GCKIXQ2&w z_d>0$*TwA?(_khi4hx6WntC!X2{{a%!bKJ*e<}ihf?jw*7>L^g=@+e^P}2zmXD$^~ z@8i*=W8@*k4*7yUi*Tr(N9qg;r~6b6G)}K076(jcvrsr>o03ODH!Xjp>myx=MVxHv5P7NNPL{|9Ld72f~= literal 0 HcmV?d00001 diff --git a/tests/fixtures/write_reference_store.py b/tests/fixtures/write_reference_store.py index 3fef60e..5b31b97 100644 --- a/tests/fixtures/write_reference_store.py +++ b/tests/fixtures/write_reference_store.py @@ -1,9 +1,9 @@ """Write a reference AnnData store, run inside a pinned anndata environment. Invoked by tests/reference_stores.py through `uv run --with anndata==`, so -this file must stay compatible with every anndata release under test (0.8 +this file must stay compatible with every anndata release under test (0.7.8 onward) and must not import anything from `adata`. Features that only exist in -later versions are attempted and skipped rather than assumed. +later versions are left out for the releases without them. Usage: write_reference_store.py """ @@ -23,6 +23,12 @@ N_OBS, N_VAR = 6, 4 +def _release() -> tuple: + from importlib.metadata import version + + return tuple(int(part) for part in version("anndata").split(".")[:2]) + + def build(): """An object exercising the encodings this tool has to understand.""" obs = pd.DataFrame( @@ -40,19 +46,22 @@ def build(): index=[f"cell_{i}" for i in range(N_OBS)], ) - # Nullable dtypes have been supported since 0.8, but guard anyway. - try: + # Nullable dtypes are written from 0.8; 0.7 fails on them part way. + if _release() >= (0, 8): obs["nullable_int"] = pd.array([1, 2, None, 4, 5, None], dtype="Int32") obs["nullable_bool"] = pd.array( [True, False, None, True, False, None], dtype="boolean" ) - except Exception: - pass var = pd.DataFrame( { "gene_ids": [f"ENSG{i}" for i in range(N_VAR)], "highly_variable": [True, False, True, False], + # Categorical in raw/var too, as scanpy leaves feature_types: + # anndata 0.7 wrote it as codes with an object reference. + "feature_types": pd.Categorical( + ["Gene Expression"] * 3 + ["Antibody Capture"] + ), }, index=[f"gene_{i}" for i in range(N_VAR)], ) @@ -76,6 +85,17 @@ def build(): obj.uns["a_list"] = ["x", "y", "z"] obj.uns["numbers"] = np.arange(5) obj.uns["nested"] = {"deep": {"value": 1.5}} + # scanpy's marker genes: record arrays, one field per group. + obj.uns["rank_genes_groups"] = { + "names": np.rec.fromarrays( + [np.array(["gene_0", "gene_2"]), np.array(["gene_1", "gene_3"])], + names=["A", "B"], + ), + "scores": np.rec.fromarrays( + [np.array([2.5, 1.0], dtype="float32"), np.array([3.0, 0.5], dtype="float32")], + names=["A", "B"], + ), + } obj.raw = obj return obj diff --git a/tests/reference_stores.py b/tests/reference_stores.py index c7b0b2b..d2794e8 100644 --- a/tests/reference_stores.py +++ b/tests/reference_stores.py @@ -6,7 +6,7 @@ environment `uv` assembles for that release, so nothing here depends on the versions installed for the test suite itself. -Stores are built once per session and cached, since assembling six +Stores are built once per session and cached, since assembling seven environments is slow the first time and free afterwards. """ @@ -30,34 +30,115 @@ class Release: spec: str #: Short label used in test ids. label: str - #: Era-appropriate pins. Modern pandas makes string columns a type the - #: older releases cannot write, so each release needs the stack it shipped - #: against rather than today's. + #: The stack the release is run on, pinned exactly. Modern pandas makes + #: string columns a type the older releases cannot write, so each needs + #: the stack it shipped against rather than today's; and a floating pin + #: could change what the job checks, or turn it red, with no change here. extras: tuple = () #: Interpreter to run under. pandas 1.x has no wheels for 3.12, so the - #: oldest releases build against 3.11. + #: oldest releases build against 3.11, and 0.7 against 3.10. python: str = "3.12" - - -#: anndata 0.8 introduced the encoding-type/encoding-version scheme, so it is -#: the oldest release whose output this tool claims to read. 0.11 is where the -#: index became a nullable-string-array group, and 0.12 is where Zarr v3 -#: arrived -- the two changes that broke the CLI. + #: Whether the release can open what adata writes. anndata 0.7 predates + #: the encoding scheme adata writes (categoricals as groups and the + #: rest), so its stores are read, never written for it. + reads_back: bool = True + + +#: anndata 0.7 wrote no encoding attributes at the root, and its categoricals +#: as codes with an object reference: the oldest layout this tool reads. 0.8 +#: introduced the encoding-type/encoding-version scheme adata writes, so it is +#: the oldest release that reads what adata writes. 0.11 is the first that can +#: read a nullable-string-array (it does not write one: anndata writes them +#: from 0.13 with pandas 3), 0.12 the first that reads a `null` and Zarr v3. RELEASES: List[Release] = [ + Release( + "anndata==0.7.8", "0.7", + extras=("scipy==1.9.3", "pandas==1.3.5", "numpy==1.23.5", + "zarr==2.10.3", "h5py==3.7.0", "numcodecs==0.13.1"), + python="3.10", reads_back=False, + ), Release( "anndata==0.8.0", "0.8", - extras=("pandas<2", "numpy<2", "zarr<3"), python="3.11", + extras=("scipy==1.17.1", "pandas==1.5.3", "numpy==1.26.4", + "zarr==2.18.7", "h5py==3.16.0"), + python="3.11", ), Release( "anndata==0.9.2", "0.9", - extras=("pandas<2", "numpy<2", "zarr<3"), python="3.11", + extras=("scipy==1.17.1", "pandas==1.5.3", "numpy==1.26.4", + "zarr==2.18.7", "h5py==3.16.0"), + python="3.11", + ), + Release( + "anndata==0.10.9", "0.10", + extras=("scipy==1.17.1", "pandas==2.3.3", "numpy==1.26.4", + "zarr==2.18.7", "h5py==3.16.0"), + ), + Release( + "anndata==0.11.4", "0.11", + extras=("scipy==1.18.1", "pandas==2.3.3", "numpy==2.5.4", + "zarr==2.18.7", "h5py==3.16.0"), + ), + Release( + "anndata==0.12.2", "0.12", + extras=("scipy==1.18.1", "pandas==2.3.3", "numpy==2.5.4", + "zarr==3.4.2", "h5py==3.16.0"), + ), + Release( + "anndata==0.13.4", "0.13", + extras=("scipy==1.18.1", "pandas==3.1.0", "numpy==2.5.4", + "zarr==3.4.2", "h5py==3.16.0"), ), - Release("anndata==0.10.9", "0.10", extras=("pandas<3", "numpy<2", "zarr<3")), - Release("anndata==0.11.4", "0.11", extras=("pandas<3", "zarr<3")), - Release("anndata==0.12.2", "0.12", extras=("pandas<3", "zarr>=3")), - Release("anndata~=0.13.3", "0.13", extras=("zarr>=3",)), ] +#: The readers the external-reader tests compare against, at exact versions, +#: for the same reason as the releases' stacks above. Move them deliberately. +ORACLES: Dict[str, str] = { + "anndata": "anndata==0.13.4", + "geopandas": "geopandas==1.2.0", + "loompy": "loompy==3.0.8", + "mudata": "mudata==0.4.1", + "pandas": "pandas==3.1.0", + "pyarrow": "pyarrow==26.0.0", + "scanpy": "scanpy==1.12.5", + "scipy": "scipy==1.18.1", + "squidpy": "squidpy==1.8.4", + "tables": "tables==3.11.1", +} + + +def oracle(package: str) -> str: + """`package` at its pinned version; a requirement with its own pin as given.""" + return ORACLES.get(package, package) + + +def with_args(release: Release) -> List[str]: + """The `uv run --with` arguments that assemble `release`'s environment.""" + args = ["--with", release.spec] + for extra in release.extras: + args += ["--with", extra] + return args + + +#: Stores anndata 0.7.8 wrote (`write_reference_store.py`, in the 0.7 +#: release's environment above), committed so the unit suite reads a real +#: legacy layout without the network. The Zarr store is zipped. +LEGACY_FIXTURES = Path(__file__).parent / "fixtures" / "anndata-0.7.8" + + +def legacy_store(fmt: str, dest: Path) -> Path: + """A fresh copy, under `dest`, of the store anndata 0.7.8 wrote as `fmt`.""" + import zipfile + + dest.mkdir(parents=True, exist_ok=True) + if fmt == "zarr": + with zipfile.ZipFile(LEGACY_FIXTURES / "reference.zarr.zip") as archive: + archive.extractall(dest) + return dest / "reference.zarr" + target = dest / "reference.h5ad" + shutil.copyfile(LEGACY_FIXTURES / "reference.h5ad", target) + return target + class ReferenceUnavailable(RuntimeError): """Raised when a store could not be produced for a release.""" @@ -89,12 +170,7 @@ def must_build() -> bool: def build(release: Release, fmt: str, out_dir: Path) -> Path: """Write one reference store, returning its path.""" out_dir.mkdir(parents=True, exist_ok=True) - cmd = [ - "uv", "run", "--no-project", "--python", release.python, - "--with", release.spec, "--with", "scipy", - ] - for extra in release.extras: - cmd += ["--with", extra] + cmd = ["uv", "run", "--no-project", "--python", release.python, *with_args(release)] cmd += [str(WRITER), str(out_dir), fmt] result = subprocess.run(cmd, capture_output=True, text=True, timeout=900) diff --git a/tests/test_anndata_roundtrip.py b/tests/test_anndata_roundtrip.py index 9e65aad..374e479 100644 --- a/tests/test_anndata_roundtrip.py +++ b/tests/test_anndata_roundtrip.py @@ -28,7 +28,7 @@ N_OBS, N_VAR = 6, 4 -def _build(tmp_path: Path, fmt: str, *, nullable_strings: bool) -> Path: +def _build(tmp_path: Path, fmt: str, *, nullable_strings: bool, prefix: str = "") -> Path: """Write a reference store with anndata covering every common encoding. `nullable_strings` selects between the two on-disk shapes anndata can give @@ -48,7 +48,7 @@ def _build(tmp_path: Path, fmt: str, *, nullable_strings: bool) -> Path: ), "free_text": ["a", "bb", "ccc", "d", "ee", "f"], }, - index=[f"cell_{i}" for i in range(N_OBS)], + index=[f"{prefix}cell_{i}" for i in range(N_OBS)], ) var = pd.DataFrame( { @@ -438,3 +438,48 @@ def test_subset_of_a_consolidated_zarr_store_round_trips(tmp_path): got = ad.read_zarr(out) assert got.shape == (2, 2) assert list(got.obs_names) == ["c0", "c2"] + + +@pytest.mark.parametrize( + "first,second", + [(False, False), (False, True), (True, False)], + ids=["string-arrays", "string-array-then-nullable", "nullable-then-string-array"], +) +def test_concat_of_plain_and_nullable_text_matches_anndata(tmp_path, fmt, first, second): + """F090: under pandas 3 anndata writes all text as nullable-string-array, + so the suite's concat never met a plain string-array -- what anndata + before 0.13, or any release under pandas before 3, wrote -- nor a mix of + the two, as when an old file is concatenated with a new one.""" + for name in ("a", "b"): + (tmp_path / name).mkdir() + a = _build(tmp_path / "a", fmt, nullable_strings=first, prefix="a_") + b = _build(tmp_path / "b", fmt, nullable_strings=second, prefix="b_") + out = tmp_path / f"merged.{fmt}" + result = runner.invoke(app, ["concat", str(a), str(b), "-o", str(out), "--keys", "a,b"]) + assert result.exit_code == 0, result.stdout + (result.stderr or "") + + got = _read(out) + want = ad.concat([_read(a), _read(b)], join="inner") + assert list(got.obs_names) == list(want.obs_names) + for column in ("cell_type", "free_text", "n_counts"): + assert got.obs[column].astype(object).tolist() == want.obs[column].astype(object).tolist(), column + assert got.obs["cell_type"].cat.ordered + assert (got.X != want.X).nnz == 0 + + +def test_export_dataframe_writes_float32_as_pandas_does(tmp_path, fmt): + """F125: a float32 column (scanpy's pct_counts_*) exported as + 0.10000000149011612 where pandas writes 0.1.""" + obs = pd.DataFrame( + {"pct": np.array([0.1, 2.3, 33.7], dtype="float32"), + "half": np.array([0.1, 2.2, 7.0], dtype="float16")}, + index=["c0", "c1", "c2"], + ) + obj = ad.AnnData(np.ones((3, 1), dtype="float32"), obs=obs) + path = tmp_path / f"f.{fmt}" + obj.write_h5ad(path) if fmt == "h5ad" else obj.write_zarr(path) + result = runner.invoke(app, ["export", "dataframe", str(path), "obs"]) + assert result.exit_code == 0, result.stdout + got = [line.split(",")[1:] for line in result.stdout.splitlines()[1:] if line] + want = [line.split(",")[1:] for line in _read(path).obs.to_csv().splitlines()[1:]] + assert got == want == [["0.1", "0.1"], ["2.3", "2.2"], ["33.7", "7.0"]] diff --git a/tests/test_anndata_versions.py b/tests/test_anndata_versions.py index b8ded8f..fdbd129 100644 --- a/tests/test_anndata_versions.py +++ b/tests/test_anndata_versions.py @@ -1,4 +1,4 @@ -"""Compatibility against stores written by real anndata releases, 0.8 to 0.13. +"""Compatibility against stores written by real anndata releases, 0.7 to 0.13. The rest of the suite checks this tool against stores it built itself, which cannot catch the thing that actually broke it: anndata changing how it writes @@ -35,9 +35,10 @@ must_build, offline, uv_available, + with_args, ) -# Building six environments on a cold uv cache is slow, so these get much +# Building seven environments on a cold uv cache is slow, so these get much # longer than the suite-wide limit. pytestmark = [pytest.mark.integration, pytest.mark.timeout(1800)] @@ -197,29 +198,26 @@ def test_encodings_are_recognised_not_guessed(store): @pytest.fixture -def read_back(release, fmt): +def read_back(release): """Read a store using the same anndata release that wrote the fixture. Checking our output with the *current* anndata would not show whether an - older release can still open what we wrote. + older release can still open what we wrote. anndata 0.7 predates the + encoding adata writes, so its stores are only read. """ import subprocess - from tests.reference_stores import Release + if not release.reads_back: + pytest.skip(f"anndata {release.label} cannot read the current encoding") def _read(path: Path, expression: str): script = ( "import warnings; warnings.filterwarnings('ignore')\n" "import anndata as ad, sys\n" - f"a = ad.read_{'zarr' if fmt == 'zarr' else 'h5ad'}(sys.argv[1])\n" + f"a = ad.read_{'zarr' if path.suffix == '.zarr' else 'h5ad'}(sys.argv[1])\n" f"print('RESULT', {expression})\n" ) - cmd = [ - "uv", "run", "--no-project", "--python", release.python, - "--with", release.spec, "--with", "scipy", - ] - for extra in release.extras: - cmd += ["--with", extra] + cmd = ["uv", "run", "--no-project", "--python", release.python, *with_args(release)] cmd += ["python", "-c", script, str(path)] out = subprocess.run(cmd, capture_output=True, text=True, timeout=900) line = [ @@ -262,6 +260,52 @@ def test_subset_preserves_raw_across_versions(store, tmp_path, fmt, read_back): assert read_back(out, "(a.raw.shape)") == "(2, 4)" +def _zarr_format(release) -> str: + """The Zarr version a release reads: zarr-python 2 reads only v2.""" + return "2" if any(e.startswith("zarr==2") for e in release.extras) else "3" + + +@pytest.mark.parametrize("target", ["h5ad", "zarr"]) +def test_convert_output_opens_in_the_release_that_wrote_the_input( + store, tmp_path, release, target, read_back +): + """F086, F017: the promise that every release from 0.8 reads what adata + writes was checked on subset outputs only. A conversion, to the same + backend or the other, rank_genes_groups included, is read back here.""" + out = tmp_path / f"converted.{target}" + extra = ["--zarr-format", _zarr_format(release)] if target == "zarr" else [] + result = runner.invoke(app, ["convert", str(store), "-o", str(out), *extra]) + assert result.exit_code == 0, _out(result) + + assert read_back(out, "(a.n_obs, a.n_vars)") == f"({N_OBS}, {N_VAR})" + assert read_back(out, "list(a.obs_names)") == str(OBS_NAMES) + assert read_back(out, "a.obs['cell_type'].cat.ordered") == "True" + assert read_back(out, "list(a.raw.var['feature_types'])") == str( + ["Gene Expression"] * 3 + ["Antibody Capture"] + ) + assert read_back( + out, "[str(v) for v in a.uns['rank_genes_groups']['names']['A']]" + ) == "['gene_0', 'gene_2']" + + +def test_split_and_concat_outputs_open_in_the_release_that_wrote_the_input( + store, tmp_path, fmt, read_back +): + """F086: split's pieces and concat's merge were read with the current + anndata only.""" + parts = tmp_path / "parts" + result = runner.invoke(app, ["split", str(store), "--by", "cell_type", "-o", str(parts)]) + assert result.exit_code == 0, _out(result) + pieces = sorted(parts.glob(f"*.{fmt}")) + assert read_back(pieces[0], "sorted(set(a.obs['cell_type']))") == "['A']" + + merged = tmp_path / f"merged.{fmt}" + result = runner.invoke(app, ["concat", *map(str, pieces), "-o", str(merged)]) + assert result.exit_code == 0, _out(result) + assert read_back(merged, "sorted(a.obs_names)") == str(sorted(OBS_NAMES)) + assert read_back(merged, "str(a.obs['cell_type'].dtype)") == "category" + + @pytest.mark.parametrize("target", ["h5ad", "zarr"]) def test_conversion_between_backends_keeps_the_data(store, tmp_path, target): """Reading with the current anndata is enough to prove the crossing works.""" diff --git a/tests/test_element_fidelity.py b/tests/test_element_fidelity.py new file mode 100644 index 0000000..166abc2 --- /dev/null +++ b/tests/test_element_fidelity.py @@ -0,0 +1,476 @@ +"""Elements anndata and scanpy write, through every copy path. + +A copy is HDF5 to HDF5, HDF5 to Zarr or Zarr to HDF5, and Zarr v2 or v3 on +either side. Each source here is written by anndata itself -- or, for anndata +0.7's layout, is a store anndata 0.7.8 wrote (`tests/fixtures/anndata-0.7.8`) +-- and anndata, the oracle, reads every copy back. +""" + +from __future__ import annotations + +import re +import subprocess +import sys +import warnings +from pathlib import Path + +import h5py +import numpy as np +import pytest +from typer.testing import CliRunner + +from adata.cli import app +from tests.reference_stores import legacy_store + +ad = pytest.importorskip("anndata") +pd = pytest.importorskip("pandas") +sparse = pytest.importorskip("scipy.sparse") +zarr = pytest.importorskip("zarr") + +runner = CliRunner() +_ANSI = re.compile(r"\x1b\[[0-9;]*[a-zA-Z]") + +BACKENDS = ["h5ad", "zarr2", "zarr3"] + + +def _out(result) -> str: + text = result.stdout + (result.stderr or "") + return " ".join(_ANSI.sub("", text).split()) + + +def _ok(*args): + result = runner.invoke(app, [str(a) for a in args]) + assert result.exit_code == 0, _out(result) + return result + + +def _path(tmp: Path, backend: str, stem: str) -> Path: + return tmp / (f"{stem}.h5ad" if backend == "h5ad" else f"{stem}.zarr") + + +def _format_flag(backend: str) -> list: + return {"zarr2": ["--zarr-format", "2"], "zarr3": ["--zarr-format", "3"]}.get(backend, []) + + +def _write(obj, path: Path, backend: str) -> Path: + if backend == "h5ad": + obj.write_h5ad(path) + return path + previous = ad.settings.zarr_write_format + ad.settings.zarr_write_format = 2 if backend == "zarr2" else 3 + try: + obj.write_zarr(path) + finally: + ad.settings.zarr_write_format = previous + return path + + +def _read(path: Path): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return ad.read_zarr(path) if path.suffix == ".zarr" else ad.read_h5ad(path) + + +def _same_frame(got, want) -> None: + """Equal values, column by column, whatever text dtype each backend + reads back (anndata reads h5ad text as pandas strings, Zarr as object).""" + assert list(got.index) == list(want.index) + assert list(got.columns) == list(want.columns) + for column in want.columns: + a, b = got[column], want[column] + if isinstance(b.dtype, pd.CategoricalDtype): + assert isinstance(a.dtype, pd.CategoricalDtype), column + assert list(a.cat.categories) == list(b.cat.categories), column + assert a.cat.ordered == b.cat.ordered, column + assert a.astype(object).tolist() == b.astype(object).tolist(), column + + +# --------------------------------------------------------------------------- +# scanpy's rank_genes_groups: record arrays + + +def _marker_genes(n_obs: int = 4, n_var: int = 3): + obj = ad.AnnData(np.arange(n_obs * n_var, dtype=np.float32).reshape(n_obs, n_var)) + obj.obs_names = [f"c{i}" for i in range(n_obs)] + obj.uns["rank_genes_groups"] = { + "params": {"groupby": "leiden", "method": "wilcoxon"}, + # As scanpy builds them: one field per group, text of any width. + "names": np.rec.fromarrays( + [np.array(["g1", "g22", "gene_333"]), np.array(["ß", "g2", ""])], + names=["0", "1"], + ), + "scores": np.rec.fromarrays( + [np.array([2.5, 1.0, -0.5], dtype="float32"), np.array([3.0, 0.5, 0.0], dtype="float32")], + names=["0", "1"], + ), + "pvals": np.rec.fromarrays( + [np.array([0.01, 0.2, 0.9]), np.array([0.001, 0.5, 1.0])], names=["0", "1"], + ), + } + return obj + + +def _same_markers(got, want) -> None: + for key in ("names", "scores", "pvals"): + a, b = got.uns["rank_genes_groups"][key], want.uns["rank_genes_groups"][key] + assert a.dtype.names == b.dtype.names, key + for field in b.dtype.names: + assert a[field].tolist() == b[field].tolist(), (key, field) + if b[field].dtype.kind == "f": + assert a[field].dtype == b[field].dtype, (key, field) + + +@pytest.mark.parametrize("target", BACKENDS) +@pytest.mark.parametrize("source", BACKENDS) +def test_a_rank_genes_groups_result_converts_to_every_backend(tmp_path, source, target): + """F017: a record array crossed no backend. To Zarr, its h5py text fields + (an `object` dtype) failed as 'ambiguous'; to HDF5, Zarr's ` Path: + obj = ad.AnnData(np.ones((2, 2), dtype=np.float32)) + obj.write_h5ad(path) + with h5py.File(path, "a") as f: + build(f) + return path + + +def test_variable_length_numbers_are_refused_by_zarr_not_turned_into_text(tmp_path): + """F126: any `object` dtype was taken for text, so ragged int lists + came out of a Zarr conversion as the strings '[1 2 3]' and '[4]'.""" + def build(f): + ds = f["uns"].create_dataset("ragged", shape=(2,), dtype=h5py.vlen_dtype(np.int32)) + ds[0], ds[1] = [1, 2, 3], [4] + + src = _with_uns(tmp_path / "src.h5ad", build) + out = tmp_path / "out.zarr" + result = runner.invoke(app, ["convert", str(src), "-o", str(out)]) + assert result.exit_code == 1 + assert "/uns/ragged holds variable-length sequences of int32" in _out(result) + assert not out.exists() + + +def test_variable_length_numbers_copy_between_h5ad_files_with_compression(tmp_path): + """F126: the copy dataset by dataset tried to write them as text and + failed with 'Can't implicitly convert non-string objects to strings'.""" + def build(f): + ds = f["uns"].create_dataset("ragged", shape=(2,), dtype=h5py.vlen_dtype(np.int32)) + ds[0], ds[1] = [1, 2, 3], [4] + + src = _with_uns(tmp_path / "src.h5ad", build) + out = tmp_path / "out.h5ad" + _ok("convert", src, "-o", out, "--compression", "gzip") + with h5py.File(out) as f: + assert h5py.check_vlen_dtype(f["uns/ragged"].dtype) == np.int32 + assert [list(v) for v in f["uns/ragged"][...]] == [[1, 2, 3], [4]] + assert [list(v) for v in _read(out).uns["ragged"]] == [[1, 2, 3], [4]] + + +def test_a_dataset_of_references_is_refused_by_zarr(tmp_path): + """F126: object references took the text path as well.""" + def build(f): + f["uns"].create_dataset("pointers", data=np.array([f["X"].ref], dtype=h5py.ref_dtype)) + + src = _with_uns(tmp_path / "src.h5ad", build) + result = runner.invoke(app, ["convert", str(src), "-o", str(tmp_path / "out.zarr")]) + assert result.exit_code == 1 + assert "/uns/pointers holds HDF5 object references" in _out(result) + + +def test_a_dataset_of_references_copies_between_h5ad_files_with_compression(tmp_path): + """F126: copied dataset by dataset, its references were stringified.""" + def build(f): + f["uns"].create_dataset("pointers", data=np.array([f["X"].ref], dtype=h5py.ref_dtype)) + + src = _with_uns(tmp_path / "src.h5ad", build) + out = tmp_path / "out.h5ad" + _ok("convert", src, "-o", out, "--compression", "gzip") + with h5py.File(out) as f: + target = f[f["uns/pointers"][0]] + np.testing.assert_array_equal(target[...], np.ones((2, 2), dtype=np.float32)) + + +# --------------------------------------------------------------------------- +# Attributes + + +def test_unusual_hdf5_attributes_convert_to_zarr(tmp_path): + """F130: an attribute holding h5py.Empty, or a 2-D array of bytes, failed + the conversion with a JSON error that named no element.""" + def build(f): + attrs = f["uns"].create_dataset("v", data=np.arange(3)).attrs + attrs["encoding-type"], attrs["encoding-version"] = "array", "0.2.0" + attrs["nothing"] = h5py.Empty("f4") + attrs["grid"] = np.array([[b"a", b"b"], [b"c", b"d"]]) + + src = _with_uns(tmp_path / "src.h5ad", build) + out = tmp_path / "out.zarr" + _ok("convert", src, "-o", out) + attrs = dict(zarr.open_group(out, mode="r")["uns/v"].attrs) + assert attrs["nothing"] is None + assert attrs["grid"] == [["a", "b"], ["c", "d"]] + np.testing.assert_array_equal(_read(out).uns["v"], np.arange(3)) + + +def test_a_null_attribute_converts_back_to_hdf5(tmp_path): + """F130: the way back, Zarr's JSON null became an attribute h5py + could not write.""" + src = _write(ad.AnnData(np.ones((2, 2), dtype=np.float32), uns={"v": np.arange(3)}), + tmp_path / "src.zarr", "zarr3") + group = zarr.open_group(src, mode="a") + group["uns/v"].attrs["nothing"] = None + zarr.consolidate_metadata(src) + out = tmp_path / "out.h5ad" + _ok("convert", src, "-o", out) + with h5py.File(out) as f: + assert isinstance(f["uns/v"].attrs["nothing"], h5py.Empty) + np.testing.assert_array_equal(_read(out).uns["v"], np.arange(3)) + + +@pytest.mark.parametrize("target", ["out.zarr", "out.h5ad"]) +def test_a_reference_attribute_is_refused_naming_its_element(tmp_path, target): + """F130: a reference attribute failed a Zarr conversion with 'Object of + type Reference is not JSON serializable', naming nothing; between HDF5 + files it was written as a pointer into the wrong file.""" + def build(f): + f["uns"].create_dataset("v", data=np.arange(3)).attrs["link"] = f["X"].ref + + src = _with_uns(tmp_path / "src.h5ad", build) + extra = ["--compression", "gzip"] if target.endswith("h5ad") else [] + result = runner.invoke(app, ["convert", str(src), "-o", str(tmp_path / target), *extra]) + assert result.exit_code == 1 + assert "Attribute 'link' of /uns/v is an HDF5 object reference" in _out(result) + + +# --------------------------------------------------------------------------- +# Zarr v2 codecs + + +def _v2_store(path: Path) -> Path: + import numcodecs + + obj = ad.AnnData(np.arange(20, dtype=np.float32).reshape(5, 4), obs={"n": np.arange(5)}) + obj.obs_names = [f"c{i}" for i in range(5)] + obj.obsm["X_pca"] = np.arange(10, dtype=np.float64).reshape(5, 2) + _write(obj, path, "zarr2") + group = zarr.open_group(path, mode="a") + for key, codec in (("X", numcodecs.Zstd(level=5)), ("obsm/X_pca", None)): + values, attrs = group[key][...], dict(group[key].attrs) + del group[key] + group.create_array(key, data=values, compressors=codec).attrs.update(attrs) + zarr.consolidate_metadata(path) + return path + + +@pytest.mark.parametrize("command", ["convert", "subset"]) +def test_a_zarr_v2_store_keeps_each_arrays_compression(tmp_path, command): + """F134, F135: an uncompressed v2 array came out Blosc-compressed, and + the codec of a compressed one was read through zarr's deprecated + `compressor`, behind an `except` that turned any error -- a deprecation + made an error, as some pipelines do -- into Blosc as well.""" + src = _v2_store(tmp_path / "src.zarr") + out = tmp_path / "out.zarr" + with warnings.catch_warnings(): + warnings.simplefilter("error", DeprecationWarning) + if command == "convert": + _ok("convert", src, "-o", out) + else: + _ok("subset", src, "-q", "n < 3", "-o", out) + group = zarr.open_group(out, mode="r") + assert group.metadata.zarr_format == 2 + assert [c.get_config() for c in group["X"].compressors] == [{"id": "zstd", "level": 5, "checksum": False}] + assert group["obsm/X_pca"].compressors == () + got, truth = _read(out), _read(src) + rows = slice(None) if command == "convert" else slice(0, 3) + np.testing.assert_array_equal(got.X, truth.X[rows]) + np.testing.assert_array_equal(got.obsm["X_pca"], truth.obsm["X_pca"][rows]) + + +# --------------------------------------------------------------------------- +# Empty dataspaces + + +def _blank(f): + f["uns"].create_dataset("blank", data=h5py.Empty("f4")) + + +def test_an_untagged_empty_dataspace_is_not_made_a_null_in_zarr(tmp_path): + """F136: an empty dataspace another HDF5 writer left, with no encoding, + was tagged `null` on its way to Zarr, and anndata 0.8 to 0.11 refuse a + `null` whole. Zarr has nothing to hold it as, so it is left out.""" + src = _with_uns(tmp_path / "src.h5ad", _blank) + out = tmp_path / "out.zarr" + with pytest.warns(UserWarning, match="Not copied: /uns/blank"): + _ok("convert", src, "-o", out, "--zarr-format", "2") + assert "blank" not in zarr.open_group(out, mode="r")["uns"] + assert "blank" not in _read(out).uns + + +def test_an_untagged_empty_dataspace_stays_untagged_between_h5ad_files(tmp_path): + """F136: copied dataset by dataset, it was given `encoding-type: null`.""" + src = _with_uns(tmp_path / "src.h5ad", _blank) + out = tmp_path / "out.h5ad" + _ok("convert", src, "-o", out, "--compression", "gzip") + with h5py.File(out) as f: + assert f["uns/blank"].shape is None + assert "encoding-type" not in f["uns/blank"].attrs + _read(out) + + +def test_a_null_anndata_wrote_stays_a_null_in_every_backend(tmp_path): + """anndata's own None: a tagged empty dataspace, still copied as a null.""" + pytest.importorskip("anndata", minversion="0.12") + src = _write(ad.AnnData(np.ones((2, 2), dtype=np.float32), uns={"none": None}), + tmp_path / "src.h5ad", "h5ad") + for out in (tmp_path / "out.zarr", tmp_path / "out.h5ad"): + _ok("convert", src, "-o", out, *(["--compression", "gzip"] if out.suffix == ".h5ad" else [])) + assert _read(out).uns["none"] is None + + +# --------------------------------------------------------------------------- +# Fill values + + +@pytest.mark.parametrize("layout", ["csr", "csc", "dense"]) +def test_recast_to_bool_works_on_a_float_h5ad_matrix(tmp_path, layout): + """F071: the float source's fill value, 0.0, was passed on to the new + bool dataset, and h5py has no conversion for it: 'no appropriate + function for conversion path'.""" + values = np.array([[0, 1, 0], [1, 1, 0]], dtype=np.float32) + matrix = {"csr": sparse.csr_matrix, "csc": sparse.csc_matrix}.get(layout, np.asarray)(values) + src = _write(ad.AnnData(matrix), tmp_path / "src.h5ad", "h5ad") + out = tmp_path / "out.h5ad" + _ok("recast", src, "X", "--dtype", "bool", "-o", out) + got = _read(out).X + got = got.toarray() if sparse.issparse(got) else got + assert got.dtype == np.bool_ + np.testing.assert_array_equal(got, values.astype(bool)) diff --git a/tests/test_elements.py b/tests/test_elements.py index 525d19d..d1b4967 100644 --- a/tests/test_elements.py +++ b/tests/test_elements.py @@ -435,3 +435,68 @@ def test_decode_str_array_preserves_shape(): def test_decode_str_array_replaces_undecodable_bytes(): assert "�" in decode_str_array(np.array([b"\xff\xfe"]))[0] + + +# --------------------------------------------------------------------------- +# rendering numbers, and dtypes h5py calls object + + +@pytest.mark.parametrize("dtype", ["float32", "float16", "float64"]) +def test_floats_render_at_their_own_precision(new_store, dtype): + """F125: a float32 was widened to a Python float first, so 0.1 printed as + 0.10000000149011612; pandas writes the shortest text for the dtype.""" + pd = pytest.importorskip("pandas") + values = np.array([0.1, 2.3, 33.7, -0.0, 1e4, 0.003], dtype=dtype) + path, opener = new_store() + with opener("a") as root: + ew.write_dense(root["uns"], "v", values) + got = read_str_chunk(root["uns"]["v"], 0, len(values)) + assert got == pd.Series(values).to_csv(index=False, header=False).splitlines() + + +def test_h5py_object_dtypes_other_than_text_are_not_text(): + """F126: every object dtype was text, so variable-length numbers and + references were copied as their string forms.""" + import h5py + + assert is_string_dtype(h5py.string_dtype()) + assert is_string_dtype(h5py.string_dtype("ascii")) + assert is_string_dtype(np.dtype(object)), "an in-memory object array of str" + assert not is_string_dtype(h5py.vlen_dtype(np.int32)) + assert not is_string_dtype(h5py.ref_dtype) + assert target_dtype(h5py.vlen_dtype(np.int32), "hdf5") == h5py.vlen_dtype(np.int32) + + +def test_record_dtypes_respell_text_fields_for_each_backend(): + """F017: as anndata writes a rec-array, text fields are variable-length + str on HDF5 and ``; reading it + from the codes made every such column unordered.""" + from adata.storage import open_store + from tests.reference_stores import legacy_store + + src = legacy_store(fmt, tmp_path) + with open_store(src, "r") as store: + obs = store.root["obs"] + assert "ordered" not in obs["cell_type"].attrs, "0.7.8 put it on the labels" + assert is_ordered(obs["cell_type"], obs) + assert not is_ordered(obs["unordered"], obs) + assert read_categories(obs["cell_type"], obs).tolist() == ["A", "B", "C"] diff --git a/tests/test_external_readers.py b/tests/test_external_readers.py index 5115a37..04f8a72 100644 --- a/tests/test_external_readers.py +++ b/tests/test_external_readers.py @@ -39,7 +39,7 @@ write_starsolo_velocyto, write_text_matrix, ) -from tests.reference_stores import must_build, offline, uv_available +from tests.reference_stores import must_build, offline, oracle, uv_available pytestmark = [pytest.mark.integration, pytest.mark.timeout(1800)] @@ -55,7 +55,8 @@ def _run(packages: List[str], script: str, *args: str, python: str = PYTHON): pytest.skip("needs uv and the network") cmd = ["uv", "run", "--no-project", "--python", python] for package in packages: - cmd += ["--with", package] + # Pinned: an oracle that moves on its own changes what is checked. + cmd += ["--with", oracle(package)] cmd += ["python", "-c", script, *args] result = subprocess.run(cmd, capture_output=True, text=True, timeout=1500) lines = [l for l in result.stdout.splitlines() if l.startswith("RESULT ")] @@ -1267,3 +1268,62 @@ def test_visium_hd_cells_import_as_10x_s_geopandas_recipe_reads_them(tmp_path): out = tmp_path / "cells.h5ad" _convert(str(hd.outs), "-o", str(out), "--cells", "--var-names", "gene_symbols") assert _run(["scanpy", "geopandas"], _COMPARE_VISIUM_CELLS, str(hd.cells.folder), str(out)) == [] + + +# --------------------------------------------------------------------------- +# scanpy's marker genes, written by scanpy, read back by scanpy after every +# copy: `rank_genes_groups` is a dict of record arrays, one field per group. + +_WRITE_MARKERS = r""" +import json, sys, warnings +warnings.filterwarnings("ignore") +import numpy as np, pandas as pd, scanpy as sc, anndata as ad +rng = np.random.default_rng(0) +a = ad.AnnData(rng.poisson(1.0, (40, 12)).astype("float32")) +a.var_names = [f"gene_{i}" for i in range(12)] +a.obs["group"] = pd.Categorical(["a", "bb"] * 20) +sc.pp.log1p(a) +sc.tl.rank_genes_groups(a, "group", method="wilcoxon") +a.write_h5ad(sys.argv[1] + ".h5ad") +a.write_zarr(sys.argv[1] + ".zarr") +print("RESULT", json.dumps(True)) +""" + +_COMPARE_MARKERS = r""" +import json, sys, warnings +warnings.filterwarnings("ignore") +import scanpy as sc, anndata as ad +read = lambda p: ad.read_zarr(p) if p.endswith(".zarr") else ad.read_h5ad(p) +want = sc.get.rank_genes_groups_df(read(sys.argv[1]), group=None) +got = sc.get.rank_genes_groups_df(read(sys.argv[2]), group=None) +problems = [] +if list(got.columns) != list(want.columns): + problems.append(f"columns {list(got.columns)} != {list(want.columns)}") +else: + for column in want.columns: + if got[column].astype(str).tolist() != want[column].astype(str).tolist(): + problems.append(f"{column} differs") +print("RESULT", json.dumps(problems)) +""" + + +@pytest.mark.parametrize( + "source,target,extra", + [ + ("h5ad", "zarr", []), + ("h5ad", "zarr", ["--zarr-format", "2"]), + ("zarr", "h5ad", []), + ("h5ad", "h5ad", ["--compression", "gzip"]), + ], + ids=["h5ad-zarr3", "h5ad-zarr2", "zarr-h5ad", "h5ad-h5ad-gzip"], +) +def test_rank_genes_groups_survives_a_conversion_as_scanpy_reads_it(tmp_path, source, target, extra): + """F017, F021: scanpy's marker genes crossed no backend (Zarr refused the + HDF5 text fields, h5py the Zarr ones), and a copy with --compression + crashed the process.""" + stem = tmp_path / "scanpy" + _run(["scanpy"], _WRITE_MARKERS, str(stem)) + src = f"{stem}.{source}" + out = tmp_path / f"out.{target}" + _convert(src, "-o", str(out), *extra) + assert _run(["scanpy"], _COMPARE_MARKERS, src, str(out)) == [] diff --git a/tests/test_legacy_copies.py b/tests/test_legacy_copies.py index 6b335dd..6da5c9b 100644 --- a/tests/test_legacy_copies.py +++ b/tests/test_legacy_copies.py @@ -132,3 +132,27 @@ def test_compression_applies_to_legacy_codes_taken_onto_a_modality(tmp_path): # Its labels are HDF5 strings, which are never compressed: only # their heap pointers would be. assert f["obs/leiden/codes"].compression == "gzip" + + +def test_a_modality_with_a_legacy_raw_var_converts_to_h5ad(tmp_path): + """F006: a modality's raw, copied whole by h5py, kept raw/var's 0.1.0 + categoricals with null references, and anndata could not open the + output: 'Invalid HDF5 object reference'.""" + from tests.conftest import write_h5mu + + truth = write_h5mu(tmp_path / "in.h5mu") + rna = truth.mods["rna"] + kinds = ["x" if i % 2 else "y" for i in range(rna.n_vars)] + with h5py.File(truth.path, "a") as f: + mod = f["mod/rna"] + if "raw" in mod: + del mod["raw"] + raw = mod.create_group("raw") + raw.attrs.update({"encoding-type": "raw", "encoding-version": "0.1.0"}) + raw.create_dataset("X", data=np.ones((rna.n_obs, rna.n_vars), dtype=np.float32)) + _legacy_frame(raw, "var", list(rna.var_names), {"kind": kinds}) + out = tmp_path / "out.h5ad" + _ok("convert", truth.path, "-o", out, "--mod", "rna") + got = _read(out) + assert list(got.raw.var["kind"]) == kinds + assert list(got.raw.var_names) == list(rna.var_names) diff --git a/tests/test_pandas_frame.py b/tests/test_pandas_frame.py index 6b3300e..5a86bc3 100644 --- a/tests/test_pandas_frame.py +++ b/tests/test_pandas_frame.py @@ -79,3 +79,23 @@ def test_obs_text_with_repeats_is_categorical(new_store): got = _read(path).obs assert got["kind"].dtype == "category" and got["kind"].tolist() == ["a", "b", "a"] assert any("obs['mixed'] holds mixed" in w for w in warnings) + + +def test_text_with_a_missing_value_in_a_table_is_a_categorical_every_release_reads(new_store): + """F133: written as a nullable-string-array, a model table's text column + holding a None (random_state=None) made a converted file that anndata + 0.8 to 0.10 refused whole. A categorical with code -1 is what every + release reads, and pandas reads the gap back as missing.""" + from adata.elements import spec + from adata.storage import open_store + + path, opener = new_store() + frame = pd.DataFrame({"Parameter": ["lda", None, "15"]}, index=["algorithm", "random_state", "n_iter"]) + with opener("a") as root: + write_frame(root["uns"], "parameters", frame) + with open_store(path, "r") as store: + column = store.root["uns/parameters/Parameter"] + assert spec.encoding_type(column) == spec.CATEGORICAL + assert column["codes"][1] == -1 + got = _read(path).uns["parameters"]["Parameter"] + assert got.tolist()[0] == "lda" and pd.isna(got.iloc[1]) and got.iloc[2] == "15" diff --git a/tests/test_storage.py b/tests/test_storage.py index 01054c9..a4fe2db 100644 --- a/tests/test_storage.py +++ b/tests/test_storage.py @@ -559,3 +559,222 @@ def test_copy_dataset_of_a_row_chunked_source_round_trips(new_store): create_dataset(root["uns"], "src", data=values, chunks=(1, 4)) copy_dataset(root["uns"]["src"], root["uns"], "dst") assert np.array_equal(root["uns"]["dst"][...], values) + + +# --------------------------------------------------------------------------- +# Data held outside the file + + +def _anndata_root(f) -> None: + import h5py + + f.attrs.update({"encoding-type": "anndata", "encoding-version": "0.1.0"}) + for key, n in (("obs", 1), ("var", 8)): + frame = ew.write_dataframe_header(f, key, [f"{key}{i}" for i in range(n)], []) + assert isinstance(frame, h5py.Group) + + +def _outside_file(temp_dir, kind: str): + """An h5ad whose X takes its data from another file.""" + import h5py + + other = temp_dir / "other.bin" + other.write_bytes(bytes(range(8))) + path = temp_dir / f"{kind}.h5ad" + with h5py.File(temp_dir / "other.h5", "w") as f: + f.create_dataset("data", data=np.arange(8, dtype="u1").reshape(1, 8)) + with h5py.File(path, "w") as f: + _anndata_root(f) + if kind == "external": + ds = f.create_dataset("X", shape=(1, 8), dtype="u1", external=[(str(other), 0, 8)]) + elif kind == "virtual": + layout = h5py.VirtualLayout(shape=(1, 8), dtype="u1") + layout[:] = h5py.VirtualSource(str(temp_dir / "other.h5"), "data", shape=(1, 8)) + ds = f.create_virtual_dataset("X", layout) + else: + f["X"] = h5py.ExternalLink(str(temp_dir / "other.h5"), "data") + return path + spec.set_encoding(ds, spec.ARRAY) + return path + + +KINDS = ["external", "virtual", "link"] + + +def _cli_out(result) -> str: + import re + + text = result.stdout + (result.stderr or "") + return " ".join(re.sub(r"\x1b\[[0-9;]*[a-zA-Z]", "", text).split()) + + +@pytest.mark.parametrize("kind", KINDS) +def test_a_store_reading_another_file_is_refused_on_opening(temp_dir, kind): + """F041: a dataset or link whose data lives in another file was read + like any other, and copied into the output.""" + from adata.storage import ExternalDataError + + path = _outside_file(temp_dir, kind) + with pytest.raises(ExternalDataError, match=r"/X (keeps its data|is a virtual|is an external link)"): + open_store(path, "r") + with pytest.raises(ExternalDataError): + open_store(path, "a") + + +@pytest.mark.parametrize("kind", KINDS) +@pytest.mark.parametrize( + "command", + [ + ["convert", "{src}", "-o", "{tmp}/out.zarr"], + ["convert", "{src}", "-o", "{tmp}/out.h5ad"], + ["subset", "{src}", "-q", "_index == 'obs0'", "-o", "{tmp}/out.h5ad"], + ["export", "array", "{src}", "X", "-o", "{tmp}/out.npy"], + ["view", "{src}"], + ], + ids=["convert-zarr", "convert-h5ad", "subset", "export", "view"], +) +def test_every_command_refuses_a_store_reading_another_file(temp_dir, kind, command): + """F041: commands read, copied and exported such data without a word.""" + from typer.testing import CliRunner + + from adata.cli import app + + src = _outside_file(temp_dir, kind) + args = [a.format(src=src, tmp=temp_dir) for a in command] + result = CliRunner().invoke(app, args) + assert result.exit_code == 1, _cli_out(result) + assert "is refused" in _cli_out(result) + assert not list(temp_dir.glob("out*")) + + +def test_an_hdf5_matrix_reading_another_file_is_refused_by_convert(temp_dir): + """F041: the other converters open their HDF5 with h5py directly.""" + import h5py + from typer.testing import CliRunner + + from adata.cli import app + from tests.conftest import write_10x_h5 + + h5 = write_10x_h5( + temp_dir / "m.h5", np.eye(3, dtype=np.int32), + barcodes=["a-1", "b-1", "c-1"], ids=["g1", "g2", "g3"], names=["G1", "G2", "G3"], + ) + secret = temp_dir / "other.bin" + secret.write_bytes(np.ones(3, dtype=np.int32).tobytes()) + with h5py.File(h5, "a") as f: + del f["matrix/data"] + f.create_dataset("matrix/data", shape=(3,), dtype=np.int32, external=[(str(secret), 0, 12)]) + result = CliRunner().invoke(app, ["convert", str(h5), "-o", str(temp_dir / "out.h5ad")]) + assert result.exit_code == 1 + assert "/matrix/data keeps its data in external files" in _cli_out(result) + assert not (temp_dir / "out.h5ad").exists() + + +@pytest.mark.parametrize("kind", ["external", "virtual"]) +def test_copy_tree_refuses_data_held_in_another_file(temp_dir, kind): + """F041: a copy from a file not opened through open_store (MuData's + modalities are copied from an h5py handle) is checked too.""" + import h5py + + from adata.storage import ExternalDataError + + src = _outside_file(temp_dir, kind) + with h5py.File(src, "r") as f, open_store(temp_dir / "out.h5ad", "w") as dst: + for compression in (None, "gzip"): + with pytest.raises(ExternalDataError): + copy_tree(f["X"], dst.root, f"X_{compression}", compression=compression) + group = dst.root.create_group("holder") + with pytest.raises(ExternalDataError): + copy_tree(f, group, "everything") + + +def test_a_store_holding_only_its_own_data_opens(temp_dir): + import h5py + + path = temp_dir / "plain.h5ad" + with h5py.File(path, "w") as f: + _anndata_root(f) + f["X"] = np.ones((1, 8)) + f["alias"] = h5py.SoftLink("/X") + with open_store(path, "r") as store: + assert store.root["alias"].shape == (1, 8) + + +# --------------------------------------------------------------------------- +# Fill values and attributes + + +def test_a_fill_value_is_converted_with_the_dtype_or_left_out(): + """F071: a float source's fill went to a bool dataset unconverted, which + h5py refuses; one the conversion would change is left to the default.""" + from adata.storage import _fill_as + + assert _fill_as(np.float32(1.0), np.bool_) == np.True_ + assert _fill_as(np.float64(7.0), np.int16) == 7 + assert _fill_as(np.float64(0.5), np.int16) is None + assert _fill_as(np.float64(np.nan), np.int64) is None + assert np.isnan(_fill_as(np.float32(np.nan), np.float64)) + assert _fill_as(np.int8(3), np.dtype([("a", "i4")])) is None + + +def test_only_a_numeric_fill_other_than_zero_is_carried(temp_dir): + """F021: a record's fill, a value for each field, crashed h5py when the + fields were text; and a zero fill is HDF5's default anyway.""" + import h5py + + path = temp_dir / "src.h5" + with h5py.File(path, "w") as f: + f.create_dataset("zero", shape=(4,), dtype="f4") + f.create_dataset("nan", shape=(4,), dtype="f4", fillvalue=np.nan) + f.create_dataset("records", shape=(4,), dtype=[("a", h5py.string_dtype()), ("b", "f4")]) + with h5py.File(path, "r") as f: + assert "fillvalue" not in dataset_create_kwargs(f["zero"], target_backend="hdf5") + assert np.isnan(dataset_create_kwargs(f["nan"], target_backend="hdf5")["fillvalue"]) + assert "fillvalue" not in dataset_create_kwargs(f["records"], target_backend="hdf5") + with open_store(temp_dir / "dst.h5ad", "w") as dst: + ds = copy_dataset(f["nan"], dst.root, "nan") + assert np.isnan(ds.fillvalue) + from adata.storage import create_dataset + + kw = dataset_create_kwargs(f["nan"], target_backend="hdf5") + assert create_dataset(dst.root, "as_int", shape=(4,), dtype="i4", **kw).fillvalue == 0 + + +def test_copy_attrs_decodes_nested_bytes_and_empties_for_zarr(temp_dir): + """F130: bytes were decoded one level deep, and h5py.Empty not at all.""" + import h5py + + src_path = temp_dir / "src.h5ad" + with h5py.File(src_path, "w") as f: + f.attrs["grid"] = np.array([[b"a", b"b"], [b"c", b"d"]]) + f.attrs["nothing"] = h5py.Empty("f4") + f.attrs["words"] = np.array(["x", "y"], dtype=h5py.string_dtype()) + with h5py.File(src_path, "r") as src, open_store(temp_dir / "dst.zarr", "w") as dst: + copy_attrs(src.attrs, dst.root.attrs, target_backend="zarr") + with open_store(temp_dir / "dst.zarr", "r") as dst: + assert dst.root.attrs["grid"] == [["a", "b"], ["c", "d"]] + assert dst.root.attrs["nothing"] is None + assert dst.root.attrs["words"] == ["x", "y"] + + +def test_dataset_create_kwargs_keeps_a_v2_arrays_compression_or_its_absence(temp_dir): + """F134, F135: a v2 array's codec was read through the deprecated + `compressor`, and an uncompressed one forwarded nothing, so zarr gave it + Blosc.""" + import numcodecs + + src = temp_dir / "v2.zarr" + with open_store(src, "w", zarr_format=2) as store: + store.root.create_array("zstd", data=np.arange(10), compressors=numcodecs.Zstd(level=5)) + store.root.create_array("none", data=np.arange(10), compressors=None) + with open_store(src, "r") as store, open_store(temp_dir / "out.zarr", "w", zarr_format=2) as out: + import warnings + + with warnings.catch_warnings(): + warnings.simplefilter("error", DeprecationWarning) + for key in ("zstd", "none"): + kw = dataset_create_kwargs(store.root[key], target_backend="zarr", zarr_format=2) + copy_dataset(store.root[key], out.root, key) + assert out.root["zstd"].compressors == (numcodecs.Zstd(level=5),) + assert out.root["none"].compressors == () + assert kw["compressors"] is None diff --git a/tests/test_storage_root_attrs.py b/tests/test_storage_root_attrs.py index 4d6e230..698b1d0 100644 --- a/tests/test_storage_root_attrs.py +++ b/tests/test_storage_root_attrs.py @@ -40,3 +40,21 @@ def test_open_store_writable_mode_sets_root_attrs(temp_dir: Path) -> None: with h5py.File(file_path, "r") as f: assert f.attrs.get("encoding-type") == "anndata" assert f.attrs.get("encoding-version") == "0.1.0" + + +def test_open_store_read_does_not_warn_for_anndata_0_7s_layout(temp_dir: Path) -> None: + """F164: anndata 0.7 never stamped the root, so every command on one of + its stores warned that a valid file had 'missing or invalid' attrs. Its + obs and var are tagged as that release's 0.1.0 dataframes.""" + import warnings + + file_path = temp_dir / "anndata_07.h5ad" + _make_minimal_h5ad(file_path) + with h5py.File(file_path, "a") as f: + for key in ("obs", "var"): + f[key].attrs.update({"encoding-type": "dataframe", "encoding-version": "0.1.0"}) + + with warnings.catch_warnings(): + warnings.simplefilter("error") + with open_store(file_path, "r"): + pass diff --git a/uv.lock b/uv.lock index e61d0a8..8890e2c 100644 --- a/uv.lock +++ b/uv.lock @@ -254,6 +254,75 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" }, ] +[[package]] +name = "msgspec" +version = "0.22.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d0/e6/6dcf9306ff3c5e486578f3bf29ed11dfbdbbc2a8bf0caf7e07d392887fda/msgspec-0.22.0.tar.gz", hash = "sha256:0a13624a4969159fe35d8c2a3d377b2b61bbd8585e327440d5e52725affcce38", size = 343188, upload-time = "2026-09-29T14:14:11.422Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a4/87/3e017dca361d09ed1cd09dc981a6df21b32e830fbec3470f7486d38b6be5/msgspec-0.22.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ab1e9e7531e353653b906cdd12a0220cc288a1e8e3436aabc65f4508d91b14d9", size = 201301, upload-time = "2026-09-29T14:12:38.048Z" }, + { url = "https://files.pythonhosted.org/packages/fb/02/109165edaafb895668d87177972a32ade9126a54f3736123d8e44be9096d/msgspec-0.22.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:b60b43425a47eb9cfe987f6874e354ca7c760e58e295b4e2273ff03574df28a1", size = 193044, upload-time = "2026-09-29T14:12:39.46Z" }, + { url = "https://files.pythonhosted.org/packages/54/a5/65de05f8804492f76ea121b21a125cdf1d97ec461c677bfa0ba354d6fbdd/msgspec-0.22.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b5a169b5b03f0f2c7a296c002647db1dab75d2cd501bca34e32b71cab0261b56", size = 224035, upload-time = "2026-09-29T14:12:40.876Z" }, + { url = "https://files.pythonhosted.org/packages/4a/cc/aa1a47f8c92280d37498a5ea56a2a36606d034383e3e6472d64cbb56cf85/msgspec-0.22.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:99c401861c5bb3a57f7d6423ea7ed4352cd57aa3f04f4fbe9f3e3e4564a10f08", size = 230377, upload-time = "2026-09-29T14:12:42.796Z" }, + { url = "https://files.pythonhosted.org/packages/61/50/f8bcdb3d613a4a4b92704297a12eba5c985cf572a64ee1a004d265759c69/msgspec-0.22.0-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:08826f5e5b0fa2f7a88592c396a243cfcc63d37e19f9d4fbe3b3f1be2fbdc404", size = 237390, upload-time = "2026-09-29T14:12:44.282Z" }, + { url = "https://files.pythonhosted.org/packages/cf/8a/473fa423f8fdd1b810b8652594323d7301df6920b62844d860daa0feff34/msgspec-0.22.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:21460f54cee9208239b1a8421fdf25bffc77293e1daba88f585711ad839b9758", size = 227733, upload-time = "2026-09-29T14:12:45.839Z" }, + { url = "https://files.pythonhosted.org/packages/03/1d/272ce23adae6c71b3f763aed3ee6e115cccc56124ed8ee0e3e3d2681e2c8/msgspec-0.22.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:cfc3d9557de9c806318725b702f3e664db33167bb42892079b693c69893fd33b", size = 236783, upload-time = "2026-09-29T14:12:47.234Z" }, + { url = "https://files.pythonhosted.org/packages/f6/26/29e0b9a8605c8819a3c718158e345a616ac42c092dd7d7ab248c2f2b0a72/msgspec-0.22.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0b25dcbc108783cb72503ed705b9fbb8c3cb02ee5801923f44b5f038c91cc365", size = 232728, upload-time = "2026-09-29T14:12:48.792Z" }, + { url = "https://files.pythonhosted.org/packages/e1/a6/99597c281d716da6c662b48dcc3f734669f716b41d5df2af367dac9e7c21/msgspec-0.22.0-cp312-cp312-win_amd64.whl", hash = "sha256:6ad64f5c260866b0d543f89f50cee43628989c1433c5de7ce820281fa28a2611", size = 192885, upload-time = "2026-09-29T14:12:50.274Z" }, + { url = "https://files.pythonhosted.org/packages/46/80/85fff923d448b886ec3a85900c578d9367f08dad54fe48879495b4c6d055/msgspec-0.22.0-cp312-cp312-win_arm64.whl", hash = "sha256:0922714feff5300aacd8ecd65fa828317ce4bf5212b3139258c0bfc0253cd80e", size = 191223, upload-time = "2026-09-29T14:12:51.699Z" }, + { url = "https://files.pythonhosted.org/packages/7f/62/5374fba2ede0408f4bd8b9b3a6c8464f8d0ea7ae9a2a064bd81ca492bd1e/msgspec-0.22.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:f13c127a945479bc9db057eb253b8851075c8e1ae07ffc967bfa1c5676203a86", size = 201355, upload-time = "2026-09-29T14:12:53.145Z" }, + { url = "https://files.pythonhosted.org/packages/cc/e3/357baa8d2a9164a98dfd7ef9d3a58125df0ed981be909945bdd337be7194/msgspec-0.22.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:5aa24eb475d070ecbbe5b21080fc3ce4b0b76c60de25cfe0c9678d8fb44bb42f", size = 193097, upload-time = "2026-09-29T14:12:54.52Z" }, + { url = "https://files.pythonhosted.org/packages/fa/1b/9cc07718d1dee8ed5e89a265801d565bc0f15ead435ccb198f9c7bf92574/msgspec-0.22.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:627bfdfe5a4b3d916b3360b30f4cddeee3a084f56593e33527c6872fa8322ff9", size = 224112, upload-time = "2026-09-29T14:12:55.983Z" }, + { url = "https://files.pythonhosted.org/packages/46/64/f33fdfe95aca76601194a7064d14816c7c22c4eccc1b03a5335785895fa3/msgspec-0.22.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c6c310ef83e7e291b01a63298828f848348bb99e84a1098c4b3923c05674d032", size = 230472, upload-time = "2026-09-29T14:12:57.648Z" }, + { url = "https://files.pythonhosted.org/packages/8e/b3/8ceaa9981c230adf43c45a6e8da25da23a381eddc7ed05aeaca1d5e7928b/msgspec-0.22.0-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:7c1e76c6bd523141b9c05c2f8a70979cd0efedbd68855a66f292f8892c0b8fc7", size = 237382, upload-time = "2026-09-29T14:12:59.414Z" }, + { url = "https://files.pythonhosted.org/packages/88/a6/7b5c4fb39e0bf2dabc8be923c33c39b07ba769a0ce6f0afbbdfaadb1f2f2/msgspec-0.22.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:bc374dedd5f85a5f4de2386dc5f737894ccb8c1ac18e9566ce66fd9839e6285d", size = 227717, upload-time = "2026-09-29T14:13:00.88Z" }, + { url = "https://files.pythonhosted.org/packages/b8/5b/2334ee638880e756c8bc54a1177bd65877c786433693a43594ef5ecbe2d8/msgspec-0.22.0-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:feafe612034d49e9144340c0b5168ee4e22c2af4aaa2c1db11ae84e1aac9543b", size = 236781, upload-time = "2026-09-29T14:13:02.468Z" }, + { url = "https://files.pythonhosted.org/packages/6c/e5/b4c5323b17ecfce45350695d40fc93e16856db957a53cbcf2f53007d6e12/msgspec-0.22.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6f48317f05312bfdf78248f53933f830f07ab75cc1c813ac3ca4220cb3b5b019", size = 232777, upload-time = "2026-09-29T14:13:04.025Z" }, + { url = "https://files.pythonhosted.org/packages/01/33/e591f9d3d8d6c9cfc02ae95f3e3c44920f2d18050f3f252c244e0f293a0e/msgspec-0.22.0-cp313-cp313-win_amd64.whl", hash = "sha256:0739b068f31f2004a364f97679ba91f2f5ecd6ec2a5b4b890188ab5c57d20672", size = 192829, upload-time = "2026-09-29T14:13:05.519Z" }, + { url = "https://files.pythonhosted.org/packages/d1/cd/a011a5b8732cd781e2ea6da5b38d71ae4a9a329338411d1f008a58f5edbf/msgspec-0.22.0-cp313-cp313-win_arm64.whl", hash = "sha256:508278300dd4efbd21cd3a4b2b016160a5feac98bc880d3673f6c06697baaf62", size = 191258, upload-time = "2026-09-29T14:13:06.909Z" }, + { url = "https://files.pythonhosted.org/packages/53/f9/ac027b35477e6b83bcee32b3d9675b37abfa130f098dd6500fa67d768852/msgspec-0.22.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:221cbcbfa4478152b91d37dcfd4830e2be92773e8139e883f43773450ebacef8", size = 201276, upload-time = "2026-09-29T14:13:08.311Z" }, + { url = "https://files.pythonhosted.org/packages/13/6b/2bffffa31662b1353a62e672442865d51c291ad778352fd490de16361dc6/msgspec-0.22.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:dd9568695911055440d2bb7099ed9098fc181d335daa772d0eb3fe8f31ba4efb", size = 193233, upload-time = "2026-09-29T14:13:09.943Z" }, + { url = "https://files.pythonhosted.org/packages/14/bc/4066416ff6aa918d1ef9295edee0041e4629e4079ad3839bdd8a68fd87f0/msgspec-0.22.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f039ef5207b847f075a0a43020ee6140cd47505f890e47e157f2deb485c2dc96", size = 225101, upload-time = "2026-09-29T14:13:11.391Z" }, + { url = "https://files.pythonhosted.org/packages/63/ba/a8d390d5bd4c7d9ccde87c95cf071ada934cc9ca2c6af4d3d50b38f2d718/msgspec-0.22.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5e4f7e09cceac7dbf4c0761b8ae7df51c55b5df5e9af7aff2c895aac1ebea015", size = 230505, upload-time = "2026-09-29T14:13:12.869Z" }, + { url = "https://files.pythonhosted.org/packages/9c/89/979664fdc913c624ef88a139b40e3a95ddf2a47c89e8b5c4147f69ee9c48/msgspec-0.22.0-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:614e2c827e0a3f934f3cf0cf4ba65210df8132b75a69a8a1f51bb3b2caf0ac5a", size = 237382, upload-time = "2026-09-29T14:13:14.317Z" }, + { url = "https://files.pythonhosted.org/packages/07/3f/7d44c614376ae008ac6099be5f589b322c4ad44e32c6dbb0edd256215028/msgspec-0.22.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:fa3689b9dfcc663358ef23ba4299d7460f01108515b041a7d30d05908ac9c32f", size = 228962, upload-time = "2026-09-29T14:13:15.763Z" }, + { url = "https://files.pythonhosted.org/packages/0b/59/bf8504e6f63f6769d01fb66f8bd856cf0ed39a07fde354f440d711640054/msgspec-0.22.0-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:d2f950239ff1fc7322c6f9634807310265149cb168270d3ddcdda5b6ada13a28", size = 236691, upload-time = "2026-09-29T14:13:17.195Z" }, + { url = "https://files.pythonhosted.org/packages/2b/40/5a9d2bde12af16a22ddbf371990a81d3e3c0dcd4bb4ef3b3f9616b033c14/msgspec-0.22.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:3c789b5ccd07c0a3c09767108ee06e089b2875f2309a4569c2648f30a8d31dfa", size = 232750, upload-time = "2026-09-29T14:13:18.691Z" }, + { url = "https://files.pythonhosted.org/packages/75/5d/c0e6bdb81a87f6bd56a663a330c271af7670490c80d8d635d9fa21ad1adf/msgspec-0.22.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:a66b1766311e42371e509c996c3933b161c7ae0eabdf361af5316dec197e1022", size = 136814, upload-time = "2026-09-29T14:13:20.415Z" }, + { url = "https://files.pythonhosted.org/packages/b9/c0/b0cfc6d33608e5ea8871f3be31f9146c56699e737a7d8862bf018484f278/msgspec-0.22.0-cp314-cp314-win_amd64.whl", hash = "sha256:749899563d26b211379f142b8ffd7e2d7da149a51717798f0ce994dce50324f0", size = 197097, upload-time = "2026-09-29T14:13:21.869Z" }, + { url = "https://files.pythonhosted.org/packages/42/1f/571f7fe7c725380605d680fc4c0084212b23d2dfcf6be0f2277f14462c56/msgspec-0.22.0-cp314-cp314-win_arm64.whl", hash = "sha256:10d0d1d464960d99a949f7ca01ef8928e51c472433a5f5ab74b2d695fb830652", size = 196779, upload-time = "2026-09-29T14:13:23.62Z" }, + { url = "https://files.pythonhosted.org/packages/ab/f3/3c87372bac651b37911e0dc6926c3958949d3fcb8cec1016adbc44d948b2/msgspec-0.22.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:e79725246291516a7359caad5fb743ddc0ec66ed40d2381fb846325b5031504e", size = 205214, upload-time = "2026-09-29T14:13:25.158Z" }, + { url = "https://files.pythonhosted.org/packages/43/4c/fbccd6e0fbbdf10c4d9b6bac8a26148dd5483b3ffff6d6c5a376ff1f5cb1/msgspec-0.22.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:38f7022fbe91954b31afe3888a0af1b652e0f370fafdeb1d425f4a814d789c9f", size = 196941, upload-time = "2026-09-29T14:13:26.637Z" }, + { url = "https://files.pythonhosted.org/packages/55/04/8db7186d3ae8818356bc623cc132db8b77da37ce4b1345f35719c8ad5726/msgspec-0.22.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b6d3ca19a8ff28d0a67a1824e2bff7ec649ec795c80a265f20ade4caa63080de", size = 229934, upload-time = "2026-09-29T14:13:28.285Z" }, + { url = "https://files.pythonhosted.org/packages/17/24/a249f3491cabbe77cc65a1a6f87c128582aa39357227149be61cac8e554f/msgspec-0.22.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a8b98ae215a102cbf6635f7df45f5c4af12f77fad1f7b71b9808fcf868a5735d", size = 234378, upload-time = "2026-09-29T14:13:29.821Z" }, + { url = "https://files.pythonhosted.org/packages/87/ee/6dbcb1b5de8e9d47e8f0fde9a288628dc178c1749a570b98251218fa10c4/msgspec-0.22.0-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e0aa0cc3f18c35bab79bd7b87fde95d6274a9deddeebd1ea541f8066a5073165", size = 243118, upload-time = "2026-09-29T14:13:31.544Z" }, + { url = "https://files.pythonhosted.org/packages/79/03/7dd2d0ca988600e01fc00ad0cf20d1d44bc59369a913c988654c65f6582b/msgspec-0.22.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8c8e84789918fbc15a503b92a829115ddd7567ecd3e4778bd418c56abbb86c11", size = 234557, upload-time = "2026-09-29T14:13:33.068Z" }, + { url = "https://files.pythonhosted.org/packages/74/e2/43f3c63bff1650efcaaea31466246e28b46927323fc9ff416c68cc6e4047/msgspec-0.22.0-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:3ca7d4cd69fbb66bd2da6211d3e79d40542d196c16c6d99bf838f76767ad35be", size = 241288, upload-time = "2026-09-29T14:13:34.532Z" }, + { url = "https://files.pythonhosted.org/packages/8b/70/11b93815a59674f33182dc3e873d343ca0b37e25be52ecb28f52092f1fed/msgspec-0.22.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:28f53f3604dd3e70225f7563c831628dbb03299b428f8e62aadb4b628e386874", size = 236432, upload-time = "2026-09-29T14:13:36.083Z" }, + { url = "https://files.pythonhosted.org/packages/b7/82/7aad0f033f8dcb3f23868773c2ede803ae162a784828ccde75aa3f9b2f9d/msgspec-0.22.0-cp314-cp314t-win_amd64.whl", hash = "sha256:7293dee54de040cfa225c22151cc3d72f17cd674b5ebcb52f38fb9f5701592e6", size = 202062, upload-time = "2026-09-29T14:13:37.955Z" }, + { url = "https://files.pythonhosted.org/packages/e3/45/cf52577926d73e2369e25927e389cb4ea1461169c489f46d3248159b5be7/msgspec-0.22.0-cp314-cp314t-win_arm64.whl", hash = "sha256:c3c510aba9015c085e514b75a9b3f1ed7c4591ae5e379655821b8bba51f30cc7", size = 201686, upload-time = "2026-09-29T14:13:39.42Z" }, + { url = "https://files.pythonhosted.org/packages/c8/63/d93937e2aae34ff1ea33b62799d1963cacc1bf432d196d6130039657a122/msgspec-0.22.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:263e110955ed76fe0af2d79f819903b50a70dc0e7a752eb7aabe79d2e0a084fb", size = 202241, upload-time = "2026-09-29T14:13:40.919Z" }, + { url = "https://files.pythonhosted.org/packages/3b/e2/46ece11a244cd56432eb2362ffbb8014f3f02963136d84d941f71fdc2a3f/msgspec-0.22.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:c6f06576eced70462179a4b4638e84cf69fdbba37f44d13a64a21739c131a830", size = 194232, upload-time = "2026-09-29T14:13:42.454Z" }, + { url = "https://files.pythonhosted.org/packages/cf/b1/1c385f2f93006cdc2af1511cc512c347cb22e2d4f11952c205230aedf586/msgspec-0.22.0-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8d67582478b0eaabb899f2fb255c878ee7de57dff80eb73ab24f1865524ec441", size = 226524, upload-time = "2026-09-29T14:13:43.876Z" }, + { url = "https://files.pythonhosted.org/packages/dc/fb/c80c8842d40347cacf89a60a4986b849dae1a6dfd25830441efdd6faa65b/msgspec-0.22.0-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:71cbbdb39631064e2f2f9e9ac2b1b69931d72276eb5f9da4ed025726296bdbb6", size = 231816, upload-time = "2026-09-29T14:13:45.329Z" }, + { url = "https://files.pythonhosted.org/packages/73/ac/90bbcfd890b4bda90c93f7e1b7fc24e84b270420486d9d43ae31443d15ab/msgspec-0.22.0-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:8f0a5c25516e2034b2db7767081759ff8996e214def9c43b3055f61e1be1caad", size = 244241, upload-time = "2026-09-29T14:13:46.851Z" }, + { url = "https://files.pythonhosted.org/packages/72/9a/eabdb5f1b5e6013b0e2f9f2a95790587f6864aa9ca37f9d7dece65b53878/msgspec-0.22.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:a1dab6a99c759d1391ab2993388c1892746a697254f4b5dc6c059ca6e3bfbc8b", size = 230198, upload-time = "2026-09-29T14:13:48.296Z" }, + { url = "https://files.pythonhosted.org/packages/e9/89/9f080532d4ac52f416dd7318e55c2053cc071853d17d58e24897a5b553bf/msgspec-0.22.0-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:a52eba5c9528fd181fcec39d22b67aaa1dccc6cfe8e24d3f5d41130e6d04289d", size = 242949, upload-time = "2026-09-29T14:13:49.829Z" }, + { url = "https://files.pythonhosted.org/packages/11/df/6baf9b2f3523ebe2b820820c7929fd72ec5f483a93147130338ecc353fac/msgspec-0.22.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:1e547966017265c0d23342bcf2e027305dde40ea042d16694a9b96b4f696a052", size = 233914, upload-time = "2026-09-29T14:13:51.5Z" }, + { url = "https://files.pythonhosted.org/packages/bb/37/9cf650779c8c1e53291ef184c838703930a4cabb1fb37e222c85a7d49fa9/msgspec-0.22.0-cp315-cp315-win_amd64.whl", hash = "sha256:0067057df265795f742658b15dbe53f3b6f21d19dcfa53676db11088cfa41e0a", size = 197910, upload-time = "2026-09-29T14:13:53.071Z" }, + { url = "https://files.pythonhosted.org/packages/f5/ce/2f78c93d4f69e0167a19c2d40d4fbf7bbd6f074e1047536735832a4368ee/msgspec-0.22.0-cp315-cp315-win_arm64.whl", hash = "sha256:05dbc8268e50c9232ec72b9af1c7b13049aade4d1197764e38c427048706e046", size = 197590, upload-time = "2026-09-29T14:13:54.47Z" }, + { url = "https://files.pythonhosted.org/packages/3f/bf/282e9a443058b85b8f706c9a651e2d8cdd11cc09d16e8fa347b6c57b75bb/msgspec-0.22.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:b3113ebcceeb7693a915183c73d92c10bf5c62851dd187cab43bd025fb587419", size = 206298, upload-time = "2026-09-29T14:13:55.913Z" }, + { url = "https://files.pythonhosted.org/packages/ef/2d/2e694fa46f55319007f72013b17341ea3868be1c77e7a597176b202dda92/msgspec-0.22.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:0dfadea8bdcfafc614bd031de55a8ede22b43445cfff6d8b77cc0c07d3edc8a8", size = 198145, upload-time = "2026-09-29T14:13:57.412Z" }, + { url = "https://files.pythonhosted.org/packages/5b/2e/2fa279cb57cb47175ae604d572787f903d4ad3f0afa867201bbd99e6647e/msgspec-0.22.0-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d7a738826936c72348c613061d260446f13c82b6fd7d5d7705b6911ab8dca2f3", size = 232362, upload-time = "2026-09-29T14:13:58.817Z" }, + { url = "https://files.pythonhosted.org/packages/a0/58/a7e759b11b28441c27f803b29d9b5f4b5ad85150c89354b5ede1baca9258/msgspec-0.22.0-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f2ddea9d78d09460f06c26a7a508adcd049761c3208776162b8eb79b8a032cff", size = 235885, upload-time = "2026-09-29T14:14:00.381Z" }, + { url = "https://files.pythonhosted.org/packages/86/56/8d7ee098e94cbd9f35fa643dc497e06a4a6307b9f562cfbe48103fc3b209/msgspec-0.22.0-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:884c28c80b0a511595b29a9b04a3a230c3797369e4a033e6d5c6d9b5427f8e09", size = 248155, upload-time = "2026-09-29T14:14:01.945Z" }, + { url = "https://files.pythonhosted.org/packages/b9/6d/1cabb4b8a5dbf696e2b24df9e482b2e0333bb3b1b13ebb5433813e6616ec/msgspec-0.22.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:f7a923bcde480065c8e25967464cfb2a687ee67000bb43157e2d57e40eca7305", size = 236416, upload-time = "2026-09-29T14:14:03.363Z" }, + { url = "https://files.pythonhosted.org/packages/ba/43/8bf0f558eb369f1f2d494b3d5ab9d0ae0907d07ecc0cdbe11b6768b02867/msgspec-0.22.0-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:65eea14bc65ccfeb8f3af62cb204841871e2961f002d7fa87dbe0f79dacf1c1c", size = 247292, upload-time = "2026-09-29T14:14:04.829Z" }, + { url = "https://files.pythonhosted.org/packages/81/33/2fbaadf98b5510cac4bb56d2b03937e0b1fb4bfcd1ae6aba20361f299583/msgspec-0.22.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:0666a1520cab86796612e794e71107e0fbf5e8ff3ddcdfcfff8f1d94b860d2f1", size = 238220, upload-time = "2026-09-29T14:14:06.408Z" }, + { url = "https://files.pythonhosted.org/packages/f1/cc/b6be6041098ab859a8472983ccc2c08339fc2ef53f28d4f5fe7f4f34276b/msgspec-0.22.0-cp315-cp315t-win_amd64.whl", hash = "sha256:885c6e0c89d6103648525fe62aa78d600054dedf7b3713d23b15d7ddb6d66a13", size = 202939, upload-time = "2026-09-29T14:14:08.079Z" }, + { url = "https://files.pythonhosted.org/packages/5a/c1/664578dd98be70cd4ab1a9dcf3a181b1376b83c65ec41ee162130b58c8c0/msgspec-0.22.0-cp315-cp315t-win_arm64.whl", hash = "sha256:268594d0bae5510572599a6ab0364dd9de43c867d24a30856cd9f5edb63d8dc6", size = 202117, upload-time = "2026-09-29T14:14:09.891Z" }, +] + [[package]] name = "natsort" version = "8.4.0" @@ -543,7 +612,7 @@ requires-dist = [ { name = "scipy", marker = "extra == 'pickle'", specifier = ">=1.15" }, { name = "shapely", marker = "extra == 'dev'", specifier = ">=2.0.6" }, { name = "typer", specifier = ">=0.20.0,<1" }, - { name = "zarr", specifier = ">=3.1.5,<4" }, + { name = "zarr", specifier = ">=3.2.0,<4" }, ] provides-extras = ["pickle", "spatial", "dev"] @@ -1061,17 +1130,18 @@ wheels = [ [[package]] name = "zarr" -version = "3.1.5" +version = "3.4.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "donfig" }, { name = "google-crc32c" }, + { name = "msgspec" }, { name = "numcodecs" }, { name = "numpy" }, { name = "packaging" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/fc/76/7fa87f57c112c7b9c82f0a730f8b6f333e792574812872e2cd45ab604199/zarr-3.1.5.tar.gz", hash = "sha256:fbe0c79675a40c996de7ca08e80a1c0a20537bd4a9f43418b6d101395c0bba2b", size = 366825, upload-time = "2025-11-21T14:06:01.492Z" } +sdist = { url = "https://files.pythonhosted.org/packages/3e/62/e8a36a4b65f01499c7aefcf103aabba0c37c018bf135fbf179f6ed2f01a0/zarr-3.4.1.tar.gz", hash = "sha256:b34bda11ceb199c81ee78ecd42cd02f46c7f67a6d8a1e9bc501cafd5a1795356", size = 923257, upload-time = "2026-10-08T17:14:25.972Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/44/15/bb13b4913ef95ad5448490821eee4671d0e67673342e4d4070854e5fe081/zarr-3.1.5-py3-none-any.whl", hash = "sha256:29cd905afb6235b94c09decda4258c888fcb79bb6c862ef7c0b8fe009b5c8563", size = 284067, upload-time = "2025-11-21T14:05:59.235Z" }, + { url = "https://files.pythonhosted.org/packages/a6/82/0dbc9bc77b49cfb9268dc2b2b1dcd04346c8c7ed52e272b76a628a941656/zarr-3.4.1-py3-none-any.whl", hash = "sha256:38b540578a119352bdce02a720d7bfd99846e77f0728c58b1bab3d1f547526a0", size = 405257, upload-time = "2026-10-08T17:14:23.926Z" }, ] From 3f5efa1bece462b3b1f20ba30df931999fef8cef Mon Sep 17 00:00:00 2001 From: Aljes Date: Fri, 30 Oct 2026 17:21:57 +0000 Subject: [PATCH 2/2] Review: references, linked folders, concat records, fills - the HDF5 layout check follows object references too, and walks into linked folders of a convert source (F041, security) - a reference is copied only inside an element HDF5 copies whole, on both copy paths, with no stray root link left behind - concat compares record arrays field by field, so --uns-merge same keeps rank_genes_groups read from an h5ad - subset's growable datasets get a fill fit for their dtype (F071) - a record field of variable-length numbers is not taken for text Co-Authored-By: Claude Opus 5.5 --- docs/reference/spec-h5ad.md | 8 +- docs/reference/spec-zarr.md | 7 +- src/adata/core/concat.py | 4 + src/adata/core/subset.py | 3 +- src/adata/elements/read.py | 14 ++- src/adata/elements/strings.py | 2 +- src/adata/storage/__init__.py | 169 ++++++++++++++++++++++++--------- tests/test_element_fidelity.py | 88 ++++++++++++++++- tests/test_legacy_copies.py | 21 ++++ tests/test_storage.py | 54 +++++++++++ 10 files changed, 313 insertions(+), 57 deletions(-) diff --git a/docs/reference/spec-h5ad.md b/docs/reference/spec-h5ad.md index 57e05d7..799ec7d 100644 --- a/docs/reference/spec-h5ad.md +++ b/docs/reference/spec-h5ad.md @@ -346,7 +346,13 @@ HDF5 lets a dataset keep its data in other files (external storage, or a virtual dataset mapping datasets of other files), and lets a link point into another file. anndata writes none of these. This tool reads only data held in the file itself: a store holding any of them is refused when it is -opened, naming the element, and so is an HDF5 source of `convert`. +opened, naming the element, and so is an HDF5 source of `convert` (with the +HDF5 files of a folder source). So is an object reference to an object the +file gives no name, which no walk of its links would meet. + +A reference is copied to another HDF5 file only inside an element HDF5 +copies whole, pointed at the copy of its target; one leading out of the +element is refused, as is a dataset of references copied on its own. ### Elements with no `encoding-type` diff --git a/docs/reference/spec-zarr.md b/docs/reference/spec-zarr.md index f2f51a1..a7b8f21 100644 --- a/docs/reference/spec-zarr.md +++ b/docs/reference/spec-zarr.md @@ -346,8 +346,11 @@ Two HDF5 dtypes have no Zarr equivalent, and a copy to Zarr refuses them before writing anything, naming the element: variable-length sequences of numbers (`h5py.vlen_dtype(int)`) and object references, whether a dataset of them or an attribute holding one. Neither is anything anndata writes. -Between HDF5 files both are copied, references pointed at the copies of -what they named. +Between HDF5 files, variable-length numbers are copied. A reference is +copied only inside an element HDF5 copies whole, pointing at the copy of +its target (as anndata 0.7's categoricals in a nested dataframe are); one +that leads out of the element, or is copied on its own (`--compression` +copies dataset by dataset), is refused, naming it. ### Elements with no `encoding-type` diff --git a/src/adata/core/concat.py b/src/adata/core/concat.py index 21ec8fa..b5b6a07 100644 --- a/src/adata/core/concat.py +++ b/src/adata/core/concat.py @@ -1208,6 +1208,10 @@ def _hashable(value: Any) -> Any: except ValueError: return tuple(_hashable(v) for v in value) if isinstance(value, np.ndarray): + if value.dtype.names is not None: + # A record array (scanpy's rank_genes_groups): its bytes hold + # h5py's text as heap pointers, so two equal ones never matched. + return ("records", value.shape, tuple((f, _hashable(value[f])) for f in value.dtype.names)) if value.dtype.kind in "OSUT": return ("text", value.shape, tuple(decode_str_array(value).reshape(-1).tolist())) return (value.shape, value.dtype.kind, value.tobytes()) diff --git a/src/adata/core/subset.py b/src/adata/core/subset.py index 92191ff..ab0c28e 100644 --- a/src/adata/core/subset.py +++ b/src/adata/core/subset.py @@ -35,6 +35,7 @@ dataset_create_kwargs, detect_backend, fit_chunks, + fit_fill, is_dataset, is_group, is_legacy_categorical, @@ -716,7 +717,7 @@ def _growable_like( if is_zarr_group(group): return group.create_array(name, shape=(0,), dtype=dtype, chunks=(step,), **kw) return group.create_dataset( - name, shape=(0,), maxshape=(None,), dtype=dtype, chunks=(step,), **kw + name, shape=(0,), maxshape=(None,), dtype=dtype, chunks=(step,), **fit_fill(kw, dtype) ) diff --git a/src/adata/elements/read.py b/src/adata/elements/read.py index 5cd0fc7..bdffeb8 100644 --- a/src/adata/elements/read.py +++ b/src/adata/elements/read.py @@ -20,7 +20,7 @@ import numpy as np from adata.elements import spec -from adata.storage import is_dataset, is_group, is_hdf5_dataset +from adata.storage import is_dataset, is_group, is_hdf5_dataset, refuse_outside_data def decode_str_array(array: np.ndarray) -> np.ndarray: @@ -168,8 +168,16 @@ def categories_dataset(col: Any, parent_group: Any | None = None) -> Any: cats_ref = col.attrs.get("categories", None) if cats_ref is not None and is_hdf5_dataset(col): - # Legacy 0.7.x HDF5: an object reference into __categories. - return col.file[cats_ref] + # Legacy 0.7.x HDF5: an object reference into __categories. It can + # reach an object no link names, which no walk of the file met. + labels = col.file[cats_ref] + if labels.name is None: + raise ValueError( + f"The categories of {col.name} are an object with no name in " + "the file, which adata does not read." + ) + refuse_outside_data(labels) + return labels if parent_group is not None and "__categories" in parent_group: col_name = str(getattr(col, "name", "")).split("/")[-1] diff --git a/src/adata/elements/strings.py b/src/adata/elements/strings.py index 1e47ef4..c18fdba 100644 --- a/src/adata/elements/strings.py +++ b/src/adata/elements/strings.py @@ -121,7 +121,7 @@ def as_records(values: np.ndarray, dtype: np.dtype) -> np.ndarray: for field in dtype.names: column = values[field] target = dtype.fields[field][0] - if is_string_dtype(target) and target.kind != column.dtype.kind or target.kind == "O": + if is_string_dtype(target) and (target.kind == "O" or target.kind != column.dtype.kind): column = as_str_array(column) out[field] = column return out diff --git a/src/adata/storage/__init__.py b/src/adata/storage/__init__.py index 8e04ac3..b511ea2 100644 --- a/src/adata/storage/__init__.py +++ b/src/adata/storage/__init__.py @@ -195,7 +195,7 @@ def _outside_data(obj: Any) -> Optional[str]: return _dataset_id_outside(obj.id) -def _refuse_outside_data(obj: Any) -> None: +def refuse_outside_data(obj: Any) -> None: reason = _outside_data(obj) if reason: raise ExternalDataError( @@ -212,16 +212,69 @@ def _dataset_id_outside(dsid: Any) -> Optional[str]: return None -def check_hdf5_contents(group: Any, path: Any = None) -> None: +def _references(oid: Any) -> list: + """The object references `oid` holds: in its attributes, and as its + values when it is a dataset of them. Other values are not read.""" + refs: list = [] + for index in range(h5py.h5a.get_num_attrs(oid)): + attr = h5py.h5a.open(oid, index=index) + if h5py.check_ref_dtype(attr.dtype) is None or attr.shape is None: + continue + values = np.empty(attr.shape, dtype=attr.dtype) + attr.read(values) + refs.extend(values.reshape(-1)) + if isinstance(oid, h5py.h5d.DatasetID) and h5py.check_ref_dtype(oid.dtype) is not None: + refs.extend(np.asarray(h5py.Dataset(oid)[()]).reshape(-1)) + return refs + + +def _object_problem(oid: Any, within: Optional[str]) -> Optional[str]: + """Why `oid` cannot be read, or copied as part of `within`, or None. + + A reference reaches an object no link does -- one created without a + name, which a walk of the links never meets -- so its target is + refused unless it has a name of its own (and then the walk checks it). + Copied as part of `within`, a reference must stay inside it: HDF5 takes + what it points to along, so a target elsewhere would be duplicated into + the output as a stray copy, or, if it read another file, carry that. + """ + if isinstance(oid, h5py.h5d.DatasetID): + reason = _dataset_id_outside(oid) + if reason: + return reason + for ref in _references(oid): + if not ref: + continue + target = h5py.h5r.dereference(ref, oid) + name = h5py.h5i.get_name(target) if target is not None else None + if name is None: + return "refers to an object with no name in the file" + name = name.decode("utf-8", "replace") + if within is not None and not ( + name == within or name.startswith(within.rstrip("/") + "/") + ): + return ( + f"refers to {name}, outside {within}, which a copy of " + f"{within} cannot take along" + ) + return None + + +def check_hdf5_contents(group: Any, path: Any = None, *, within: Optional[str] = None) -> None: """Refuse an HDF5 file, or a group of one, that reads data from elsewhere. Every link below `group` is looked at once, without reading any data: an external link opens another file, and a dataset stored externally or virtually reads one. None of these is something anndata writes, and any of them would quietly copy another file's contents into an output, - so the input is refused before anything is read from it. + so the input is refused before anything is read from it. The object + references each object holds are followed too (`_object_problem`); + `within` names the element being copied, which they must stay inside. """ found: list = [] + root_problem = _object_problem(group.id, within) + if root_problem: + found.append(("", root_problem)) def visit(name: bytes, info: Any) -> None: if found: @@ -230,19 +283,18 @@ def visit(name: bytes, info: Any) -> None: if info.type == h5py.h5l.TYPE_EXTERNAL: found.append((where, "is an external link into another file")) elif info.type == h5py.h5l.TYPE_HARD: - oid = h5py.h5o.open(group.id, name) - if isinstance(oid, h5py.h5d.DatasetID): - reason = _dataset_id_outside(oid) - if reason: - found.append((where, reason)) + reason = _object_problem(h5py.h5o.open(group.id, name), within) + if reason: + found.append((where, reason)) elif info.type != h5py.h5l.TYPE_SOFT: found.append((where, "is a user-defined link")) - group.id.links.visit(visit, info=True) + if is_hdf5_group(group): + group.id.links.visit(visit, info=True) if found: where, reason = found[0] base = getattr(group, "name", "/") or "/" - element = f"{base.rstrip('/')}/{where}" + element = f"{base.rstrip('/')}/{where}".rstrip("/") or "/" source = f"'{path}'" if path is not None else "The input" raise ExternalDataError( f"{source} is refused: {element} {reason}. adata reads only " @@ -264,13 +316,25 @@ def check_hdf5_file(path: Path) -> None: def check_hdf5_inputs(path: Path) -> None: """`check_hdf5_file` for a source that is not opened through `open_store`: an HDF5 file, or the HDF5 files in a folder of outputs.""" + import os + path = Path(path) if path.is_file(): files = [path] elif path.is_dir() and not is_zarr_path(path): - files = sorted( - p for p in path.rglob("*") if p.suffix in HDF5_SUFFIXES and p.is_file() - ) + # Into linked folders too, as the converters' own globs go; each + # real folder once, so a link loop ends. + files, seen = [], set() + for folder, subfolders, names in os.walk(path, followlinks=True): + real = os.path.realpath(folder) + if real in seen: + subfolders[:] = [] + continue + seen.add(real) + files.extend( + Path(folder, n) for n in sorted(names) + if Path(n).suffix in HDF5_SUFFIXES and Path(folder, n).is_file() + ) else: return for file in files: @@ -539,6 +603,18 @@ def _fill_as(fill: Any, dtype: Any) -> Any: return converted[()] +def fit_fill(kw: dict, dtype: Any) -> dict: + """Creation kwargs `kw` with the fill value made fit for `dtype` + (`_fill_as`), for a caller creating the HDF5 dataset itself.""" + if "fillvalue" not in kw: + return kw + kw = dict(kw) + fill = _fill_as(kw.pop("fillvalue"), dtype) + if fill is not None: + kw["fillvalue"] = fill + return kw + + def _create_string_dataset( parent: Any, name: str, @@ -607,13 +683,10 @@ def create_dataset( kwargs.pop("filters", None) if "fillvalue" in kwargs and not is_zarr_group(parent): - kwargs = dict(kwargs) target = dtype if dtype is not None else getattr(data, "dtype", None) if target is None and data is not None: target = np.asarray(data).dtype - fill = _fill_as(kwargs.pop("fillvalue"), target) - if fill is not None: - kwargs["fillvalue"] = fill + kwargs = fit_fill(kwargs, target) if is_zarr_group(parent): zarr_format = getattr(getattr(parent, "metadata", None), "zarr_format", None) @@ -906,7 +979,7 @@ def copy_dataset( from adata.elements.strings import target_dtype target_backend = "zarr" if is_zarr_group(dst_group) else "hdf5" - _refuse_outside_data(src) + refuse_outside_data(src) if _is_null(src): # anndata writes an absent element, `raw` most often, as a null: an # empty dataspace on HDF5 and a 0-d bool on Zarr. Neither can be read @@ -920,12 +993,7 @@ def copy_dataset( if is_hdf5_dataset(src) and src.shape is None: return _copy_empty(src, dst_group, name, target_backend) if is_hdf5_dataset(src): - _refuse_beyond_zarr(src, target_backend) - if h5py.check_ref_dtype(src.dtype) is not None: - # References name objects by their address in the source. HDF5's - # own copy brings what they point to along and repoints them. - dst_group.copy(src, dst_group, name, expand_refs=True) - return dst_group[name] + _refuse_unportable(src, target_backend) if src.dtype.names is not None: return _copy_records( src, dst_group, name, compression=compression, skip_attrs=skip_attrs @@ -991,25 +1059,31 @@ def _copy_empty(src: Any, dst_group: Any, name: str, target_backend: str) -> Any return None -def _refuse_beyond_zarr(src: Any, target_backend: str) -> None: - """Refuse an HDF5 dataset Zarr cannot hold, before anything is written. +def _refuse_unportable(src: Any, target_backend: str) -> None: + """Refuse an HDF5 dataset a copy element by element cannot take, before + anything is written. Its dtype is an `object` to numpy, which this layer once took for text: - variable-length numbers came out as the strings '[1 2 3]'. + variable-length numbers came out as the strings '[1 2 3]'. References + name objects by their address in this file, which means nothing in + another; HDF5's own copy of a whole element (`copy_tree`) repoints those + that stay inside it, and that is the only way one is copied. Zarr holds + neither; a record's fields are checked one by one. """ - if target_backend != "zarr": - return - if h5py.check_ref_dtype(src.dtype) is not None: - raise ValueError( - f"{src.name} holds HDF5 object references, which cannot be " - "copied to Zarr." - ) - base = h5py.check_vlen_dtype(src.dtype) - if base is not None and base not in (str, bytes): - raise ValueError( - f"{src.name} holds variable-length sequences of {np.dtype(base)}, " - "which Zarr cannot store." - ) + dtype = src.dtype + fields = [dtype.fields[f][0] for f in dtype.names] if dtype.names else [dtype] + for sub in fields: + if h5py.check_ref_dtype(sub) is not None: + raise ValueError( + f"{src.name} holds HDF5 object references, which cannot be " + "copied out of its file on their own." + ) + base = h5py.check_vlen_dtype(sub) + if target_backend == "zarr" and base is not None and base not in (str, bytes): + raise ValueError( + f"{src.name} holds variable-length sequences of {np.dtype(base)}, " + "which Zarr cannot store." + ) def _copy_records( @@ -1171,14 +1245,19 @@ def copy_tree( # HDF5's own copy keeps every dataset exactly as it was, which is # what is wanted unless the caller asked for something else. if not exclude and compression is None: - if is_hdf5_group(src_obj): - check_hdf5_contents(src_obj) - else: - _refuse_outside_data(src_obj) + check_hdf5_contents(src_obj, within=src_obj.name) # References below it -- anndata 0.7's categoricals, in a frame # nested in raw, obsm or uns -- would otherwise come out null: - # with expand_refs HDF5 repoints them at their copies. + # with expand_refs HDF5 repoints them at their copies. A target + # copied before its place in the tree is reached also gets a + # second link, `~obj_pointed_by_` at the root; every target is + # inside what was copied, so that link is only a duplicate name. + root = dst_group.file + before = set(root.keys()) dst_group.copy(src_obj, dst_group, name, expand_refs=True) + for key in set(root.keys()) - before: + if key.startswith("~obj_pointed_by_") and h5py.h5o.get_info(root[key].id).rc > 1: + del root[key] return dst_group[name] if is_dataset(src_obj): return copy_dataset(src_obj, dst_group, name, compression=compression) diff --git a/tests/test_element_fidelity.py b/tests/test_element_fidelity.py index 166abc2..737fe5b 100644 --- a/tests/test_element_fidelity.py +++ b/tests/test_element_fidelity.py @@ -306,17 +306,80 @@ def build(f): assert "/uns/pointers holds HDF5 object references" in _out(result) -def test_a_dataset_of_references_copies_between_h5ad_files_with_compression(tmp_path): - """F126: copied dataset by dataset, its references were stringified.""" +@pytest.mark.parametrize("extra", [[], ["--compression", "gzip"]], ids=["whole", "by-dataset"]) +def test_a_reference_out_of_the_element_copied_is_refused_between_h5ad_files(tmp_path, extra): + """F126: copied dataset by dataset, references were stringified; copied + whole, HDF5 took their targets along -- here all of X, again, as a + stray `~obj_pointed_by_...` at the output's root. Both copies now refuse + a reference that leaves the element, alike.""" def build(f): f["uns"].create_dataset("pointers", data=np.array([f["X"].ref], dtype=h5py.ref_dtype)) + f["uns"].create_dataset("v", data=np.arange(2)).attrs["link"] = f["X"].ref + + src = _with_uns(tmp_path / "src.h5ad", build) + result = runner.invoke(app, ["convert", str(src), "-o", str(tmp_path / "out.h5ad"), *extra]) + assert result.exit_code == 1 + assert re.search(r"/uns/(pointers|v) (holds HDF5 object references|refers to /X|is an HDF5 object reference)|Attribute 'link' of /uns/v", _out(result)) + assert not (tmp_path / "out.h5ad").exists() + + +def test_a_reference_inside_the_element_copied_is_repointed(tmp_path): + """F006's mechanism, for any reference that stays inside the element + copied: HDF5 points it at the copy of its target.""" + def build(f): + group = f["uns"].create_group("g") + group.create_dataset("target", data=np.arange(3)) + group.create_dataset("pointer", data=np.array([group["target"].ref], dtype=h5py.ref_dtype)) src = _with_uns(tmp_path / "src.h5ad", build) out = tmp_path / "out.h5ad" + _ok("convert", src, "-o", out) + with h5py.File(out) as f: + target = f[f["uns/g/pointer"][0]] + assert target.name == "/uns/g/target" + np.testing.assert_array_equal(target[...], np.arange(3)) + assert [k for k in f if k.startswith("~")] == [] + + +@pytest.mark.parametrize("target", ["out.zarr", "out.h5ad"]) +def test_a_record_with_a_field_of_variable_length_numbers(tmp_path, target): + """F126, for a record field: its numbers were taken for text, which h5py + refused with an error about a str, and Zarr with 'ambiguous Object'.""" + def build(f): + dtype = np.dtype([("name", h5py.string_dtype()), ("values", h5py.vlen_dtype(np.int32))]) + ds = f["uns"].create_dataset("records", shape=(2,), dtype=dtype) + ds[0] = ("a", np.array([1, 2], dtype=np.int32)) + ds[1] = ("b", np.array([3], dtype=np.int32)) + + src = _with_uns(tmp_path / "src.h5ad", build) + out = tmp_path / target + if target.endswith("zarr"): + result = runner.invoke(app, ["convert", str(src), "-o", str(out)]) + assert result.exit_code == 1 + assert "/uns/records holds variable-length sequences of int32" in _out(result) + return _ok("convert", src, "-o", out, "--compression", "gzip") with h5py.File(out) as f: - target = f[f["uns/pointers"][0]] - np.testing.assert_array_equal(target[...], np.ones((2, 2), dtype=np.float32)) + rows = f["uns/records"][...] + assert [r["name"] for r in rows] == [b"a", b"b"] + assert [list(r["values"]) for r in rows] == [[1, 2], [3]] + + +def test_concat_keeps_a_rank_genes_groups_result_every_input_shares(tmp_path): + """scanpy's marker genes went through `--uns-merge same` as raw bytes, + which for h5py's text are heap pointers: two identical results never + compared equal, and the merge dropped them. anndata.concat keeps them.""" + truth = _marker_genes() + a = _write(truth, tmp_path / "a.h5ad", "h5ad") + other = truth.copy() + other.obs_names = [f"d{i}" for i in range(other.n_obs)] + b = _write(other, tmp_path / "b.zarr", "zarr3") + out = tmp_path / "out.h5ad" + _ok("concat", a, b, "-o", out, "--uns-merge", "same") + want = ad.concat([_read(a), _read(b)], uns_merge="same") + got = _read(out) + assert sorted(got.uns["rank_genes_groups"]) == sorted(want.uns["rank_genes_groups"]) + _same_markers(got, truth) # --------------------------------------------------------------------------- @@ -460,6 +523,23 @@ def test_a_null_anndata_wrote_stays_a_null_in_every_backend(tmp_path): # Fill values +@pytest.mark.parametrize("fill", [np.nan, 2.0]) +def test_recast_to_bool_works_when_the_source_has_a_fill_of_its_own(tmp_path, fill): + """F071: a dense matrix made sparse creates its arrays as growable h5py + datasets, and the float fill went to them unconverted.""" + values = np.array([[0, 1, 0], [1, 1, 0]], dtype=np.float32) + src = _write(ad.AnnData(values), tmp_path / "src.h5ad", "h5ad") + with h5py.File(src, "a") as f: + attrs = dict(f["X"].attrs) + del f["X"] + f.create_dataset("X", data=values, chunks=(1, 3), fillvalue=fill).attrs.update(attrs) + out = tmp_path / "out.h5ad" + _ok("recast", src, "X", "--dtype", "bool", "--layout", "csr", "-o", out) + got = _read(out).X + assert got.dtype == np.bool_ + np.testing.assert_array_equal(got.toarray(), values.astype(bool)) + + @pytest.mark.parametrize("layout", ["csr", "csc", "dense"]) def test_recast_to_bool_works_on_a_float_h5ad_matrix(tmp_path, layout): """F071: the float source's fill value, 0.0, was passed on to the new diff --git a/tests/test_legacy_copies.py b/tests/test_legacy_copies.py index 6da5c9b..670307a 100644 --- a/tests/test_legacy_copies.py +++ b/tests/test_legacy_copies.py @@ -156,3 +156,24 @@ def test_a_modality_with_a_legacy_raw_var_converts_to_h5ad(tmp_path): got = _read(out) assert list(got.raw.var["kind"]) == kinds assert list(got.raw.var_names) == list(rna.var_names) + + +def test_a_nested_legacy_column_named_before_its_labels_leaves_no_stray_link(tmp_path): + """F006: HDF5 copies in name order, so a column sorting before + `__categories` ("Phase") had its labels copied ahead of their place in + the tree, under a second name at the output's root, + `~obj_pointed_by_`.""" + path = tmp_path / "legacy.h5ad" + with h5py.File(path, "w") as f: + _legacy_frame(f, "obs", CELLS, {"Phase": ["G1", "S", "G1", "G2M"]}) + _legacy_frame(f, "var", ["g1", "g2"], {"kind": ["x", "y"]}) + f.create_dataset("X", data=np.arange(8, dtype=np.float32).reshape(4, 2)) + raw = f.create_group("raw") + raw.attrs.update({"encoding-type": "raw", "encoding-version": "0.1.0"}) + raw.create_dataset("X", data=np.ones((4, 2), dtype=np.float32)) + _legacy_frame(raw, "var", ["g1", "g2"], {"Kind": ["x", "y"]}) + out = tmp_path / "out.h5ad" + _ok("convert", path, "-o", out) + with h5py.File(out) as f: + assert not [k for k in f if k.startswith("~")] + assert list(_read(out).raw.var["Kind"]) == ["x", "y"] diff --git a/tests/test_storage.py b/tests/test_storage.py index a4fe2db..81a11eb 100644 --- a/tests/test_storage.py +++ b/tests/test_storage.py @@ -778,3 +778,57 @@ def test_dataset_create_kwargs_keeps_a_v2_arrays_compression_or_its_absence(temp assert out.root["zstd"].compressors == (numcodecs.Zstd(level=5),) assert out.root["none"].compressors == () assert kw["compressors"] is None + + +def test_a_reference_to_an_object_no_link_names_is_refused(temp_dir): + """F041: the check walked links, and an object reachable only through a + reference -- here a legacy categorical's labels, created without a name + and holding external data -- was never seen, and was read.""" + import h5py + + from adata.storage import ExternalDataError + + other = temp_dir / "other.bin" + other.write_bytes(b"ABC") + path = temp_dir / "anon.h5ad" + with h5py.File(path, "w") as f: + for key in ("obs", "var"): + frame = f.create_group(key) + frame.attrs.update({"_index": "_index", "encoding-type": "dataframe", "encoding-version": "0.1.0"}) + frame.create_dataset("_index", data=np.array([b"a", b"b", b"c"])) + # A group linked to itself outlives its last name: what it holds is + # then reachable by reference only. + hidden = f.create_group("hidden") + h5py.h5o.link(hidden.id, hidden.id, b"self") + labels = hidden.create_dataset("labels", shape=(3,), dtype="S1", external=[(str(other), 0, 3)]) + codes = f["obs"].create_dataset("kind", data=np.array([0, 1, 2], dtype="i1")) + codes.attrs["categories"] = labels.ref + del f["hidden"] + with pytest.raises(ExternalDataError, match="/obs/kind refers to an object with no name"): + open_store(path, "r") + with h5py.File(path, "r") as f: + from adata.elements.read import categories_dataset + + with pytest.raises(ValueError, match="no name in the file"): + categories_dataset(f["obs/kind"], f["obs"]) + + +def test_the_hdf5_files_of_a_folder_are_checked_through_linked_folders(temp_dir): + """F041: the folder walk did not follow a linked subfolder, which the + converters' own globs do.""" + import h5py + + from adata.storage import ExternalDataError, check_hdf5_inputs + + outs = temp_dir / "outs" + real = temp_dir / "elsewhere" / "binned" + real.mkdir(parents=True) + outs.mkdir() + (outs / "binned_outputs").symlink_to(real, target_is_directory=True) + (real / "loop").symlink_to(outs, target_is_directory=True) + other = temp_dir / "other.bin" + other.write_bytes(bytes(4)) + with h5py.File(real / "matrix.h5", "w") as f: + f.create_dataset("data", shape=(4,), dtype="u1", external=[(str(other), 0, 4)]) + with pytest.raises(ExternalDataError, match="matrix.h5' is refused: /data keeps its data"): + check_hdf5_inputs(outs)