Skip to content

B6: Elements written by import - #153

Open
Claptar wants to merge 3 commits into
mainfrom
fix/b6
Open

Claptar wants to merge 3 commits into
mainfrom
fix/b6

Conversation

@Claptar

@Claptar Claptar commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

Batch B6 of #149: what import array writes is what anndata reads back. It owns formats/array.py and formats/validate.py, plus tests and docs.

Closes #140 (F199, F200, F201, F202).

What changes

F199 (H): import array obs/<new> exits 0 but anndata never shows the column. import_npy wrote the column into the frame without adding it to the frame's column-order, the list anndata reads a frame's columns from.

  • Now, when the parent is a dataframe, the name is added to column-order. A replaced column keeps its place and is listed once. The same root cause applied to obs, var and raw/var, and to frames in obsm or uns, so all of them are fixed.
  • Every column of a dataframe is now checked in validate_dimensions, so import's precheck refuses before the store is copied. A column must:
    • be 1-D (as before);
    • not be named as the frame's index, which it would replace. On 0.17.8, obs/_index exited 0 and anndata's obs_names became '0.0', '1.0', …. _index and __categories, anndata's own names in a frame, are refused too;
    • be in a dataframe the store holds:
      • raw/var/score in a store with no raw used to create raw and raw/var as dict mappings: exit 0, and anndata showed a raw copied from X, without the column;
      • a frame encoded as anything but a dataframe (that dict) is refused;
      • a frame with no encoding at all is still accepted, because anndata reads such a frame (as some older writers left obs) with every member as a column;
    • be as long as the frame, for a frame no axis measures (one in uns). Listed at the wrong length, it would leave a store anndata cannot read.

F200 (M): raw/var/<col> was written at any length. _validate_raw now measures a column of raw/var against raw's own variables (raw/X's width), as it already did raw/var and raw/varm. Paths inside a column, such as a categorical's categories, are left alone, as before.

F201 (L): a 0-d .npy into obsm/varm/obsp failed with Error: tuple index out of range.

  • The root cause was that validate_dimensions read dimensions without checking the input had them. Every such read now follows a check, and an aligned path needs as many dimensions as it is aligned on. The refusal names the shape, e.g. 'obsp/s' needs a 6×6 matrix, a row and a column per cell, but the input is 1-D (6).
  • The same check covers a 1-D array into obsp or varp. That used to be written, though anndata cannot read a store holding one (Values of obsp must match dimensions ('obs', 'obs')).
  • With no readable obs, obsp's square check no longer refuses with "expected None×None".

F202 (L): obs/var were matched as bare prefixes. The prefixes are now obs/, var/, obsm/, … and the X/layers match is exact.

One departure from the audit. The audit expected a top-level variance_explained to be written once the prefix bug was fixed ("anndata keeps unknown top-level keys"). It does not. anndata passes every top-level member to AnnData():

  • variance_explained there fails on h5ad, Zarr v2 and v3 with AnnData.__init__() got an unexpected keyword argument;
  • shape fails as a constructor argument;
  • raw.X beside raw is "both legacy and current raw formats".

So check_target refuses a top-level name outside the layout for that reason, for every import kind, and suggests uns/<name>. Writing it would have turned a misleading refusal into an unreadable store. A test pins anndata's behaviour.

MuData's own groups (mod, obsmap, varmap) are the exception:

  • import takes an .h5mu as the HDF5 file it is, and mod/rna/obsm/… is AnnData, so they are still written to, as on main, in a store laid out as a MuData (one with a mod group).
  • In an AnnData store, validate_dimensions, which sees the store, refuses them, since anndata could not read the result.
  • The check asks the layout, not the root's encoding, because open_store stamps encoding-type: anndata on the copy an import writes into.

Repros (copies with WT pointed at this branch)

Ref On main On this branch
F199 (storage/13) DEFECT: imported obs/score exits 0 but anndata does not show the column OK: an imported obs column is visible to anndata
F200 (storage/10) DEFECT: a 5-row column was imported into a 4-row raw/var without a dimension check OK: a raw/var column of the wrong length is refused
F201, F202 (storage/11) DEFECT: a top-level 'variance_explained' is refused against n_var; a scalar into obsm/ fails with 'tuple index out of range' OK: validate_dimensions matches axis paths exactly and explains scalar refusals (variance_explained: 'variance_explained' is outside the AnnData layout … Put it in uns; obsm/s: 'obsm/s' needs one row per cell (3), but the input is a scalar.)

Tests

Each regression test's docstring starts with its ref. Each checks the result with anndata reading it back, on h5ad, Zarr v2 and Zarr v3, and refusals run with --inplace, so the source that anndata reads afterwards is the store a write would have changed. Each regression test fails on main's two source files and passes here. Run against the review round's starting point, so do the tests for the review's points.

  • tests/test_import.py:
    • F199: the column is listed in obs, var and raw.var, and in anndata 0.7.8's legacy stores (h5ad and Zarr);
    • F199: a text column goes into a frame with none, and a replaced column is listed once in its place;
    • F199: columns of frames in obsm and uns are listed, and measured against the frame;
    • F199: index names are refused;
    • F200: raw/var's columns are measured against raw's 4 variables, not var's 2;
    • F201: scalars, and 1-D obsp and varp inputs, are refused by name;
    • F202: top-level keys outside the layout are refused, and anndata cannot read a store holding one, on every backend;
    • F202: mod and obsmap are refused in an AnnData store;
    • guards: an unencoded obs takes a column, and an .h5mu modality is still a target.
  • tests/test_validate.py: unit cases for every new refusal; no bare prefix matched; paths inside a raw/var column; encoded and unencoded frames; every name of the layout still a target; MuData's groups refused outside a MuData layout and accepted in one.
  • docs/reference/testing.md: test_validate.py's row.

On the final commit (8c53a25), locally on macOS with Python 3.12: uv run pytest -m "not integration" gives 4274 passed, 9 skipped (357 integration tests deselected); uv run pytest -m perf gives 209 passed.

Docs

  • docs/reference/commands.md, import:
    • the layout's top level (and MuData's);
    • raw's own variables, and the dimensions an aligned path needs;
    • how an array becomes a dataframe column, and what is refused.
  • docs/troubleshooting.md:
    • the new top-level refusal;
    • the "First dimension mismatch" entry, corrected;
    • a new "Row count mismatch" entry.

