Skip to content

fix: most immutable setting situtations - #2095

Merged
flying-sheep merged 14 commits into
x-layers-unificationfrom
ig/backed_mode_unify_x_layers
Aug 29, 2025
Merged

flying-sheep merged 14 commits into
x-layers-unificationfrom
ig/backed_mode_unify_x_layers

Conversation

@ilan-gold

@ilan-gold ilan-gold commented Aug 27, 2025 •

Copy link
Copy Markdown
Contributor

This is a PR to help push things along a bit here. There are two commits here:

  1. Bring back backed mode in its former state
  2. Update the logic in initialization so that (a) Raw is initialized with an AnnData object that has a valid layers (hence the change of where the Raw declaration happens) and (b) better handle the interaction between layers and X
  3. EDIT: various small sharp edges

There are still quite a few errors but at least they fall into only a few categories I can address a bit more clearly now, I think. Most of the remaining issues have to do with setting on a view or similar now, which is a bit fraught because setting on X is special-cased

One of the issues with the current logic is that layers now may or may not contain None but in backed mode, it never does even if X is not None, which is a problem for testing but I think also a bit of a rough edge. I'm going to play around with holding a SparseDataset class in memory at None and seeing how that goes.

  • Closes #
  • Tests added
  • Release note added (or unnecessary)

Comment thread src/anndata/_core/anndata.py Resolved
@ilan-gold
ilan-gold requested a review from flying-sheep August 27, 2025 13:50
@codecov

codecov Bot commented Aug 27, 2025 •

Copy link
Copy Markdown

❌ 134 Tests Failed:

Tests completed Failed Passed Skipped
6534 134 6400 1163
View the top 3 failed test(s) by shortest run time
tests.test_deprecations::test_dtype_warning
Stack Traces | 0.001s run time
#x1B[0m#x1B[94mdef#x1B[39;49;00m#x1B[90m #x1B[39;49;00m#x1B[92mtest_dtype_warning#x1B[39;49;00m():#x1B[90m#x1B[39;49;00m
        #x1B[90m# Tests a warning is thrown#x1B[39;49;00m#x1B[90m#x1B[39;49;00m
        #x1B[94mwith#x1B[39;49;00m pytest.warns(#x1B[96mFutureWarning#x1B[39;49;00m):#x1B[90m#x1B[39;49;00m
