Skip to content

feat: write support for keys that aren’t file names - #2662

Merged
flying-sheep merged 21 commits into
mainfrom
feat/escape-keys
Nov 26, 2026
Merged

flying-sheep merged 21 commits into
mainfrom
feat/escape-keys

Conversation

@flying-sheep

@flying-sheep flying-sheep commented Sep 25, 2026 •

Copy link
Copy Markdown
Member

This and the two PRs below it are I need in 0.14 (for scanpy 2.0 preview), except for .uns accessors.

See also zarr-developers/zarr-specs#128

  • Release note not necessary because:

@codecov

codecov Bot commented Sep 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.70642% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 86.55%. Comparing base (ac61721) to head (1e55306).
⚠️ Report is 5 commits behind head on main.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
src/anndata/_io/utils.py 97.29% 3 Missing ⚠️
src/anndata/_io/specs/methods.py 95.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2662      +/-   ##
==========================================
- Coverage   88.00%   86.55%   -1.46%     
==========================================
  Files          51       51              
  Lines        8454     8603     +149     
==========================================
+ Hits         7440     7446       +6     
- Misses       1014     1157     +143     
Files with missing lines Coverage Δ
src/anndata/_core/xarray.py 95.19% <100.00%> (+0.04%) ⬆️
src/anndata/_io/h5ad.py 92.88% <100.00%> (ø)
src/anndata/_io/specs/lazy_methods.py 96.84% <100.00%> (+0.23%) ⬆️
src/anndata/_io/specs/registry.py 94.97% <100.00%> (+0.28%) ⬆️
src/anndata/_io/zarr.py 84.67% <100.00%> (ø)
src/anndata/_write_compat.py 96.66% <100.00%> (+0.11%) ⬆️
src/anndata/experimental/backed/_io.py 93.44% <100.00%> (+0.10%) ⬆️
src/anndata/experimental/merge.py 90.16% <100.00%> (+1.78%) ⬆️
src/anndata/_io/specs/methods.py 93.32% <95.00%> (+0.70%) ⬆️
src/anndata/_io/utils.py 85.16% <97.29%> (+6.31%) ⬆️

... and 10 files with indirect coverage changes

Comment thread docs/fileformat-prose.md Resolved
Comment thread docs/fileformat-prose.md Resolved
@flying-sheep flying-sheep changed the title feat: escape unsafe keys in 0.14 compat profile feat: write support for keys/columns that aren’t file names Sep 25, 2026

@ilan-gold ilan-gold 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.

Discussion is a bit mangled now, but scverse/zarr-convention-dataframe#1 is quite a strong suggestion that seems simpler to implement. Maybe let's discuss there and then I will implement there (and you here) whatever mechanism we settle on (your implementation here of other data frame things does not have to match mine otherwise)

Comment thread docs/fileformat-prose.md Resolved
@flying-sheep
flying-sheep force-pushed the feat/escape-keys branch 2 times, most recently from 622fd5a to 20b6199 Compare October 14, 2026 11:31
@flying-sheep
flying-sheep force-pushed the feat/escape-keys branch 2 times, most recently from 0428361 to ed0ed9c Compare October 20, 2026 15:15
Comment thread docs/fileformat-prose.md Resolved

