Skip to content

Do not swallow non-TypeError exceptions in feature-detection fallbacks - #1382

Merged
asvetlov merged 8 commits into
aio-libs:masterfrom
devdanzin:fix/broad-pyerr-clear
Sep 5, 2026
Merged

asvetlov merged 8 commits into
aio-libs:masterfrom
devdanzin:fix/broad-pyerr-clear

Conversation

@devdanzin

Copy link
Copy Markdown
Contributor

What do these changes do?

Several feature-detection fallbacks cleared every pending exception when a fallback path was taken:
view richcompare and items-view __contains__ measuring len(other), items-view __contains__
computing the identity, MultiDict.__eq__ probing keys(), and extend()/constructor probing
items(). A MemoryError or KeyboardInterrupt raised by the user object was silently discarded. Each
is now guarded with PyErr_ExceptionMatches() so only the expected TypeError/AttributeError is
cleared and anything else propagates — the same pattern the sibling sites in views.h already use.
C-extension-only; the pure-Python backend propagates naturally.

Are there changes in behavior for the user?

Yes (edge case): an exception other than TypeError/AttributeError (notably MemoryError,
KeyboardInterrupt) raised by an object being probed now propagates instead of being swallowed. The
normal fallbacks (a non-sized or non-mapping object) are unchanged.

Is it a substantial burden for the maintainers to support this?

No. It applies the module's existing guard pattern to the few sites that missed it.

Related issue number

Findings from the C-extension analysis report #1306.

Checklist

  • I think the code is well written
  • Unit tests for the changes exist (test_non_typeerror_exceptions_are_not_swallowed)
  • Documentation reflects the changes (no public API change)
  • N/A — no CONTRIBUTORS.txt in this repo
  • Add a new news fragment into the CHANGES/ folder

Several probes cleared *every* pending exception when a fallback path was
taken: view richcompare and items-view __contains__ measuring len(other),
items-view __contains__ computing the identity, MultiDict.__eq__ probing
keys(), and extend()/ctor probing items().  A MemoryError or KeyboardInterrupt
raised by the user object was silently discarded.

Guard each with PyErr_ExceptionMatches() so only the expected
TypeError/AttributeError is cleared and anything else propagates -- the same
pattern the sibling sites in views.h already use.

Adds a C-extension regression test.
@devdanzin
devdanzin requested a review from asvetlov as a code owner July 24, 2026 14:06
@devdanzin
devdanzin requested a review from webknjaz as a code owner July 24, 2026 14:06
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Jul 24, 2026
@codspeed

codspeed Bot commented Jul 24, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 248 untouched benchmarks


Comparing devdanzin:fix/broad-pyerr-clear (50a6a62) with master (2dd3185)

Open in CodSpeed

@codecov

codecov Bot commented Jul 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.86%. Comparing base (2dd3185) to head (50a6a62).

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #1382   +/-   ##
=======================================
  Coverage   99.86%   99.86%           
=======================================
  Files          29       29           
  Lines        3710     3728   +18     
  Branches      275      275           
=======================================
+ Hits         3705     3723   +18     
  Misses          3        3           
  Partials        2        2           
Flag Coverage Δ
CI-GHA 99.86% <100.00%> (+<0.01%) ⬆️
pytest 99.86% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Comment thread tests/test_multidict.py Resolved
@greptile-apps

greptile-apps Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

Safe to merge: the changed C-extension fallback paths preserve compatibility behavior and propagate unexpected exceptions.

No blocking failure remains.

T-Rex T-Rex Logs

What T-Rex did

  • The PR's focused C-extension test script was executed against the compiled multidict._multidict extension, exercising constructor and update items() probes, equality keys() probes, view-comparison and item-containment length probes, and case-insensitive item identity calculation, with TypeError and AttributeError fallbacks observed and MemoryError and KeyboardInterrupt propagated, and the run completed successfully.
  • The standalone run confirmed the imported implementation was multidict._multidict from the compiled .so, and all focused checks exited with code 0, while the execution log recorded each observed fallback and the propagated exceptions.
  • Artifacts documenting the focused C-extension test were created, including the test script and its execution output, to help reviewers inspect the test harness and its results.
  • Overall, the results demonstrate that the test harness exercised the intended error pathways as designed and produced a clean exit, without unexpected non-propagated failures.

View all artifacts

T-Rex Ran code and verified through T-Rex

Reviews (2): Last reviewed commit: "Update tests/test_multidict.py" | Re-trigger Greptile

Comment thread tests/test_multidict.py Resolved
Comment thread tests/test_multidict.py Resolved
@asvetlov

asvetlov commented Sep 5, 2026

Copy link
Copy Markdown
Member

@devdanzin thanks!

@asvetlov
asvetlov enabled auto-merge (squash) September 5, 2026 15:39
@asvetlov
asvetlov merged commit 0b5beca into aio-libs:master Sep 5, 2026
60 of 71 checks passed
asvetlov added a commit that referenced this pull request Sep 22, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

`_multidict_extend_parse_args()` cleared every pending exception when
`PyObject_LengthHint()` failed on the positional argument, so a
`MemoryError` or `KeyboardInterrupt` raised by that object's `__len__`
was discarded and the update simply went ahead with no size estimate.
The fallback is now guarded with `PyErr_ExceptionMatches()`, so only the
`TypeError` from an unusable `__length_hint__` is ignored. That is the
same pattern the sibling probes picked up in #1382.

`PyObject_LengthHint()` already absorbs a missing `__len__` or
`__length_hint__` internally, so the only `TypeError` that reaches this
branch is "`__length_hint__` must be an integer"; a broken hint costs
the preallocation estimate and nothing else, so it stays ignored.

C-extension only. The pure-Python backend reaches `__len__` through a
plain truth test and already propagates, so this closes a divergence
rather than creating one. Plain `MultiDict(arg)` is unaffected on either
backend: its vectorcall path never probes the argument's length, so only
`extend()`, `update()`, `merge()` and subclass construction ever reached
the cleared branch.

## Are there changes in behavior for the user?

Yes, in an edge case. `extend()`, `update()`, `merge()` and subclass
construction now propagate a `MemoryError` or `KeyboardInterrupt` raised
by the argument's `__len__` instead of swallowing it. Arguments without
a
usable length, the common case for a generator, are unchanged.

## Is it a substantial burden for the maintainers to support this?

No. It applies the module's existing guard pattern to the one site that
still missed it.

## Related issue number

Findings from the C-extension analysis report #1306. This was the last
open item from that report; everything else in it is already fixed on
master, so #1306 can probably be closed once this lands.

## Checklist

- [x] I think the code is well written
- [x] Unit tests for the changes exist
- [x] Documentation reflects the changes (no public API change)
- [ ] N/A, no `CONTRIBUTORS.txt` in this repo
- [x] Add a new news fragment into the `CHANGES/` folder
- [x] `make doc-spelling` passes and any new technical words are added
to `docs/spelling_wordlist.txt`

Drafted with Claude Code (Opus 5); reviewed by @asvetlov.

<details>
<summary>Agent run details (optional, for reviewers)</summary>

Behaviour of an argument whose `__len__` raises `MemoryError`, before
and after, on both backends:

| | `MultiDict(x)` | subclass ctor | extend/update/merge |
| --- | --- | --- | --- |
| C ext, before | ok | swallowed | swallowed |
| C ext, after | ok | raises | raises |
| pure Python | raises | raises | raises |

The remaining `MultiDict(x)` column is a separate, pre-existing
difference: `_multidict_vectorcall_impl()` never calls
`PyObject_LengthHint()`, so there is no exception to swallow there. It
is
not an error-handling bug and is left alone here.

Tests, CPython 3.13.12:

- C extension build, `pytest tests -q`: 2198 passed, 21 skipped.
- Pure-Python build, installed with `MULTIDICT_NO_EXTENSIONS=1` into a
  clean copy of the tree and run with `--no-c-extensions`: 1097 passed,
  0 failed, 15 skipped. The same run on unmodified `master` gives 1083
  passed, 0 failed, 15 skipped; the difference is exactly the new
  pure-Python cases.

The new tests were checked against the unpatched parent commit built as
a C extension: `test_sizing_argument_does_not_swallow_exceptions` and
`test_subclass_construction_does_not_swallow_exceptions` fail there on
`cs-c` and `ci-c` and pass on the `-py` variants, so they do guard the
behaviour rather than passing vacuously.

New tests are parametrised over both backends, 28 cases. Checked the
coverage report for uncovered lines inside the new test bodies; an
unreachable `__iter__` on the `__len__`-raising stub was dropped because
`__len__` raises first.

Lint: `pre-commit run --files ...` on the touched files, ruff check,
ruff format, clang-format, MyPy 3.13 and 3.11 all pass.
`make doc-spelling`: build succeeded.

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

Labels

bot:chronographer:provided There is a change note present in this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants