From e8331eb1244ae20b436fb171f9a443a089cf6665 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Wed, 9 Sep 2026 12:44:59 +0200 Subject: [PATCH 1/3] fix(metadata): handle argless KeyError from a codec's from_dict parse_codecs (src/zarr/core/metadata/v3.py) converts a KeyError raised by a codec's from_dict into a MetadataValidationError so that zarr.open's array-then-group fallback (which only catches ValueError) reports the codec problem instead of an unrelated group error. The handler formatted the message with e.args[0], so a KeyError raised without arguments (`raise KeyError`) inside a third-party from_dict escaped as `IndexError: tuple index out of range`. That IndexError is not a ValueError, so it bypassed the fallback and broke zarr.open, Group.members(), `"child" in group`, and anything else that parses the child's metadata. Only include the key in the message when the KeyError carries one, and reword the message to "KeyError 'K' while parsing the configuration for codec 'X'": a KeyError out of a third-party from_dict is not necessarily a missing configuration key, it can be an internal lookup miss. Tests: parametrize the existing parse_codecs test over keyed and argless KeyErrors, and add a zarr.open test that asserts MetadataValidationError (a ValueError subclass) rather than IndexError. Assisted-by: ClaudeCode:claude-fable-5-1 --- changes/0000.bugfix.md | 1 + src/zarr/core/metadata/v3.py | 6 ++- tests/test_registry.py | 85 ++++++++++++++++++++++++++++++------ 3 files changed, 78 insertions(+), 14 deletions(-) create mode 100644 changes/0000.bugfix.md diff --git a/changes/0000.bugfix.md b/changes/0000.bugfix.md new file mode 100644 index 0000000000..d71f105ef8 --- /dev/null +++ b/changes/0000.bugfix.md @@ -0,0 +1 @@ +Opening a Zarr format 3 array whose codec's ``from_dict`` raised a ``KeyError`` with no arguments used to fail with an unrelated ``IndexError: tuple index out of range`` while formatting the error message. Because that ``IndexError`` is not a ``ValueError``, it also escaped the array-then-group fallback in ``zarr.open`` and broke group operations such as ``Group.members()`` and ``"child" in group`` when any child array used such a codec. The ``KeyError`` is now always reported as a ``MetadataValidationError`` naming the codec, with the offending key included only when the ``KeyError`` carried one. diff --git a/src/zarr/core/metadata/v3.py b/src/zarr/core/metadata/v3.py index 6228e17b75..316a66d4b4 100644 --- a/src/zarr/core/metadata/v3.py +++ b/src/zarr/core/metadata/v3.py @@ -83,8 +83,12 @@ def parse_codecs(data: object) -> tuple[Codec, ...]: # configuration surfaces as a KeyError. Convert it: a bare KeyError escaping # metadata parsing is swallowed by the array-then-group fallback in # `zarr.api.asynchronous.open`, which then reports an unrelated group error. + # The KeyError may carry no arguments (`raise KeyError`), and it may come from + # an internal lookup rather than the configuration mapping itself, so name the + # key only when there is one and don't claim it was a missing configuration key. + key_text = f" {e.args[0]!r}" if e.args else "" raise MetadataValidationError( - f"Invalid configuration for codec {name_parsed!r}: missing key {e.args[0]!r}." + f"KeyError{key_text} while parsing the configuration for codec {name_parsed!r}." ) from e return out diff --git a/tests/test_registry.py b/tests/test_registry.py index 767d3e0439..d19b8837be 100644 --- a/tests/test_registry.py +++ b/tests/test_registry.py @@ -352,23 +352,82 @@ def test_parse_codecs_with_unregistered_config_pin_raises_bad_config_error() -> parse_codecs([{"name": "bytes"}]) -def test_parse_codecs_converts_keyerror_from_from_dict(monkeypatch: pytest.MonkeyPatch) -> None: - """A codec whose from_dict indexes a malformed config must not leak a KeyError. +@pytest.fixture +def keyerror_codec(monkeypatch: pytest.MonkeyPatch, request: pytest.FixtureRequest) -> str: + """Register a codec whose ``from_dict`` raises a KeyError and return its name. - A bare KeyError out of metadata parsing is caught by the array-then-group fallback in - `zarr.api.asynchronous.open`, which then reports an unrelated group error. + Parametrize indirectly with the KeyError's args tuple: ``("required_option",)`` for a + codec that indexes its configuration directly, ``()`` for a bare ``raise KeyError``. """ from zarr.codecs import BytesCodec - from zarr.errors import MetadataValidationError from zarr.registry import register_codec - class PickyCodec(BytesCodec): + keyerror_args: tuple[object, ...] = request.param + + class KeyErrorCodec(BytesCodec): @classmethod - def from_dict(cls, data: object) -> PickyCodec: - data["configuration"]["required_option"] # type: ignore[index] - return cls() + def from_dict(cls, data: object) -> KeyErrorCodec: + raise KeyError(*keyerror_args) + + name = "test_keyerror" + monkeypatch.setitem(zarr.registry._codec_registries, name, zarr.registry.Registry()) + register_codec(name, KeyErrorCodec) + return name + + +@pytest.mark.parametrize( + ("keyerror_codec", "expected_message"), + [ + ( + ("required_option",), + "KeyError 'required_option' while parsing the configuration for codec 'test_keyerror'.", + ), + ((), "KeyError while parsing the configuration for codec 'test_keyerror'."), + ], + indirect=["keyerror_codec"], + ids=["with_key", "argless"], +) +def test_parse_codecs_converts_keyerror_from_from_dict( + keyerror_codec: str, expected_message: str +) -> None: + """A KeyError out of a codec's from_dict becomes a MetadataValidationError naming the codec. + + A bare KeyError out of metadata parsing is caught by the array-then-group fallback in + `zarr.api.asynchronous.open`, which then reports an unrelated group error. The KeyError + may carry no arguments, in which case the message simply omits the key. + """ + from zarr.errors import MetadataValidationError + + with pytest.raises(MetadataValidationError) as excinfo: + parse_codecs([{"name": keyerror_codec, "configuration": {}}]) + assert str(excinfo.value) == expected_message + assert isinstance(excinfo.value.__cause__, KeyError) - monkeypatch.setitem(zarr.registry._codec_registries, "test_picky", zarr.registry.Registry()) - register_codec("test_picky", PickyCodec) - with pytest.raises(MetadataValidationError, match="test_picky.*required_option"): - parse_codecs([{"name": "test_picky", "configuration": {}}]) + +@pytest.mark.parametrize("keyerror_codec", [()], indirect=True, ids=["argless"]) +async def test_open_with_argless_keyerror_codec_raises_value_error(keyerror_codec: str) -> None: + """`zarr.open` on an array whose codec raises a bare KeyError reports the codec, not IndexError. + + Formatting the argless KeyError used to raise ``IndexError: tuple index out of range``, + which is not a ValueError and so escaped the array-then-group fallback in ``zarr.open``. + """ + from zarr.errors import MetadataValidationError + + store = MemoryStore() + metadata = { + "zarr_format": 3, + "node_type": "array", + "shape": [4], + "chunk_grid": {"name": "regular", "configuration": {"chunk_shape": [4]}}, + "chunk_key_encoding": {"name": "default"}, + "data_type": "float64", + "fill_value": 0.0, + "codecs": [{"name": keyerror_codec}], + "attributes": {}, + } + await store.set( + "zarr.json", + default_buffer_prototype().buffer.from_bytes(json.dumps(metadata).encode()), + ) + with pytest.raises(MetadataValidationError, match=keyerror_codec): + zarr.open(store=store, mode="r") From 5789492865e662e463494936f746dd1db2357e59 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Wed, 9 Sep 2026 12:48:55 +0200 Subject: [PATCH 2/3] chore: rename changelog fragment to the PR number Assisted-by: ClaudeCode:claude-fable-5-1 --- changes/{0000.bugfix.md => 4324.bugfix.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename changes/{0000.bugfix.md => 4324.bugfix.md} (100%) diff --git a/changes/0000.bugfix.md b/changes/4324.bugfix.md similarity index 100% rename from changes/0000.bugfix.md rename to changes/4324.bugfix.md From 4ad539dfffe57318e2b89e1345f3cfdc3c636fe2 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Wed, 9 Sep 2026 19:07:30 +0200 Subject: [PATCH 3/3] docs: clarify argless codec error test behavior Assisted-by: Codex:gpt-6 --- tests/test_registry.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_registry.py b/tests/test_registry.py index d19b8837be..cae7a89d98 100644 --- a/tests/test_registry.py +++ b/tests/test_registry.py @@ -408,8 +408,8 @@ def test_parse_codecs_converts_keyerror_from_from_dict( async def test_open_with_argless_keyerror_codec_raises_value_error(keyerror_codec: str) -> None: """`zarr.open` on an array whose codec raises a bare KeyError reports the codec, not IndexError. - Formatting the argless KeyError used to raise ``IndexError: tuple index out of range``, - which is not a ValueError and so escaped the array-then-group fallback in ``zarr.open``. + An argless KeyError must propagate as a MetadataValidationError naming the codec. + Opening still fails because the codec configuration could not be parsed. """ from zarr.errors import MetadataValidationError