From 8b2d6d9a15620f2d0492ea7efd2e8c9eb819ea3b Mon Sep 17 00:00:00 2001 From: Aljes Date: Fri, 4 Dec 2026 15:55:43 +0000 Subject: [PATCH 1/3] B2: Pickle reader (#136) A crafted pickle is refused with an Error line rather than crash the reader, as the docs promise. Lengths a pickle names are held to the bytes it holds, and the sniffer reads only a file's head. Column labels a store cannot hold as names are renamed, and such fragments samples refused. Object integers past int64 keep their values. pandas 3's Arrow text reads, without pyarrow. Co-Authored-By: Claude Opus 5.5 --- docs/reference/commands.md | 7 +- docs/reference/formats/cistopic.md | 31 +- docs/reference/testing.md | 6 +- docs/troubleshooting.md | 19 + src/adata/conversion/cistopic.py | 50 ++- src/adata/formats/pandas_frame.py | 67 ++- src/adata/formats/pickled.py | 690 ++++++++++++++++++++++++----- tests/test_cistopic.py | 145 +++++- tests/test_pandas_frame.py | 53 +++ tests/test_pickled.py | 599 ++++++++++++++++++++++++- 10 files changed, 1535 insertions(+), 132 deletions(-) diff --git a/docs/reference/commands.md b/docs/reference/commands.md index ce88b37..6a7021f 100644 --- a/docs/reference/commands.md +++ b/docs/reference/commands.md @@ -196,7 +196,12 @@ of that with one choice. Elements are not re-encoded, so a store written by anndata 0.7 keeps its legacy layout. The input and the options are checked before anything is written; what only -the data can show, such as an index out of range, stops the copy. Either way +the data can show, such as an index out of range, stops the copy. A +pycisTopic pickle is refused if it holds anything a pycisTopic object's +pickle never does, or names a length its bytes do not hold (see +[pycisTopic pickles](formats/cistopic.md#pickles-are-trusted-input)), or if +a sample in its `path_to_fragments` holds `/` or is empty, which a store +cannot hold as a key. Either way the output is written beside its destination (`out.adata-tmp.zarr`) and moved into place only once complete, so a failed conversion leaves nothing behind. An existing output is diff --git a/docs/reference/formats/cistopic.md b/docs/reference/formats/cistopic.md index 57d8c3c..24e9b69 100644 --- a/docs/reference/formats/cistopic.md +++ b/docs/reference/formats/cistopic.md @@ -55,15 +55,36 @@ written: - every sparse matrix has its indices within its shape and an `indptr` that rises from 0 to its number of entries, every categorical's codes lie within its categories, and every table's columns hold as many rows - as its index. + as its index. Each is checked as soon as it is complete, before + anything else in the file can take it apart; +- the few builtins a pickle may call are given only what a pickle of them + holds (`set` a list, `range` integers), and nothing is hashed, as a + dict's key or a set's item, but numbers, text and tuples of them; +- a length the file names rather than holds, such as a `range`, a + `RangeIndex`, or the shape of an empty array or a sparse matrix, is no + more than the bytes the file holds, so a small file cannot make the + conversion take gigabytes. Dates and times are not read; pycisTopic's objects hold none. A pickle written by pycisTopic's pandas 1.5 reads with pandas 2 or 3, as CI -checks. Columns are written as anndata writes them: Categorical as -categorical, nullable integers and booleans as nullable, numbers held as -`object` as numbers, repeated text as categorical. Anything else on the -object is named in a warning and left out. +checks, and so does one saved again under pandas 3, whose text is held in +Arrow: that text is decoded here, every offset checked against the text it +indexes, without pyarrow. Columns are written as anndata writes them: +Categorical as categorical, nullable integers and booleans as nullable, +numbers held as `object` as numbers (integers as int64, or as uint64 past +it, as pandas reads them; as floats, with a warning, when no integer dtype +holds them, or when a missing value sits beside an integer a float cannot +hold exactly), repeated text as categorical. Anything else on the object is +named in a warning and left out. + +A column label is the column's name in the store, and HDF5 and Zarr read a +`/` in a name as a path: a label holding one, or an empty label, is renamed +(`a/b` to `a_b`, `""` to `_`) with a warning, to a name no other column +has. A sample in `path_to_fragments` is a key in the same way, but one +holding `/`, or empty, is refused instead: cell_data's `sample_id` and the +cell names, which end with it, name the sample as it is, and a renamed key +would no longer match them. ## Memory diff --git a/docs/reference/testing.md b/docs/reference/testing.md index 1dcd98e..5b631a5 100644 --- a/docs/reference/testing.md +++ b/docs/reference/testing.md @@ -87,12 +87,12 @@ inside every release before PyPI has it. | `test_text.py` | Text matrices in every layout anndata's `read_text` tells apart (corner, short and comment headers, no header, no row names), each delimiter, gzip, `--transpose` CSR and dense, dtypes, refusals by line, small blocks | | `test_hdf5.py` | One dataset of a plain HDF5 file: the listing without `--key`, `read_hdf`'s `row_names` / `col_names` and other names, `--transpose` CSR and dense, slabs of chunks, `--from hdf5` on `.h5` | | `test_dense.py` | `conversion/dense.py`, which the loom and HDF5 importers read a dense matrix through: datasets chunked every way that changes how it reads them, on each output backend, read back by anndata | -| `test_cistopic.py` | pycisTopic pickles read through the allowlist: a CistopicObject's matrices, frames, model and projections, an imputed-features pickle, a pickle naming `os.system` refused unrun, the missing-extra hint | -| `test_pickled.py` | The restricted unpickler against crafted pickles that name only allowlisted globals, each loaded in a child process so a crash cannot take the run down | +| `test_cistopic.py` | pycisTopic pickles read through the allowlist: a CistopicObject's matrices, frames, model and projections, an imputed-features pickle, a pickle naming `os.system` refused unrun, the missing-extra hint; a pickle pandas 3 saved, its Arrow text read with pyarrow hidden; labels a store cannot hold renamed, such samples refused; integers past int64; names a pickle does not hold refused unlisted | +| `test_pickled.py` | The restricted unpickler against crafted pickles that name only allowlisted globals, each loaded in a child process so a crash cannot take the run down, then here once refused: objects refused before a `set` or a hash takes them apart, lengths held to the bytes the file holds, every check reached by a pickle crafted for it, Arrow text decoded (malformed layouts refused, as pyarrow's own validation refuses them), the sniff reading only a file's head | | `test_visium.py` | Space Ranger output: standard Visium (Space Ranger 1 to 4) laid out as `squidpy.read.visium` lays it out, Visium HD bins at each size, segmented cells, Space Ranger's analysis, images, refusals | | `test_xenium.py` | Xenium bundles (XOA 1 to 4): the cell table in or out of the matrix's order, cells the matrix lacks, Xenium's analysis with gaps | | `test_geojson.py` | `formats/geojson.py`: Space Ranger 4's cell outlines read a feature at a time, centroids and areas against shapely | -| `test_pandas_frame.py` | Each pandas dtype written as anndata writes it, on every backend | +| `test_pandas_frame.py` | Each pandas dtype written as anndata writes it, on every backend; labels a store cannot hold as a name renamed, integers past int64 kept | | `test_concat_axis_elements.py` | `concat` on obsm dataframes and varm, against `anndata.concat` for each join and merge strategy | | `test_legacy_copies.py` | anndata 0.7's dataframes (categoricals as codes with an object reference into `__categories`) copied by `subset` (h5ad and Zarr), `convert` to Zarr v2/v3 and a MuData import: written as current `categorical` groups in a 0.2.0 frame, read back by anndata with their categories | | `test_subset_categories.py` | `subset` and `split` narrow categoricals as anndata's subsetting does: unused categories dropped (on an axis kept whole too), order and `ordered` kept, `uns["_colors"]` narrowed with them; compared with anndata's own subset | diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 0b927b3..e402a13 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -199,6 +199,25 @@ written. Drop the element from a copy first, or subset it with anndata. `subset` with no selection would copy the store. Use `convert` to copy, or add a selection. +### `obj.pkl: the pickle ..., which a pycisTopic object's never does, so it is not read.` + +The pickle names, calls or holds something a pycisTopic object's pickle +never does: a function outside what such an object holds, an array, matrix +or table that is not well formed, or a length (of a `range`, an index, an +empty array) longer than the file itself. Nothing in it was run, and +nothing was written. A pickle that pycisTopic saved is not refused; if +yours was, please +[report it](https://github.com/cellgeni/adata-cli/issues) with the message. + +### `obj.pkl: path_to_fragments names the sample 's/1', which an h5ad or Zarr store cannot hold as a key: ...` + +Each sample's fragment file is written under the sample's name, and HDF5 +and Zarr read `/` in a name as a path. A column label like that is renamed +with a warning, but a sample is not: cell_data's `sample_id` and the cell +names would no longer match the renamed key. Rename the sample in pycisTopic +(in `path_to_fragments`, and in `sample_id` and the cell names to keep them +matching), save the object again, and convert that. + ## Visium and Xenium These are refused before anything is written too. diff --git a/src/adata/conversion/cistopic.py b/src/adata/conversion/cistopic.py index f01f117..88a3fcf 100644 --- a/src/adata/conversion/cistopic.py +++ b/src/adata/conversion/cistopic.py @@ -57,7 +57,7 @@ from adata.formats import pickled from adata.storage import COMPRESSIONS, create_dataset, is_zarr_group, open_store, with_compression from adata.util.markup import literal -from adata.util.names import claim, count_duplicates, make_index_unique, sanitize_label +from adata.util.names import claim, count_duplicates, make_index_unique, sanitize_label, storable EXTENSIONS = (".pkl", ".pickle", ".pkl.gz", ".pickle.gz") @@ -224,6 +224,35 @@ def _names(values: Any) -> List[str]: return [str(v) for v in list(values)] +def _count(values: Any, what: str, name: str) -> int: + """How many names `values` holds, counted without listing them: they + are compared with the matrix before anything is made of them.""" + try: + return len(values) + except TypeError: + raise ValueError(f"{name}: its {what} is a {type(values).__name__}, not a list of names.") from None + + +def _check_samples(fragments: Any, name: str) -> None: + """`path_to_fragments`' samples, as keys a store can hold. A sample + holding `/`, or empty, is refused rather than renamed: cell_data's + `sample_id` and every cell name's suffix name it as it is, and a + renamed key would no longer match them.""" + if not isinstance(fragments, dict): + return + seen = set() + for sample in fragments: + key = str(sample) + if storable(key) != key: + raise ValueError( + f"{name}: path_to_fragments names the sample {key!r}, which an h5ad or Zarr " + "store cannot hold as a key: '/' separates its paths, and it has no empty names." + ) + if key in seen: + raise ValueError(f"{name}: path_to_fragments names the sample {key!r} twice.") + seen.add(key) + + def _ordered(frame: Any, names: List[str], axis: str, what: str, warnings: List[str]) -> Any: """`frame` with its rows (or, `axis="columns"`, columns) in `names` order.""" labels = frame.index if axis == "index" else frame.columns @@ -244,12 +273,15 @@ def _plan_object(obj: Any, name: str, warnings: List[str]) -> _Import: matrix = getattr(obj, "fragment_matrix", None) if not _is_sparse(matrix): raise ValueError(f"{name}: its CistopicObject holds no sparse fragment_matrix.") - cells, regions = _names(obj.cell_names), _names(obj.region_names) - if matrix.shape != (len(regions), len(cells)): + n_regions = _count(getattr(obj, "region_names", None), "region_names", name) + n_cells = _count(getattr(obj, "cell_names", None), "cell_names", name) + if matrix.shape != (n_regions, n_cells): raise ValueError( f"{name}: fragment_matrix is {matrix.shape[0]:,} x {matrix.shape[1]:,}, but " - f"the object names {len(regions):,} regions and {len(cells):,} cells." + f"the object names {n_regions:,} regions and {n_cells:,} cells." ) + _check_samples(getattr(obj, "path_to_fragments", None), name) + cells, regions = _names(obj.cell_names), _names(obj.region_names) detail = _Import("CistopicObject", obj, len(cells), len(regions), cells, regions) if _is_frame(getattr(obj, "cell_data", None)): detail.cell_data = _ordered(obj.cell_data, cells, "index", "cell_data", warnings) @@ -296,13 +328,15 @@ def _plan_object(obj: Any, name: str, warnings: List[str]) -> _Import: def _plan_imputed(obj: Any, name: str) -> _Import: matrix = getattr(obj, "mtx", None) - features, cells = _names(obj.feature_names), _names(obj.cell_names) - if matrix is None or tuple(matrix.shape) != (len(features), len(cells)): + n_features = _count(getattr(obj, "feature_names", None), "feature_names", name) + n_cells = _count(getattr(obj, "cell_names", None), "cell_names", name) + if matrix is None or tuple(matrix.shape) != (n_features, n_cells): shape = "nothing" if matrix is None else f"{matrix.shape[0]:,} x {matrix.shape[1]:,}" raise ValueError( - f"{name}: its matrix is {shape}, but it names {len(features):,} features " - f"and {len(cells):,} cells." + f"{name}: its matrix is {shape}, but it names {n_features:,} features " + f"and {n_cells:,} cells." ) + features, cells = _names(obj.feature_names), _names(obj.cell_names) if not _is_sparse(matrix): if not isinstance(matrix, np.ndarray) or matrix.ndim != 2: raise ValueError(f"{name}: its matrix is a {type(matrix).__name__}, not an array.") diff --git a/src/adata/formats/pandas_frame.py b/src/adata/formats/pandas_frame.py index 8395cb0..dca68af 100644 --- a/src/adata/formats/pandas_frame.py +++ b/src/adata/formats/pandas_frame.py @@ -15,9 +15,15 @@ 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; + as numbers (integers as int64, or uint64 past it, as pandas reads them), + text as text, anything mixed as text with a warning; * datetimes as ISO text, with a warning. Anything else is left out, with a warning. + +A column is written under its label, but for one that HDF5 and Zarr cannot +hold as a name: holding `/`, which they read as a path (`/var` would land at +the store's root), or empty. Such a label is renamed, `/` to `_`, with a +warning, as `convert` renames a loom's fields. """ from __future__ import annotations @@ -36,7 +42,7 @@ write_masked, write_string_array, ) -from adata.util.names import natural_sorted +from adata.util.names import claim, natural_sorted, storable def write_frame( @@ -58,10 +64,8 @@ def write_frame( labels = [str(v) for v in (df.index if index is None else index)] group = write_dataframe_header(parent, name, labels, []) written = [] - for position, column in enumerate(df.columns): - key = str(column) - if key in spec.RESERVED_DATAFRAME_KEYS or key in written: - warnings.append(f"Not written: {what or name} column {key!r}, a name a dataframe reserves or repeats.") + for position, key in enumerate(_column_keys([str(c) for c in df.columns], warnings, what or name)): + if key is None: continue # By position: a repeated label selects every column it names. if write_column(group, key, df.iloc[:, position], categorize=categorize, @@ -71,6 +75,34 @@ def write_frame( return group +def _column_keys(labels: List[str], warnings: List[str], what: str) -> List[Optional[str]]: + """Each column's name in the store, None for one left out: a label a + dataframe reserves, or one repeated, is left out with a warning. A label + HDF5 and Zarr cannot hold as a name is renamed with a warning, to a name + no other column has: the labels they can hold keep theirs first.""" + keys: List[Optional[str]] = [] + seen = set() + for label in labels: + if label in spec.RESERVED_DATAFRAME_KEYS or label in seen: + warnings.append(f"Not written: {what} column {label!r}, a name a dataframe reserves or repeats.") + keys.append(None) + else: + keys.append(label) + seen.add(label) + taken = {key for key in keys if key is not None and storable(key) == key} | set(spec.RESERVED_DATAFRAME_KEYS) + renamed = [] + for position, key in enumerate(keys): + if key is not None and storable(key) != key: + keys[position] = claim(storable(key), taken) + renamed.append(f"{key!r} as {keys[position]!r}") + if renamed: + warnings.append( + f"Renamed in {what}: {', '.join(renamed)} -- HDF5 and Zarr read '/' in a name " + "as a path, and hold no empty name." + ) + return keys + + def write_column( parent: Any, name: str, column: Any, *, categorize: bool, warnings: List[str], what: str ) -> bool: @@ -107,10 +139,14 @@ def write_column( inferred = pd.api.types.infer_dtype(column, skipna=True) if inferred in ("integer", "floating", "mixed-integer-float", "decimal"): values = pd.to_numeric(column, errors="coerce") - if inferred == "integer" and not values.isna().any(): - write_dense(parent, name, values.to_numpy(dtype=np.int64)) - else: - write_dense(parent, name, values.to_numpy(dtype=np.float64)) + if inferred == "integer" and values.dtype.kind in "iu": + # int64, or uint64 for integers past it: as pandas reads them. + write_dense(parent, name, values.to_numpy()) + return True + floats = values.to_numpy(dtype=np.float64) + if inferred in ("integer", "mixed-integer-float") and _rounded(column, floats): + warnings.append(f"{what} holds integers no float holds exactly; written as floats, rounded.") + write_dense(parent, name, floats) return True if inferred == "boolean" and not column.isna().any(): write_dense(parent, name, column.to_numpy(dtype=bool)) @@ -130,6 +166,17 @@ def write_column( return False +def _rounded(column: Any, floats: np.ndarray) -> bool: + """Whether an integer in `column` is not the float written for it: one + past 2**53 beside missing values, or past the 64 bits pandas reads + integers into.""" + for value, written in zip(column, floats): + if isinstance(value, (int, np.integer)) and not isinstance(value, (bool, np.bool_)): + if not np.isfinite(written) or int(written) != int(value): + return True + return False + + def _missing(value: Any) -> bool: import pandas as pd diff --git a/src/adata/formats/pickled.py b/src/adata/formats/pickled.py index 79ae511..bf1fe43 100644 --- a/src/adata/formats/pickled.py +++ b/src/adata/formats/pickled.py @@ -17,14 +17,26 @@ * classes are created empty and given their state, as every pickle of them does; they are never constructed from a file's arguments, so pandas never parses a dtype or a timezone from it (`dateutil/` opens that path); +* every scipy and pandas object is checked the moment it is complete, and + one created empty is held by nothing until it has its state: a sparse + matrix's indices must lie within its shape and its `indptr` rise from 0 + to its entries, a Categorical's and a MultiIndex's codes lie within their + categories, a nullable array's mask match its values, and a frame's + blocks fill its rows and hold each column once. scipy's and pandas' + compiled code indexes with all of these unchecked, and a pickle can hand + an object to something that iterates or hashes it before the file ends; +* the builtins that take what they are given apart are given only what a + pickle of them holds: `set` and `frozenset` a list, `OrderedDict` a list + of pairs, `slice`, `range` and `complex` numbers; and nothing is hashed + (a dict's keys, a set's items, an index's name) but Python's and numpy's + own values, so no pandas code runs to hash one; * containers are filled only through `dict`, `list` and `set`, never by writing into an array that has been checked; -* once the whole file is read, every sparse matrix's indices must lie within - its shape and its `indptr` must rise from 0 to its entries, every - Categorical's and MultiIndex's codes within its categories, and every - nullable array's mask must match its values, and every frame's blocks - must fill its rows and hold each column once: scipy's and pandas' - compiled code indexes with them unchecked. +* a length the file names rather than holds (a `range`, a `RangeIndex`, an + empty array's or a sparse matrix's shape) is at most the bytes the file + holds, and a frame's columns are counted before pandas makes room for + them, so a pickle of a few hundred bytes cannot make the reader, or the + conversion after it, allocate gigabytes. That keeps a crafted file from corrupting memory or reading files through what it names, but it is still parsed by numpy, scipy and pandas: a pickle @@ -40,10 +52,14 @@ run. numpy, scipy and pandas are resolved to whatever versions are installed: numpy 2's `numpy._core` for a numpy 1 pickle's `numpy.core`, and pandas' own table of renamed classes (`pandas.compat.pickle_compat`) for a -pickle written by pycisTopic's pinned pandas 1.5. +pickle written by pycisTopic's pinned pandas 1.5. pyarrow is not needed +either: pandas 3 keeps text in Arrow arrays, and those are decoded here, +every offset checked against the text it indexes, into pandas' own string +arrays. `sniff` tells a pycisTopic pickle by its first opcodes, read with -`pickletools`, which parses a pickle and executes none of it. +`pickletools`, which parses a pickle and executes none of it, from the +first `SNIFF_BYTES` of the file alone. """ from __future__ import annotations @@ -52,6 +68,7 @@ import copyreg import gzip import importlib +import io import pickle import pickletools from collections import OrderedDict @@ -68,6 +85,11 @@ #: the outermost one, so its class is named within the first few. SNIFF_OPCODES = 64 +#: Bytes read before deciding: those opcodes lie in the first few hundred. +#: Any file is sniffed, text tables too, and the first letters of a table +#: can read as an opcode taking gigabytes ("B" and a length of "arco"). +SNIFF_BYTES = 1 << 16 + #: Globals an object's reconstruction names before its class, in protocols #: 0 and 1: `copy_reg._reconstructor(cls, object, state)`. _HELPERS = frozenset({ @@ -119,7 +141,13 @@ }), "pandas.arrays": frozenset({ "BooleanArray", "IntegerArray", "FloatingArray", "StringArray", "Categorical", + "ArrowStringArray", }), + # Text held in Arrow (pandas 3's default, and `string[pyarrow]` in 2.x), + # and how pyarrow rebuilds the Arrow array: both read here without + # pyarrow, which is never imported. + "pandas.core.arrays.string_arrow": frozenset({"ArrowStringArray", "ArrowStringArrayNumpySemantics"}), + "pyarrow.lib": frozenset({"_restore_array", "type_for_alias", "py_buffer"}), "builtins": frozenset({ "slice", "set", "frozenset", "complex", "bytes", "bytearray", "range", "object", }), @@ -128,6 +156,16 @@ "_codecs": frozenset({"encode"}), } +#: pandas' Arrow-backed string arrays, read as its Python-backed one. +_ARROW_STRING_ARRAYS = frozenset({"ArrowStringArray", "ArrowStringArrayNumpySemantics"}) + +#: pyarrow's names, and the method of the unpickler each stands for. +_ARROW_CALLS = {"_restore_array": "_arrow_array", "type_for_alias": "_arrow_type", "py_buffer": "_arrow_buffer"} + +#: The Arrow types pandas keeps text in, by the alias pyarrow pickles them +#: with, and the width of their offsets. +_ARROW_TEXT = {"string": 4, "utf8": 4, "large_string": 8, "large_utf8": 8} + #: numpy dtype kinds an array may have: no structured or void dtypes, #: which nothing pycisTopic holds uses. _KINDS = frozenset("biufcOUSMm") @@ -136,7 +174,7 @@ #: the most arguments it passes: none of them parses a dtype from text, and #: pandas' managers get no third, which would turn off their own check of #: their blocks. Any other class is only ever created empty and given its -#: state. +#: state. What each is given is checked too (`_Unpickler._arguments`). _CONSTRUCTED = { **{("builtins", name): 3 for name in ("slice", "range", "bytes", "bytearray")}, **{("builtins", name): 1 for name in ("set", "frozenset")}, @@ -164,6 +202,14 @@ _INDEX_KEYS = frozenset({"data", "name", "names", "levels", "codes", "labels", "sortorder", "start", "stop", "step"}) +#: What an ArrowStringArray's state holds: its Arrow array (`_data` before +#: pandas 2.1) and its dtype. +_ARROW_STATE = frozenset({"_pa_array", "_data", "_dtype"}) + +#: Keys whose hash and equality are Python's own: hashing anything else +#: runs its class's code (pandas' dtypes hash their categories). +_PLAIN = (str, bytes, int, float, complex, bool, type(None)) + class PycistopicObject: """A pycisTopic object, its attributes restored and nothing more. @@ -205,6 +251,23 @@ def __repr__(self) -> str: _NDARRAY = _ArrayClass() + +class _ArrowType: + """An Arrow text type, as `type_for_alias` names it: the width of its + offsets, and nothing a pickle may call.""" + + def __init__(self, width: int) -> None: + self.width = width + + +class _ArrowText: + """An Arrow string array, decoded: its values, None where one is + missing. Only an ArrowStringArray's state takes one.""" + + def __init__(self, values: np.ndarray, missing: np.ndarray) -> None: + self.values, self.missing = values, missing + + #: Not found: unlike None, never an object a pickle holds. _MISSING = object() @@ -225,6 +288,22 @@ def _is_count(value: Any) -> bool: return isinstance(value, (int, np.integer)) and not isinstance(value, (bool, np.bool_)) and value >= 0 +def _is_integer(value: Any) -> bool: + return isinstance(value, (int, np.integer)) and not isinstance(value, (bool, np.bool_)) + + +def _is_plain_key(value: Any) -> bool: + """A key Python or numpy hashes and compares without running anything + of the pickle's: a number, text, None, pandas' NA, or a tuple of them.""" + if type(value) in _PLAIN or isinstance(value, np.generic): + return True + if type(value) in (tuple, frozenset): + return all(_is_plain_key(item) for item in value) + if type(value) is slice: + return all(_is_plain_key(part) for part in (value.start, value.stop, value.step)) + return type(value).__name__ == "NAType" and type(value).__module__ == "pandas._libs.missing" + + def _shape(value: Any, what: str) -> Tuple[int, ...]: if type(value) is not tuple or not all(_is_count(n) for n in value): raise _refuse(f"gives {what} the shape {value!r}") @@ -238,6 +317,13 @@ def _size(shape: Tuple[int, ...]) -> int: return size +def _range_length(span: range) -> int: + """How many numbers `span` names, even past what `len` can count.""" + if span.step > 0: + return max(0, (span.stop - span.start + span.step - 1) // span.step) + return max(0, (span.start - span.stop - span.step - 1) // -span.step) + + def check_dtype(dtype: Any, what: str = "an array") -> np.dtype: """`dtype`, if it is one numpy builds for itself: a kind pycisTopic's arrays use, and the state numpy writes for it (flags, item size, @@ -251,6 +337,16 @@ def check_dtype(dtype: Any, what: str = "an array") -> np.dtype: return dtype +def _array_dtype(dtype: Any) -> np.dtype: + """An array's dtype: checked, and with items of some size. numpy sizes + an unsized text dtype (`S`, `U`) to one before making an array of it, + and an array of items of no size could name any number of them.""" + dtype = check_dtype(dtype) + if not dtype.itemsize: + raise _refuse(f"gives a numpy array the dtype {dtype.str}, whose items have no size") + return dtype + + def _vector(state: Dict[str, Any], key: str, kinds: str, what: str) -> np.ndarray: value = state.get(key) if type(value) is not np.ndarray or value.ndim != 1 or value.dtype.kind not in kinds: @@ -332,10 +428,31 @@ def _is_frame_or_series(value: Any) -> bool: return isinstance(value, (pd.DataFrame, pd.Series)) -def _check_manager(manager: Any, what: str) -> None: +def _placement_length(locs: Any) -> int: + """How many columns a block's placement names: a slice (of integers, as + a pickle can build one) or an array of integers, counted from the + slice's bounds or the array held, so never by listing what a slice + names.""" + from pandas._libs.internals import BlockPlacement + + if isinstance(locs, BlockPlacement): + return len(locs) + if type(locs) is not slice and not (type(locs) is np.ndarray and locs.ndim == 1 and locs.dtype.kind in "iu"): + raise _refuse(f"places a block at {type(locs).__name__}") + try: + return len(BlockPlacement(locs)) + except (TypeError, ValueError, OverflowError) as exc: + raise _refuse(f"places a block at {locs!r} ({exc})") from None + + +def _check_manager(manager: Any, what: str, held: int) -> None: """A DataFrame's or Series' blocks fill its axes: each block as many rows as the index, and between them every column once. pandas checks - neither when it unpickles a frame, and indexes the blocks by the axes.""" + neither when it unpickles a frame, and indexes the blocks by the axes. + + The columns are counted before they are listed: blocks hold as many + columns as their data, except when there are no rows, and then the + columns a frame names may number no more than the `held` bytes.""" import pandas as pd from pandas.api.extensions import ExtensionArray from pandas.core.internals.managers import SingleBlockManager @@ -347,7 +464,7 @@ def _check_manager(manager: Any, what: str) -> None: if len(axes) != (1 if single else 2) or (single and len(blocks) != 1): raise _refuse(f"gives {what} {len(axes)} axes and {len(blocks)} blocks") n_rows = len(axes[-1]) - covered = [] + placed = 0 for block in blocks: values = getattr(block, "values", None) if not (type(values) is np.ndarray or isinstance(values, ExtensionArray)): @@ -356,25 +473,35 @@ def _check_manager(manager: Any, what: str) -> None: if block.ndim != 1 or values.shape != (n_rows,): raise _refuse(f"gives {what} {values.shape} values for {n_rows:,} rows") continue - locs = block.mgr_locs.as_array - fits = values.shape == (len(locs), n_rows) or ( - values.ndim == 1 and len(locs) == 1 and values.shape[0] == n_rows + n_locs = _placement_length(block.mgr_locs) + fits = values.shape == (n_locs, n_rows) or ( + values.ndim == 1 and n_locs == 1 and values.shape[0] == n_rows ) if block.ndim != 2 or not fits: raise _refuse( - f"gives {what} a block of shape {values.shape} for {len(locs):,} columns " + f"gives {what} a block of shape {values.shape} for {n_locs:,} columns " f"of {n_rows:,} rows" ) - covered.append(np.asarray(locs, dtype=np.int64)) - if not single: - columns = np.sort(np.concatenate(covered)) if covered else np.zeros(0, dtype=np.int64) - if not np.array_equal(columns, np.arange(len(axes[0]))): - raise _refuse(f"gives {what} blocks that do not hold each of its {len(axes[0]):,} columns once") - - -def _check_pandas(value: Any) -> None: + placed += n_locs + if single: + return + n_columns = len(axes[0]) + if placed != n_columns: + raise _refuse(f"gives {what} blocks that do not hold each of its {n_columns:,} columns once") + if not n_rows and n_columns > held: + raise _refuse(f"gives {what} {n_columns:,} columns of no rows, more than the {held:,} bytes it holds") + columns = ( + np.sort(np.concatenate([np.asarray(block.mgr_locs.as_array, dtype=np.int64) for block in blocks])) + if blocks else np.zeros(0, dtype=np.int64) + ) + if not np.array_equal(columns, np.arange(n_columns)): + raise _refuse(f"gives {what} blocks that do not hold each of its {n_columns:,} columns once") + + +def _check_pandas(value: Any, held: int) -> None: """pandas objects whose integer codes and blocks its compiled code - indexes with unchecked: within what they index.""" + indexes with unchecked: within what they index. `held` is the bytes + the pickle has given so far.""" import pandas as pd from pandas.core.arrays.masked import BaseMaskedArray from pandas.core.internals.managers import BlockManager, SingleBlockManager @@ -384,18 +511,24 @@ def _check_pandas(value: Any) -> None: kind = SingleBlockManager if isinstance(value, pd.Series) else BlockManager if type(manager) is not kind: raise _refuse(f"gives a {type(value).__name__} a {type(manager).__name__} for its data") - _check_manager(manager, f"a {type(value).__name__}") + _check_manager(manager, f"a {type(value).__name__}", held) elif type(value) in (BlockManager, SingleBlockManager): - _check_manager(value, f"a {type(value).__name__}") + _check_manager(value, f"a {type(value).__name__}", held) elif isinstance(value, pd.Categorical): what = "a Categorical" - codes = value._ndarray - categories = getattr(value.dtype, "categories", None) - if not isinstance(value.dtype, pd.CategoricalDtype) or not isinstance(categories, pd.Index): + codes, dtype = value._ndarray, value._dtype + categories = getattr(dtype, "_categories", None) if isinstance(dtype, pd.CategoricalDtype) else None + if not isinstance(categories, pd.Index): raise _refuse(f"gives {what} no categories") if type(codes) is not np.ndarray or codes.ndim != 1 or codes.dtype.kind != "i": raise _refuse(f"gives {what} its codes as {type(codes).__name__}") _within(codes, -1, len(categories), f"{what}'s codes") + elif isinstance(value, pd.CategoricalDtype): + categories, ordered = getattr(value, "_categories", None), getattr(value, "_ordered", None) + if not (categories is None or isinstance(categories, pd.Index)): + raise _refuse(f"gives a CategoricalDtype the categories {type(categories).__name__}") + if not (ordered is None or isinstance(ordered, (bool, np.bool_))): + raise _refuse(f"gives a CategoricalDtype the order {type(ordered).__name__}") elif isinstance(value, pd.MultiIndex): levels, codes = list(value.levels), list(value.codes) if len(levels) != len(codes) or len({len(c) for c in codes}) > 1: @@ -413,6 +546,27 @@ def _check_pandas(value: Any) -> None: values = value._ndarray if type(values) is not np.ndarray or values.ndim != 1 or values.dtype != object: raise _refuse("gives a StringArray values that are not text") + if not isinstance(value._dtype, pd.StringDtype) or getattr(value._dtype, "storage", None) != "python": + raise _refuse(f"gives a StringArray the dtype {value._dtype!r}") + + +class _Counted: + """The file, its bytes counted as the unpickler reads them: what a + length the pickle names is held to.""" + + def __init__(self, file: BinaryIO) -> None: + self._file = file + self.count = 0 + + def read(self, size: int = -1) -> bytes: + data = self._file.read(size) + self.count += len(data) + return data + + def readline(self, size: int = -1) -> bytes: + line = self._file.readline(size) + self.count += len(line) + return line class _Unpickler(pickle._Unpickler): @@ -420,32 +574,39 @@ class _Unpickler(pickle._Unpickler): object's state or fills a container checked first. `_fresh`: objects this pickle created and has not yet given their state; - each is given it once. `_unbuilt`: those of them that are numpy arrays - and dtypes, which nothing may hold until they have their state. + each is given it once. `_unbuilt`: those of them that nothing may hold + until they have their state: numpy arrays and dtypes, and scipy's and + pandas' objects (but for pandas' dtypes, which some pickles never give + one). """ dispatch = dict(pickle._Unpickler.dispatch) def __init__(self, file: BinaryIO) -> None: - super().__init__(file) + self._source = _Counted(file) + super().__init__(self._source) self._fresh: Dict[int, Any] = {} self._unbuilt: Dict[int, Any] = {} self._dtype_args: Dict[int, Tuple[str, bool]] = {} - self._loaded: Dict[int, Any] = {} self._own: Dict[Tuple[str, int], Callable[..., Any]] = {} self._classes: Optional[Dict[int, Tuple[type, int]]] = None + #: The longest length the pickle names without holding the data + #: for it, and what names it. + self._named: Tuple[int, str] = (0, "") def load(self) -> Any: value = super().load() - for item in self._loaded.values(): - if isinstance(item, np.ndarray): - continue - if type(item).__module__.startswith("scipy"): - check_sparse(item) - else: - _check_pandas(item) + length, what = self._named + if length > self._source.count: + raise _refuse(f"names {what}, more than the {self._source.count:,} bytes it holds") return value + def _names_length(self, length: int, what: str) -> None: + """A length the pickle names rather than holds, held to its bytes + once it is read.""" + if length > self._named[0]: + self._named = (length, what) + # -- names --------------------------------------------------------- def find_class(self, module: str, name: str) -> Any: @@ -463,6 +624,10 @@ def find_class(self, module: str, name: str) -> Any: f"the pickle asks for {module}.{name}, which a pycisTopic object " "never holds, so it is not read." ) + if module == "pyarrow.lib": + return getattr(self, _ARROW_CALLS[name]) + if name in _ARROW_STRING_ARRAYS: + return _resolve("pandas.arrays", "StringArray") value = _resolve(module, name) if value is np.ndarray: return _NDARRAY @@ -504,22 +669,45 @@ def _wrappers(self) -> Dict[Tuple[str, int], Callable[..., Any]]: # -- what may be held, and by what --------------------------------- - def _created(self, obj: Any, fresh: bool = True) -> Any: + def _created(self, obj: Any, *, fresh: bool = True, built: bool = False) -> Any: + """`obj`, just made: `fresh` when the pickle may yet give it its + state (once), `built` when it is complete. A scipy or pandas object + is checked once complete, and until then is held by nothing (but + for pandas' dtypes, which some pickles never give a state).""" if fresh: self._fresh[id(obj)] = obj - if not isinstance(obj, (PycistopicObject, np.dtype)) and ( - type(obj).__module__.startswith(("scipy", "pandas")) - ): - self._loaded[id(obj)] = obj + if _is_checked(obj): + if built: + self._check(obj) + elif _needs_state(obj): + self._unbuilt[id(obj)] = obj return obj + def _check(self, obj: Any) -> None: + """A scipy or pandas object, complete: checked before anything can + hold it.""" + if type(obj).__module__.startswith("scipy"): + check_sparse(obj) + self._names_length(max(obj._shape), f"a scipy {type(obj).__name__} of shape {obj._shape}") + else: + _check_pandas(obj, self._source.count) + def _held(self, items: Iterable[Any], by: str) -> None: - """Refuse a numpy array or dtype that is handed on before it has - its state: what it is handed to sees it empty.""" + """Refuse an object handed on before it has its state: what it is + handed to sees it empty.""" unbuilt = self._unbuilt for item in items: if unbuilt.get(id(item), _MISSING) is item: - raise _refuse(f"hands a numpy {type(item).__name__} to {by} before giving it its state") + raise _refuse(f"hands a {_name(type(item))} to {by} before giving it its state") + + def _keys(self, keys: Iterable[Any], as_what: str) -> None: + """Refuse to hash anything but Python's or numpy's own values: + hashing a key, or comparing it with another, runs its class's code + on whatever the pickle gave it. `as_what` names what hashes it (`a + key of a dict`).""" + for key in keys: + if not _is_plain_key(key): + raise _refuse(f"hashes a {_name(type(key))} as {as_what}") def _operands(self, count: Optional[int] = None) -> list: """The items an opcode is about to consume: the last `count`, or all @@ -536,20 +724,92 @@ def _call(self, func: Any, args: Any) -> Any: return func(*args) if isinstance(func, type): if not args: - return self._created(func()) + return self._created(func(), built=True) found, most = self._constructed().get(id(func), (None, 0)) - if found is func: - if len(args) > most: - raise _refuse(f"constructs {_name(func)} from {len(args)} arguments") - if func in (bytes, bytearray) and any(not isinstance(a, (str, bytes)) for a in args): - raise _refuse(f"calls {func.__name__} with {', '.join(type(a).__name__ for a in args)}") - return self._created(func(*args), fresh=False) - raise _refuse(f"constructs {_name(func)} from arguments") + if found is not func: + raise _refuse(f"constructs {_name(func)} from arguments") + if len(args) > most: + raise _refuse(f"constructs {_name(func)} from {len(args)} arguments") + if func.__module__.startswith("pandas") and func.__name__ == "StringDtype": + return self._string_dtype(*args) + self._arguments(func, args) + made = func(*args) + if func is range: + self._names_length(_range_length(made), f"a range of {_range_length(made):,}") + return self._created(made, fresh=False, built=True) module = getattr(func, "__module__", "") or "" if module.startswith("pandas") and getattr(func, "__name__", "") in ("_unpickle_block", "new_block"): - return self._created(func(*args), fresh=False) + self._block_arguments(args) + return self._created(func(*args), fresh=False, built=True) raise _refuse(f"calls {_name(func)}") + def _arguments(self, func: type, args: tuple) -> None: + """What a pickle gives each class it constructs, as pickles of it + hold: anything else would be taken apart (iterated, hashed, read as + a number) by the class before it could be checked.""" + what = f"{func.__module__}.{func.__qualname__}" + if func in (slice, range, complex): + if func is slice: + numbers = all(arg is None or _is_integer(arg) for arg in args) + elif func is range: + numbers = all(_is_integer(arg) for arg in args) + else: + numbers = all(isinstance(arg, (int, float, np.integer, np.floating)) for arg in args) + if not numbers: + raise _refuse(f"calls {what} with {', '.join(type(a).__name__ for a in args)}") + elif func in (bytes, bytearray): + if any(not isinstance(a, (str, bytes)) for a in args): + raise _refuse(f"calls {func.__name__} with {', '.join(type(a).__name__ for a in args)}") + elif func in (set, frozenset, OrderedDict): + (items,) = args + if type(items) is not list: + raise _refuse(f"calls {what} with a {_name(type(items))}, where a pickle of one holds a list") + if func is OrderedDict: + if not all(type(pair) in (list, tuple) and len(pair) == 2 for pair in items): + raise _refuse(f"calls {what} with items that are not pairs") + self._keys([pair[0] for pair in items], "a key of an OrderedDict") + else: + self._keys(items, f"an item of a {func.__name__}") + else: + self._manager_arguments(func, args) + + def _manager_arguments(self, func: type, args: tuple) -> None: + """pandas' managers, given blocks and indexes, and its placements, + given a slice or an array: before pandas acts on them.""" + import pandas as pd + from pandas._libs.internals import BlockPlacement + from pandas.core.internals.blocks import Block + from pandas.core.internals.managers import SingleBlockManager + + what = f"a {func.__name__}" + if func is BlockPlacement: + _placement_length(args[0]) + elif func is SingleBlockManager: + if len(args) != 2 or not isinstance(args[0], Block) or not isinstance(args[1], pd.Index): + raise _refuse(f"builds {what} from {', '.join(type(a).__name__ for a in args)}") + else: + blocks, axes = (args + (None,))[:2] + if (type(blocks) not in (tuple, list) or not all(isinstance(b, Block) for b in blocks) + or type(axes) is not list or len(axes) != 2 + or not all(isinstance(a, pd.Index) for a in axes)): + raise _refuse(f"builds {what} from something other than blocks and two indexes") + if sum(_placement_length(block.mgr_locs) for block in blocks) != len(axes[0]): + raise _refuse(f"gives {what} blocks that do not hold each of its {len(axes[0]):,} columns once") + + def _block_arguments(self, args: tuple) -> None: + """pandas' `_unpickle_block(values, placement, ndim)`.""" + from pandas.api.extensions import ExtensionArray + + described = ", ".join(type(a).__name__ for a in args) + if len(args) != 3: + raise _refuse(f"builds a pandas block from {described}") + values, locs, ndim = args + if not (type(values) is np.ndarray or isinstance(values, ExtensionArray)) or not ( + _is_integer(ndim) and ndim in (1, 2) + ): + raise _refuse(f"builds a pandas block from {described}") + _placement_length(locs) + def load_reduce(self) -> None: stack = self.stack args = stack.pop() @@ -606,70 +866,152 @@ def load_build(self) -> None: setstate(state) else: inst.__dict__.update(state) + self._check(inst) elif type(inst).__module__.startswith("pandas"): - if _is_frame_or_series(inst) and type(state) is dict: - unknown = sorted(map(str, set(state) - _FRAME_STATE)) - if unknown: - raise _refuse(f"gives a {type(inst).__name__} {', '.join(unknown)}") - stack.append(state) - super().load_build() + self._build_pandas(inst, state) else: raise _refuse(f"sets the state of {_name(type(inst))}") self._unbuilt.pop(id(inst), None) dispatch[pickle.BUILD[0]] = load_build + def _build_pandas(self, inst: Any, state: Any) -> None: + """A pandas object's state: what pandas pickles it with, checked + before pandas builds from it where pandas would act on it, and the + object checked once built.""" + import pandas as pd + from pandas.api.extensions import ExtensionDtype + from pandas.core.internals.managers import BlockManager, SingleBlockManager + + if isinstance(inst, pd.Index): + # An index is rebuilt from `_new_Index`'s keys alone: a pickle + # never gives one a state. + raise _refuse(f"sets the state of a pandas {type(inst).__name__}") + if _is_frame_or_series(inst): + if type(state) is dict: + unknown = sorted(map(str, set(state) - _FRAME_STATE)) + if unknown: + raise _refuse(f"gives a {type(inst).__name__} {', '.join(unknown)}") + elif type(state) is dict and "_cache" in state: + # What pandas worked out from the rest (an array's dtype, a + # dtype's numpy dtype), pickled with it once used: dropped, for + # pandas to work out again from what is checked. + state = {k: v for k, v in state.items() if k != "_cache"} + if type(inst) in (BlockManager, SingleBlockManager): + self._check_manager_state(inst, state) + elif isinstance(inst, ExtensionDtype) and not isinstance(inst, (pd.CategoricalDtype, pd.StringDtype)): + # `Int64Dtype` and the like are complete when created; a pickle + # gives one at most its cache. + if state: + raise _refuse(f"gives a pandas {type(inst).__name__} the state {state!r}") + self._check(inst) + return + elif isinstance(inst, pd.StringDtype) and type(state) is dict: + # pandas before 2.3 pickled a StringDtype as its storage; text is + # held in Python strings here, Arrow's too. + if state.get("storage") == "pyarrow_numpy": + state = {**state, "storage": "python", "_na_value": np.nan} + elif state.get("storage") == "pyarrow": + state = {**state, "storage": "python"} + if isinstance(inst, pd.arrays.StringArray) and type(state) is dict and isinstance( + state.get("_pa_array", state.get("_data")), _ArrowText + ): + inst.__setstate__(self._from_arrow(state)) + else: + self.stack.append(state) + super().load_build() + self._check(inst) + + def _check_manager_state(self, manager: Any, state: Any) -> None: + """A manager's state as pandas 1.5 pickles it, before pandas builds + the manager from it, which makes room for each column it names: as + many columns placed as named, and, with no rows to hold them, no more + than the bytes the pickle holds.""" + import pandas as pd + from pandas.api.extensions import ExtensionArray + from pandas.core.internals.managers import SingleBlockManager + + what = f"a {type(manager).__name__}" + legacy = state[3].get("0.14.1") if type(state) is tuple and len(state) >= 4 and type(state[3]) is dict else None + axes = legacy.get("axes") if type(legacy) is dict else None + blocks = legacy.get("blocks") if type(legacy) is dict else None + n_axes = 1 if isinstance(manager, SingleBlockManager) else 2 + if (type(axes) is not list or len(axes) != n_axes or not all(isinstance(a, pd.Index) for a in axes) + or type(blocks) is not list): + raise _refuse(f"gives {what} a state without its axes and blocks") + placed = 0 + for block in blocks: + values = block.get("values") if type(block) is dict else None + if not (type(values) is np.ndarray or isinstance(values, ExtensionArray)): + raise _refuse(f"gives {what} a block of {type(values).__name__}") + placed += _placement_length(block.get("mgr_locs")) + if n_axes == 2: + n_columns = len(axes[0]) + if placed != n_columns: + raise _refuse(f"gives {what} blocks that do not hold each of its {n_columns:,} columns once") + if not len(axes[1]) and n_columns > self._source.count: + raise _refuse( + f"gives {what} {n_columns:,} columns of no rows, more than the " + f"{self._source.count:,} bytes it holds" + ) + # -- containers: only dict, list and set are filled -------------------- - def _fill(self, target: Any, kinds: Tuple[type, ...], items: list, by: str) -> None: + def _fill(self, target: Any, kinds: Tuple[type, ...], items: list, by: str, keys: list, as_what: str) -> None: if type(target) not in kinds: raise _refuse(f"{by} into a {_name(type(target))}") self._held(items, f"a {type(target).__name__}") + self._keys(keys, f"{as_what} of a {type(target).__name__}") def load_append(self) -> None: - self._fill(self.stack[-2], (list,), self.stack[-1:], "appends") + self._fill(self.stack[-2], (list,), self.stack[-1:], "appends", [], "") super().load_append() dispatch[pickle.APPEND[0]] = load_append def load_appends(self) -> None: - self._fill(self.metastack[-1][-1], (list,), self.stack, "appends") + self._fill(self.metastack[-1][-1], (list,), self.stack, "appends", [], "") super().load_appends() dispatch[pickle.APPENDS[0]] = load_appends def load_setitem(self) -> None: - self._fill(self.stack[-3], (dict, OrderedDict), self.stack[-2:], "writes") + self._fill(self.stack[-3], (dict, OrderedDict), self.stack[-2:], "writes", self.stack[-2:-1], "a key") super().load_setitem() dispatch[pickle.SETITEM[0]] = load_setitem def load_setitems(self) -> None: - self._fill(self.metastack[-1][-1], (dict, OrderedDict), self.stack, "writes") + self._fill(self.metastack[-1][-1], (dict, OrderedDict), self.stack, "writes", self.stack[0::2], "a key") super().load_setitems() dispatch[pickle.SETITEMS[0]] = load_setitems def load_additems(self) -> None: - self._fill(self.metastack[-1][-1], (set,), self.stack, "adds") + self._fill(self.metastack[-1][-1], (set,), self.stack, "adds", self.stack, "an item") super().load_additems() dispatch[pickle.ADDITEMS[0]] = load_additems - def _packed(load: Callable[[Any], None], count: Optional[int]) -> Callable[[Any], None]: # type: ignore[misc] + def _packed(load: Callable[[Any], None], count: Optional[int], hashed: Optional[Tuple[slice, str]]) -> Callable[[Any], None]: # type: ignore[misc] def packed(self: "_Unpickler") -> None: + operands = self._operands(count) if self._unbuilt: - self._held(self._operands(count), "a tuple, list, dict or set") + self._held(operands, "a tuple, list, dict or set") + if hashed is not None: + self._keys(operands[hashed[0]], hashed[1]) load(self) return packed - for _opcode, _count in ( - (pickle.TUPLE, None), (pickle.TUPLE1, 1), (pickle.TUPLE2, 2), (pickle.TUPLE3, 3), - (pickle.LIST, None), (pickle.DICT, None), (pickle.FROZENSET, None), + for _opcode, _count, _hashed in ( + (pickle.TUPLE, None, None), (pickle.TUPLE1, 1, None), (pickle.TUPLE2, 2, None), + (pickle.TUPLE3, 3, None), (pickle.LIST, None, None), + (pickle.DICT, None, (slice(0, None, 2), "a key of a dict")), + (pickle.FROZENSET, None, (slice(None), "an item of a frozenset")), ): - dispatch[_opcode[0]] = _packed(dispatch[_opcode[0]], _count) - del _opcode, _count, _packed + dispatch[_opcode[0]] = _packed(dispatch[_opcode[0]], _count, _hashed) + del _opcode, _count, _hashed, _packed # -- numpy ----------------------------------------------------------- @@ -722,7 +1064,7 @@ def _build_array(self, array: np.ndarray, state: Any) -> None: if len(state) == 5 and not _is_count(state[0]): raise _refuse(f"gives a numpy array the version {state[0]!r}") shape = _shape(shape, "a numpy array") - dtype = check_dtype(dtype) + dtype = _array_dtype(dtype) if not isinstance(fortran, (bool, int)): raise _refuse(f"gives a numpy array the order {fortran!r}") size = _size(shape) @@ -735,6 +1077,8 @@ def _build_array(self, array: np.ndarray, state: Any) -> None: f"gives a numpy {dtype} array of shape {shape} {length} bytes of data, " f"not {size * dtype.itemsize:,}" ) + if not size and shape: + self._names_length(max(shape), f"an empty numpy array of shape {shape}") array.__setstate__(state) def _frombuffer(self, buffer: Any, dtype: Any, shape: Any, order: Any) -> np.ndarray: @@ -742,20 +1086,22 @@ def _frombuffer(self, buffer: Any, dtype: Any, shape: Any, order: Any) -> np.nda the shape fills exactly.""" from numpy import frombuffer - dtype = check_dtype(dtype) + dtype = _array_dtype(dtype) shape = _shape(shape, "a numpy array") if dtype.hasobject or type(buffer) not in (bytes, bytearray) or order not in ("C", "F"): raise _refuse(f"builds a numpy {dtype} array from {type(buffer).__name__}") if len(buffer) != _size(shape) * dtype.itemsize: raise _refuse(f"gives a numpy {dtype} array of shape {shape} {len(buffer):,} bytes of data") + if not _size(shape) and shape: + self._names_length(max(shape), f"an empty numpy array of shape {shape}") return frombuffer(buffer, dtype=dtype).reshape(shape, order=order) def _scalar(self, dtype: Any, raw: Any = None) -> Any: - """numpy's `scalar`: an object as itself, or bytes as wide as the - dtype's items.""" + """numpy's `scalar`: bytes as wide as the dtype's items. numpy + never pickles a scalar of objects, and refuses to read one.""" dtype = check_dtype(dtype, "a scalar") if dtype.hasobject: - return raw + raise _refuse("gives numpy a scalar of objects") if type(raw) is not bytes or len(raw) != dtype.itemsize: raise _refuse(f"gives a numpy {dtype} scalar {type(raw).__name__} of the wrong size") return np.frombuffer(raw, dtype=dtype)[0] @@ -778,8 +1124,9 @@ def _reconstructor(self, cls: Any, base: Any, state: Any) -> Any: def _new_index(self, cls: Any, d: Any) -> Any: """pandas' `_new_Index(cls, d)`, which passes `d` to the class: only the keys pandas pickles an index with, so never a dtype or a - timezone to parse.""" + timezone to parse, and each of the kind pandas pickles there.""" import pandas as pd + from pandas.api.extensions import ExtensionArray from pandas.core.indexes.base import _new_Index if not (isinstance(cls, type) and issubclass(cls, pd.Index)) or type(d) is not dict: @@ -787,7 +1134,25 @@ def _new_index(self, cls: Any, d: Any) -> Any: unknown = sorted(set(d) - _INDEX_KEYS) if unknown: raise _refuse(f"builds a {cls.__name__} with {', '.join(map(str, unknown))}") - return self._created(_new_Index(cls, d), fresh=False) + what = f"builds a {cls.__name__} from" + data = d.get("data", None) + if not (data is None or type(data) is np.ndarray or isinstance(data, ExtensionArray)): + raise _refuse(f"{what} {type(data).__name__}") + if not all(d.get(key) is None or _is_integer(d[key]) for key in ("start", "stop", "step", "sortorder")): + raise _refuse(f"{what} bounds that are not integers") + levels, codes = d.get("levels"), d.get("codes", d.get("labels")) + if levels is not None or codes is not None: + if (type(levels) is not list or not all(isinstance(level, pd.Index) for level in levels) + or type(codes) is not list + or not all(type(c) is np.ndarray and c.ndim == 1 for c in codes)): + raise _refuse(f"{what} levels and codes that are not indexes and arrays") + names = d.get("names") + if names is not None and type(names) not in (list, tuple): + raise _refuse(f"{what} names given as {type(names).__name__}") + self._keys([d.get("name"), *(names or ())], f"the name of a {cls.__name__}") + index = _new_Index(cls, d) + self._names_length(len(index), f"an index of {len(index):,}") + return self._created(index, fresh=False, built=True) def _ndarray_backed(self, cls: Any, checksum: Any, state: Any = None) -> Any: """pandas' unpickling of its Categorical and StringArray.""" @@ -795,7 +1160,119 @@ def _ndarray_backed(self, cls: Any, checksum: Any, state: Any = None) -> Any: if cls not in (pd.Categorical, pd.arrays.StringArray): raise _refuse(f"builds {cls!r} through pandas' __pyx_unpickle_NDArrayBacked") - return self._created(_ndarray_backed()(cls, checksum, state), fresh=state is None) + built = _ndarray_backed()(cls, checksum, state) + return self._created(built, fresh=state is None, built=state is not None) + + def _string_dtype(self, storage: Any = None, na_value: Any = _MISSING) -> Any: + """pandas' `StringDtype(storage, na_value)`, held in Python strings + whatever storage it names: Arrow's text is decoded here, so pyarrow + is not needed. Missing values are pandas' NA, or NaN as pandas 3's + `str` has them, where this pandas has that.""" + import pandas as pd + + if storage not in (None, "python", "pyarrow", "pyarrow_numpy"): + raise _refuse(f"builds a StringDtype held in {storage!r}") + if storage == "pyarrow_numpy": + na_value = np.nan + if na_value is _MISSING or na_value is pd.NA: + return pd.StringDtype("python") + if not (isinstance(na_value, float) and np.isnan(na_value)): + raise _refuse(f"builds a StringDtype whose missing values are {na_value!r}") + try: + return pd.StringDtype("python", na_value=np.nan) + except TypeError: # pragma: no cover - pandas before 2.3, whose text misses values as NA only + return pd.StringDtype("python") + + # -- Arrow text, read without pyarrow -------------------------------- + + def _arrow_type(self, alias: Any) -> _ArrowType: + """pyarrow's `type_for_alias`, for the types pandas keeps text in: + `string`, whose offsets are int32, and `large_string`, int64.""" + width = _ARROW_TEXT.get(alias) if type(alias) is str else None + if width is None: + raise _refuse(f"rebuilds an Arrow array of type {alias!r}") + return _ArrowType(width) + + def _arrow_buffer(self, data: Any) -> bytes: + """pyarrow's `py_buffer`: the bytes, as they are.""" + if type(data) not in (bytes, bytearray): + raise _refuse(f"builds an Arrow buffer from {type(data).__name__}") + return bytes(data) + + def _arrow_array(self, data: Any) -> _ArrowText: + """pyarrow's `_restore_array`, for an Arrow string array: decoded to + Python strings, every offset first checked to rise within the text + it indexes, the validity bitmap to cover the values, and the text + to be UTF-8.""" + if type(data) is not tuple or len(data) != 7: + raise _refuse(f"rebuilds an Arrow array from {type(data).__name__}") + kind, length, null_count, offset, buffers, children, dictionary = data + if type(kind) is not _ArrowType: + raise _refuse(f"rebuilds an Arrow array of {_name(type(kind))}") + if not (_is_count(length) and _is_count(offset) and _is_integer(null_count)): + raise _refuse("rebuilds an Arrow array whose length or offset is not a count") + if (children != [] or dictionary is not None or type(buffers) is not list or len(buffers) != 3 + or not all(b is None or type(b) is bytes for b in buffers)): + raise _refuse("rebuilds an Arrow string array from parts a string array never has") + validity, offsets, text = buffers + length, offset = int(length), int(offset) + values = np.full(length, None, dtype=object) + missing = np.zeros(length, dtype=bool) + if not length: + return _ArrowText(values, missing) + width = kind.width + if offsets is None or len(offsets) // width < offset + length + 1: + raise _refuse(f"gives an Arrow string array of {length:,} values too few offsets") + bounds = np.frombuffer(offsets, dtype=f" len(text) or (np.diff(bounds) < 0).any(): + raise _refuse(f"gives an Arrow string array offsets outside its {len(text):,} bytes of text") + if validity is not None: + if len(validity) * 8 < offset + length: + raise _refuse("gives an Arrow string array a validity bitmap shorter than its values") + bits = np.unpackbits(np.frombuffer(validity, dtype=np.uint8), count=offset + length, bitorder="little") + missing = ~bits[offset:].astype(bool) + starts, ends = bounds[:-1].tolist(), bounds[1:].tolist() + try: + for i in np.flatnonzero(~missing).tolist(): + values[i] = text[starts[i] : ends[i]].decode("utf-8") + except UnicodeDecodeError as exc: + raise _refuse(f"gives an Arrow string array text that is not UTF-8 ({exc.reason})") from None + return _ArrowText(values, missing) + + def _from_arrow(self, state: Dict[str, Any]) -> Dict[str, Any]: + """An ArrowStringArray's state, as the StringArray it is read as: + the decoded text, missing values as its dtype has them.""" + import pandas as pd + + unknown = sorted(map(str, set(state) - _ARROW_STATE)) + if unknown: + raise _refuse(f"gives an ArrowStringArray {', '.join(unknown)}") + text, dtype = state.get("_pa_array", state.get("_data")), state.get("_dtype") + if not isinstance(dtype, pd.StringDtype): + raise _refuse(f"gives an ArrowStringArray the dtype {type(dtype).__name__}") + values = text.values.copy() + values[text.missing] = dtype.na_value + return {"_ndarray": values, "_dtype": dtype} + + +def _is_checked(obj: Any) -> bool: + """An object of scipy's or pandas', checked once complete.""" + return not isinstance(obj, (PycistopicObject, np.dtype, np.ndarray)) and ( + type(obj).__module__.startswith(("scipy", "pandas")) + ) + + +def _needs_state(obj: Any) -> bool: + """Whether an object created empty is incomplete until it has its state: + every one of scipy's and pandas' but pandas' dtypes, which pickles of + some (`Int64Dtype`) never give one, and whose empty instances are + plain Python objects.""" + if type(obj).__module__.startswith("scipy"): + return True + from pandas.api.extensions import ExtensionDtype + + return not isinstance(obj, ExtensionDtype) def _ndarray_backed() -> Callable[..., Any]: @@ -862,26 +1339,35 @@ def load(path: Path) -> Any: def pickled_class(path: Path) -> Optional[str]: """The pycisTopic class a pickle holds (`CistopicObject`, ...), from its - first opcodes alone; None for any other file.""" + first opcodes alone, in its first `SNIFF_BYTES`; None for any other + file.""" try: with open_pickle(path) as fh: - strings: list = [] - for i, (op, arg, _) in enumerate(pickletools.genops(fh)): - if i >= SNIFF_OPCODES: + head = fh.read(SNIFF_BYTES) + except Exception: # unreadable, or a gzip that is not one: not this format + return None + # A pickle opens with PROTO (protocol 2 and later) or, in protocols 0 + # and 1, with the GLOBAL that names its object's class or copy_reg's. + if head[:1] not in (b"\x80", b"c"): + return None + strings: list = [] + try: + for i, (op, arg, _) in enumerate(pickletools.genops(io.BytesIO(head))): + if i >= SNIFF_OPCODES: + return None + if op.name in ("SHORT_BINUNICODE", "BINUNICODE", "UNICODE", "BINUNICODE8"): + strings.append(arg) + elif op.name in ("STACK_GLOBAL", "GLOBAL"): + if op.name == "GLOBAL": + module, _, name = str(arg).partition(" ") + elif len(strings) >= 2: + module, name = strings[-2], strings[-1] + else: return None - if op.name in ("SHORT_BINUNICODE", "BINUNICODE", "UNICODE", "BINUNICODE8"): - strings.append(arg) - elif op.name in ("STACK_GLOBAL", "GLOBAL"): - if op.name == "GLOBAL": - module, _, name = str(arg).partition(" ") - elif len(strings) >= 2: - module, name = strings[-2], strings[-1] - else: - return None - if (module, name) in _HELPERS: - continue # the class itself comes next - return name if module.startswith(PYCISTOPIC) else None - except Exception: # not a pickle, or a truncated one: not this format + if (module, name) in _HELPERS: + continue # the class itself comes next + return name if module.startswith(PYCISTOPIC) else None + except Exception: # not a pickle, or one cut short within the head: not this format return None return None diff --git a/tests/test_cistopic.py b/tests/test_cistopic.py index f731847..71e7454 100644 --- a/tests/test_cistopic.py +++ b/tests/test_cistopic.py @@ -11,6 +11,8 @@ import pickle import re +import subprocess +import sys from pathlib import Path import numpy as np @@ -18,12 +20,19 @@ from typer.testing import CliRunner from adata.cli import app -from tests.conftest import write_cistopic_pickle, write_imputed_pickle +from tests.conftest import _pycistopic_classes, write_cistopic_pickle, write_imputed_pickle ad = pytest.importorskip("anndata") pd = pytest.importorskip("pandas") sparse = pytest.importorskip("scipy.sparse") +try: # to write pickles as pandas 3 writes them; reading them needs none + import pyarrow # noqa: F401 + + _ARROW_TEXT = int(pd.__version__.split(".")[0]) >= 3 +except ImportError: # pragma: no cover - pyarrow comes with the dev extra + _ARROW_TEXT = False + runner = CliRunner() _ANSI = re.compile(r"\x1b\[[0-9;]*[a-zA-Z]") @@ -384,6 +393,140 @@ def test_repeated_column_labels_keep_the_first_with_a_warning(tmp_path): assert np.array_equal(got.obs["TSS_enrichment"], expected), "the first one is kept" +def _texts(values) -> list: + return [None if pd.isna(v) else str(v) for v in values] + + +@pytest.mark.parametrize("suffix", [".h5ad", ".zarr"]) +def test_labels_a_store_cannot_hold_are_renamed_and_the_output_opens(tmp_path, suffix): + """F175, end to end: a cell_data column "/var" wrote an h5ad anndata + could not open, "/uns/injected" a stray uns["injected"] at the root, + and "a/b" a nested group, all with exit 0. They are renamed with a + warning; anndata, the oracle, opens the output and reads each column's + values under its new name.""" + truth = write_cistopic_pickle(tmp_path / "obj.pkl", model=False, projections=False) + renames = {"TSS_enrichment": "/var", "celltype": "/uns/injected", "note": "a/b"} + with pd.option_context("future.infer_string", False): # as pycisTopic's pandas writes text + truth.obj.cell_data = truth.obj.cell_data.rename(columns=renames) + truth.path.write_bytes(pickle.dumps(truth.obj, protocol=4)) + out = tmp_path / f"out{suffix}" + result = _ok(truth.path, "-o", out) + assert "Renamed in obs: '/var' as '_var', '/uns/injected' as '_uns_injected', 'a/b' as 'a_b'" in _out(result) + got = _read(out) + assert list(got.uns) == ["pycistopic"] + cell_data = truth.obj.cell_data.loc[truth.obj.cell_names] + for label, name in (("/var", "_var"), ("/uns/injected", "_uns_injected"), ("a/b", "a_b")): + assert _texts(got.obs[name]) == _texts(cell_data[label]), label + + +@pytest.mark.parametrize("samples, phrase", [ + ({"s/1": "/data/s1.tsv.gz"}, "names the sample 's/1', which an h5ad or Zarr store cannot hold as a key"), + ({"": "/data/s1.tsv.gz"}, "names the sample '', which an h5ad or Zarr store cannot hold as a key"), + ({1: "/data/a.tsv.gz", "1": "/data/b.tsv.gz"}, "names the sample '1' twice"), +], ids=["slash", "empty", "twice"]) +def test_a_fragments_sample_a_store_cannot_hold_as_a_key_is_refused(tmp_path, samples, phrase): + """F175: path_to_fragments was written with its samples as the keys of + a group, and a sample "s/1" read back as {"s": {"1": ...}}, with exit + 0. Renaming it would break its match with cell_data's sample_id and + the cells' names, which end with it, so it is refused before anything + is written, as anndata, the oracle, refuses such a key itself.""" + with pytest.raises(ValueError, match="slashes"): + ad.AnnData(uns={"path_to_fragments": {"s/1": "/data/s1.tsv.gz"}}).write_h5ad(tmp_path / "oracle.h5ad") + truth = write_cistopic_pickle(tmp_path / "obj.pkl", model=False, projections=False) + truth.obj.path_to_fragments = samples + with pd.option_context("future.infer_string", False): + truth.path.write_bytes(pickle.dumps(truth.obj, protocol=4)) + out = tmp_path / "out.h5ad" + result = _convert(truth.path, "-o", out) + assert result.exit_code == 1 and phrase in _out(result), _out(result) + assert not out.exists() + + +def test_object_integers_past_int64_keep_their_values(tmp_path): + """F176, end to end: a cell_data column of Python integers holding + 2**63 converted with exit 0 and read back as -2**63. It is written as + uint64, as pandas, the oracle, reads it.""" + truth = write_cistopic_pickle(tmp_path / "obj.pkl", model=False, projections=False) + big = pd.Series([2**63 + i for i in range(len(truth.obj.cell_names))], dtype=object, + index=truth.obj.cell_data.index) + truth.obj.cell_data["big"] = big + with pd.option_context("future.infer_string", False): + truth.path.write_bytes(pickle.dumps(truth.obj, protocol=4)) + out = tmp_path / "out.h5ad" + _ok(truth.path, "-o", out) + got = _read(out).obs["big"] + assert got.dtype == pd.to_numeric(big).dtype == np.uint64 + assert [int(v) for v in got] == [int(v) for v in big.loc[truth.obj.cell_names]] + + +def _pandas_3_object(path: Path): + """A CistopicObject pickled as pandas 3 pickles its text by default: + Arrow-backed, in its columns, its index and its categories.""" + classes = _pycistopic_classes() + cells = [f"AAAC{i}-1___s{i % 2}" for i in range(4)] + obj = classes["CistopicObject"]() + obj.fragment_matrix = sparse.csr_matrix(np.arange(12, dtype=np.int32).reshape(3, 4)) + obj.cell_names, obj.region_names = cells, [f"chr1:{i}-{i + 1}" for i in range(3)] + obj.cell_data = pd.DataFrame({ + "celltype": ["B", "T", None, "NK"], + "sample_id": pd.Categorical(["s0", "s1", "s0", "s1"]), + "note": ["é", "", "c", "d"], + "n": [1, 2, 3, 4], + }, index=pd.Index(cells)) + obj.region_data = pd.DataFrame({"Chromosome": ["chr1"] * 3}, index=pd.Index(obj.region_names)) + obj.path_to_fragments = {"s0": "/data/s0.tsv.gz", "s1": "/data/s1.tsv.gz"} + assert type(obj.cell_data["celltype"].array).__name__ == "ArrowStringArray" + path.write_bytes(pickle.dumps(obj, protocol=4)) + return obj + + +@pytest.mark.skipif(not _ARROW_TEXT, reason="needs pandas 3 and pyarrow to write the pickle") +def test_a_pickle_saved_by_pandas_3_converts_with_its_text(tmp_path): + """F179: pandas 3 keeps text in Arrow arrays by default, and a + CistopicObject re-saved under it was refused: the pickle asks for + pyarrow's own rebuilding, outside the allowlist. Its text is decoded + without pyarrow, as the run with pyarrow hidden shows, and obs is what + pandas, the oracle, reads back from the pickle.""" + path = tmp_path / "obj.pkl" + _pandas_3_object(path) + out = tmp_path / "out.h5ad" + _ok(path, "-o", out) + hidden = tmp_path / "hidden.h5ad" + code = "import sys; sys.modules['pyarrow'] = None; from adata.cli import app; app()" + result = subprocess.run([sys.executable, "-c", code, "convert", str(path), "-o", str(hidden)], + capture_output=True, text=True, timeout=120) + assert result.returncode == 0, result.stderr[-2000:] + truth = pd.read_pickle(path).cell_data + for got in (_read(out), _read(hidden)): + assert list(got.obs_names) == list(truth.index) + for column in ("celltype", "sample_id", "note"): + assert _texts(got.obs[column]) == _texts(truth[column]), column + assert got.obs["n"].tolist() == truth["n"].tolist() + assert got.uns["pycistopic"]["path_to_fragments"] == {"s0": "/data/s0.tsv.gz", "s1": "/data/s1.tsv.gz"} + + +def test_names_the_pickle_does_not_hold_are_refused_before_they_are_listed(tmp_path): + """F180, in the converter: cell names given as a `range` of 10**7 and a + fragment matrix of 1 x 10**7 with no entries, in a pickle of a few + hundred bytes, were listed name by name before anything refused them. + A length the pickle names is held to the bytes it holds.""" + from tests.perf_counters import count_allocations + + classes = _pycistopic_classes() + obj = classes["CistopicObject"]() + obj.fragment_matrix = sparse.csr_matrix((1, 10**7), dtype=np.int32) + obj.cell_names, obj.region_names = range(10**7), ["chr1:0-1"] + path = tmp_path / "obj.pkl" + path.write_bytes(pickle.dumps(obj, protocol=4)) + out = tmp_path / "out.h5ad" + _convert(write_cistopic_pickle(tmp_path / "warm.pkl").path, "-o", tmp_path / "warm.h5ad") + with count_allocations() as peak: + result = _convert(path, "-o", out) + assert result.exit_code == 1 and "bytes it holds" in _out(result), _out(result) + assert peak[0] < 16 << 20, f"{peak[0]:,} bytes to refuse a {path.stat().st_size}-byte pickle" + assert not out.exists() + + @pytest.mark.parametrize("protocol", [0, 1]) def test_old_protocols_are_recognised_and_read(tmp_path, protocol): """Protocols 0 and 1 name copy_reg._reconstructor before the object's diff --git a/tests/test_pandas_frame.py b/tests/test_pandas_frame.py index 5a86bc3..38f5bd4 100644 --- a/tests/test_pandas_frame.py +++ b/tests/test_pandas_frame.py @@ -99,3 +99,56 @@ def test_text_with_a_missing_value_in_a_table_is_a_categorical_every_release_rea 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" + + +def test_a_label_a_store_cannot_hold_as_a_name_is_renamed_with_a_warning(new_store): + """F175: a column label was used as the member's name as it stood, and + HDF5 and Zarr read `/` in a name as a path: a label "/uns/injected" + wrote a stray uns["injected"] at the store's root, "a/b" a nested + group, and "/var" an h5ad anndata could not open, all with exit 0. A + label holding `/`, or empty, is renamed with a warning, to a name no + other column has; anndata, the oracle, reads every value back under + the new names, and the store holds nothing else.""" + path, opener = new_store() + warnings = [] + labels = ["a/b", "/uns/injected", "/var", "", "a_b", ".", "_var"] + frame = pd.DataFrame({label: [float(i), i + 0.5] for i, label in enumerate(labels)}, index=["r0", "r1"]) + with opener("a") as root: + write_frame(root["uns"], "table", frame, warnings=warnings, what="t") + got = _read(path) + assert list(got.uns) == ["table"], "nothing written outside the frame" + names = {"a/b": "a_b_1", "/uns/injected": "_uns_injected", "/var": "_var_1", "": "_", "a_b": "a_b", ".": "_.", + "_var": "_var"} + table = got.uns["table"] + assert list(table.columns) == [names[label] for label in labels] + for label in labels: + assert table[names[label]].tolist() == frame[label].tolist(), label + renamed = [w for w in warnings if w.startswith("Renamed in t:")] + assert len(renamed) == 1 and "'a/b' as 'a_b_1'" in renamed[0] and "'' as '_'" in renamed[0], warnings + + +def test_object_integers_keep_their_values_past_int64(new_store): + """F176: an object column of Python integers holding 2**63, which + pandas reads as uint64, was forced to int64 and came back as -2**63, + with exit 0. Integers keep the dtype pandas reads them as (the oracle: + `pd.to_numeric`), int64 or uint64; any that neither holds, or that sit + beside a missing value past what a float holds exactly, are written as + floats with a warning that they are rounded.""" + path, opener = new_store() + warnings = [] + columns = { + "big": [2**63, 1], "past_uint64": [2**64 + 1, 1], "both_signs": [-1, 2**63 + 1], + "gap": [2**53 + 1, None], "small_gap": [3, None], + } + frame = pd.DataFrame({k: pd.Series(v, dtype=object, index=["r0", "r1"]) for k, v in columns.items()}) + with opener("a") as root: + write_frame(root["uns"], "table", frame, warnings=warnings, what="t") + got = _read(path).uns["table"] + assert pd.to_numeric(frame["big"]).dtype == np.uint64 + assert got["big"].dtype == np.uint64 and [int(v) for v in got["big"]] == [2**63, 1] + for column in ("past_uint64", "both_signs", "gap"): + assert got[column].dtype == np.float64 + assert np.array_equal(got[column], pd.to_numeric(frame[column]).to_numpy(dtype=np.float64), equal_nan=True) + assert any(w.startswith(f"t[{column!r}] holds integers no float holds exactly") for w in warnings), column + assert got["small_gap"].tolist()[0] == 3.0 and np.isnan(got["small_gap"].iloc[1]) + assert not any("small_gap" in w for w in warnings), "3 is a float exactly" diff --git a/tests/test_pickled.py b/tests/test_pickled.py index 9ea92ed..76d87f3 100644 --- a/tests/test_pickled.py +++ b/tests/test_pickled.py @@ -9,7 +9,9 @@ some of them crashed the interpreter, which would have taken the test run with it. The child loads the file and then uses what it got, as a conversion would, so a pickle that slipped through shows as a crash or a -wrong answer rather than as nothing. +wrong answer rather than as nothing. Once the child shows a file refused, +it is loaded here too, where the same check refuses it and coverage sees +which one did. """ from __future__ import annotations @@ -19,6 +21,7 @@ import pickle import subprocess import sys +from collections import OrderedDict from pathlib import Path import numpy as np @@ -32,6 +35,11 @@ _reconstruct = np.ndarray.__reduce__(np.zeros(1))[0] +try: # the oracle for Arrow text, where it is installed; the reader never needs it + import pyarrow as pa +except ImportError: # pragma: no cover - pyarrow comes with the dev extra + pa = None + class _Crafted: """Pickles as `func(*args)`, then `state` set on what that returned: @@ -62,6 +70,34 @@ def __reduce_ex__(self, protocol): return copyreg.__newobj__, (self.cls,), self.state +class _Global: + """A global as a crafted pickle names it, by its name alone: pyarrow's + functions are named so whether or not pyarrow is installed.""" + + def __init__(self, module, name): + self.module, self.name = module, name + + def __call__(self, *args): # pragma: no cover - only ever pickled + raise NotImplementedError + + +class _Pickler(pickle._Pickler): + """Python's pickler, writing a `_Global` as the GLOBAL it names.""" + + dispatch = dict(pickle._Pickler.dispatch) + + def _save_by_name(self, obj): + self.write(pickle.GLOBAL + f"{obj.module}\n{obj.name}\n".encode()) + + dispatch[_Global] = _save_by_name + + +def _dumps(obj, protocol: int = 4) -> bytes: + out = io.BytesIO() + _Pickler(out, protocol).dump(obj) + return out.getvalue() + + def _array(dtype, shape, raw): """An ndarray as numpy pickles one, with whatever state is given.""" return _Crafted(_reconstruct, (np.ndarray, (0,), b"b"), (1, shape, dtype, False, raw)) @@ -110,7 +146,7 @@ def _load_isolated(path: Path, watched: Path = None) -> subprocess.CompletedProc def _write(path: Path, obj, protocol: int = 4) -> Path: - path.write_bytes(pickle.dumps(obj, protocol=protocol)) + path.write_bytes(_dumps(obj, protocol=protocol)) return path @@ -120,6 +156,10 @@ def _refused(result: subprocess.CompletedProcess, *phrases: str) -> str: for phrase in phrases: assert phrase in result.stdout, result.stdout assert "OPENED" not in result.stdout, result.stdout + # Refused in the child, so refused here by the same check, before + # anything acts on what the file holds. + with pytest.raises(pickled.RefusedPickle): + pickled.load(result.args[3]) return result.stdout @@ -475,6 +515,561 @@ def test_a_class_is_never_constructed_from_a_pickles_arguments(tmp_path): _refused(_load_isolated(path), "_reconstructor") +# --------------------------------------------------------------------------- +# what the file hands on before it ends + + +def _bad_csc(): + """A CSC matrix of 4 x 1 whose one entry's row is 2**40: converting it + to CSR, scipy counts that entry at the row's place in a 5-entry array.""" + state = {"_shape": (4, 1), "data": np.array([1.0]), "indices": np.array([1 << 40], dtype=np.int64), + "indptr": np.array([0, 1], dtype=np.int64), "maxprint": 50} + return _New(sp.csc_matrix, state) + + +def _bad_categorical(): + """A Categorical of two categories whose second code is 10**8.""" + cat = pd.Categorical(np.array([1.5, 2.5])) + func, args = cat.__reduce__()[:2] + return _Crafted(func, (args[0], args[1], (cat.dtype, np.array([0, 10**8], dtype=np.int64)))) + + +@pytest.mark.parametrize("consumer", [set, frozenset, OrderedDict], ids=["set", "frozenset", "OrderedDict"]) +@pytest.mark.parametrize("payload", ["csc", "categorical"]) +def test_a_crafted_object_is_refused_before_anything_in_the_file_takes_it_apart(tmp_path, consumer, payload): + """F174: sparse matrices and Categoricals were checked only once the + whole file was read, but `set`, `frozenset` and `OrderedDict`, which a + pickle may call, take apart what they are given while it is read: a + CSC matrix with a row of 2**40 crashed the reader (SIGSEGV: scipy + writes at that row's place converting it to CSR), and a Categorical + with a code of 10**8 read past its categories (SIGBUS). Each object is + now checked the moment it is complete, before anything can hold it. + The oracle: scipy's and pandas' own validators call both invalid.""" + if payload == "csc": + with pytest.raises(ValueError): + sp.csc_matrix((np.array([1.0]), np.array([1 << 40]), np.array([0, 1])), shape=(4, 1)).check_format( + full_check=True + ) + bad, phrase = _bad_csc(), "indices out of range" + else: + with pytest.raises(ValueError): + pd.Categorical.from_codes([0, 10**8], categories=[1.5, 2.5]) + bad, phrase = _bad_categorical(), "codes out of range" + _refused(_load_isolated(_write(tmp_path / "evil.pkl", _Crafted(consumer, (bad,)))), phrase) + + +def test_convert_refuses_a_crafted_cistopic_object_with_an_error_line(tmp_path): + """F174, end to end: a CistopicObject that sniffs as one, with the + crafted matrix in a set in its `project`, killed `adata convert` with + SIGSEGV and printed no Error: line.""" + classes = _pycistopic_classes() + obj = classes["CistopicObject"]() + obj.fragment_matrix = sp.csr_matrix(np.ones((1, 1), dtype=np.int32)) + obj.cell_names, obj.region_names = ["c0"], ["r0"] + obj.project = _Crafted(set, (_bad_csc(),)) + path = _write(tmp_path / "evil.pkl", obj) + out = tmp_path / "out.h5ad" + result = subprocess.run( + [sys.executable, "-c", "from adata.cli import app; app()", "convert", str(path), "-o", str(out)], + capture_output=True, text=True, timeout=120, + ) + assert result.returncode == 1, (result.returncode, result.stdout[-2000:], result.stderr[-2000:]) + message = " ".join(result.stderr.split()) + assert "Error: evil.pkl: the pickle holds a scipy csc_matrix's indices out of range" in message, message + assert not out.exists() + + +def _body(obj) -> bytes: + """`obj` as a protocol 2 pickle's opcodes, without PROTO and STOP: a + piece to build a crafted pickle from.""" + return pickle.dumps(obj, protocol=2)[2:-1] + + +@pytest.mark.parametrize("route", [ + "setitem", "setitems", "dict", "additems", "frozenset", "set-call", "ordereddict-call", "index-name", +]) +def test_nothing_but_pythons_own_values_is_hashed_while_the_file_is_read(tmp_path, route): + """F174, by hashing: a dict's keys, a set's items and an index's name + are hashed while the file is read, and hashing one of pandas' dtypes + runs pandas' code on what the file gave it. A CategoricalDtype hashes + its categories by listing them: over a RangeIndex of 10**12 of them, + that ran on past a minute. A key must be a number, text, None, NA, or + a tuple of them.""" + from pandas.core.indexes.base import _new_Index + + key = pd.CategoricalDtype([1.5, 2.5]) + body = _body(key) + raw = { + "setitem": b"}" + body + b"K\x01s", # EMPTY_DICT, key, value, SETITEM + "setitems": b"}(" + body + b"K\x01u", # EMPTY_DICT, MARK, key, value, SETITEMS + "dict": b"(" + body + b"K\x01d", # MARK, key, value, DICT + "additems": b"\x8f(" + body + b"\x90", # EMPTY_SET, MARK, item, ADDITEMS + "frozenset": b"(" + body + b"\x91", # MARK, item, FROZENSET + } + crafted = { + "set-call": _Crafted(set, ([key],)), + "ordereddict-call": _Crafted(OrderedDict, ([[key, 1]],)), + "index-name": _Crafted(_new_Index, (pd.Index, {"data": np.array([1, 2]), "name": key})), + } + path = tmp_path / "key.pkl" + if route in raw: + path.write_bytes(b"\x80\x02" + raw[route] + b".") + else: + _write(path, crafted[route]) + _refused(_load_isolated(path), "CategoricalDtype as") + + +@pytest.mark.parametrize("crafted, phrase", [ + (lambda: _Crafted(set, (sp.csr_matrix(np.eye(2)),)), "where a pickle of one holds a list"), + (lambda: _Crafted(frozenset, (range(10**10),)), "where a pickle of one holds a list"), + (lambda: _Crafted(OrderedDict, ([[1, 2, 3]],)), "not pairs"), + (lambda: _Crafted(slice, (0, 2.5)), "builtins.slice with int, float"), + (lambda: _Crafted(range, (np.float64(4.0),)), "builtins.range with float64"), + (lambda: _Crafted(complex, ("1", 2)), "builtins.complex with str, int"), + (lambda: _Crafted(bytes, (3,)), "calls bytes with int"), +], ids=["set-of-a-matrix", "frozenset-of-a-range", "ordereddict-of-triples", "slice", "range", "complex", "bytes"]) +def test_a_builtin_a_pickle_may_call_is_given_only_what_its_pickle_holds(tmp_path, crafted, phrase): + """F174 and F180: the builtins a pickle may call take apart what they + are given, so each is given only what a pickle of it holds: `set` and + `frozenset` a list (`set(range(10**10))` would list ten billion + numbers), `OrderedDict` a list of pairs, `slice`, `range` and + `complex` numbers, `bytes` text.""" + _refused(_load_isolated(_write(tmp_path / "builtin.pkl", crafted())), phrase) + + +# --------------------------------------------------------------------------- +# what the file names but does not hold + + +def test_a_frame_naming_columns_its_blocks_do_not_hold_is_refused_before_pandas_makes_room(tmp_path): + """F180: a 559-byte pickle of a frame naming a RangeIndex of 2e7 + columns and no blocks had pandas build its map of the 2e7 columns, and + the check list them, before refusing it: 373 MiB, and an OOM kill at + 1e10. The blocks' columns are counted against those named first.""" + from pandas.core.internals.managers import BlockManager + + from tests.perf_counters import count_allocations + + with pd.option_context("future.infer_string", False): + rows = pd.Index([], dtype=object) + crafted = _frame_of(_New(BlockManager, _manager_state(pd.RangeIndex(20_000_000), rows, []))) + path = _write(tmp_path / "tiny.pkl", crafted) + assert path.stat().st_size < 1000 + _refused(_load_isolated(path), "do not hold each of its 20,000,000 columns once") + with count_allocations() as peak: + with pytest.raises(pickled.RefusedPickle): + pickled.load(path) + assert peak[0] < 1 << 20, f"{peak[0]:,} bytes to refuse a {path.stat().st_size}-byte pickle" + + +@pytest.mark.parametrize("route", ["pandas-1.5-state", "constructor"]) +def test_columns_of_no_rows_number_no_more_than_the_bytes_the_pickle_holds(tmp_path, route): + """F180 without any data at all: a block of 10**9 columns of no rows + holds no bytes, so its columns count as many as the frame names, and + pandas would make room for a billion of them. With no rows, the + columns a frame names are held to the bytes of the pickle.""" + from pandas._libs.internals import _unpickle_block + from pandas.core.internals.managers import BlockManager + + n = 10**9 + columns, rows, values = pd.RangeIndex(n), pd.RangeIndex(0), np.empty((n, 0)) + if route == "constructor": + block = _Crafted(_unpickle_block, (values, slice(0, n, 1), 2)) + manager = _Crafted(BlockManager, ((block,), [columns, rows])) + else: + manager = _New(BlockManager, _manager_state(columns, rows, [(values, slice(0, n, 1))])) + _refused(_load_isolated(_write(tmp_path / "wide.pkl", _frame_of(manager))), "1,000,000,000 columns of no rows") + + +@pytest.mark.parametrize("value, phrase", [ + (range(10**10), "a range of 10,000,000,000"), + (pd.RangeIndex(10**12), "an index of 1,000,000,000,000"), + (np.empty((10**9, 0)), "an empty numpy array of shape (1000000000, 0)"), + (sp.csr_matrix((1, 10**10), dtype=np.float32), "a scipy csr_matrix of shape (1, 10000000000)"), + (pd.Categorical.from_codes([0, 1], categories=pd.RangeIndex(10**12)), "an index of 1,000,000,000,000"), +], ids=["range", "RangeIndex", "empty-array", "sparse-shape", "categories"]) +def test_a_length_the_pickle_names_is_held_to_the_bytes_it_holds(tmp_path, value, phrase): + """F180: a length a pickle names costs it no data, and what it names is + listed in full after the read (the cells' names, a Categorical's + categories, an index), so a pickle of a few hundred bytes could ask + for gigabytes. A range, an index, an empty array's or a sparse + matrix's shape is no longer than the bytes the pickle holds.""" + _refused(_load_isolated(_write(tmp_path / "named.pkl", value)), phrase, "more than the") + + +def test_an_array_of_items_of_no_size_is_refused(tmp_path): + """numpy sizes `S` and `U` to one before it makes an array of them, so + it never pickles an array of items of no size; one would name any + number of items in no bytes.""" + dtype = _dtype("S0", (3, "|", None, None, None, 0, 1, 0)) + _refused(_load_isolated(_write(tmp_path / "empty.pkl", _array(dtype, (10**9,), b""))), "no size") + + +# --------------------------------------------------------------------------- +# every check, and what the checks let through + +# The child for many files: one line each, REFUSED and the refusal or +# LOADED, so that one child reads them all; a crash ends it, and the lines +# before say which file did it. +_CHILD_MANY = r""" +import sys +from adata.formats import pickled +for path in sys.argv[1:]: + try: + pickled.load(path) + print("LOADED", flush=True) + except pickled.RefusedPickle as exc: + print("REFUSED", " ".join(str(exc).split()), flush=True) +""" + + +def _check_cases(): + """A pickle for each check, and what its refusal says.""" + import _codecs + import importlib + + from pandas._libs.internals import BlockPlacement, _unpickle_block + from pandas.core.indexes.base import _new_Index + from pandas.core.internals.managers import BlockManager, SingleBlockManager + + frombuffer = importlib.import_module("numpy._core.numeric")._frombuffer + scalar = np.int64(1).__reduce__()[0] + backed, (_, checksum, _) = pd.Categorical([1.5]).__reduce__()[:2] + empty, int64, one = (np.ndarray, (0,), b"b"), np.dtype("= 3 + +_RESTORE = _Global("pyarrow.lib", "_restore_array") + + +def _arrow(alias, length, null_count, offset, buffers, children=(), dictionary=None): + """An Arrow array as pyarrow pickles one: `_restore_array` of its type, + length, null count, offset, buffers, children and dictionary.""" + kind = _Crafted(_Global("pyarrow.lib", "type_for_alias"), (alias,)) + parts = [None if b is None else _Crafted(_Global("pyarrow.lib", "py_buffer"), (b,)) for b in buffers] + return _Crafted(_RESTORE, ((kind, length, null_count, offset, parts, list(children), dictionary),)) + + +def _layout(values, width, skip=0): + """The buffers of an Arrow string array of `values` (None missing), + after `skip` values its offset steps over.""" + values = ["x"] * skip + list(values) + encoded = [b"" if v is None else v.encode() for v in values] + offsets = np.concatenate([[0], np.cumsum([len(e) for e in encoded])]).astype(f"= 0: + with pytest.raises((pa.lib.ArrowException, ValueError, IndexError)): + pa.Array.from_buffers( + pa.large_string(), length, [None if b is None else pa.py_buffer(b) for b in buffers], offset=offset + ).validate(full=True) + + +_EMPTY_TEXT = [None, None, None] + + +@pytest.mark.parametrize("crafted, phrase", [ + (lambda: _Crafted(pd.StringDtype, ("rust", None)), "held in 'rust'"), + (lambda: _Crafted(pd.StringDtype, ("python", 0.0)), "missing values are 0.0"), + (lambda: _New(pd.arrays.ArrowStringArray, {"_pa_array": _arrow("string", 0, 0, 0, _EMPTY_TEXT), + "_dtype": _Crafted(pd.StringDtype, ("pyarrow", np.nan)), + "_cache": {}, "_extra": 1}), "_extra"), + (lambda: _New(pd.arrays.ArrowStringArray, {"_pa_array": _arrow("string", 0, 0, 0, _EMPTY_TEXT), + "_dtype": pd.CategoricalDtype([1.5])}), "the dtype CategoricalDtype"), + (lambda: _Crafted(_Global("pyarrow.lib", "py_buffer"), ("text",)), "Arrow buffer from str"), + (lambda: _Crafted(_RESTORE, ([1, 2],)), "Arrow array from list"), + (lambda: _Crafted(_RESTORE, ((1, 2, 0, 0, [], [], None),)), "Arrow array of builtins.int"), + (lambda: _Crafted(_Global("pyarrow.lib", "chunked_array"), ([],)), "pyarrow.lib.chunked_array"), +], ids=["storage", "na-value", "state", "dtype", "buffer", "array", "type", "unlisted"]) +def test_what_pandas_3_pickles_its_text_with_is_checked_too(tmp_path, crafted, phrase): + """F179: the StringDtype, the ArrowStringArray's state and pyarrow's + pieces take only what pandas and pyarrow pickle them with, and pyarrow + is named for nothing else.""" + _refused(_load_isolated(_bytes(tmp_path / "text.pkl", _dumps(crafted()))), phrase) + + +def test_a_text_array_whose_dtype_is_not_pythons_text_is_refused(tmp_path): + """Text is held in Python strings here whatever storage a pickle names; + a StringArray given any other dtype is refused rather than left at odds + with itself.""" + func, args = pd.array(["a"], dtype=pd.StringDtype("python")).__reduce__()[:2] + crafted = _Crafted(func, (args[0], args[1], (pd.CategoricalDtype([1.5]), np.array(["a"], dtype=object)))) + _refused(_load_isolated(_write(tmp_path / "text.pkl", crafted)), "gives a StringArray the dtype") + + +# --------------------------------------------------------------------------- +# sniffing + + +@pytest.mark.parametrize("gz", [False, True], ids=["plain", "gzipped"]) +def test_sniffing_reads_only_the_head_of_a_file(tmp_path, monkeypatch, gz): + """F177: format detection sniffs every input for a pickle, text tables + too, and pickletools read a table whose header starts "Barcode" as the + opcode BINBYTES with "arco", 1.87 GB, as its length (the oracle below): + 173 MiB of a 1.2 MB gzipped table was inflated only to decide it was + not a pickle. Sniffing reads `SNIFF_BYTES` at most, whatever the file.""" + import gzip + import struct + from contextlib import contextmanager + + from adata.conversion import detect_format + + header = b"Barcode," + b",".join(b"g%d" % i for i in range(200)) + b"\n" + assert struct.unpack(" 1_800_000_000 + data = header + (b"AAACCTGAGAAACCAT-1," + b",".join([b"0"] * 200) + b"\n") * 20_000 + path = tmp_path / ("counts.csv.gz" if gz else "counts.csv") + path.write_bytes(gzip.compress(data, compresslevel=1) if gz else data) + counts = [] + real = pickled.open_pickle + + @contextmanager + def counted(source): + with real(source) as fh: + reader = pickled._Counted(fh) + yield reader + counts.append(reader.count) + + monkeypatch.setattr(pickled, "open_pickle", counted) + assert detect_format(path) == "text" + assert counts and max(counts) <= pickled.SNIFF_BYTES < len(data), counts + + +@pytest.mark.parametrize("head", [ + b"BINBYTES", b"\x80\x04\x95", b"c" + b"x" * 70_000, b"(", b"", b"\x1f\x8b" + b"\0" * 16, + b"\x80\x02" + b"N" * 100 + b".", b"\x80\x04\x93.", +], ids=["text", "cut-short", "global-past-the-head", "no-proto", "empty", "broken-gzip", "no-class-in-64-opcodes", + "global-of-nothing"]) +def test_a_file_that_does_not_open_as_a_pycistopic_pickle_is_not_one(tmp_path, head): + path = tmp_path / "head.pkl" + path.write_bytes(head) + assert not pickled.sniff(path) + + # --------------------------------------------------------------------------- # what pycisTopic writes still reads From 86d17675111e331b74bff8bf5017ebdcd5dea7a1 Mon Sep 17 00:00:00 2001 From: Aljes Date: Fri, 4 Dec 2026 16:50:13 +0000 Subject: [PATCH 2/3] Review fixes: state forms, block checks before pandas builds Each pandas class's state is taken only in the form pandas 1.5 to 3 pickles it in, with its values checked: a frame's name and attrs' keys, which pandas' setters hash, must be Python's own values. pandas 1.5's manager state is checked as a built manager is, shapes and positions included, before pandas builds from it. Arrow text's offsets are counted before room is made for its values. A manager shared by many frames is checked once. Names that list otherwise than they count (a table) are refused. A frame's attrs are copied once, not once per column, and an integer past any float is written as text. Co-Authored-By: Claude Opus 5.5 --- docs/reference/formats/cistopic.md | 29 +-- src/adata/conversion/cistopic.py | 13 +- src/adata/formats/pandas_frame.py | 38 ++-- src/adata/formats/pickled.py | 323 ++++++++++++++++++----------- tests/test_cistopic.py | 30 +++ tests/test_pandas_frame.py | 37 ++++ tests/test_pickled.py | 144 ++++++++++++- 7 files changed, 451 insertions(+), 163 deletions(-) diff --git a/docs/reference/formats/cistopic.md b/docs/reference/formats/cistopic.md index 24e9b69..8031a33 100644 --- a/docs/reference/formats/cistopic.md +++ b/docs/reference/formats/cistopic.md @@ -54,16 +54,19 @@ written: every pickle of them does, never constructed from the file's arguments; - every sparse matrix has its indices within its shape and an `indptr` that rises from 0 to its number of entries, every categorical's codes - lie within its categories, and every table's columns hold as many rows - as its index. Each is checked as soon as it is complete, before - anything else in the file can take it apart; + lie within its categories, and every table's blocks hold as many rows as + its index and each of its columns once. Each is checked as soon as it is + complete, before anything else in the file can take it apart, and is + given its state only in the form pandas or scipy pickles it in; - the few builtins a pickle may call are given only what a pickle of them holds (`set` a list, `range` integers), and nothing is hashed, as a - dict's key or a set's item, but numbers, text and tuples of them; + dict's key, a set's item, or a name, but numbers, text and tuples of + them; - a length the file names rather than holds, such as a `range`, a `RangeIndex`, or the shape of an empty array or a sparse matrix, is no - more than the bytes the file holds, so a small file cannot make the - conversion take gigabytes. + more than the bytes the file holds (inflated, for a gzipped pickle), and + is counted before anything is made for it, so a small file cannot make + the conversion take gigabytes. Dates and times are not read; pycisTopic's objects hold none. @@ -79,12 +82,14 @@ hold exactly), repeated text as categorical. Anything else on the object is named in a warning and left out. A column label is the column's name in the store, and HDF5 and Zarr read a -`/` in a name as a path: a label holding one, or an empty label, is renamed -(`a/b` to `a_b`, `""` to `_`) with a warning, to a name no other column -has. A sample in `path_to_fragments` is a key in the same way, but one -holding `/`, or empty, is refused instead: cell_data's `sample_id` and the -cell names, which end with it, name the sample as it is, and a renamed key -would no longer match them. +`/` in a name as a path, and `""`, `.` and `..` as the group itself or its +parent: such a label is renamed (`a/b` to `a_b`, `""` to `_`) with a +warning, to a name no other column has. A sample in `path_to_fragments` is +a key in the same way, but one like that is refused instead: cell_data's +`sample_id` and the cell names, which end with it, name the sample as it +is, and a renamed key would no longer match them. Names are read from a +list, an array, an index or a Series of them; cell or feature names given +as anything else, such as a table, are refused. ## Memory diff --git a/src/adata/conversion/cistopic.py b/src/adata/conversion/cistopic.py index 88a3fcf..7177a1f 100644 --- a/src/adata/conversion/cistopic.py +++ b/src/adata/conversion/cistopic.py @@ -226,11 +226,16 @@ def _names(values: Any) -> List[str]: def _count(values: Any, what: str, name: str) -> int: """How many names `values` holds, counted without listing them: they - are compared with the matrix before anything is made of them.""" - try: + are compared with the matrix before anything is made of them. Only a + sequence of names lists as many as it counts: a frame's length is its + rows, but listing it gives its columns.""" + import pandas as pd + + if isinstance(values, (list, tuple, range, pd.Index, pd.Series)) or ( + isinstance(values, np.ndarray) and values.ndim == 1 + ): return len(values) - except TypeError: - raise ValueError(f"{name}: its {what} is a {type(values).__name__}, not a list of names.") from None + raise ValueError(f"{name}: its {what} is a {type(values).__name__}, not a list of names.") def _check_samples(fragments: Any, name: str) -> None: diff --git a/src/adata/formats/pandas_frame.py b/src/adata/formats/pandas_frame.py index dca68af..9228eef 100644 --- a/src/adata/formats/pandas_frame.py +++ b/src/adata/formats/pandas_frame.py @@ -22,8 +22,9 @@ A column is written under its label, but for one that HDF5 and Zarr cannot hold as a name: holding `/`, which they read as a path (`/var` would land at -the store's root), or empty. Such a label is renamed, `/` to `_`, with a -warning, as `convert` renames a loom's fields. +the store's root), or `""`, `.` or `..`, which name the group itself or its +parent. Such a label is renamed (`/` to `_`, `""` to `_`) with a warning, +as `convert` renames a loom's fields. """ from __future__ import annotations @@ -61,6 +62,11 @@ def write_frame( names the frame in warnings (`obs`, `uns/pycistopic/metrics`). """ warnings = warnings if warnings is not None else [] + if df.attrs: + # pandas deep-copies a frame's attrs into each column taken from it, + # which would cost attrs once per column; nothing here reads them. + df = df.copy(deep=False) + df.attrs = {} labels = [str(v) for v in (df.index if index is None else index)] group = write_dataframe_header(parent, name, labels, []) written = [] @@ -98,7 +104,7 @@ def _column_keys(labels: List[str], warnings: List[str], what: str) -> List[Opti if renamed: warnings.append( f"Renamed in {what}: {', '.join(renamed)} -- HDF5 and Zarr read '/' in a name " - "as a path, and hold no empty name." + "as a path, and '', '.' and '..' as the group itself or its parent." ) return keys @@ -137,21 +143,27 @@ def write_column( return True if dtype.kind in "OSU" or isinstance(dtype, pd.StringDtype): inferred = pd.api.types.infer_dtype(column, skipna=True) + told = False if inferred in ("integer", "floating", "mixed-integer-float", "decimal"): - values = pd.to_numeric(column, errors="coerce") - if inferred == "integer" and values.dtype.kind in "iu": - # int64, or uint64 for integers past it: as pandas reads them. - write_dense(parent, name, values.to_numpy()) + try: + values = pd.to_numeric(column, errors="coerce") + except (OverflowError, ValueError): # an integer past what any float holds + warnings.append(f"{what} holds integers past what a float holds; written as text.") + told = True + else: + if inferred == "integer" and values.dtype.kind in "iu": + # int64, or uint64 for integers past it: as pandas reads them. + write_dense(parent, name, values.to_numpy()) + return True + floats = values.to_numpy(dtype=np.float64) + if inferred in ("integer", "mixed-integer-float") and _rounded(column, floats): + warnings.append(f"{what} holds integers no float holds exactly; written as floats, rounded.") + write_dense(parent, name, floats) return True - floats = values.to_numpy(dtype=np.float64) - if inferred in ("integer", "mixed-integer-float") and _rounded(column, floats): - warnings.append(f"{what} holds integers no float holds exactly; written as floats, rounded.") - write_dense(parent, name, floats) - return True if inferred == "boolean" and not column.isna().any(): write_dense(parent, name, column.to_numpy(dtype=bool)) return True - if categorize and inferred not in ("string", "empty", "unicode", "bytes"): + if categorize and not told and inferred not in ("string", "empty", "unicode", "bytes"): # In obs and var a column of mixed values is worth a word; in a # table of parameters ("lda", 15, True) it is what is expected. warnings.append(f"{what} holds {inferred} values; written as text.") diff --git a/src/adata/formats/pickled.py b/src/adata/formats/pickled.py index bf1fe43..f3a5f9b 100644 --- a/src/adata/formats/pickled.py +++ b/src/adata/formats/pickled.py @@ -25,18 +25,24 @@ blocks fill its rows and hold each column once. scipy's and pandas' compiled code indexes with all of these unchecked, and a pickle can hand an object to something that iterates or hashes it before the file ends; +* each class's state takes only the form pandas (1.5 to 3) or scipy + pickles it in, its values of the kinds they hold there, checked before + pandas builds from it: a frame's name and attrs, which pandas' setters + hash, a manager's blocks, against its axes, before pandas makes room for + each column and writes at each one a block names; * the builtins that take what they are given apart are given only what a pickle of them holds: `set` and `frozenset` a list, `OrderedDict` a list of pairs, `slice`, `range` and `complex` numbers; and nothing is hashed - (a dict's keys, a set's items, an index's name) but Python's and numpy's - own values, so no pandas code runs to hash one; + (a dict's keys, a set's items, a name) but Python's and numpy's own + values, so no pandas code runs to hash one; * containers are filled only through `dict`, `list` and `set`, never by writing into an array that has been checked; * a length the file names rather than holds (a `range`, a `RangeIndex`, an empty array's or a sparse matrix's shape) is at most the bytes the file - holds, and a frame's columns are counted before pandas makes room for - them, so a pickle of a few hundred bytes cannot make the reader, or the - conversion after it, allocate gigabytes. + holds (inflated, if gzipped), and anything made for a length (pandas' + map of a frame's columns, Arrow text's values) is made only once it is + counted against what holds it, so a pickle of a few hundred bytes cannot + make the reader, or the conversion after it, allocate gigabytes. That keeps a crafted file from corrupting memory or reading files through what it names, but it is still parsed by numpy, scipy and pandas: a pickle @@ -428,59 +434,52 @@ def _is_frame_or_series(value: Any) -> bool: return isinstance(value, (pd.DataFrame, pd.Series)) -def _placement_length(locs: Any) -> int: - """How many columns a block's placement names: a slice (of integers, as - a pickle can build one) or an array of integers, counted from the - slice's bounds or the array held, so never by listing what a slice +def _placement(locs: Any) -> Any: + """A block's placement as pandas holds it: from a slice (of integers, as + a pickle can build one) or an array of integers. Its length comes from + the slice's bounds or the array held, never by listing what a slice names.""" from pandas._libs.internals import BlockPlacement if isinstance(locs, BlockPlacement): - return len(locs) + return locs if type(locs) is not slice and not (type(locs) is np.ndarray and locs.ndim == 1 and locs.dtype.kind in "iu"): raise _refuse(f"places a block at {type(locs).__name__}") try: - return len(BlockPlacement(locs)) + return BlockPlacement(locs) except (TypeError, ValueError, OverflowError) as exc: raise _refuse(f"places a block at {locs!r} ({exc})") from None -def _check_manager(manager: Any, what: str, held: int) -> None: - """A DataFrame's or Series' blocks fill its axes: each block as many - rows as the index, and between them every column once. pandas checks - neither when it unpickles a frame, and indexes the blocks by the axes. +def _check_blocks(blocks: Any, axes: Any, single: bool, what: str, held: int) -> None: + """A frame's or Series' blocks, (values, placement) pairs, against its + axes: each block as many rows as the index and as many columns as it + is placed at, and between them every column once. pandas checks none + of it when it unpickles a frame, and indexes the blocks by the axes. - The columns are counted before they are listed: blocks hold as many - columns as their data, except when there are no rows, and then the - columns a frame names may number no more than the `held` bytes.""" + The columns are listed only once they are counted: blocks hold as many + columns as their data, but for a frame of no rows, whose columns may + number no more than the `held` bytes.""" import pandas as pd from pandas.api.extensions import ExtensionArray - from pandas.core.internals.managers import SingleBlockManager - axes, blocks = getattr(manager, "axes", None), getattr(manager, "blocks", None) - if type(axes) is not list or not all(isinstance(axis, pd.Index) for axis in axes) or type(blocks) is not tuple: - raise _refuse(f"gives {what} a manager without its axes and blocks") - single = isinstance(manager, SingleBlockManager) + if type(axes) is not list or not all(isinstance(axis, pd.Index) for axis in axes): + raise _refuse(f"gives {what} axes that are not indexes") if len(axes) != (1 if single else 2) or (single and len(blocks) != 1): raise _refuse(f"gives {what} {len(axes)} axes and {len(blocks)} blocks") n_rows = len(axes[-1]) placed = 0 - for block in blocks: - values = getattr(block, "values", None) + for values, locs in blocks: if not (type(values) is np.ndarray or isinstance(values, ExtensionArray)): raise _refuse(f"gives {what} a block of {type(values).__name__}") + n_locs = len(locs) if single: - if block.ndim != 1 or values.shape != (n_rows,): + if values.shape != (n_rows,): raise _refuse(f"gives {what} {values.shape} values for {n_rows:,} rows") continue - n_locs = _placement_length(block.mgr_locs) - fits = values.shape == (n_locs, n_rows) or ( - values.ndim == 1 and n_locs == 1 and values.shape[0] == n_rows - ) - if block.ndim != 2 or not fits: + if not (values.shape == (n_locs, n_rows) or (values.ndim == 1 and n_locs == 1 and values.shape[0] == n_rows)): raise _refuse( - f"gives {what} a block of shape {values.shape} for {n_locs:,} columns " - f"of {n_rows:,} rows" + f"gives {what} a block of shape {values.shape} for {n_locs:,} columns of {n_rows:,} rows" ) placed += n_locs if single: @@ -491,30 +490,65 @@ def _check_manager(manager: Any, what: str, held: int) -> None: if not n_rows and n_columns > held: raise _refuse(f"gives {what} {n_columns:,} columns of no rows, more than the {held:,} bytes it holds") columns = ( - np.sort(np.concatenate([np.asarray(block.mgr_locs.as_array, dtype=np.int64) for block in blocks])) + np.sort(np.concatenate([np.asarray(locs.as_array, dtype=np.int64) for _, locs in blocks])) if blocks else np.zeros(0, dtype=np.int64) ) if not np.array_equal(columns, np.arange(n_columns)): raise _refuse(f"gives {what} blocks that do not hold each of its {n_columns:,} columns once") +def _check_manager(manager: Any, what: str, held: int) -> None: + """A built manager: its blocks of its own number of dimensions, and + filling its axes (`_check_blocks`).""" + from pandas.core.internals.blocks import Block + from pandas.core.internals.managers import SingleBlockManager + + axes, blocks = getattr(manager, "axes", None), getattr(manager, "blocks", None) + single = isinstance(manager, SingleBlockManager) + if type(blocks) is not tuple or not all(isinstance(b, Block) and b.ndim == (1 if single else 2) for b in blocks): + raise _refuse(f"gives {what} a manager without its blocks") + _check_blocks([(block.values, block.mgr_locs) for block in blocks], axes, single, what, held) + + +def _state_dict(name: str, state: Any, keys: Iterable[str], required: Iterable[str] = ()) -> Dict[str, Any]: + """A state that is a dict of `keys` (`required` among them), as pandas + pickles the class, without its `_cache`: what pandas worked out from + the rest once the object was used (a dtype's numpy dtype), pickled with + it, and dropped here for pandas to work out again from what is checked. + A view's `_readonly` flag (pandas 3) must be a flag.""" + what = f"a {name}" + if type(state) is not dict: + raise _refuse(f"gives {what} the state {type(state).__name__}") + unknown = sorted(map(str, set(state) - set(keys) - {"_cache"})) + if unknown: + raise _refuse(f"gives {what} {', '.join(unknown)}") + missing = sorted(set(required) - set(state)) + if missing: + raise _refuse(f"gives {what} no {', '.join(missing)}") + if not isinstance(state.get("_readonly", False), (bool, np.bool_)): + raise _refuse(f"gives {what} a _readonly of {type(state['_readonly']).__name__}") + return {k: v for k, v in state.items() if k != "_cache"} + + +def _backed_state(name: str, state: Any) -> tuple: + """A Categorical's or a StringArray's state as pandas pickles it: its + dtype and values, and before pandas 3 a dict of its attributes, which + pandas sets on it as they stand: empty, or a view's read-only flag.""" + if type(state) is not tuple or len(state) not in (2, 3): + raise _refuse(f"gives a {name} the state {type(state).__name__}") + if len(state) == 2: + return state + return state[0], state[1], _state_dict(name, state[2], {"_readonly"}) + + def _check_pandas(value: Any, held: int) -> None: - """pandas objects whose integer codes and blocks its compiled code - indexes with unchecked: within what they index. `held` is the bytes - the pickle has given so far.""" + """pandas objects whose integer codes its compiled code indexes with + unchecked: within what they index. Frames and their managers are + checked by the unpickler, once each.""" import pandas as pd from pandas.core.arrays.masked import BaseMaskedArray - from pandas.core.internals.managers import BlockManager, SingleBlockManager - - if _is_frame_or_series(value): - manager = vars(value).get("_mgr") - kind = SingleBlockManager if isinstance(value, pd.Series) else BlockManager - if type(manager) is not kind: - raise _refuse(f"gives a {type(value).__name__} a {type(manager).__name__} for its data") - _check_manager(manager, f"a {type(value).__name__}", held) - elif type(value) in (BlockManager, SingleBlockManager): - _check_manager(value, f"a {type(value).__name__}", held) - elif isinstance(value, pd.Categorical): + + if isinstance(value, pd.Categorical): what = "a Categorical" codes, dtype = value._ndarray, value._dtype categories = getattr(dtype, "_categories", None) if isinstance(dtype, pd.CategoricalDtype) else None @@ -542,12 +576,21 @@ def _check_pandas(value: Any, held: int) -> None: if (type(data) is not np.ndarray or type(mask) is not np.ndarray or mask.dtype != np.bool_ or data.shape != mask.shape): raise _refuse(f"gives a {type(value).__name__} a mask that does not match its values") + if getattr(value.dtype, "numpy_dtype", None) != data.dtype: + raise _refuse(f"gives a {type(value).__name__} {data.dtype} values for its dtype {value.dtype}") elif isinstance(value, pd.arrays.StringArray): values = value._ndarray if type(values) is not np.ndarray or values.ndim != 1 or values.dtype != object: raise _refuse("gives a StringArray values that are not text") - if not isinstance(value._dtype, pd.StringDtype) or getattr(value._dtype, "storage", None) != "python": - raise _refuse(f"gives a StringArray the dtype {value._dtype!r}") + if not isinstance(value._dtype, pd.StringDtype): + raise _refuse(f"gives a StringArray the dtype {type(value._dtype).__name__}") + if isinstance(value, pd.StringDtype) or isinstance(getattr(value, "_dtype", None), pd.StringDtype): + dtype = value if isinstance(value, pd.StringDtype) else value._dtype + missing = getattr(dtype, "na_value", None) + if getattr(dtype, "storage", None) != "python" or not ( + missing is pd.NA or (isinstance(missing, float) and np.isnan(missing)) + ): + raise _refuse("gives a StringDtype other than Python text missing values as NA or NaN") class _Counted: @@ -593,6 +636,8 @@ def __init__(self, file: BinaryIO) -> None: #: The longest length the pickle names without holding the data #: for it, and what names it. self._named: Tuple[int, str] = (0, "") + #: Managers checked, by identity: frames that share one check it once. + self._managers: Dict[int, Any] = {} def load(self) -> Any: value = super().load() @@ -685,12 +730,27 @@ def _created(self, obj: Any, *, fresh: bool = True, built: bool = False) -> Any: def _check(self, obj: Any) -> None: """A scipy or pandas object, complete: checked before anything can - hold it.""" + hold it. A frame's manager is checked once, however many frames + share it.""" if type(obj).__module__.startswith("scipy"): check_sparse(obj) self._names_length(max(obj._shape), f"a scipy {type(obj).__name__} of shape {obj._shape}") - else: - _check_pandas(obj, self._source.count) + return + import pandas as pd + from pandas.core.internals.managers import BlockManager, SingleBlockManager + + manager = obj + if _is_frame_or_series(obj): + manager = vars(obj).get("_mgr") + kind = SingleBlockManager if isinstance(obj, pd.Series) else BlockManager + if type(manager) is not kind: + raise _refuse(f"gives a {type(obj).__name__} a {type(manager).__name__} for its data") + if type(manager) in (BlockManager, SingleBlockManager): + if self._managers.get(id(manager)) is not manager: + _check_manager(manager, f"a {type(obj).__name__}", self._source.count) + self._managers[id(manager)] = manager + return + _check_pandas(obj, self._source.count) def _held(self, items: Iterable[Any], by: str) -> None: """Refuse an object handed on before it has its state: what it is @@ -783,7 +843,7 @@ def _manager_arguments(self, func: type, args: tuple) -> None: what = f"a {func.__name__}" if func is BlockPlacement: - _placement_length(args[0]) + _placement(args[0]) elif func is SingleBlockManager: if len(args) != 2 or not isinstance(args[0], Block) or not isinstance(args[1], pd.Index): raise _refuse(f"builds {what} from {', '.join(type(a).__name__ for a in args)}") @@ -793,7 +853,7 @@ def _manager_arguments(self, func: type, args: tuple) -> None: or type(axes) is not list or len(axes) != 2 or not all(isinstance(a, pd.Index) for a in axes)): raise _refuse(f"builds {what} from something other than blocks and two indexes") - if sum(_placement_length(block.mgr_locs) for block in blocks) != len(axes[0]): + if sum(len(_placement(block.mgr_locs)) for block in blocks) != len(axes[0]): raise _refuse(f"gives {what} blocks that do not hold each of its {len(axes[0]):,} columns once") def _block_arguments(self, args: tuple) -> None: @@ -808,7 +868,7 @@ def _block_arguments(self, args: tuple) -> None: _is_integer(ndim) and ndim in (1, 2) ): raise _refuse(f"builds a pandas block from {described}") - _placement_length(locs) + _placement(locs) def load_reduce(self) -> None: stack = self.stack @@ -876,84 +936,99 @@ def load_build(self) -> None: dispatch[pickle.BUILD[0]] = load_build def _build_pandas(self, inst: Any, state: Any) -> None: - """A pandas object's state: what pandas pickles it with, checked - before pandas builds from it where pandas would act on it, and the - object checked once built.""" + """A pandas object's state, in the form pandas pickles its class + with (pandas 1.5 to 3), checked before pandas builds from it, and the + object checked once built. No other pandas object is given a state + by a pickle: an index is rebuilt from `_new_Index`'s keys, a block by + `_unpickle_block`.""" import pandas as pd - from pandas.api.extensions import ExtensionDtype + from pandas.core.arrays.masked import BaseMaskedArray + from pandas.core.dtypes.dtypes import BaseMaskedDtype from pandas.core.internals.managers import BlockManager, SingleBlockManager - if isinstance(inst, pd.Index): - # An index is rebuilt from `_new_Index`'s keys alone: a pickle - # never gives one a state. - raise _refuse(f"sets the state of a pandas {type(inst).__name__}") if _is_frame_or_series(inst): - if type(state) is dict: - unknown = sorted(map(str, set(state) - _FRAME_STATE)) - if unknown: - raise _refuse(f"gives a {type(inst).__name__} {', '.join(unknown)}") - elif type(state) is dict and "_cache" in state: - # What pandas worked out from the rest (an array's dtype, a - # dtype's numpy dtype), pickled with it once used: dropped, for - # pandas to work out again from what is checked. - state = {k: v for k, v in state.items() if k != "_cache"} - if type(inst) in (BlockManager, SingleBlockManager): + self._check_frame_state(inst, state) + inst.__setstate__(state) + elif type(inst) in (BlockManager, SingleBlockManager): self._check_manager_state(inst, state) - elif isinstance(inst, ExtensionDtype) and not isinstance(inst, (pd.CategoricalDtype, pd.StringDtype)): - # `Int64Dtype` and the like are complete when created; a pickle - # gives one at most its cache. - if state: - raise _refuse(f"gives a pandas {type(inst).__name__} the state {state!r}") - self._check(inst) - return - elif isinstance(inst, pd.StringDtype) and type(state) is dict: - # pandas before 2.3 pickled a StringDtype as its storage; text is - # held in Python strings here, Arrow's too. - if state.get("storage") == "pyarrow_numpy": - state = {**state, "storage": "python", "_na_value": np.nan} - elif state.get("storage") == "pyarrow": - state = {**state, "storage": "python"} - if isinstance(inst, pd.arrays.StringArray) and type(state) is dict and isinstance( + inst.__setstate__(state) + elif isinstance(inst, pd.arrays.StringArray) and type(state) is dict and isinstance( state.get("_pa_array", state.get("_data")), _ArrowText ): inst.__setstate__(self._from_arrow(state)) + elif isinstance(inst, (pd.Categorical, pd.arrays.StringArray)): + inst.__setstate__(_backed_state(type(inst).__name__, state)) + elif isinstance(inst, BaseMaskedArray): + state = _state_dict(type(inst).__name__, state, {"_data", "_mask", "_dtype", "_readonly"}, + required={"_data", "_mask"}) + if "_dtype" in state and not isinstance(state["_dtype"], BaseMaskedDtype): + raise _refuse(f"gives a {type(inst).__name__} the dtype {type(state['_dtype']).__name__}") + inst.__dict__.update(state) + elif isinstance(inst, pd.CategoricalDtype): + inst.__setstate__(_state_dict(type(inst).__name__, state, {"categories", "ordered"})) + elif isinstance(inst, pd.StringDtype): + # Before pandas 2.3, a StringDtype was pickled as its storage. + # Text is held in Python strings here, Arrow's too. + state = _state_dict(type(inst).__name__, state, {"storage", "_na_value"}) + if state.get("storage") == "pyarrow_numpy": + state.update(storage="python", _na_value=np.nan) + elif state.get("storage") == "pyarrow": + state["storage"] = "python" + setstate = getattr(inst, "__setstate__", None) + if setstate is not None: + setstate(state) + else: # pragma: no cover - pandas before 2.3, as the floors job has it + inst.__dict__.update(state) + elif isinstance(inst, BaseMaskedDtype): + _state_dict(type(inst).__name__, state, set()) # complete when created: at most its cache else: - self.stack.append(state) - super().load_build() + raise _refuse(f"sets the state of a pandas {type(inst).__name__}") self._check(inst) + def _check_frame_state(self, frame: Any, state: Any) -> None: + """A DataFrame's or Series' state as pandas pickles it: a dict of + `_FRAME_STATE`'s keys, each holding what pandas puts there. pandas + sets a name and attrs through the class's own setters, which hash + the name and attrs' keys: both must be Python's own values.""" + what = f"a {type(frame).__name__}" + if type(state) is not dict: + raise _refuse(f"gives {what} the state {type(state).__name__}") + unknown = sorted(map(str, set(state) - _FRAME_STATE)) + if unknown: + raise _refuse(f"gives {what} {', '.join(unknown)}") + for key, value in state.items(): + if key in ("name", "_name"): + fits = _is_plain_key(value) + elif key in ("attrs", "_attrs"): + fits = value is None or (type(value) is dict and all(_is_plain_key(k) for k in value)) + elif key == "_flags": + fits = type(value) is dict and set(value) <= {"allows_duplicate_labels"} and all( + isinstance(v, (bool, np.bool_)) for v in value.values() + ) + elif key == "_metadata": + fits = type(value) is list and all(v in ("name", "_name") for v in value) + elif key == "_typ": + fits = type(value) is str + else: # its manager, checked once the frame is built + fits = True + if not fits: + raise _refuse(f"gives {what} {key} of {type(value).__name__}") + def _check_manager_state(self, manager: Any, state: Any) -> None: - """A manager's state as pandas 1.5 pickles it, before pandas builds - the manager from it, which makes room for each column it names: as - many columns placed as named, and, with no rows to hold them, no more - than the bytes the pickle holds.""" - import pandas as pd - from pandas.api.extensions import ExtensionArray + """A manager's state as pandas 1.5 pickles it, checked as a built + manager is, but before pandas builds the manager from it: pandas + makes room for each column it names, and writes at each column its + blocks are placed at.""" from pandas.core.internals.managers import SingleBlockManager what = f"a {type(manager).__name__}" legacy = state[3].get("0.14.1") if type(state) is tuple and len(state) >= 4 and type(state[3]) is dict else None axes = legacy.get("axes") if type(legacy) is dict else None blocks = legacy.get("blocks") if type(legacy) is dict else None - n_axes = 1 if isinstance(manager, SingleBlockManager) else 2 - if (type(axes) is not list or len(axes) != n_axes or not all(isinstance(a, pd.Index) for a in axes) - or type(blocks) is not list): + if type(blocks) is not list or not all(type(block) is dict for block in blocks): raise _refuse(f"gives {what} a state without its axes and blocks") - placed = 0 - for block in blocks: - values = block.get("values") if type(block) is dict else None - if not (type(values) is np.ndarray or isinstance(values, ExtensionArray)): - raise _refuse(f"gives {what} a block of {type(values).__name__}") - placed += _placement_length(block.get("mgr_locs")) - if n_axes == 2: - n_columns = len(axes[0]) - if placed != n_columns: - raise _refuse(f"gives {what} blocks that do not hold each of its {n_columns:,} columns once") - if not len(axes[1]) and n_columns > self._source.count: - raise _refuse( - f"gives {what} {n_columns:,} columns of no rows, more than the " - f"{self._source.count:,} bytes it holds" - ) + pairs = [(block.get("values"), _placement(block.get("mgr_locs"))) for block in blocks] + _check_blocks(pairs, axes, isinstance(manager, SingleBlockManager), what, self._source.count) # -- containers: only dict, list and set are filled -------------------- @@ -1160,6 +1235,8 @@ def _ndarray_backed(self, cls: Any, checksum: Any, state: Any = None) -> Any: if cls not in (pd.Categorical, pd.arrays.StringArray): raise _refuse(f"builds {cls!r} through pandas' __pyx_unpickle_NDArrayBacked") + if state is not None: + state = _backed_state(cls.__name__, state) built = _ndarray_backed()(cls, checksum, state) return self._created(built, fresh=state is None, built=state is not None) @@ -1201,9 +1278,10 @@ def _arrow_buffer(self, data: Any) -> bytes: def _arrow_array(self, data: Any) -> _ArrowText: """pyarrow's `_restore_array`, for an Arrow string array: decoded to - Python strings, every offset first checked to rise within the text - it indexes, the validity bitmap to cover the values, and the text - to be UTF-8.""" + Python strings. Its length is held to the offsets it has before + anything is made for its values, every offset is checked to rise + within the text it indexes, the validity bitmap to cover the values, + and the text to be UTF-8.""" if type(data) is not tuple or len(data) != 7: raise _refuse(f"rebuilds an Arrow array from {type(data).__name__}") kind, length, null_count, offset, buffers, children, dictionary = data @@ -1215,23 +1293,22 @@ def _arrow_array(self, data: Any) -> _ArrowText: or not all(b is None or type(b) is bytes for b in buffers)): raise _refuse("rebuilds an Arrow string array from parts a string array never has") validity, offsets, text = buffers - length, offset = int(length), int(offset) - values = np.full(length, None, dtype=object) - missing = np.zeros(length, dtype=bool) + length, offset, width = int(length), int(offset), kind.width if not length: - return _ArrowText(values, missing) - width = kind.width + return _ArrowText(np.empty(0, dtype=object), np.zeros(0, dtype=bool)) if offsets is None or len(offsets) // width < offset + length + 1: raise _refuse(f"gives an Arrow string array of {length:,} values too few offsets") bounds = np.frombuffer(offsets, dtype=f" len(text) or (np.diff(bounds) < 0).any(): raise _refuse(f"gives an Arrow string array offsets outside its {len(text):,} bytes of text") + missing = np.zeros(length, dtype=bool) if validity is not None: if len(validity) * 8 < offset + length: raise _refuse("gives an Arrow string array a validity bitmap shorter than its values") bits = np.unpackbits(np.frombuffer(validity, dtype=np.uint8), count=offset + length, bitorder="little") missing = ~bits[offset:].astype(bool) + values = np.full(length, None, dtype=object) starts, ends = bounds[:-1].tolist(), bounds[1:].tolist() try: for i in np.flatnonzero(~missing).tolist(): diff --git a/tests/test_cistopic.py b/tests/test_cistopic.py index 71e7454..ba19c70 100644 --- a/tests/test_cistopic.py +++ b/tests/test_cistopic.py @@ -505,6 +505,36 @@ def test_a_pickle_saved_by_pandas_3_converts_with_its_text(tmp_path): assert got.uns["pycistopic"]["path_to_fragments"] == {"s0": "/data/s0.tsv.gz", "s1": "/data/s1.tsv.gz"} +@pytest.mark.parametrize("kind", ["object", "imputed"]) +@pytest.mark.parametrize("names", ["frame", "two-d"]) +def test_names_that_list_otherwise_than_they_count_are_refused(tmp_path, kind, names): + """Found in review: names were counted with `len` and listed with + `list`, which differ for a frame (its rows, its column labels): a 3 x 4 + fragment matrix with a 4 x 2 frame for its cell names converted, with + exit 0, to an X anndata read as 2 x 3, two cells dropped. Names must be + a list, a 1-d array, an index or a Series of them.""" + classes = _pycistopic_classes() + with pd.option_context("future.infer_string", False): + given = (pd.DataFrame(np.zeros((4, 2)), columns=["x", "y"]) if names == "frame" + else np.array([[f"c{i}"] for i in range(4)], dtype=object)) + if kind == "object": + obj = classes["CistopicObject"]() + obj.fragment_matrix = sparse.csc_matrix(np.arange(1, 13, dtype=np.int32).reshape(3, 4)) + obj.region_names = ["r0", "r1", "r2"] + else: + obj = classes["CistopicImputedFeatures"]() + obj.mtx = np.ones((3, 4), dtype=np.float32) + obj.feature_names = ["g0", "g1", "g2"] + obj.cell_names = given + path = tmp_path / "obj.pkl" + path.write_bytes(pickle.dumps(obj, protocol=4)) + out = tmp_path / "out.h5ad" + result = _convert(path, "-o", out) + assert result.exit_code == 1, _out(result) + assert f"its cell_names is a {type(given).__name__}, not a list of names" in _out(result) + assert not out.exists() + + def test_names_the_pickle_does_not_hold_are_refused_before_they_are_listed(tmp_path): """F180, in the converter: cell names given as a `range` of 10**7 and a fragment matrix of 1 x 10**7 with no entries, in a pickle of a few diff --git a/tests/test_pandas_frame.py b/tests/test_pandas_frame.py index 38f5bd4..9a9cba5 100644 --- a/tests/test_pandas_frame.py +++ b/tests/test_pandas_frame.py @@ -152,3 +152,40 @@ def test_object_integers_keep_their_values_past_int64(new_store): assert any(w.startswith(f"t[{column!r}] holds integers no float holds exactly") for w in warnings), column assert got["small_gap"].tolist()[0] == 3.0 and np.isnan(got["small_gap"].iloc[1]) assert not any("small_gap" in w for w in warnings), "3 is a float exactly" + + +def test_object_integers_past_any_float_are_written_as_text(new_store): + """Found in review: an object column holding 10**400, past what any + float holds, made `pd.to_numeric` raise mid-write and the conversion + fail. It is written as text, with a warning; the text is Python's own + (the oracle: `str`).""" + path, opener = new_store() + warnings = [] + frame = pd.DataFrame({"huge": pd.Series([10**400, 1], dtype=object, index=["r0", "r1"])}) + with opener("a") as root: + write_frame(root["uns"], "table", frame, warnings=warnings, what="t") + assert _read(path).uns["table"]["huge"].tolist() == [str(10**400), "1"] + assert any(w.startswith("t['huge'] holds integers past what a float holds") for w in warnings), warnings + + +def test_a_frames_attrs_are_copied_at_most_once_however_many_columns(new_store): + """Found in review: pandas deep-copies a frame's attrs into each column + taken from it, so writing a frame cost its attrs once per column, 12.6 + s for a frame of 200 columns with large attrs. They are copied at most + once; anndata, the oracle, reads every column back.""" + copies = [] + + class Counted: + def __deepcopy__(self, memo): + copies.append(1) + return self + + path, opener = new_store() + frame = pd.DataFrame({f"c{i}": [float(i), i + 0.5] for i in range(30)}, index=["r0", "r1"]) + frame.attrs["note"] = Counted() + with opener("a") as root: + write_frame(root["uns"], "table", frame) + assert len(copies) <= 1, len(copies) + got = _read(path).uns["table"] + assert all(got[c].tolist() == frame[c].tolist() for c in frame.columns) + assert frame.attrs["note"].__class__ is Counted, "the frame given is left as it was" diff --git a/tests/test_pickled.py b/tests/test_pickled.py index 76d87f3..a83bbe9 100644 --- a/tests/test_pickled.py +++ b/tests/test_pickled.py @@ -642,10 +642,11 @@ def test_a_builtin_a_pickle_may_call_is_given_only_what_its_pickle_holds(tmp_pat def test_a_frame_naming_columns_its_blocks_do_not_hold_is_refused_before_pandas_makes_room(tmp_path): - """F180: a 559-byte pickle of a frame naming a RangeIndex of 2e7 - columns and no blocks had pandas build its map of the 2e7 columns, and - the check list them, before refusing it: 373 MiB, and an OOM kill at - 1e10. The blocks' columns are counted against those named first.""" + """F180: a pickle of a few hundred bytes, a frame naming a RangeIndex + of 2e7 columns and no blocks, had pandas build its map of the 2e7 + columns, and the check list them, before it was refused: hundreds of + MiB, and at 1e10 columns a kill for memory rather than a refusal. The + blocks' columns are counted against those named first.""" from pandas.core.internals.managers import BlockManager from tests.perf_counters import count_allocations @@ -697,6 +698,93 @@ def test_a_length_the_pickle_names_is_held_to_the_bytes_it_holds(tmp_path, value _refused(_load_isolated(_write(tmp_path / "named.pkl", value)), phrase, "more than the") +def _peak_refusing(path: Path) -> int: + """The most Python and numpy hold at once while `path` is refused here.""" + from tests.perf_counters import count_allocations + + with count_allocations() as peak: + with pytest.raises(pickled.RefusedPickle): + pickled.load(path) + return peak[0] + + +def test_an_arrow_array_naming_more_values_than_its_offsets_is_refused_before_room_is_made(tmp_path): + """F180 in F179's decoder, found in review: an Arrow string array of 2e8 + values and no buffers, a pickle of about a hundred bytes, had room made + for its values (1.5 GB) before its offsets were found missing. The + offsets are counted first.""" + path = _bytes(tmp_path / "text.pkl", _dumps(_arrow("string", 2 * 10**8, 0, 0, [None, None, None]))) + _refused(_load_isolated(path), "too few offsets") + assert _peak_refusing(path) < 1 << 20 + + +@pytest.mark.parametrize("key, value, phrase", [ + ("name", "dtype", "name of CategoricalDtype"), + ("attrs", "pairs", "attrs of list"), + ("attrs", "keyed", "CategoricalDtype as a key of a dict"), +], ids=["name", "attrs-pairs", "attrs-key"]) +def test_what_pandas_hashes_as_it_sets_a_frames_state_is_pythons_own(tmp_path, key, value, phrase): + """F174 and F180, found in review: pandas sets a Series' name and a + frame's attrs through their setters, which hash the name and attrs' + keys; a name, or a key, that was a CategoricalDtype over a RangeIndex + of 1e8 had pandas list the 1e8 categories (2 GB) before the length was + refused at the end of the file. Both must be Python's own values.""" + dtype = _New(pd.CategoricalDtype, {"categories": pd.RangeIndex(10**8), "ordered": False}) + with pd.option_context("future.infer_string", False): + state = dict(pd.Series([1.0, 2.0]).__getstate__()) + state[key] = {"dtype": dtype, "pairs": [(dtype, 1)], "keyed": {dtype: 1}}[value] + path = _write(tmp_path / "series.pkl", _New(pd.Series, state)) + _refused(_load_isolated(path), phrase) + assert _peak_refusing(path) < 1 << 20 + + +@pytest.mark.parametrize("locs, phrase", [ + (slice(0, 10**8, 1), "a block of shape (1, 1) for 100,000,000 columns of 1 rows"), + (np.array([10**7]), "do not hold each of its 1 columns once"), + (np.array([-(10**7)]), "do not hold each of its 1 columns once"), + (slice(5, 6, 1), "do not hold each of its 1 columns once"), +], ids=["wide", "far", "negative", "past-the-end"]) +def test_a_pandas_15_manager_state_is_checked_as_a_built_one_before_pandas_builds_it(tmp_path, locs, phrase): + """F174 and F180, found in review: pandas 1.5's state of a manager was + checked for its count of columns alone before pandas built from it, + and pandas makes room for each column named and writes at each column + a block is placed at. A one-row frame naming 1e8 columns, its one + value placed at all of them, took 1.6 GB before it was refused, and a + block placed outside the columns met pandas' own bounds check, an + error, rather than a refusal. The state is checked as a built manager + is, before pandas builds anything.""" + from pandas._libs.internals import BlockPlacement + from pandas.core.internals.managers import BlockManager + + with pd.option_context("future.infer_string", False): + rows = pd.Index(["a"]) + columns = pd.RangeIndex(len(BlockPlacement(locs))) + state = _manager_state(columns, rows, [(np.ones((1, 1)), locs)]) + path = _write(tmp_path / "frame.pkl", _frame_of(_New(BlockManager, state))) + _refused(_load_isolated(path), phrase) + assert _peak_refusing(path) < 1 << 20 + + +def test_frames_sharing_a_manager_check_it_once(tmp_path, monkeypatch): + """Found in review: each frame checked its manager in full, so a pickle + of 400 frames over one manager of 1e6 columns took ten times as long + as pickle's own reading. A manager is checked once, however many + frames share it; pandas, the oracle, reads the frames equal.""" + with pd.option_context("future.infer_string", False): + frame = pd.DataFrame(np.arange(50.0).reshape(1, 50)) + frames = [_New(pd.DataFrame, dict(frame.__getstate__())) for _ in range(20)] + data = _dumps(frames) + calls = [] + real = pickled._check_manager + monkeypatch.setattr(pickled, "_check_manager", lambda *args: calls.append(1) or real(*args)) + got = pickled.load(_bytes(tmp_path / "frames.pkl", data)) + assert len(calls) == 1 + truth = pickle.loads(data) + assert len(got) == 20 and all(f._mgr is got[0]._mgr for f in got) + for mine, theirs in zip(got, truth): + pd.testing.assert_frame_equal(mine, theirs) + + def test_an_array_of_items_of_no_size_is_refused(tmp_path): """numpy sizes `S` and `U` to one before it makes an array of them, so it never pickles an array of items of no size; one would name any @@ -778,7 +866,30 @@ def index(cls, **d): # pandas "index-state": (_Crafted(copyreg._reconstructor, (pd.Index, object, None), {"_data": np.array([1])}), "sets the state of a pandas Index"), - "dtype-state": (_New(pd.Int64Dtype, {"_cache": {}, "type": 1}), "gives a pandas Int64Dtype the state"), + "dtype-state": (_New(pd.Int64Dtype, {"_cache": {}, "type": 1}), "gives a Int64Dtype type"), + "masked-dtype-state-list": (_New(pd.Int64Dtype, [1]), "gives a Int64Dtype the state list"), + "frame-state-ordered": (_New(pd.DataFrame, OrderedDict(_mgr=None)), "gives a DataFrame the state OrderedDict"), + "frame-flags": (_New(pd.DataFrame, {"_flags": {"allows_duplicate_labels": True, "x": 1}}), "_flags of dict"), + "frame-metadata": (_New(pd.DataFrame, {"_metadata": ["_mgr"]}), "_metadata of list"), + "frame-typ": (_New(pd.DataFrame, {"_typ": 1}), "_typ of int"), + "masked-slots": (_New(pd.arrays.IntegerArray, ({"_data": np.array([1]), "_mask": np.array([False])}, + {"_dtype": pd.CategoricalDtype([1.5])})), + "gives a IntegerArray the state tuple"), + "masked-missing": (_New(pd.arrays.IntegerArray, {"_data": np.array([1])}), "gives a IntegerArray no _mask"), + "masked-dtype": (_New(pd.arrays.IntegerArray, {"_data": np.array([1]), "_mask": np.array([False]), + "_dtype": pd.CategoricalDtype([1.5])}), "the dtype CategoricalDtype"), + "masked-readonly": (_New(pd.arrays.IntegerArray, {"_data": np.array([1]), "_mask": np.array([False]), + "_readonly": "no"}), "a _readonly of str"), + "masked-values": (_New(pd.arrays.BooleanArray, {"_data": np.array([1.5]), "_mask": np.array([False]), + "_dtype": pd.BooleanDtype()}), "float64 values for its dtype"), + "categorical-attributes": ( + _Crafted(backed, (pd.Categorical, checksum, (pd.CategoricalDtype([1.5]), np.array([0], dtype=np.int8), + {"isna": 1}))), "gives a Categorical isna"), + "categorical-dict-state": (_Crafted(backed, (pd.Categorical, checksum, None), + {"_codes": np.array([0], dtype=np.int8)}), + "gives a Categorical the state dict"), + "string-dtype-missing": (_New(pd.StringDtype, {"storage": "python", "_na_value": 0.0}), + "other than Python text missing values as NA or NaN"), "categories-array": (_New(pd.CategoricalDtype, {"categories": np.array([1.5]), "ordered": False}), "the categories ndarray"), "categories-order": (_New(pd.CategoricalDtype, {"categories": None, "ordered": "yes"}), "the order str"), @@ -810,8 +921,13 @@ def index(cls, **d): "other than blocks and two indexes"), "manager-columns": (_Crafted(BlockManager, ((block(np.ones((1, 2))),), [pd.RangeIndex(2), pd.RangeIndex(2)])), "do not hold each of its 2 columns once"), - "manager-state": (_New(BlockManager, ([], [], [], {"0.14.1": {"axes": "x", "blocks": []}})), - "a state without its axes and blocks"), + "manager-state-axes": (_New(BlockManager, ([], [], [], {"0.14.1": {"axes": "x", "blocks": []}})), + "axes that are not indexes"), + "manager-state-blocks": (_New(BlockManager, ([], [], [], {"0.14.1": {"axes": [], "blocks": "x"}})), + "a state without its axes and blocks"), + "manager-state-axes-count": (_New(BlockManager, _manager_state(pd.RangeIndex(1), pd.RangeIndex(1), [])[:3] + + ({"0.14.1": {"axes": [pd.RangeIndex(1)], "blocks": []}},)), + "1 axes and 0 blocks"), "manager-state-block": (_New(BlockManager, _manager_state(pd.RangeIndex(1), pd.RangeIndex(1), [([1.0], slice(0, 1, 1))])), "a block of list"), "frame-of-a-series-manager": ( @@ -890,7 +1006,12 @@ def test_a_string_dtype_as_pandas_before_2_3_pickled_it_holds_python_text(tmp_pa """pandas before 2.3 pickled a StringDtype as its storage, or built it from that. Text is held in Python strings here, Arrow's too, so the storage read is Python's; missing values stay what the storage named - misses them as (`pyarrow_numpy`, pandas 2.2's, as NaN).""" + misses them as (`pyarrow_numpy`, pandas 2.2's, as NaN), where this + pandas has text missing as NaN (2.3 and later).""" + try: + pd.StringDtype("python", na_value=np.nan) + except TypeError: # pragma: no cover - pandas before 2.3, as the floors job has it + na_value = "NA" got = pickled.load(_write(tmp_path / "dtype.pkl", crafted())) assert got.storage == "python" assert (got.na_value is pd.NA) if na_value == "NA" else (isinstance(got.na_value, float) and np.isnan(got.na_value)) @@ -1030,9 +1151,10 @@ def test_a_text_array_whose_dtype_is_not_pythons_text_is_refused(tmp_path): def test_sniffing_reads_only_the_head_of_a_file(tmp_path, monkeypatch, gz): """F177: format detection sniffs every input for a pickle, text tables too, and pickletools read a table whose header starts "Barcode" as the - opcode BINBYTES with "arco", 1.87 GB, as its length (the oracle below): - 173 MiB of a 1.2 MB gzipped table was inflated only to decide it was - not a pickle. Sniffing reads `SNIFF_BYTES` at most, whatever the file.""" + opcode BINBYTES with "arco", 1.87 GB, as its length (the oracle below), + so it read on into the table, a gzipped one inflated, only to decide it + was not a pickle. Sniffing reads `SNIFF_BYTES` at most, whatever the + file.""" import gzip import struct from contextlib import contextmanager From 999bf2de2eaaf9f82c0e6d3ece9a5a51937e7453 Mon Sep 17 00:00:00 2001 From: Aljes Date: Fri, 4 Dec 2026 17:17:08 +0000 Subject: [PATCH 3/3] Second review: shared parts counted, Arrow cache and views read A value whose parts a pickle shares (a tuple of the same tuple at each level) costs a few bytes a level but comes to twice as many values a level. A key is counted, its shared parts once, against the bytes the pickle holds before anything hashes it, and nested 32 deep at most; refusals show what they name in brief; names must be text or numbers; only text, numbers and flat lists of them are written as text. pandas 3's Arrow text read with its cache and a view's read-only flag, and pandas' NA read as a key under pandas 3. Co-Authored-By: Claude Opus 5.5 --- docs/reference/formats/cistopic.md | 13 ++- docs/reference/testing.md | 4 +- src/adata/conversion/cistopic.py | 36 +++++--- src/adata/formats/pandas_frame.py | 53 ++++++++++-- src/adata/formats/pickled.py | 134 +++++++++++++++++++++-------- tests/test_cistopic.py | 25 +++++- tests/test_pandas_frame.py | 30 +++++++ tests/test_pickled.py | 100 +++++++++++++++++++-- 8 files changed, 331 insertions(+), 64 deletions(-) diff --git a/docs/reference/formats/cistopic.md b/docs/reference/formats/cistopic.md index 8031a33..921d7a8 100644 --- a/docs/reference/formats/cistopic.md +++ b/docs/reference/formats/cistopic.md @@ -61,7 +61,9 @@ written: - the few builtins a pickle may call are given only what a pickle of them holds (`set` a list, `range` integers), and nothing is hashed, as a dict's key, a set's item, or a name, but numbers, text and tuples of - them; + them, counted first: a tuple made of the same tuple at each level costs + a pickle a few bytes a level, and comes to twice as many values a + level; - a length the file names rather than holds, such as a `range`, a `RangeIndex`, or the shape of an empty array or a sparse matrix, is no more than the bytes the file holds (inflated, for a gzipped pickle), and @@ -88,8 +90,13 @@ warning, to a name no other column has. A sample in `path_to_fragments` is a key in the same way, but one like that is refused instead: cell_data's `sample_id` and the cell names, which end with it, name the sample as it is, and a renamed key would no longer match them. Names are read from a -list, an array, an index or a Series of them; cell or feature names given -as anything else, such as a table, are refused. +list, an array, an index or a Series of them, each text or a number; cell +or feature names given as anything else, such as a table, are refused. + +Only text, numbers and flat lists or tuples of them are written as text: +a column holding anything else, nested deeper or not plain data, is left +out with a warning, and a label like that refused. Written out, a value +nested in itself would come to twice as much text a level. ## Memory diff --git a/docs/reference/testing.md b/docs/reference/testing.md index 5b631a5..6273ab7 100644 --- a/docs/reference/testing.md +++ b/docs/reference/testing.md @@ -88,11 +88,11 @@ inside every release before PyPI has it. | `test_hdf5.py` | One dataset of a plain HDF5 file: the listing without `--key`, `read_hdf`'s `row_names` / `col_names` and other names, `--transpose` CSR and dense, slabs of chunks, `--from hdf5` on `.h5` | | `test_dense.py` | `conversion/dense.py`, which the loom and HDF5 importers read a dense matrix through: datasets chunked every way that changes how it reads them, on each output backend, read back by anndata | | `test_cistopic.py` | pycisTopic pickles read through the allowlist: a CistopicObject's matrices, frames, model and projections, an imputed-features pickle, a pickle naming `os.system` refused unrun, the missing-extra hint; a pickle pandas 3 saved, its Arrow text read with pyarrow hidden; labels a store cannot hold renamed, such samples refused; integers past int64; names a pickle does not hold refused unlisted | -| `test_pickled.py` | The restricted unpickler against crafted pickles that name only allowlisted globals, each loaded in a child process so a crash cannot take the run down, then here once refused: objects refused before a `set` or a hash takes them apart, lengths held to the bytes the file holds, every check reached by a pickle crafted for it, Arrow text decoded (malformed layouts refused, as pyarrow's own validation refuses them), the sniff reading only a file's head | +| `test_pickled.py` | The restricted unpickler against crafted pickles that name only allowlisted globals, each loaded in a child process so a crash cannot take the run down, then here once refused: objects refused before a `set` or a hash takes them apart, states only in the forms pandas pickles, lengths and shared parts held to the bytes the file holds, every check reached by a pickle crafted for it, Arrow text decoded (malformed layouts refused, as pyarrow's own validation refuses them), the sniff reading only a file's head | | `test_visium.py` | Space Ranger output: standard Visium (Space Ranger 1 to 4) laid out as `squidpy.read.visium` lays it out, Visium HD bins at each size, segmented cells, Space Ranger's analysis, images, refusals | | `test_xenium.py` | Xenium bundles (XOA 1 to 4): the cell table in or out of the matrix's order, cells the matrix lacks, Xenium's analysis with gaps | | `test_geojson.py` | `formats/geojson.py`: Space Ranger 4's cell outlines read a feature at a time, centroids and areas against shapely | -| `test_pandas_frame.py` | Each pandas dtype written as anndata writes it, on every backend; labels a store cannot hold as a name renamed, integers past int64 kept | +| `test_pandas_frame.py` | Each pandas dtype written as anndata writes it, on every backend; labels a store cannot hold as a name renamed, integers past int64 kept, past any float written as text; only text, numbers and flat lists written as text; attrs copied once | | `test_concat_axis_elements.py` | `concat` on obsm dataframes and varm, against `anndata.concat` for each join and merge strategy | | `test_legacy_copies.py` | anndata 0.7's dataframes (categoricals as codes with an object reference into `__categories`) copied by `subset` (h5ad and Zarr), `convert` to Zarr v2/v3 and a MuData import: written as current `categorical` groups in a 0.2.0 frame, read back by anndata with their categories | | `test_subset_categories.py` | `subset` and `split` narrow categoricals as anndata's subsetting does: unused categories dropped (on an axis kept whole too), order and `ordered` kept, `uns["_colors"]` narrowed with them; compared with anndata's own subset | diff --git a/src/adata/conversion/cistopic.py b/src/adata/conversion/cistopic.py index 7177a1f..572533a 100644 --- a/src/adata/conversion/cistopic.py +++ b/src/adata/conversion/cistopic.py @@ -220,8 +220,19 @@ def _is_sparse(value: Any) -> bool: return sp.issparse(value) -def _names(values: Any) -> List[str]: - return [str(v) for v in list(values)] +#: What a name may be: text, or a number written as text. +_NAMES = (str, bytes, int, float, np.generic, type(None)) + + +def _names(values: Any, what: str, name: str) -> List[str]: + """Names as text. Each must be text or a number: anything else may + share its parts with itself many times over (a tuple of the same tuple + at each level) and spell out as text far longer than it is held.""" + listed = list(values) + for value in listed: + if not isinstance(value, _NAMES): + raise ValueError(f"{name}: its {what} holds a {type(value).__name__}, not a name.") + return [str(v) for v in listed] def _count(values: Any, what: str, name: str) -> int: @@ -246,8 +257,10 @@ def _check_samples(fragments: Any, name: str) -> None: if not isinstance(fragments, dict): return seen = set() - for sample in fragments: + for sample, path in fragments.items(): key = str(sample) + if not isinstance(path, (str, bytes)): + raise ValueError(f"{name}: path_to_fragments gives the sample {key!r} a {type(path).__name__}, not a path.") if storable(key) != key: raise ValueError( f"{name}: path_to_fragments names the sample {key!r}, which an h5ad or Zarr " @@ -260,14 +273,17 @@ def _check_samples(fragments: Any, name: str) -> None: def _ordered(frame: Any, names: List[str], axis: str, what: str, warnings: List[str]) -> Any: """`frame` with its rows (or, `axis="columns"`, columns) in `names` order.""" - labels = frame.index if axis == "index" else frame.columns - if [str(v) for v in labels] == names: + from adata.formats.pandas_frame import label_text + + labels = [label_text(v, f"A row of {what}" if axis == "index" else f"A column of {what}") + for v in (frame.index if axis == "index" else frame.columns)] + if labels == names: return frame frame = frame.copy() if axis == "index": - frame.index = [str(v) for v in frame.index] + frame.index = labels else: - frame.columns = [str(v) for v in frame.columns] + frame.columns = labels missing = len(set(names) - set(frame.index if axis == "index" else frame.columns)) if missing: warnings.append(f"{what} lacks {missing:,} of the names; they are missing values.") @@ -286,7 +302,7 @@ def _plan_object(obj: Any, name: str, warnings: List[str]) -> _Import: f"the object names {n_regions:,} regions and {n_cells:,} cells." ) _check_samples(getattr(obj, "path_to_fragments", None), name) - cells, regions = _names(obj.cell_names), _names(obj.region_names) + cells, regions = _names(obj.cell_names, "cell_names", name), _names(obj.region_names, "region_names", name) detail = _Import("CistopicObject", obj, len(cells), len(regions), cells, regions) if _is_frame(getattr(obj, "cell_data", None)): detail.cell_data = _ordered(obj.cell_data, cells, "index", "cell_data", warnings) @@ -298,7 +314,7 @@ def _plan_object(obj: Any, name: str, warnings: List[str]) -> _Import: if isinstance(model, pickled.PycistopicObject): cell_topic = getattr(model, "cell_topic", None) if _is_frame(cell_topic): - detail.topics = _names(cell_topic.index) + detail.topics = _names(cell_topic.index, "model's topics", name) frame = _ordered(cell_topic, cells, "columns", "cell_topic", warnings) detail.arrays.append(("obsm", claim("X_topic", taken), frame.to_numpy().T)) harmony = getattr(model, "cell_topic_harmony", None) @@ -341,7 +357,7 @@ def _plan_imputed(obj: Any, name: str) -> _Import: f"{name}: its matrix is {shape}, but it names {n_features:,} features " f"and {n_cells:,} cells." ) - features, cells = _names(obj.feature_names), _names(obj.cell_names) + features, cells = _names(obj.feature_names, "feature_names", name), _names(obj.cell_names, "cell_names", name) if not _is_sparse(matrix): if not isinstance(matrix, np.ndarray) or matrix.ndim != 2: raise ValueError(f"{name}: its matrix is a {type(matrix).__name__}, not an array.") diff --git a/src/adata/formats/pandas_frame.py b/src/adata/formats/pandas_frame.py index 9228eef..3ff4fc1 100644 --- a/src/adata/formats/pandas_frame.py +++ b/src/adata/formats/pandas_frame.py @@ -16,7 +16,9 @@ `strings_to_categoricals` makes it; * an `object` column by what it holds (`pd.api.types.infer_dtype`): numbers as numbers (integers as int64, or uint64 past it, as pandas reads them), - text as text, anything mixed as text with a warning; + text as text, anything mixed as text with a warning, but only text, + numbers and flat lists of them: anything nested deeper is left out, with + a warning, as its text could double with each level it nests; * datetimes as ISO text, with a warning. Anything else is left out, with a warning. @@ -67,10 +69,13 @@ def write_frame( # which would cost attrs once per column; nothing here reads them. df = df.copy(deep=False) df.attrs = {} - labels = [str(v) for v in (df.index if index is None else index)] + labels = ( + [label_text(v, f"A row of {what or name}") for v in df.index] if index is None else [str(v) for v in index] + ) group = write_dataframe_header(parent, name, labels, []) written = [] - for position, key in enumerate(_column_keys([str(c) for c in df.columns], warnings, what or name)): + columns = [label_text(c, f"A column of {what or name}") for c in df.columns] + for position, key in enumerate(_column_keys(columns, warnings, what or name)): if key is None: continue # By position: a repeated label selects every column it names. @@ -81,6 +86,30 @@ def write_frame( return group +#: Values written as text by their own short text. +_SCALARS = (str, bytes, bytearray, int, float, complex, bool, type(None), slice, range) + + +def _is_scalar(value: Any) -> bool: + return type(value) in _SCALARS or isinstance(value, np.generic) or type(value).__name__ == "NAType" + + +def flat(value: Any) -> bool: + """Whether `value` is written as text no longer than what holds it: a + number or text, or a tuple or list of them. A value nested deeper (or + an array, a frame, a dict) can hold one part many times over, a tuple + of the same tuple at each level costing a pickle a few bytes a level, + and its text would double with each level.""" + return _is_scalar(value) or (type(value) in (tuple, list) and all(_is_scalar(v) for v in value)) + + +def label_text(value: Any, what: str) -> str: + """A row's or a column's label as text: refused unless `flat`.""" + if not flat(value): + raise ValueError(f"{what} is labelled by a {type(value).__name__} holding more than text and numbers.") + return str(value) + + def _column_keys(labels: List[str], warnings: List[str], what: str) -> List[Optional[str]]: """Each column's name in the store, None for one left out: a label a dataframe reserves, or one repeated, is left out with a warning. A label @@ -117,7 +146,9 @@ def write_column( dtype = column.dtype if isinstance(dtype, pd.CategoricalDtype): - _categorical(parent, name, np.asarray(column.cat.codes), dtype.categories, dtype.ordered) + if not _categorical(parent, name, np.asarray(column.cat.codes), dtype.categories, dtype.ordered): + warnings.append(f"Not written: {what}, whose categories are more than text and numbers.") + return False return True if isinstance(dtype, pd.BooleanDtype) or ( isinstance(dtype, pd.api.extensions.ExtensionDtype) and dtype.kind in "iu" @@ -163,6 +194,9 @@ def write_column( if inferred == "boolean" and not column.isna().any(): write_dense(parent, name, column.to_numpy(dtype=bool)) return True + if not all(flat(v) for v in column): + warnings.append(f"Not written: {what}, which holds more than text, numbers and flat lists of them.") + return False if categorize and not told and inferred not in ("string", "empty", "unicode", "bytes"): # In obs and var a column of mixed values is worth a word; in a # table of parameters ("lda", 15, True) it is what is expected. @@ -192,6 +226,8 @@ def _rounded(column: Any, floats: np.ndarray) -> bool: def _missing(value: Any) -> bool: import pandas as pd + if not _is_scalar(value): # pandas would make an array of a list + return False try: return bool(pd.isna(value)) except (TypeError, ValueError): @@ -211,7 +247,9 @@ def _text(parent: Any, name: str, values: List[Optional[str]], *, categorize: bo write_string_array(parent, name, np.asarray(values, dtype=object)) -def _categorical(parent: Any, name: str, codes: np.ndarray, categories: Any, ordered: bool) -> None: +def _categorical(parent: Any, name: str, codes: np.ndarray, categories: Any, ordered: bool) -> bool: + """A Categorical as a `categorical`; False, writing nothing, when a + category is not `flat`.""" values = np.asarray(categories) if values.dtype.kind in "biuf": group = parent.create_group(name) @@ -219,5 +257,8 @@ def _categorical(parent: Any, name: str, codes: np.ndarray, categories: Any, ord group.attrs["ordered"] = bool(ordered) write_dense(group, "categories", values) write_dense(group, "codes", codes.astype(_codes_dtype(len(values)))) - return + return True + if not all(flat(v) for v in values): + return False write_categorical(parent, name, codes, [str(v) for v in values], ordered=bool(ordered)) + return True diff --git a/src/adata/formats/pickled.py b/src/adata/formats/pickled.py index f3a5f9b..b68ee78 100644 --- a/src/adata/formats/pickled.py +++ b/src/adata/formats/pickled.py @@ -77,6 +77,7 @@ import io import pickle import pickletools +import reprlib from collections import OrderedDict from contextlib import contextmanager from pathlib import Path @@ -209,13 +210,18 @@ "start", "stop", "step"}) #: What an ArrowStringArray's state holds: its Arrow array (`_data` before -#: pandas 2.1) and its dtype. -_ARROW_STATE = frozenset({"_pa_array", "_data", "_dtype"}) +#: pandas 2.1), its dtype, and in pandas 3 a view's read-only flag (with its +#: cache, which every state may carry). +_ARROW_STATE = frozenset({"_pa_array", "_data", "_dtype", "_readonly"}) #: Keys whose hash and equality are Python's own: hashing anything else #: runs its class's code (pandas' dtypes hash their categories). _PLAIN = (str, bytes, int, float, complex, bool, type(None)) +#: How deep a key may nest tuples: Python hashes them recursively, with no +#: guard on the depth. +_KEY_DEPTH = 32 + class PycistopicObject: """A pycisTopic object, its attributes restored and nothing more. @@ -290,6 +296,30 @@ def _refuse(message: str) -> RefusedPickle: return RefusedPickle(f"the pickle {message}, which a pycisTopic object's never does, so it is not read.") +class _Brief(reprlib.Repr): + """reprlib's short reprs, but for an object other than Python's own + containers and scalars only its type: its own repr could spell out + what the pickle shares many times over, in full.""" + + def repr_instance(self, value: Any, level: int) -> str: + if type(value) in _PLAIN or type(value) is slice or isinstance(value, np.generic): + return super().repr_instance(value, level) + if value is _NDARRAY or isinstance(value, type) or callable(value): + return _name(value) # a class or a function: its name + return _name(type(value)) + + +_BRIEF = _Brief() +_BRIEF.maxlevel, _BRIEF.maxstring, _BRIEF.maxother = 3, 80, 80 + + +def _shown(value: Any) -> str: + """`value` as a refusal names it, in brief: a tuple made of the same + tuple at each level is a few bytes a level in a pickle, and twice as + long a level written out.""" + return _BRIEF.repr(value) + + def _is_count(value: Any) -> bool: return isinstance(value, (int, np.integer)) and not isinstance(value, (bool, np.bool_)) and value >= 0 @@ -298,21 +328,41 @@ def _is_integer(value: Any) -> bool: return isinstance(value, (int, np.integer)) and not isinstance(value, (bool, np.bool_)) -def _is_plain_key(value: Any) -> bool: - """A key Python or numpy hashes and compares without running anything - of the pickle's: a number, text, None, pandas' NA, or a tuple of them.""" +def _key_size(value: Any, sizes: Dict[int, int], depth: int = 0) -> Optional[int]: + """How many values `value` comes to as it is hashed, if it is a key + Python or numpy hashes without running anything of the pickle's: a + number, text, None, pandas' NA, or a tuple, frozenset or slice of + them; None if not. A part the pickle shares is walked once, `sizes` + holding what it came to, but counted each time it appears, as hashing + counts it.""" if type(value) in _PLAIN or isinstance(value, np.generic): - return True - if type(value) in (tuple, frozenset): - return all(_is_plain_key(item) for item in value) + return 1 + if type(value).__name__ == "NAType" and type(value).__module__.startswith("pandas"): # pandas' NA + return 1 if type(value) is slice: - return all(_is_plain_key(part) for part in (value.start, value.stop, value.step)) - return type(value).__name__ == "NAType" and type(value).__module__ == "pandas._libs.missing" + parts: Iterable[Any] = (value.start, value.stop, value.step) + elif type(value) in (tuple, frozenset): + parts = value + else: + return None + known = sizes.get(id(value)) + if known is not None: + return known + if depth >= _KEY_DEPTH: + raise _refuse(f"nests a key more than {_KEY_DEPTH} deep") + size = 1 + for part in parts: + counted = _key_size(part, sizes, depth + 1) + if counted is None: + return None + size += counted + sizes[id(value)] = size # `value` is held by the key, and so alive, while `sizes` is used + return size def _shape(value: Any, what: str) -> Tuple[int, ...]: if type(value) is not tuple or not all(_is_count(n) for n in value): - raise _refuse(f"gives {what} the shape {value!r}") + raise _refuse(f"gives {what} the shape {_shown(value)}") return tuple(int(n) for n in value) @@ -391,7 +441,7 @@ def check_sparse(matrix: Any) -> None: raise _refuse(f"gives {what} {', '.join(unknown)}") shape = state.get("_shape") if type(shape) is not tuple or len(shape) != 2 or not all(_is_count(n) for n in shape): - raise _refuse(f"gives {what} the shape {shape!r}") + raise _refuse(f"gives {what} the shape {_shown(shape)}") # Plain integers, as scipy makes them: it sizes its arrays from the # shape, and `np.uint8(255) + 1` is 0. n_rows, n_cols = (int(n) for n in shape) @@ -448,7 +498,7 @@ def _placement(locs: Any) -> Any: try: return BlockPlacement(locs) except (TypeError, ValueError, OverflowError) as exc: - raise _refuse(f"places a block at {locs!r} ({exc})") from None + raise _refuse(f"places a block at {_shown(locs)} ({exc})") from None def _check_blocks(blocks: Any, axes: Any, single: bool, what: str, held: int) -> None: @@ -763,11 +813,21 @@ def _held(self, items: Iterable[Any], by: str) -> None: def _keys(self, keys: Iterable[Any], as_what: str) -> None: """Refuse to hash anything but Python's or numpy's own values: hashing a key, or comparing it with another, runs its class's code - on whatever the pickle gave it. `as_what` names what hashes it (`a - key of a dict`).""" + on whatever the pickle gave it. Nor more values than the bytes the + pickle holds: a key that shares its parts, a tuple of the same + tuple at each level, is a few bytes a level and hashes twice as + many values a level. `as_what` names what hashes it (`a key of a + dict`).""" + sizes: Dict[int, int] = {} for key in keys: - if not _is_plain_key(key): + size = _key_size(key, sizes) + if size is None: raise _refuse(f"hashes a {_name(type(key))} as {as_what}") + if size > self._source.count: + raise _refuse( + f"hashes a key of {size:,} values as {as_what}, more than the " + f"{self._source.count:,} bytes it holds" + ) def _operands(self, count: Optional[int] = None) -> list: """The items an opcode is about to consume: the last `count`, or all @@ -879,7 +939,7 @@ def load_reduce(self) -> None: def _new(self, cls: Any, args: Any, kwargs: Any) -> Any: if not isinstance(cls, type): - raise _refuse(f"creates an instance of {cls!r}") + raise _refuse(f"creates an instance of {_shown(cls)}") if args or kwargs: raise _refuse(f"constructs {_name(cls)} from arguments") return self._created(cls.__new__(cls)) @@ -998,9 +1058,12 @@ def _check_frame_state(self, frame: Any, state: Any) -> None: raise _refuse(f"gives {what} {', '.join(unknown)}") for key, value in state.items(): if key in ("name", "_name"): - fits = _is_plain_key(value) + self._keys([value], f"the name of {what}") + fits = True elif key in ("attrs", "_attrs"): - fits = value is None or (type(value) is dict and all(_is_plain_key(k) for k in value)) + fits = value is None or type(value) is dict + if fits and value: + self._keys(value, f"a key of {what}'s attrs") elif key == "_flags": fits = type(value) is dict and set(value) <= {"allows_duplicate_labels"} and all( isinstance(v, (bool, np.bool_)) for v in value.values() @@ -1115,7 +1178,7 @@ def _build_dtype(self, dtype: np.dtype, state: Any) -> None: try: probe.__setstate__(state) except Exception as exc: # numpy's own refusal of the tuple - raise _refuse(f"gives the numpy dtype {spec!r} the state {state!r} ({exc})") from None + raise _refuse(f"gives the numpy dtype {spec!r} the state {_shown(state)} ({exc})") from None check_dtype(probe, "a dtype") dtype.__setstate__(state) @@ -1123,9 +1186,9 @@ def _reconstruct(self, subtype: Any, shape: Any, typecode: Any = b"b") -> np.nda """numpy's `_reconstruct`, as numpy pickles an array: an empty ndarray, given its state next.""" if subtype is not _NDARRAY: - raise _refuse(f"reconstructs {subtype!r} through numpy's _reconstruct") + raise _refuse(f"reconstructs {_shown(subtype)} through numpy's _reconstruct") if shape != (0,) or type(shape) is not tuple: - raise _refuse(f"reconstructs an array of shape {shape!r} through numpy's _reconstruct") + raise _refuse(f"reconstructs an array of shape {_shown(shape)} through numpy's _reconstruct") array = np.ndarray.__new__(np.ndarray, (0,), np.dtype("b")) self._unbuilt[id(array)] = array return self._created(array) @@ -1137,11 +1200,11 @@ def _build_array(self, array: np.ndarray, state: Any) -> None: raise _refuse(f"gives a numpy array the state {type(state).__name__}") shape, dtype, fortran, raw = state[-4:] if len(state) == 5 and not _is_count(state[0]): - raise _refuse(f"gives a numpy array the version {state[0]!r}") + raise _refuse(f"gives a numpy array the version {_shown(state[0])}") shape = _shape(shape, "a numpy array") dtype = _array_dtype(dtype) if not isinstance(fortran, (bool, int)): - raise _refuse(f"gives a numpy array the order {fortran!r}") + raise _refuse(f"gives a numpy array the order {_shown(fortran)}") size = _size(shape) if dtype.hasobject: if type(raw) is not list or len(raw) != size: @@ -1186,14 +1249,14 @@ def _scalar(self, dtype: Any, raw: Any = None) -> Any: def _encode(self, text: Any, encoding: Any = "utf-8") -> bytes: """`_codecs.encode`, which protocols 0-2 write bytes with.""" if type(text) is not str or encoding not in ("latin1", "latin-1"): - raise _refuse(f"encodes {type(text).__name__} as {encoding!r}") + raise _refuse(f"encodes {type(text).__name__} as {_shown(encoding)}") return text.encode("latin-1") def _reconstructor(self, cls: Any, base: Any, state: Any) -> Any: """`copyreg._reconstructor` as protocols 0 and 1 write it: an empty instance, given its state next.""" if base is not object or state is not None or not isinstance(cls, type): - raise _refuse(f"calls copyreg._reconstructor for {cls!r} from {base!r}") + raise _refuse(f"calls copyreg._reconstructor for {_shown(cls)} from {_shown(base)}") return self._created(object.__new__(cls)) def _new_index(self, cls: Any, d: Any) -> Any: @@ -1205,7 +1268,7 @@ def _new_index(self, cls: Any, d: Any) -> Any: from pandas.core.indexes.base import _new_Index if not (isinstance(cls, type) and issubclass(cls, pd.Index)) or type(d) is not dict: - raise _refuse(f"builds an index with pandas' _new_Index from {cls!r}") + raise _refuse(f"builds an index with pandas' _new_Index from {_shown(cls)}") unknown = sorted(set(d) - _INDEX_KEYS) if unknown: raise _refuse(f"builds a {cls.__name__} with {', '.join(map(str, unknown))}") @@ -1234,7 +1297,7 @@ def _ndarray_backed(self, cls: Any, checksum: Any, state: Any = None) -> Any: import pandas as pd if cls not in (pd.Categorical, pd.arrays.StringArray): - raise _refuse(f"builds {cls!r} through pandas' __pyx_unpickle_NDArrayBacked") + raise _refuse(f"builds {_shown(cls)} through pandas' __pyx_unpickle_NDArrayBacked") if state is not None: state = _backed_state(cls.__name__, state) built = _ndarray_backed()(cls, checksum, state) @@ -1248,13 +1311,13 @@ def _string_dtype(self, storage: Any = None, na_value: Any = _MISSING) -> Any: import pandas as pd if storage not in (None, "python", "pyarrow", "pyarrow_numpy"): - raise _refuse(f"builds a StringDtype held in {storage!r}") + raise _refuse(f"builds a StringDtype held in {_shown(storage)}") if storage == "pyarrow_numpy": na_value = np.nan if na_value is _MISSING or na_value is pd.NA: return pd.StringDtype("python") if not (isinstance(na_value, float) and np.isnan(na_value)): - raise _refuse(f"builds a StringDtype whose missing values are {na_value!r}") + raise _refuse(f"builds a StringDtype whose missing values are {_shown(na_value)}") try: return pd.StringDtype("python", na_value=np.nan) except TypeError: # pragma: no cover - pandas before 2.3, whose text misses values as NA only @@ -1267,7 +1330,7 @@ def _arrow_type(self, alias: Any) -> _ArrowType: `string`, whose offsets are int32, and `large_string`, int64.""" width = _ARROW_TEXT.get(alias) if type(alias) is str else None if width is None: - raise _refuse(f"rebuilds an Arrow array of type {alias!r}") + raise _refuse(f"rebuilds an Arrow array of type {_shown(alias)}") return _ArrowType(width) def _arrow_buffer(self, data: Any) -> bytes: @@ -1319,12 +1382,13 @@ def _arrow_array(self, data: Any) -> _ArrowText: def _from_arrow(self, state: Dict[str, Any]) -> Dict[str, Any]: """An ArrowStringArray's state, as the StringArray it is read as: - the decoded text, missing values as its dtype has them.""" + the decoded text, missing values as its dtype has them. Its cache + and its read-only flag (pandas 3 sets one on a view, such as the + text index of every Series it pickles) are dropped with it: the + decoded values are its own.""" import pandas as pd - unknown = sorted(map(str, set(state) - _ARROW_STATE)) - if unknown: - raise _refuse(f"gives an ArrowStringArray {', '.join(unknown)}") + state = _state_dict("ArrowStringArray", state, _ARROW_STATE) text, dtype = state.get("_pa_array", state.get("_data")), state.get("_dtype") if not isinstance(dtype, pd.StringDtype): raise _refuse(f"gives an ArrowStringArray the dtype {type(dtype).__name__}") diff --git a/tests/test_cistopic.py b/tests/test_cistopic.py index ba19c70..5b8882a 100644 --- a/tests/test_cistopic.py +++ b/tests/test_cistopic.py @@ -423,7 +423,8 @@ def test_labels_a_store_cannot_hold_are_renamed_and_the_output_opens(tmp_path, s ({"s/1": "/data/s1.tsv.gz"}, "names the sample 's/1', which an h5ad or Zarr store cannot hold as a key"), ({"": "/data/s1.tsv.gz"}, "names the sample '', which an h5ad or Zarr store cannot hold as a key"), ({1: "/data/a.tsv.gz", "1": "/data/b.tsv.gz"}, "names the sample '1' twice"), -], ids=["slash", "empty", "twice"]) + ({"s1": ("a",)}, "gives the sample 's1' a tuple, not a path"), +], ids=["slash", "empty", "twice", "not-a-path"]) def test_a_fragments_sample_a_store_cannot_hold_as_a_key_is_refused(tmp_path, samples, phrase): """F175: path_to_fragments was written with its samples as the keys of a group, and a sample "s/1" read back as {"s": {"1": ...}}, with exit @@ -535,6 +536,28 @@ def test_names_that_list_otherwise_than_they_count_are_refused(tmp_path, kind, n assert not out.exists() +def test_a_name_that_shares_its_parts_is_refused_before_it_is_written(tmp_path): + """Found in review: a cell name made of the same tuple at each level + costs a pickle a few bytes a level, and was written as its text, which + doubles with each level: a 529-byte pickle wrote a 67 MB h5ad at depth + 23, and would have needed 86 GB at depth 30. A name must be text or a + number.""" + classes = _pycistopic_classes() + shared = (1,) + for _ in range(30): + shared = (shared, shared) + obj = classes["CistopicObject"]() + obj.fragment_matrix = sparse.csr_matrix(np.ones((1, 1), dtype=np.int32)) + obj.cell_names, obj.region_names = [shared], ["chr1:0-1"] + path = tmp_path / "obj.pkl" + path.write_bytes(pickle.dumps(obj, protocol=4)) + assert path.stat().st_size < 1000 + out = tmp_path / "out.h5ad" + result = _convert(path, "-o", out) + assert result.exit_code == 1 and "its cell_names holds a tuple, not a name" in _out(result), _out(result) + assert not out.exists() + + def test_names_the_pickle_does_not_hold_are_refused_before_they_are_listed(tmp_path): """F180, in the converter: cell names given as a `range` of 10**7 and a fragment matrix of 1 x 10**7 with no entries, in a pickle of a few diff --git a/tests/test_pandas_frame.py b/tests/test_pandas_frame.py index 9a9cba5..60a59f0 100644 --- a/tests/test_pandas_frame.py +++ b/tests/test_pandas_frame.py @@ -168,6 +168,36 @@ def test_object_integers_past_any_float_are_written_as_text(new_store): assert any(w.startswith("t['huge'] holds integers past what a float holds") for w in warnings), warnings +def test_only_text_numbers_and_flat_lists_of_them_are_written_as_text(new_store): + """Found in review: a value made of the same tuple at each level costs + a pickle a few bytes a level, and its text doubles with each level, and + object columns, categories and labels were written as their text. Text + is written only of text, numbers and flat lists or tuples of them (as + Python's `str` spells them, the oracle); a column holding anything else + is left out with a warning, and such a label is refused.""" + shared = (1,) + for _ in range(30): + shared = (shared, shared) + index = ["r0", "r1"] + frame = pd.DataFrame({ + "deep": pd.Series([shared, "x"], dtype=object, index=index), + "flat": pd.Series([(1, "a"), ["b", 2.5]], dtype=object, index=index), + "nested_categories": pd.Categorical([((1,), (2,)), "x"]), + "numbers": [1.0, 2.0], + }, index=index) + path, opener = new_store() + warnings = [] + with opener("a") as root: + write_frame(root["uns"], "table", frame, warnings=warnings, what="t") + with pytest.raises(ValueError, match="labelled by a tuple holding more than text and numbers"): + write_frame(root["uns"], "labels", pd.DataFrame({"x": [1.0]}, index=[shared])) + got = _read(path).uns["table"] + assert list(got.columns) == ["flat", "numbers"] + assert got["flat"].tolist() == [str((1, "a")), str(["b", 2.5])] + assert any(w.startswith("Not written: t['deep'], which holds more than text") for w in warnings), warnings + assert any(w.startswith("Not written: t['nested_categories'], whose categories") for w in warnings), warnings + + def test_a_frames_attrs_are_copied_at_most_once_however_many_columns(new_store): """Found in review: pandas deep-copies a frame's attrs into each column taken from it, so writing a frame cost its attrs once per column, 12.6 diff --git a/tests/test_pickled.py b/tests/test_pickled.py index a83bbe9..e5e6b05 100644 --- a/tests/test_pickled.py +++ b/tests/test_pickled.py @@ -587,6 +587,7 @@ def _body(obj) -> bytes: @pytest.mark.parametrize("route", [ "setitem", "setitems", "dict", "additems", "frozenset", "set-call", "ordereddict-call", "index-name", + "inside-a-tuple", ]) def test_nothing_but_pythons_own_values_is_hashed_while_the_file_is_read(tmp_path, route): """F174, by hashing: a dict's keys, a set's items and an index's name @@ -610,13 +611,14 @@ def test_nothing_but_pythons_own_values_is_hashed_while_the_file_is_read(tmp_pat "set-call": _Crafted(set, ([key],)), "ordereddict-call": _Crafted(OrderedDict, ([[key, 1]],)), "index-name": _Crafted(_new_Index, (pd.Index, {"data": np.array([1, 2]), "name": key})), + "inside-a-tuple": _Crafted(set, ([(1, (2, key))],)), } path = tmp_path / "key.pkl" if route in raw: path.write_bytes(b"\x80\x02" + raw[route] + b".") else: _write(path, crafted[route]) - _refused(_load_isolated(path), "CategoricalDtype as") + _refused(_load_isolated(path), "builtins.tuple as" if route == "inside-a-tuple" else "CategoricalDtype as") @pytest.mark.parametrize("crafted, phrase", [ @@ -719,7 +721,7 @@ def test_an_arrow_array_naming_more_values_than_its_offsets_is_refused_before_ro @pytest.mark.parametrize("key, value, phrase", [ - ("name", "dtype", "name of CategoricalDtype"), + ("name", "dtype", "CategoricalDtype as the name of a Series"), ("attrs", "pairs", "attrs of list"), ("attrs", "keyed", "CategoricalDtype as a key of a dict"), ], ids=["name", "attrs-pairs", "attrs-key"]) @@ -785,6 +787,52 @@ def test_frames_sharing_a_manager_check_it_once(tmp_path, monkeypatch): pd.testing.assert_frame_equal(mine, theirs) +def _shared(depth: int) -> tuple: + """A tuple of the same tuple at each level: a pickle memoizes each level + once, a few bytes a level, and it comes to 2**depth values as it is + hashed or written out.""" + shared = (1,) + for _ in range(depth): + shared = (shared, shared) + return shared + + +@pytest.mark.parametrize("route, depth, phrase", [ + ("dict-key", 24, "more than the"), + ("set-item", 24, "more than the"), + ("series-name", 24, "more than the"), + ("dict-key", 40, "nests a key more than 32 deep"), +], ids=["dict-key", "set-item", "series-name", "too-deep"]) +def test_a_key_that_shares_its_parts_is_counted_before_it_is_hashed(tmp_path, route, depth, phrase): + """Found in review: a key made of the same tuple at each level is a few + bytes a level, and hashing it walks every value it comes to: a 117-byte + dict key of depth 24 took 8 s to hash, four times as long each two + levels more. A key is counted, its shared parts walked once, against + the bytes the pickle holds before anything hashes it; and Python's + hash recurses with no guard on the depth, so a key is nested 32 deep + at most.""" + key = _shared(depth) + if route == "series-name": + with pd.option_context("future.infer_string", False): + state = dict(pd.Series([1.0]).__getstate__()) + path = _write(tmp_path / "key.pkl", _New(pd.Series, {**state, "name": key})) + else: + ops = b"}" + _body(key) + b"K\x01s" if route == "dict-key" else b"\x8f(" + _body(key) + b"\x90" + path = _bytes(tmp_path / "key.pkl", b"\x80\x02" + ops + b".") + assert path.stat().st_size < 1000 + _refused(_load_isolated(path), phrase) + + +def test_a_refusal_names_what_the_pickle_gave_in_brief(tmp_path): + """Found in review: a refusal named the value a pickle gave in full, + and a tuple of the same tuple at each level spells out twice as long + a level: NEWOBJ on one of depth 22, a pickle of 120 bytes, was refused + with a message of 33.5 million characters. Values are named in brief.""" + path = _bytes(tmp_path / "newobj.pkl", _assemble(_body((_shared(40), np.zeros(2))) + b")\x81")) + stdout = _refused(_load_isolated(path), "creates an instance of", "numpy.ndarray") + assert len(stdout) < 300, len(stdout) + + def test_an_array_of_items_of_no_size_is_refused(tmp_path): """numpy sizes `S` and `U` to one before it makes an array of them, so it never pickles an array of items of no size; one would name any @@ -961,20 +1009,26 @@ def test_what_is_pickled_less_often_reads_back_as_python_numpy_and_pandas_read_i """What the checks must let through, read back as Python's, numpy's, scipy's and pandas' own reading has it (the oracle): Python 2's names (protocol 2 writes `range` as `__builtin__.xrange`), a range counting - down, tuple, slice and frozenset keys, pandas 1.5's Int64Index, an - instance made by the OBJ opcode, a placement on its own, and a sparse - matrix whose arrays run past its entries (scipy's `prune` trims them; - so does the reader).""" + down, tuple, slice, frozenset and NA keys, a frame with attrs and a + named Series, pandas 1.5's Int64Index, an instance made by the OBJ + opcode, a placement on its own, and a sparse matrix whose arrays run + past its entries (scipy's `prune` trims them; so does the reader).""" from pandas._libs.internals import BlockPlacement from pandas.core.indexes.base import _new_Index long_arrays = sp.csr_matrix(np.array([[1, 0], [0, 2]], dtype=np.int32)) long_arrays.indices = np.array([0, 1, 1], dtype=np.int32) long_arrays.data = np.array([1, 2, 9], dtype=np.int32) + with pd.option_context("future.infer_string", False): + frame = pd.DataFrame({"x": [1.0, 2.0]}, index=["a", "b"]) + frame.attrs.update({"source": "pycisTopic", ("run", 2): [1, 2]}) + named = pd.Series([1.0, 2.0], name=("topic", 1)) cases = { "xrange": pickle.dumps(range(3), protocol=2), "down": _dumps(range(10, 0, -3)), - "keys": _dumps({(1, "a"): 1, slice(0, 2): 2, frozenset({3}): 3, np.int64(4): 4, None: 5}), + "keys": _dumps({(1, "a"): 1, slice(0, 2): 2, frozenset({3}): 3, np.int64(4): 4, None: 5, pd.NA: 6}), + "attrs": _dumps(frame), + "named": _dumps(named), "int64index": _dumps(_Crafted(_new_Index, (_Global("pandas.core.indexes.numeric", "Int64Index"), {"data": np.array([1, 2]), "name": "n"}))), "placement": _dumps(_Crafted(BlockPlacement, (slice(0, 2, 1),))), @@ -986,6 +1040,11 @@ def test_what_is_pickled_less_often_reads_back_as_python_numpy_and_pandas_read_i truth.prune() assert np.array_equal(got.indices, truth.indices) and np.array_equal(got.data, truth.data) assert np.array_equal(got.toarray(), truth.toarray()) + elif name == "attrs": + pd.testing.assert_frame_equal(got, truth) + assert got.attrs == truth.attrs == frame.attrs + elif name == "named": + pd.testing.assert_series_equal(got, truth) elif name == "int64index": pd.testing.assert_index_equal(got, truth) elif name == "placement": @@ -1072,6 +1131,33 @@ def test_arrow_text_reads_without_pyarrow_as_pandas_reads_it(tmp_path, alias, sk assert got.dtype.na_value is truth.dtype.na_value +@pytest.mark.skipif(not (_PANDAS_3 and pa is not None), reason="needs pandas 3 and pyarrow to write the pickle") +@pytest.mark.parametrize("made", ["cached", "view", "series"]) +def test_arrow_text_pandas_3_cached_or_viewed_reads(tmp_path, made): + """Found in review: pandas 3 pickles an ArrowStringArray with what it + has cached once used, and with a read-only flag when it is a view, as + the text index of every Series it pickles is, or a frame's after a + slice or set_index; such text was refused. Both are dropped with the + Arrow array, and the values read are what pandas, the oracle, reads.""" + if made == "cached": + value = pd.Series(["a", None, "b"]).array + value._can_hold_na # noqa: B018 - read once, so that pandas caches it + assert "_cache" in vars(value), "pandas caches what it works out" + elif made == "view": + value = pd.DataFrame({"x": [1.0, 2.0, 3.0]}, index=["a", "b", "c"]).iloc[1:] + else: + value = pd.Series([1.0, 2.0], index=["a", "b"]) + data = pickle.dumps(value, protocol=4) + got, truth = pickled.load(_bytes(tmp_path / "text.pkl", data)), pickle.loads(data) + if made == "cached": + assert [None if pd.isna(v) else v for v in got] == [None if pd.isna(v) else v for v in truth] + elif made == "view": # the same labels and values, the text in Python's strings + pd.testing.assert_frame_equal(got, truth, check_index_type=False, check_column_type=False) + assert list(got.index) == ["b", "c"] + else: + assert list(got.index) == ["a", "b"] and got.tolist() == truth.tolist() + + def _broken(alias="large_string", length=2, offset=0, **change): """The parts of an Arrow string array of "ab" and "c", some changed.""" validity, offsets, text = _layout(["ab", "c"], 8 if alias.startswith("large") else 4)