Skip to content

Forbid direct instantiation of iterator types - #1377

Merged
asvetlov merged 14 commits into
aio-libs:masterfrom
devdanzin:fix/iterator-forbidden-new
Sep 5, 2026
Merged

asvetlov merged 14 commits into
aio-libs:masterfrom
devdanzin:fix/iterator-forbidden-new

Conversation

@devdanzin

Copy link
Copy Markdown
Contributor

What do these changes do?

type(iter(md.keys())).__new__(t) built an uninitialised iterator whose internal md pointer was NULL;
calling next() on it dereferenced NULL and segfaulted. The view types were given a forbidden tp_new
for exactly this reason in #1163; the iterator types share the hole. This adds the same forbidden
tp_new to the items/keys/values iterator specs. This is a C-extension-only concern (the pure-Python
iterators are ordinary Python objects); no pure-Python change is needed.

Are there changes in behavior for the user?

Yes: directly constructing an internal iterator type now raises
TypeError: cannot create '..._keysiter' instances directly instead of crashing. Normal iteration is
unaffected.

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

No. It mirrors the existing view-type fix (#1163).

Related issue number

Direct analog of #1163 (view types); same crash class as #1161. Surfaced by the analysis report #1306.

Checklist

  • I think the code is well written
  • Unit tests for the changes exist (test_iter_direct_instantiation_segfault)
  • 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

type(iter(md.keys())).__new__(t) built an uninitialised iterator whose md
pointer was NULL; calling next() on it dereferenced NULL and segfaulted.
The view types were given a forbidden tp_new in aio-libs#1163 for the same reason
(aio-libs#1161); the iterator types share the hole. Add the same forbidden tp_new
to the items/keys/values iterator specs.

Adds a C-extension regression test mirroring the view one.
@devdanzin
devdanzin requested a review from webknjaz as a code owner July 24, 2026 14:06
@devdanzin
devdanzin requested a review from asvetlov 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/iterator-forbidden-new (e2eaf3b) with master (1c227ee)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

No blocking failure remains.

Direct construction was exercised for keys, items, and values iterators, and each call raised TypeError; normal iteration also returned the expected values.

T-Rex T-Rex Logs

What T-Rex did

  • Ran the verification script to exercise direct instantiation of internal iterator types and observed TypeError on direct __new__ calls while ordinary iterators yielded the expected entries.
  • Ran the focused multidict regression test for iterator direct instantiation and it passed (1 passed in 0.27s).
  • The results confirm that the constructor guard rejects all three internal iterator types without affecting normal iteration.
  • Uploaded the authored before-script and the after-script outputs to trex-artifacts for review.

View all artifacts

T-Rex Ran code and verified through T-Rex

Reviews (4): Last reviewed commit: "[pre-commit.ci] auto fixes from pre-comm..." | Re-trigger Greptile

@asvetlov

asvetlov commented Sep 5, 2026

Copy link
Copy Markdown
Member

@aiolibsbot rr

@aiolibsbot

Copy link
Copy Markdown
Contributor

PR Review — Forbid direct instantiation of iterator types

The C fix is correct and complete; one stray line in the test file silently un-marks a neighbouring test and will break the pure-Python CI leg.

The C-side change is exactly right and I verified the parts that matter. git grep -n "Py_tp_new" across multidict/ now shows all six view and iterator types guarded, with no remaining PyType_Spec lacking a tp_new (istr, MultiDict, CIMultiDict and the proxies all have real ones). Normal iteration cannot regress, because multidict_items_iter_new/_keys_iter_new/_values_iter_new allocate via PyObject_GC_New (iter.h:30, :45, :60) and never route through tp_new. The types carry Py_TPFLAGS_IMMUTABLETYPE without Py_TPFLAGS_BASETYPE, so nothing subclasses them, and multidict_iter_methods exposes only __length_hint__, so no __reduce__ path depends on construction. The unused args/kwargs parameters are safe under the repo's -Wall -Werror flags (-Wunused-parameter needs -Wextra), and views.h already compiles the identical signature.

The PR's dual-backend claim also checks out: pure-Python _Iter (_multidict_py.py:49) is an ordinary __slots__ class whose uninitialised __next__ raises AttributeError rather than crashing, so declining to touch that backend is the right call and is stated explicitly, as AGENTS.md requires.

  • 🟡 tests/test_multidict.py:1468 — pytest.mark.c_extension is missing its @. The new test absorbed the decorator that master had on test_non_typeerror_exceptions_are_not_swallowed, so that test is now unmarked and gets collected under --no-c-extensions, where its MemoryError assertions do not hold. Neither ruff (only I/PLC0415/UP selected) nor coverage will flag it.
  • 🟢 multidict/_multilib/iter.h:178 — multidict_iter_forbidden_new is a verbatim copy of multidict_view_forbidden_new in views.h; both land in the same translation unit, so one shared helper in state.h would remove the duplicate outright.
  • 🟢 CHANGES/1377.bugfix.rst:1 — :issue:1161`` is the wrong link. Git history and the PR description both put the view fix at Fix segfault creating view objects #1163 (CHANGES/1164.bugfix.rst, commit `b5a24b7`).
  • 🟢 tests/test_multidict.py:1462 — the '.*' match drops the type-name assertion the companion view test makes; pinning _keysiter/_itemsiter/_valuesiter would catch a mis-wired slot table.

🟡 Important

1. Missing `@` turns the marker into a no-op and un-marks the neighbouring test
tests/test_multidict.py:1468

Line 1468 is a bare expression statement, not a decorator. The new test took over the @pytest.mark.c_extension that used to sit above test_non_typeerror_exceptions_are_not_swallowed, and the replacement line lost its @.

Verified against master: git grep -B2 "def test_non_typeerror_exceptions_are_not_swallowed" master -- tests/test_multidict.py shows the decorator at master:tests/test_multidict.py:1452. At the PR head, grep -n "pytest.mark.c_extension" tests/test_multidict.py returns 1427, 1452, and 1468 — only the first two are decorators.

Why it matters — this breaks the pure-Python CI leg:

  • tests/conftest.py:194 deselects items carrying the c_extension marker when --no-c-extensions is passed, and .github/workflows/ci-cd.yml:379 passes exactly that flag for the MULTIDICT_NO_EXTENSIONS matrix cell.
  • With the marker gone, test_non_typeerror_exceptions_are_not_swallowed is now collected against the pure-Python build, where its assertions do not hold. md.keys() <= BadLen() resolves to collections.abc.Set.__le__, which returns NotImplemented for a non-Set without ever calling len(other), so a TypeError propagates instead of the expected MemoryError. The next assertion fails too: _ItemsView.__contains__ (multidict/_multidict_py.py:79-81) short-circuits on not isinstance(item, (tuple, list)) and returns False without evaluating len(item).
  • Lint will not catch this. [tool.ruff.lint].select in pyproject.toml is limited to I, PLC0415, and UP, so bugbear's B018 (useless expression) is not enabled. Coverage will not catch it either, since the bare statement does execute at import time.

Fix: restore the decorator in place and drop the stray statement.

pytest.mark.c_extension


def test_non_typeerror_exceptions_are_not_swallowed() -> None:

🟢 Suggestions

2. `multidict_iter_forbidden_new` duplicates `multidict_view_forbidden_new` verbatim
multidict/_multilib/iter.h:178-186

This helper is byte-for-byte identical to multidict_view_forbidden_new at multidict/_multilib/views.h:1045-1052 — same parameters, same PyErr_Format, same message. The only difference is the name and the missing inline.

Both headers are compiled into the same translation unit (multidict/_multidict.c:7 and :11), and both already include state.h and dict.h, so a single shared helper would work without any include-graph change. Hoisting one multidict_forbidden_new into state.h (or dict.h) and referencing it from all six slot tables would delete the copy rather than relocate it.

Non-blocking: the duplication is small, but it is the second copy of a message string that a future wording change now has to be applied to twice.

static PyObject*
multidict_iter_forbidden_new(PyTypeObject* type, PyObject* args,
                             PyObject* kwargs)
{
    PyErr_Format(PyExc_TypeError,
                 "cannot create '%s' instances directly",
                 type->tp_name);
    return NULL;
}
3. `:issue:`1161`` points at the wrong reference for the view-type fix
CHANGES/1377.bugfix.rst:1

The fragment says the view types "were fixed in :issue:1161", but that is not the view fix. git log -S "multidict_view_forbidden_new" -- multidict/_multilib/views.h resolves to commit b5a24b7 — "Fix segfault creating view objects (#1163)", which shipped CHANGES/1164.bugfix.rst.

The PR description agrees with git history, not with the fragment: it states the view types got a forbidden tp_new "in #1163" and lists #1161 separately as the "same crash class". Towncrier renders :issue: as a live link, so as written the published changelog sends readers to the wrong place.

Suggest :issue:1163`` (the PR that fixed the view types), or drop the cross-reference and keep the prose comparison.

Fixed a segfault when constructing a multidict iterator type directly, e.g. ``type(iter(md.keys())).__new__(...)``. Such an iterator had a NULL internal pointer that ``next()`` dereferenced. The iterator types now forbid direct instantiation, the same way the view types were fixed in :issue:`1161`.
4. Loose `'.*'` match does not pin the iterator type name
tests/test_multidict.py:1462-1465

The companion test_view_direct_instantiation_segfault (lines 1430-1448) asserts the concrete type in each message (cannot create '.*_ItemsView' instances directly, and so on). This test relaxes that to '.*'.

Because iter_type is derived from the object under test, the loop passes as long as some forbidden tp_new fires — it would not notice if, say, two of the three specs were wired to the same slot table and one iterator type were left unguarded behind an alias. Pinning the names keeps the test honest about which of the three types it actually exercised.

A small mapping over the loop would do it:

for view_name, iter_name in (("keys", "_keysiter"), ("items", "_itemsiter"), ("values", "_valuesiter")):
    iter_type = type(iter(getattr(md, view_name)()))
    with pytest.raises(TypeError, match=f"cannot create '.*{iter_name}' instances directly"):
        iter_type.__new__(iter_type)  # type: ignore[call-overload]
    for view_name in ("keys", "items", "values"):
        iter_type = type(iter(getattr(md, view_name)()))
        with pytest.raises(TypeError, match="cannot create '.*' instances directly"):

Checklist

  • C fix covers all affected types (no remaining unguarded tp_new)
  • Normal iteration path unaffected by the new tp_new
  • Compiles under -Wall -Wconversion -Werror
  • Dual-backend discipline: pure-Python impact assessed and stated
  • New behaviour is exercised by a test
  • Test suite passes on both CI legs — warning #1
  • No pre-existing test coverage silently dropped — warning #1
  • Assertions pin observable behaviour specifically — suggestion #4
  • CHANGES fragment present, correctly categorised and signed
  • CHANGES fragment cross-references are accurate — suggestion #3
  • No duplicated helper where a canonical one exists — suggestion #2
  • PR description matches the diff (no scope creep)

To rebase and address feedback, mention me: @aiolibsbot rebase critical (fixes 🔴 only), @aiolibsbot rebase important (fixes 🔴 + 🟡), or @aiolibsbot rebase --fix for all. (A bare @aiolibsbot rebase only rebases onto the base branch.)


Automated review by Kōan (Claude) HEAD=4a61945 6 min 41s

Comment thread tests/test_multidict.py Resolved
Comment thread CHANGES/1377.bugfix.rst Resolved
@aiolibsbot

Copy link
Copy Markdown
Contributor

Rebase with requested adjustments

Branch fix/iterator-forbidden-new was rebased onto master and review feedback was applied.

Warning

Force-push safety check — the rewrite of fix/iterator-forbidden-new needs attention.

Commits whose patch changed in-flight and whose content could not be verified as preserved — check these survived:

  • 19f843a Forbid direct instantiation of iterator types
  • ee22955 [pre-commit.ci] auto fixes from pre-commit.com hooks
  • 6f341fe [pre-commit.ci] auto fixes from pre-commit.com hooks
  • 00a3c23 Merge branch 'master' into fix/iterator-forbidden-new
  • cbdbef5 Merge branch 'master' into fix/iterator-forbidden-new

Previous PR head: 4a61945b649a8f30cc30ff81f5ba8b6e646c19b5 — everything it contained is recoverable: git fetch origin 4a61945b649a8f30cc30ff81f5ba8b6e646c19b5 && git switch -c koan-prerebase-4a61945b649a FETCH_HEAD

Changes applied

  • All four review points addressed. Both backends pass.
  • Removed a duplicate test_iter_direct_instantiation_segfault at the end of tests/test_multidict.py (warning #1). A pre-commit auto-fix commit had left a second, shadowing copy carrying the old loose assertions; mypy flagged it no-redef, and Python bound the later definition, so the earlier one never ran.
  • Pinned the iterator type names in the test (suggestion #4): the loop now maps each view to its concrete iterator (_keysiter, _itemsiter, _valuesiter) and matches cannot create '.*<name>' instances directly, matching the style of test_view_direct_instantiation_segfault.
  • Corrected the news fragment cross-reference from :issue:1161 to `:issue:`1163 (suggestion #3). Confirmed by git log -S "multidict_view_forbidden_new" -- multidict/_multilib/views.h → b5a24b7 Fix segfault creating view objects (#1163).
  • Deduplicated the forbidden tp_new helper (suggestion #2). Reusing multidict_view_forbidden_new from iter.h directly is not possible: views.h depends on iter.h for multidict_itemsview_iter, so including it the other way is circular. Instead the identical body now lives once as multidict_forbidden_new in dict.h, the shared header both already include; both copies deleted and all six slot entries repointed.
  • Verification (not requested, but rule zero):
  • Rebuilt the C extension with the project's own flags; clean.
  • pytest tests/ → 1718 passed (C extension); `--no-c-exte

Stats

5 files changed, 40 insertions(+), 13 deletions(-)
Actions performed
  • Already-solved check: negative (confidence=high, reasoning=Master has forbidden tp_new only on view types in views.h; iter.h iterator specs still lack it and n)
  • Resolved merge conflicts (2 round(s))
  • Rebased fix/iterator-forbidden-new onto upstream/master
  • Applied review feedback
  • Pre-push CI check: previous run still pending
  • Force-pushed fix/iterator-forbidden-new to origin
  • Private review gate skipped: disabled by config
  • Force-push guard: original PR content was dropped, modified, or raced — see the warning at the top of this comment
  • CI check enqueued in ## CI (async)

CI status

CI will be checked asynchronously.


Automated by Kōan

Comment thread tests/test_multidict.py Resolved
@asvetlov

asvetlov commented Sep 5, 2026

Copy link
Copy Markdown
Member

@aiolibsbot rv

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

asvetlov commented Sep 5, 2026

Copy link
Copy Markdown
Member

@aiolibsbot rv

@codecov

codecov Bot commented Sep 5, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.86%. Comparing base (1c227ee) to head (e2eaf3b).

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #1377   +/-   ##
=======================================
  Coverage   99.86%   99.86%           
=======================================
  Files          29       29           
  Lines        3756     3763    +7     
  Branches      279      280    +1     
=======================================
+ Hits         3751     3758    +7     
  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.

@asvetlov
asvetlov merged commit 8f0f754 into aio-libs:master Sep 5, 2026
56 of 57 checks passed
@asvetlov

asvetlov commented Sep 5, 2026

Copy link
Copy Markdown
Member

@devdanzin thanks again!

asvetlov added a commit that referenced this pull request Sep 25, 2026
…TANTIATION (#1595)

<!-- Thank you for your contribution! -->

## What do these changes do?

The C view types (`_ItemsView`, `_KeysView`, `_ValuesView`) and the
three iterator types blocked direct instantiation with hand-written
`tp_new` slots that just raised `TypeError`. CPython has provided
`Py_TPFLAGS_DISALLOW_INSTANTIATION` for exactly this since 3.10, the
project minimum, so the slots and their helpers are replaced by the
flag. The dead `PY_VERSION_HEX >= 3.10` guards around
`Py_TPFLAGS_IMMUTABLETYPE` in the same specs are dropped too.

The types were already final (no `Py_TPFLAGS_BASETYPE`); a new test
locks that in. The pure-Python backend has no equivalent types, so it is
unaffected.

## Are there changes in behavior for the user?

Only the error text: `cannot create '..._KeysView' instances directly`
became CPython's `cannot create '..._KeysView' instances`. On 3.10,
`T.__new__(T)` is refused by `object.__new__`'s safety check with
`object.__new__(T) is not safe` instead.

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

No, it removes code.

## Related issue number

Follow-up to #1163 and #1377.

## Checklist

- [x] I think the code is well written
- [x] Unit tests for the changes exist
- [x] Documentation reflects the changes (N/A, private types)
- [ ] If you provide code modification, please add yourself to
`CONTRIBUTORS.txt` (N/A)
- [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 (Claude Opus 5.5); reviewed by @asvetlov.

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

Tests, rebased on 27fec2d:
- C extension, CPython 3.10.17: 2771 passed, 170 skipped
- C extension, CPython 3.14.7t: 2758 passed, 183 skipped
- Pure Python (`MULTIDICT_NO_EXTENSIONS=1 --no-c-extensions`), 3.10.17,
clean tree copy: 1301 passed, 17 skipped

Lint: pre-commit on the changed files passed. `make doc-spelling`
passed.
Not verified locally: PyPy (whether cpyext honours
`Py_TPFLAGS_DISALLOW_INSTANTIATION`).
</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.

4 participants