TableModel rejects int8/uint8 instance-key columns although the error message promises 'uint equivalents' (breaks aggregate/to_circles on uint8 labels)

Abierto Apto para principiantes
#1,229 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
76/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
numpy, pandas, python
Área
data

Línea de trabajo

Comienza en src/spatialdata/models/models.py, en TableModel._validate_table_annotation_metadata, y ejecuta el repro.py proporcionado con uv run. Comprueba la validación de dtype para int8 y uint8; después, verifica que la reproducción acepte esos dtypes y que aggregate(image, by=uint8 labels) se ejecute correctamente.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

bug 🚨 element: labels 🏷️ element: table 📑 models needs: triage priority: medium

[!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

uint8/int8 instance ids raise TypeError: Only integer (int, np.int16, np.int32, np.int64, and uint equivalents), string ... allowed as dtype for instance_key column in obs. Dtype found to be uint8, while uint16/int64 pass.

Severity (agent's assessment): medium — Labels2DModel.parse(np.zeros(..., dtype=np.uint8)) is common, and aggregate(image, by=uint8_labels) / to_circles(uint8_labels) fail when the result table is built

Where: src/spatialdata/models/models.py::TableModel._validate_table_annotation_metadata (_INT_TYPES = [int, np.int16, np.uint16, np.int32, np.uint32, np.int64, np.uint64])

Expected behaviour

All integer dtypes accepted.

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",
# ]
# ///
"""TableModel rejects int8/uint8 instance-key columns although the error message promises 'uint equivalents'."""
import warnings
import numpy as np
import pandas as pd
from anndata import AnnData
from spatialdata import aggregate
from spatialdata.models import Image2DModel, Labels2DModel, TableModel

warnings.simplefilter("ignore")
bug = False
for dt in [np.uint8, np.int8, np.uint16, np.int64]:
    obs = pd.DataFrame({"region": pd.Categorical(["lab"] * 3), "instance_id": np.array([1, 2, 3], dtype=dt)})
    try:
        TableModel.parse(AnnData(X=np.zeros((3, 1)), obs=obs), region="lab", region_key="region", instance_key="instance_id")
        print(f"instance_id dtype {dt.__name__:6s}: OK")
    except Exception as e:  # noqa: BLE001
        print(f"instance_id dtype {dt.__name__:6s}: {type(e).__name__}: {str(e)[:70]}...")
        bug = True
# consequence: aggregating an image by uint8 labels fails when the result table is built
labels = Labels2DModel.parse(np.array([[0, 1], [2, 2]], dtype=np.uint8))
image = Image2DModel.parse(np.ones((1, 2, 2)))
try:
    aggregate(values=image, by=labels, agg_func="sum")
    print("aggregate(image, by=uint8 labels): OK")
except Exception as e:  # noqa: BLE001
    print("aggregate(image, by=uint8 labels):", type(e).__name__, str(e)[:70], "...")
print("VERDICT:", "BUG REPRODUCED" if bug else "NOT REPRODUCED")
Observed output
instance_id dtype uint8 : TypeError: Only integer (int, np.int16, np.int32, np.int64, and uint equivalents)...
instance_id dtype int8  : TypeError: Only integer (int, np.int16, np.int32, np.int64, and uint equivalents)...
instance_id dtype uint16: OK
instance_id dtype int64 : OK
aggregate(image, by=uint8 labels): TypeError Only integer (int, np.int16, np.int32, np.int64, and uint equivalents) ...
VERDICT: BUG REPRODUCED

Possible fix direction (unverified)

Replace the whitelist with np.issubdtype(d, np.integer) (plus pandas nullable integer dtypes if desired).

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.

Lenguaje dominante
Python
Estrellas
394
Forks
95
Merge medio
3 d 9 h
PR fusionados (30 d)
5

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de scverse/spatialdata

Todos los issues de scverse/spatialdata

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.