scverse / scverse/spatialdata

`sdata.images = {...}` (and the other element setters) break cross-type name uniqueness; the resulting store cannot be read back

Open
#1,212 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

API bug 🚨 needs: triage priority: high
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 the spatialdata code base. It has not been verified or triaged by a human yet; the needs: triage label 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

All Elements containers share one set (SpatialData._shared_keys) to reject a name already used by another element type. The setters create a new set and hand it only to the new container, so after sdata.images = {"a": img} the labels/points/shapes containers still reference the old set and sdata.labels["a"] = lab is accepted. sdata["a"] then raises Found multiple elements with name 'a', write() succeeds, and read_zarr() fails with KeyError: Element names must be unique.

Severity (agent's assessment): high — violates the core invariant that element names are unique; write() succeeds and read_zarr() then fails

Where: src/spatialdata/_core/spatialdata.py, property setters images/labels/points/shapes/tables (self._shared_keys = self._shared_keys - set(...) rebinds the shared set instead of mutating it)

Expected behaviour

sdata.labels["a"] = lab raises KeyError('Key a is not unique ...') exactly as it does when the object was built through the constructor.

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",
# ]
# ///
"""sdata.images = {...} (and the other element setters) break the cross-type name-uniqueness check."""
import os
import shutil
import tempfile
import warnings
import numpy as np
from spatialdata import SpatialData, read_zarr
from spatialdata.models import Image2DModel, Labels2DModel

warnings.simplefilter("ignore")
img = Image2DModel.parse(np.zeros((1, 5, 5), dtype=np.uint8))
lab = Labels2DModel.parse(np.zeros((5, 5), dtype=np.uint8))

sdata = SpatialData(images={"a": img})
try:
    sdata.labels["a"] = lab
    print("constructor path: no error (unexpected)")
except KeyError as e:
    print("constructor path: KeyError as expected:", str(e)[:70])

sdata = SpatialData()
sdata.images = {"a": img}          # property setter rebinds the shared key set -> containers no longer share it
bug = False
try:
    sdata.labels["a"] = lab
    bug = True
    print("after `sdata.images = {...}`: NO ERROR -> images:", list(sdata.images), "labels:", list(sdata.labels))
    try:
        sdata["a"]
    except ValueError as e:
        print("sdata['a'] ->", e)
    tmp = tempfile.mkdtemp()
    sdata.write(os.path.join(tmp, "store.zarr"))
    print("write(): succeeded")
    try:
        read_zarr(os.path.join(tmp, "store.zarr"))
        print("read_zarr(): succeeded")
    except Exception as e:  # noqa: BLE001
        print("read_zarr():", type(e).__name__, str(e)[:100])
    shutil.rmtree(tmp)
except KeyError as e:
    print("after `sdata.images = {...}`: KeyError as expected:", e)
print("VERDICT:", "BUG REPRODUCED" if bug else "NOT REPRODUCED")
Observed output
constructor path: KeyError as expected: 'Key `a` is not unique as it exists with a different element type, or
after `sdata.images = {...}`: NO ERROR -> images: ['a'] labels: ['a']
sdata['a'] -> Found multiple elements with name 'a'
write(): succeeded
read_zarr(): KeyError "Element names must be unique. The following element names are used multiple times: {'a'}"
VERDICT: BUG REPRODUCED

Possible fix direction (unverified)

Mutate the shared set in place (self._shared_keys.difference_update(self._images.keys())) and reuse it for the new container; consider calling _validate_element_names_are_unique() in write() too.

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). Also reproduced in a second environment with pandas 2.3.3 / anndata 0.12.11 / numpy 2.4.4 / zarr 3.2.1.


Automatically generated; discovered by an AI agent (Claude) and not yet reviewed by a human.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in src/spatialdata/_core/spatialdata.py, focusing on the images, labels, points, shapes, and tables property setters and their shared-key handling. Run the supplied repro.py to confirm the constructor path, setter path, and write/read_zarr behavior. Done means cross-type duplicate names are rejected after a setter assignment and a valid store can be read back.

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
Clearly specified
Newbie friendliness
74/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.