@selmanozleyen selmanozleyen left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Plus here is a Claude adverserial report

  • 1. write_use with a column named "" overwrites the obs index

    An unnamed index is stored as "", but _resolve_use compares against idx.name (which reads back as None), so names.index("") returns the index's position and the column data replaces the index.

    Test
    def test_write_use_empty_col_keeps_index(tmp_path, fmt):
        p = tmp_path / f"t.{fmt}"
        adata = ad.AnnData(np.zeros((2, 3)), obs=pd.DataFrame({"a": [1, 2]}, index=["c1", "c2"]))
        write(adata, p, fmt, compat="0.14")
        adata.obs[""] = [7, 8]
        write(adata, p, fmt, use=A.obs[""], compat="0.14")
        pd.testing.assert_frame_equal(read(p, fmt).obs, adata.obs)  # index is now ['7', '8']
  • 2. ad.io.write_elem into a 0.2.0 dict / 0.3.0 dataframe group silently loses data or corrupts the group

    write_elem(f["uns"], "new", …) writes a child no reader sees. "item_0" overwrites another key's value. "keys"/"columns" replaces the names array, so the whole group reads back garbled with no error (read_names does str(n) on whatever it finds). This should raise and point to write_use, and read_names should reject anything that isn't a string array.

    Test
    @pytest.mark.parametrize("key", ["new", "item_0", "keys"])
    def test_write_elem_into_indexed_dict_raises(tmp_path, key):
        p = tmp_path / "t.h5ad"
        ad.AnnData(np.zeros((2, 3)), uns={"a": 1}).write_h5ad(p, compat="0.14")
        with h5py.File(p, "r+") as f, pytest.raises(ValueError):
            ad.io.write_elem(f["uns"], key, 2)
    
    
    @pytest.mark.parametrize("key", ["new", "column_0", "columns"])
    def test_write_elem_into_indexed_df_raises(tmp_path, key):
        p = tmp_path / "t.h5ad"
        obs = pd.DataFrame({"a": [1, 2]}, index=["c1", "c2"])
        ad.AnnData(np.zeros((2, 3)), obs=obs).write_h5ad(p, compat="0.14")
        with h5py.File(p, "r+") as f, pytest.raises(ValueError):
            ad.io.write_elem(f["obs"], key, np.array([3, 4]))
  • 3. read_lazy can't read a file the PR newly allows

    test_column_named_index makes _index a normal column name, but read_lazy on that file raises NotImplementedError, because the unnamed index is renamed to _index and collides with the column.

    Test
    def test_read_lazy_col_named_index(tmp_path, fmt):
        pytest.importorskip("xarray")
        p = tmp_path / f"t.{fmt}"
        obs = pd.DataFrame({"_index": [1, 2]}, index=["c1", "c2"])
        write(ad.AnnData(np.zeros((2, 3)), obs=obs), p, fmt, compat="0.14")
        lazy = ad.experimental.read_lazy(p)
        pd.testing.assert_frame_equal(lazy.obs.to_memory(), obs)
  • 4. "Any string works" isn't true for h5ad (not sure if this one is important)

    h5py variable-length strings reject embedded NUL characters (ValueError: VLEN strings do not support embedded NULLs). zarr is fine. Either reword the docs or handle it. The NUL in the indexed_keys docstring is also ambiguous (the Windows device name or the character?).

    Test
    def test_nul_in_key(tmp_path, fmt):  # fails for h5ad only
        p = tmp_path / f"t.{fmt}"
        write(ad.AnnData(np.zeros((2, 3)), uns={"a\x00b": 1}), p, fmt, compat="0.14")
        assert list(read(p, fmt).uns) == ["a\x00b"]
  • 5. Docs: path access to children no longer works

    With compat="0.14", children of mappings are item_N, so g["layers/dense"] (the recipe in the read_elem_lazy docstring) raises KeyError, and read_dispatched callbacks see /obsm/item_0 instead of /obsm/X_pca. Neither the release note nor write-compat.md mentions this. A note there would help, ideally with a public way to get a child by key (e.g. exposing mapping_items).

    Test helpers
    import h5py
    import numpy as np
    import pandas as pd
    import pytest
    
    import anndata as ad
    from anndata.acc import A
    
    
    @pytest.fixture(params=["h5ad", "zarr"])
    def fmt(request):
        return request.param
    
    
    def write(adata, path, fmt, **kw):
        getattr(adata, f"write_{fmt}")(path, **kw)
    
    
    def read(path, fmt):
        return getattr(ad, f"read_{fmt}")(path)

@flying-sheep

Copy link
Copy Markdown
Member Author

1 & 3: yup, fixing!

2: idk how defensive we should be. write_elem is a low-level tool that requires you to know what you’re doing.

4: I know. Intentional omission, because that’s a HDF5 implementation detail that doesn’t have anything to do with the spec. I thought there was no way to handle it, is there? (also regarding the NUL: yeah, will make clear that this is the windows device name, the string "NUL"

5: same as your inline comment, yes!

Comment thread docs/release-notes/2662.feat.md Resolved
Comment thread docs/fileformat-prose.md Resolved
Comment thread docs/fileformat-prose.md Resolved
Comment thread src/anndata/_io/specs/methods.py Resolved
Comment thread src/anndata/_io/utils.py Resolved

@ilan-gold ilan-gold 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.

Should scverse/zarr-convention-dataframe#4 be part of this as well?

Comment thread docs/fileformat-prose.md Resolved
Comment thread docs/fileformat-prose.md Resolved

@ilan-gold ilan-gold 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.

I replied to #2757! But otherwise, this looks good.

Comment thread docs/release-notes/2662.feat.md Resolved
@flying-sheep
flying-sheep enabled stacked auto-merge (squash) November 26, 2026 09:24
@flying-sheep
flying-sheep merged commit d75006d into main Nov 26, 2026
28 checks passed
@flying-sheep
flying-sheep deleted the feat/escape-keys branch November 26, 2026 09:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

3 participants