Changelog entry (for 0.17.11, ### Fixed)

  • An array imported into obs, var or raw/var is a column anndata reads
    (#140). adata import array data.h5ad obs/score score.npy exited 0 and wrote the column, but left
    it out of obs's column-order, the list anndata reads a frame's columns
    from, so anndata never showed it and a round trip through anndata dropped
    it. The column is now listed, in a frame in obsm or uns too, and a
    column it replaces keeps its place. A column of raw/var is measured
    against raw's variables, where one of any length was written, and one of a
    frame in uns against the frame. A column named as the frame's index, which
    it used to replace (obs/_index turned obs_names into 0.0, 1.0, …), or
    _index or __categories, is refused, and so is a column of a frame the
    store does not hold as a dataframe.
  • import names the shape a path needs, where an input lacks a dimension
    (#140). A scalar .npy
    into obsm, varm, obsp, varp or raw/varm failed with Error: tuple index out of range, and a 1-D array into obsp or varp was written,
    though anndata cannot read a store holding one.
  • A top-level name outside the AnnData layout is refused for what it is
    (#140). var was
    matched as a bare prefix, so adata import array data.h5ad variance_explained v.npy was measured against var and refused because
    "var has 2 features". anndata cannot read a store with an element it does
    not know at its top level, so every import now refuses one, naming the
    layout, and suggests uns/. A MuData .h5mu's own mod, obsmap and
    varmap are still written to in a store laid out as a MuData, and refused
    in an AnnData store.

Review

An independent subagent reviewed the diff twice.

The first pass found these, fixed in the second commit:

  • a path inside a raw/var column was measured, and a scalar there crashed;
  • a dict-encoded frame was accepted;
  • .h5mu modalities were refused;
  • docs and messages were inaccurate;
  • some refusal checks could not fail.

The second pass found that letting MuData's groups through in check_target accepted them in AnnData stores too; the third commit fixes that. It suggested judging by the root's encoding. I judge by the layout instead, because open_store restamps the root; a test pins that case.

Noticed, not fixed (outside B6's files or findings)

  • MuData.

    • An import into an .h5mu restamps its root as encoding-type: anndata. storage.open_store calls ensure_anndata_root_attrs on any store opened to write, as on main.
    • Inside an .h5mu, a modality's own layout is not checked: an array as mod, mod/rna/obs or mod/rna/obsm breaks the modality, as on main.
    • import dict into a top-level mod, obsmap or varmap of an AnnData store is not refused, because json_data.py runs no check that sees the store.
  • import dict uns/table/score … and import dataframe uns/table/sub … (into a frame in uns or obsm) exit 0, but anndata never shows the member: F199's symptom for other kinds. The fix belongs in formats/json_data.py and formats/dataframe.py.

  • import array accepts a 3-D array into X or layers: anndata 0.13 reads it, but refuses to write it back ("violates the AnnData specification").

  • import array data.h5ad X/data v.npy writes into a sparse X's group unchecked (any length).

  • Paths inside an element fail or misjudge, as on main:

    • obs/<categorical>/categories is measured against obs as if it were a column;
    • obs/<col>/codes into a dataset fails with 'Dataset' object has no attribute 'create_dataset';
    • X/sub on a dense X fails with "truth value of an array … is ambiguous".

    A single "the parent is not a group" refusal would make the last two clear.

🤖 Generated with Claude Code

Claptar and others added 3 commits December 4, 2026 17:21
What `import array` writes is now what anndata reads back.

- F199: a column written into a dataframe is added to its column-order,
  which anndata reads a frame's columns from; before, `obs/score` exited
  0 and anndata never showed it. A column of any dataframe (obs, var,
  raw/var, or one in obsm or uns) must be 1-D, as long as the frame, in a
  frame the store has, and not named as its index (which `obs/_index`
  used to replace), `_index` or `__categories`.
- F200: a column of raw/var is measured against raw's own variables; it
  was written at any length.
- F201: an aligned path needs the dimensions it is aligned on, and the
  refusal names the shape: a scalar into obsm failed with 'tuple index
  out of range', and a 1-D array into obsp or varp was written, though
  anndata cannot read a store holding one.
- F202: obs and var are no longer matched as bare prefixes. A top-level
  name outside the AnnData layout, such as `variance_explained`, is
  refused for what it is: anndata hands every top-level member to
  `AnnData()` and cannot read a store holding one it does not know.
- docs: the import section of commands.md, troubleshooting, and the test
  map's row for test_validate.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ames

- A path inside a column of raw/var (a categorical's categories) is no
  longer measured against raw's variables as if it were a column, nor
  fails on a scalar with 'tuple index out of range'; every dimension
  lookup in validate.py now follows a check that the input has it.
- A frame encoded as anything but a dataframe (the dict raw/var 0.17.8
  left behind) takes no column; one with no encoding still does, since
  anndata reads its every member as a column.
- MuData's own top-level groups (mod, obsmap, varmap) are written to as
  before: an .h5mu is HDF5 to import, and `mod/rna/obsm/...` is AnnData.
- Messages: a frame's length in rows; shapes with '×' throughout.
- Tests: refusals run with --inplace, so the source read afterwards is
  the store a write would have changed; anndata's refusal of an unknown
  top-level key on every backend; a text column into a frame with none;
  an unencoded obs; an .h5mu modality; anndata 0.7's layout.
- Docs: the troubleshooting entries for both length messages, MuData's
  groups and the frame refusal in commands.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
check_target cannot see the store, so it let `mod`, `obsmap` and
`varmap` through everywhere, and `import array data.h5ad mod/x` wrote
a store anndata cannot read. validate_dimensions, which sees the store
and runs in import's precheck, now refuses them unless the store is laid
out as a MuData (a `mod` group). It asks the layout, not the root's
encoding: open_store stamps AnnData's encoding on the copy an import
writes into, so an .h5mu says "anndata" there.

The troubleshooting entry for "Row count mismatch" no longer claims the
columns of obs and var, which fail with "First dimension mismatch".

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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

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

@chatgpt-codex-connector

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

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-04T21:58:06.177884Z 8c53a25 PR opened
ℹ️ About Codex in GitHub

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

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

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

@github-actions

github-actions Bot commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

Test Results (py3.12)

4 074 tests   4 061 ✅  6m 36s ⏱️
    1 suites     13 💤
    1 files        0 ❌

Results for commit 8c53a25.

@github-actions

github-actions Bot commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

Test Results (py3.13)

4 074 tests   4 061 ✅  11m 5s ⏱️
    1 suites     13 💤
    1 files        0 ❌

Results for commit 8c53a25.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

B6: Elements written by import

2 participants