aggregate(values, by=<labels with no non-background instance>) raises a misleading 'regions do not match' error
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 394
- Forks
- 95
- Avg merge
- 4d 3h
- Merged PRs (30d)
- 7
Description
[!NOTE]
This whole message is AI-generated. The issue was automatically discovered and reported by an AI agent (Claude) during an autonomous bug hunt on thespatialdatacode base. It has not been verified or triaged by a human yet; theneeds: triagelabel is set so that a maintainer can confirm it. The reproduction script below was executed by the agent in an isolated environment (see Environment) and its output is pasted verbatim.
Summary
Found while triaging #215. aggregate(values=<image>, by=<labels containing only background, i.e. no non-zero label id>) does not return an empty table (0 obs) as one might expect; it raises ValueError: Regions in the AnnData object and \region` do not match. — a message about the table schema that gives no hint that the actual cause is "there were no labelled instances to aggregate". Same underlying validation error text as #1096 (there triggered by assigning a 0-row table to a SpatialData object directly), but reached from a different code path (aggregate()` on all-background labels) with no data-dependent workaround available to the caller (the labels crop is what it is).
Severity (agent's assessment): low — confusing error message rather than wrong results, but easy to hit (e.g. a labels crop that happens to contain no cells) and unhelpful for debugging
Where: src/spatialdata/_core/operations/aggregate.py::_create_sdata_from_table_and_shapes → TableModel.parse(...) → src/spatialdata/models/models.py::_validate_table_annotation_metadata (raises ValueError: Regions in the AnnData object and \{region_key}` do not match.` when the table built from the (empty) aggregation result has 0 rows and therefore an empty/mismatched region column).
Expected behaviour
Either an empty table (0 obs) is returned, or a clear, specific error such as ValueError: no non-background instances found in <by>, cannot aggregate is raised.
Reproduction
Save as repro.py and run uv run repro.py (the PEP 723 header pins spatialdata to the commit the bug was found on; replace the URL fragment with @main to test the current main branch).
# /// script
# requires-python = ">=3.12"
# dependencies = [
# "spatialdata @ git+https://github.com/scverse/spatialdata.git@ccf1ea048d054b6624214bf618008a9f9ae223e0",
# ]
# ///
"""New (minor) finding while triaging #215: aggregating by a labels element that contains only background
raises a misleading `ValueError: Regions in the AnnData object and 'region' do not match` instead of a clear
'no labels found' error (or an empty table)."""
import numpy as np
from spatialdata import aggregate
from spatialdata.models import Image2DModel, Labels2DModel
img = Image2DModel.parse(np.random.default_rng(0).random((2, 16, 16)))
labels = Labels2DModel.parse(np.zeros((16, 16), dtype=np.int32)) # only background
try:
t = aggregate(values=img, by=labels, agg_func="mean")["table"]
print("aggregate(image, all-background labels) -> OK", t.shape)
print("VERDICT: NOT REPRODUCED")
except Exception as e: # noqa: BLE001
print("aggregate(image, all-background labels) ->", type(e).__name__, str(e)[:150])
print("VERDICT: REPRODUCED (misleading error message for labels without any instance)")
Observed output
aggregate(image, all-background labels) -> ValueError Regions in the AnnData object and `region` do not match.
VERDICT: REPRODUCED (misleading error message for labels without any instance)
Possible fix direction (unverified)
In _create_sdata_from_table_and_shapes (or earlier, where the per-label statistics are computed), special-case the 0-row result before calling TableModel.parse() and either return an empty table or raise a dedicated, descriptive error. Related: #1096 requests the same kind of "more informative error when subsetting/aggregating results in no observations" improvement for a different trigger.
Environment
uv run repro.py with the PEP 723 metadata in the script (fresh, isolated environment; spatialdata built from main @ ccf1ea0 (2026-08-28); Python 3.13, latest releases of the dependencies at run time: pandas 3.0, anndata 0.13, zarr 3.3, dask 2026.8, numpy 2.5, geopandas 1.1, shapely 2.1). macOS (arm64).
Possibly related issues
#1096
Automatically generated; discovered by an AI agent (Claude) and not yet reviewed by a human.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Run the provided repro with uv run repro.py, then inspect src/spatialdata/_core/operations/aggregate.py at _create_sdata_from_table_and_shapes and the validation path in src/spatialdata/models/models.py. Confirm the all-background case and make the resulting behavior or error message specific to having no non-background instances, without regressing normal aggregation.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- data
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Active
- Clarity
- Mostly clear
- Newbie friendliness
- 64/100