>           a = AnnData(np.ones((#x1B[94m3#x1B[39;49;00m, #x1B[94m3#x1B[39;49;00m)), dtype=np.float32)#x1B[90m#x1B[39;49;00m

#x1B[1m#x1B[31mtests/test_deprecations.py#x1B[0m:81: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

args_all = (<[AttributeError("'AnnData' object has no attribute '_is_view'") raised in repr()] AnnData object at 0x7f85cfe24590>, array([[1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.]]))
kw = {'dtype': <class 'numpy.float32'>}

    #x1B[0m#x1B[37m@wraps#x1B[39;49;00m(fn)#x1B[90m#x1B[39;49;00m
    #x1B[94mdef#x1B[39;49;00m#x1B[90m #x1B[39;49;00m#x1B[92mfn_compatible#x1B[39;49;00m(*args_all: P.args, **kw: P.kwargs) -> R:#x1B[90m#x1B[39;49;00m
        #x1B[94mif#x1B[39;49;00m #x1B[96mlen#x1B[39;49;00m(args_all) <= n_positional:#x1B[90m#x1B[39;49;00m
>           #x1B[94mreturn#x1B[39;49;00m fn(*args_all, **kw)#x1B[90m#x1B[39;49;00m
#x1B[1m#x1B[31mE           TypeError: AnnData.__init__() got an unexpected keyword argument 'dtype'#x1B[0m

#x1B[1m#x1B[31m../../../..../anndata/88DSKUwu/hatch-test.pre/lib/python3.13.../site-packages/legacy_api_wrap/__init__.py#x1B[0m:82: TypeError

#x1B[33mDuring handling of the above exception, another exception occurred:#x1B[0m

    #x1B[0m#x1B[94mdef#x1B[39;49;00m#x1B[90m #x1B[39;49;00m#x1B[92mtest_dtype_warning#x1B[39;49;00m():#x1B[90m#x1B[39;49;00m
        #x1B[90m# Tests a warning is thrown#x1B[39;49;00m#x1B[90m#x1B[39;49;00m
>       #x1B[94mwith#x1B[39;49;00m pytest.warns(#x1B[96mFutureWarning#x1B[39;49;00m):#x1B[90m#x1B[39;49;00m
#x1B[1m#x1B[31mE       Failed: DID NOT WARN. No warnings of type (<class 'FutureWarning'>,) were emitted.#x1B[0m
#x1B[1m#x1B[31mE        Emitted warnings: [].#x1B[0m

#x1B[1m#x1B[31mtests/test_deprecations.py#x1B[0m:80: Failed
tests.test_repr::test_removal[layers]
Stack Traces | 0.003s run time
adata = AnnData object with n_obs × n_vars = 20 × 10
    obs: 'obs_key'
    var: 'var_key'
    uns: 'uns_key'
    obsm: 'obsm_key'
    varm: 'varm_key'
    layers: None
    obsp: 'obsp_key'
    varp: 'varp_key'
adata_attr = 'layers'

    #x1B[0m#x1B[94mdef#x1B[39;49;00m#x1B[90m #x1B[39;49;00m#x1B[92mtest_removal#x1B[39;49;00m(adata, adata_attr):#x1B[90m#x1B[39;49;00m
        attr = adata_attr#x1B[90m#x1B[39;49;00m
        #x1B[94massert#x1B[39;49;00m re.search(#x1B[33mrf#x1B[39;49;00m#x1B[33m"#x1B[39;49;00m#x1B[33m^#x1B[39;49;00m#x1B[33m\#x1B[39;49;00m#x1B[33ms+#x1B[39;49;00m#x1B[33m{#x1B[39;49;00mattr#x1B[33m}#x1B[39;49;00m#x1B[33m:.*$#x1B[39;49;00m#x1B[33m"#x1B[39;49;00m, #x1B[96mrepr#x1B[39;49;00m(adata), flags=re.MULTILINE)#x1B[90m#x1B[39;49;00m
        #x1B[96mdelattr#x1B[39;49;00m(adata, attr)#x1B[90m#x1B[39;49;00m
>       #x1B[94massert#x1B[39;49;00m re.search(#x1B[33mrf#x1B[39;49;00m#x1B[33m"#x1B[39;49;00m#x1B[33m^#x1B[39;49;00m#x1B[33m\#x1B[39;49;00m#x1B[33ms+#x1B[39;49;00m#x1B[33m{#x1B[39;49;00mattr#x1B[33m}#x1B[39;49;00m#x1B[33m:.*$#x1B[39;49;00m#x1B[33m"#x1B[39;49;00m, #x1B[96mrepr#x1B[39;49;00m(adata), flags=re.MULTILINE) #x1B[95mis#x1B[39;49;00m #x1B[94mNone#x1B[39;49;00m#x1B[90m#x1B[39;49;00m
#x1B[1m#x1B[31mE       assert <re.Match object; span=(144, 160), match='    layers: None'> is None#x1B[0m
#x1B[1m#x1B[31mE        +  where <re.Match object; span=(144, 160), match='    layers: None'> = <function search at 0x7f862c074ae0>('^\\s+layers:.*$', "AnnData object with n_obs × n_vars = 20 × 10\n    obs: 'obs_key'\n    var: 'var_key'\n    uns: 'uns_key'\n    obsm: 'obsm_key'\n    varm: 'varm_key'\n    layers: None\n    obsp: 'obsp_key'\n    varp: 'varp_key'", flags=re.MULTILINE)#x1B[0m
#x1B[1m#x1B[31mE        +    where <function search at 0x7f862c074ae0> = re.search#x1B[0m
#x1B[1m#x1B[31mE        +    and   "AnnData object with n_obs × n_vars = 20 × 10\n    obs: 'obs_key'\n    var: 'var_key'\n    uns: 'uns_key'\n    obsm: 'obsm_key'\n    varm: 'varm_key'\n    layers: None\n    obsp: 'obsp_key'\n    varp: 'varp_key'" = repr(AnnData object with n_obs × n_vars = 20 × 10\n    obs: 'obs_key'\n    var: 'var_key'\n    uns: 'uns_key'\n    obsm: 'obsm_key'\n    varm: 'varm_key'\n    layers: None\n    obsp: 'obsp_key'\n    varp: 'varp_key')#x1B[0m
#x1B[1m#x1B[31mE        +    and   re.MULTILINE = re.MULTILINE#x1B[0m

#x1B[1m#x1B[31mtests/test_repr.py#x1B[0m:62: AssertionError
tests.test_views::test_set_scalar_subset_X[scipy_csr_matrix-list_bool_subset]
Stack Traces | 0.003s run time
matrix_type = <class 'scipy.sparse._csr.csr_matrix'>
subset_func = <function list_bool_subset at 0x7f85f86ff380>

    #x1B[0m#x1B[37m@IGNORE_SPARSE_EFFICIENCY_WARNING#x1B[39;49;00m#x1B[90m#x1B[39;49;00m
    #x1B[94mdef#x1B[39;49;00m#x1B[90m #x1B[39;49;00m#x1B[92mtest_set_scalar_subset_X#x1B[39;49;00m(matrix_type, subset_func):#x1B[90m#x1B[39;49;00m
        adata = ad.AnnData(matrix_type(np.zeros((#x1B[94m10#x1B[39;49;00m, #x1B[94m10#x1B[39;49;00m))))#x1B[90m#x1B[39;49;00m
        orig_X_val = adata.X.copy()#x1B[90m#x1B[39;49;00m
        subset_idx = subset_func(adata.obs_names)#x1B[90m#x1B[39;49;00m
    #x1B[90m#x1B[39;49;00m
        adata_subset = adata[subset_idx, :]#x1B[90m#x1B[39;49;00m
    #x1B[90m#x1B[39;49;00m
>       adata_subset.X = #x1B[94m1#x1B[39;49;00m#x1B[90m#x1B[39;49;00m

#x1B[1m#x1B[31mtests/test_views.py#x1B[0m:389: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
#x1B[1m#x1B[.../anndata/_core/anndata.py#x1B[0m:595: in X
    #x1B[0m#x1B[96mself#x1B[39;49;00m.layers[#x1B[94mNone#x1B[39;49;00m] = value#x1B[90m#x1B[39;49;00m
#x1B[1m#x1B[.../anndata/_core/aligned_mapping.py#x1B[0m:174: in __setitem__
    #x1B[0mvalue = #x1B[96mself#x1B[39;49;00m._validate_value(value, key)  #x1B[90m# Validate before mutating#x1B[39;49;00m#x1B[90m#x1B[39;49;00m
#x1B[1m#x1B[.../anndata/_core/aligned_mapping.py#x1B[0m:86: in _validate_value
    #x1B[0m#x1B[94mif#x1B[39;49;00m #x1B[96mself#x1B[39;49;00m.parent.shape[axis] == axis_len(val, i):#x1B[90m#x1B[39;49;00m
#x1B[1m#x1B[31m../../../..../uv/python/cpython-3.13.7-linux-x86_64-gnu/lib/python3.13/functools.py#x1B[0m:934: in wrapper
    #x1B[0m#x1B[94mreturn#x1B[39;49;00m dispatch(args[#x1B[94m0#x1B[39;49;00m].#x1B[91m__class__#x1B[39;49;00m)(*args, **kw)#x1B[90m#x1B[39;49;00m
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

x = 1, axis = 0

    #x1B[0m#x1B[37m@singledispatch#x1B[39;49;00m#x1B[90m#x1B[39;49;00m
    #x1B[94mdef#x1B[39;49;00m#x1B[90m #x1B[39;49;00m#x1B[92maxis_len#x1B[39;49;00m(x, axis: Literal[#x1B[94m0#x1B[39;49;00m, #x1B[94m1#x1B[39;49;00m]) -> #x1B[96mint#x1B[39;49;00m | #x1B[94mNone#x1B[39;49;00m:#x1B[90m#x1B[39;49;00m
    #x1B[90m    #x1B[39;49;00m#x1B[33m"""\#x1B[39;49;00m
    #x1B[33m    Return the size of an array in dimension `axis`.#x1B[39;49;00m
    #x1B[33m#x1B[39;49;00m
    #x1B[33m    Returns None if `x` is an awkward array with variable length in the requested dimension.#x1B[39;49;00m
    #x1B[33m    """#x1B[39;49;00m#x1B[90m#x1B[39;49;00m
>       #x1B[94mreturn#x1B[39;49;00m x.shape[axis]#x1B[90m#x1B[39;49;00m
#x1B[1m#x1B[31mE       AttributeError: 'int' object has no attribute 'shape'#x1B[0m

#x1B[1m#x1B[31msrc/anndata/utils.py#x1B[0m:118: AttributeError

To view more test analytics, go to the Test Analytics Dashboard
📋 Got 3 mins? Take this short survey to help us improve Test Analytics.

@ilan-gold ilan-gold changed the title Ig/backed mode unify x layers fix: backed mode + initialization logic Aug 27, 2025
@ilan-gold

ilan-gold commented Aug 27, 2025 •

Copy link
Copy Markdown
Contributor Author

I'm going to play around with holding a SparseDataset class in memory at None and seeing how that goes.

So the issue here is apparently doing anything after the object is a view and the file is closed. You can't just reopen it so something like

backed_v = backed_adata[obs_idx, var_idx]
backed_v.to_memory() # closes file handle
backed_v.write_h5ad(final_pth)

doesn't work because backed_v has a closed file handle and thus can no longer read data. We could change the behavior of to_memory to not close the file, but that would be a breaking change, and I'm not confident enough to say it is even a good idea.

Comment thread src/anndata/_core/anndata.py Resolved
@ilan-gold ilan-gold changed the title fix: backed mode + initialization logic fix: most read cases Aug 29, 2025
@ilan-gold ilan-gold changed the title fix: most read cases fix: most non-setting situtations Aug 29, 2025
@ilan-gold ilan-gold changed the title fix: most non-setting situtations fix: most immutable setting situtations Aug 29, 2025
@ilan-gold
ilan-gold requested a review from flying-sheep August 29, 2025 06:37
Comment on lines +852 to +853
# TODO: This is helpful in backed mode where `X is not None` but `None not in layers`.
# Does this filter make sense in general? Is there a case where we explicitly want to check `None in layers`?

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.

Yeah, backed mode complicates things.

My plan for the PR was that these two invariants should hold:

  • adata.X is adata.layers.get(None)
  • (adata.X is None) is (None not in adata.layers)

I get why you’re going the route of making X’s getter/setter more complex instead of layers, but I think my initial idea is more obvious from an API standpoint, don’t you think?

@ilan-gold ilan-gold Aug 29, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Totally agree, and I absolutely would go that way, but to do that we would need to deprecate parts of our current X functionality. Things like

import anndata as ad, numpy as np
adata = ad.AnnData(np.random.rand(3, 10), layers = { "a_layer":np.random.rand(3, 10) })
# updates adata.X
adata[:2].X = 1
# does not update adata.layers["a_layer"]
adata[:2].layers["a_layer"] = np.ones((2, 10))

actually do two different things so if were to route the former through the later, we would be dropping functionality that the former offers. That's the same reason adata.X is adata.layers.get(None) doesn't hold; if it were to hold, we would be dropping functionality from what I can tell (in this case, backed mode more or less, where we never hold an array-like reference to the object, instead reopening the file on access). Like I mentioned here, I would love to be able to remedy this, but we would be breaking even more currently standardized behavior then.

Maybe I'm missing what you're saying, but from my perspective, that was most of the idea with this PR - to bring back this functionality (largely).

@ilan-gold ilan-gold Aug 29, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

In summation

  1. backed mode currently has various edge cases, like never holding anything other than a reference to a file handle for X
  2. Setting on adata.X has fundamentally different semantics than other elems

If we broke both of these, then I could see your invariants holding / complexity being removed.

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.

yeah, that’s what I meant with

I get why you’re going the route of making X’s getter/setter more complex instead of layers

→ in order to make it all work transparently, we’d have to modify the Layers* classes more heavily to make all of this work the same.

but anyway, your approach here is “in backed mode, .layers[None] behaves as if .X was None”?

Comment thread tests/test_views.py
Comment on lines -499 to +507
# Should now have same value as default
assert_equal(getattr(subset, attr), getattr(empty, attr))
# Should now have same value as default, except for `layers`, which still has the `None` key for `subset`
if attr == "layers":
assert_equal(
{k: v for k, v in getattr(subset, attr).items() if k is not None},
getattr(empty, attr),
)
else:
assert_equal(getattr(subset, attr), getattr(empty, attr))

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.

I wonder if we should make Layers with only None inside falsey.

That way del ad.layers; assert not layers would work.

@flying-sheep
flying-sheep merged commit 3756974 into x-layers-unification Aug 29, 2025
@flying-sheep
flying-sheep deleted the ig/backed_mode_unify_x_layers branch August 29, 2025 11:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants