Skip to content

Struct rename= mapping silently swallows non-KeyError exceptions from __getitem__ #1407

Done

Description

@shashank11yadav

Description

When rename= is a mapping, msgspec looks each field name up with __getitem__ and clears any exception, not just KeyError. A mapping that raises something else (here RuntimeError) is silently ignored, the class is created, and the raw field name is used on the wire. A callable rename= propagates its errors.

from collections.abc import Mapping
import msgspec


class M(Mapping):
    def __getitem__(self, k):
        if k == "a":
            raise RuntimeError("boom")
        raise KeyError(k)

    def __iter__(self):
        return iter(())

    def __len__(self):
        return 0


class S(msgspec.Struct, rename=M()):
    a: int
    b: int = 0


print("EXPECTED: RuntimeError propagated from rename mapping __getitem__")
print("ACTUAL: no error, class created, encoded as", msgspec.json.encode(S(1)).decode())

Output on main (45b5424) and on 0.23.0:

EXPECTED: RuntimeError propagated from rename mapping __getitem__
ACTUAL: no error, class created, encoded as {"a":1,"b":0}

Expected behavior

Only a missing key (KeyError) should fall back to the field name. Any other exception should propagate when the class is defined, as rename_callable (src/msgspec/_core.c, just above rename_mapping) already does for callables.

Versions

  • msgspec 0.23.0 and main @ 45b5424
  • Python 3.12, Linux

Additional context

rename_mapping (src/msgspec/_core.c:5911-5917) calls PyErr_Clear() on any failure of PyObject_GetItem. A fix is to clear only when PyErr_ExceptionMatches(PyExc_KeyError) and otherwise return NULL.

I have a fix with a regression test ready and will open a pull request for it right after filing this issue; it will link back here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions