Skip to content

Fix segfault from an uninitialised MultiDict/CIMultiDict created via __new__ - #1378

Merged
asvetlov merged 8 commits into
aio-libs:masterfrom
devdanzin:fix/uninitialized-container-proxy
Sep 5, 2026
Merged

asvetlov merged 8 commits into
aio-libs:masterfrom
devdanzin:fix/uninitialized-container-proxy

Conversation

@devdanzin

Copy link
Copy Markdown
Contributor

What do these changes do?

MultiDict.__new__(MultiDict) (or a subclass that skips super().__init__()) left md->state and
md->keys as NULL, and the first method call dereferenced them and segfaulted. The container now has a
tp_new that initialises the object to a valid empty state (state set, keys = the shared
&empty_htkeys sentinel), with is_ci derived from the type so CIMultiDict stays case-insensitive.
The sentinel is not heap-allocated, so the md_init() that tp_init runs on normal construction does
not leak.

Scope: this fixes the container types. The proxy types (MultiDictProxy/CIMultiDictProxy) have the
same latent issue (self->md left NULL by __new__) but need a different fix (moving argument
validation into tp_new); I'll send that as a follow-up rather than fold a construction-protocol change
in here. The pure-Python backend raises AttributeError for the same __new__-without-__init__ case
(no crash); aligning it to also yield a valid empty mapping can be a small follow-up if you'd prefer
exact parity.

Are there changes in behavior for the user?

Yes (mild): MultiDict.__new__(MultiDict) and subclasses that skip super().__init__() now behave as a
valid empty mapping instead of crashing.

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

No. One tp_new function shared by both container types.

Related issue number

Generalises the point fixes #1159 (setdefault) and #1161/#1163 (view types) to the containers.
Surfaced by the analysis report #1306.

Checklist

  • I think the code is well written
  • Unit tests for the changes exist (test_new_without_init_is_valid_empty, both container types + a subclass)
  • 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

MultiDict.__new__(MultiDict) (or a subclass skipping super().__init__())
left md->state and md->keys as NULL, and the first method call dereferenced
them.  Give the container a tp_new that initialises the object to a valid
empty state (state set, keys = the shared &empty_htkeys sentinel), with is_ci
derived from the type so CIMultiDict stays case-insensitive.  The empty
sentinel is not allocated, so the md_init() done later by tp_init on normal
construction does not leak.

Adds a C-extension regression test over both container types and a subclass
that skips super().__init__().

Note: the proxy types have the same latent issue (self->md left NULL) and
will be addressed separately.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Jul 24, 2026
Comment thread tests/test_multidict.py Dismissed
@codspeed

codspeed Bot commented Jul 24, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 248 untouched benchmarks


Comparing devdanzin:fix/uninitialized-container-proxy (9581fbe) with master (8f0f754)

Open in CodSpeed

@Vizonex
Vizonex self-requested a review July 24, 2026 18:14

@Vizonex Vizonex left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@devdanzin As long as the spelling mistakes are changed we can move forward with this PR.

Comment thread multidict/_multidict.c Resolved
@asvetlov

asvetlov commented Sep 5, 2026

Copy link
Copy Markdown
Member

@copilot resolve the merge conflicts in this pull request

1 similar comment
@asvetlov

asvetlov commented Sep 5, 2026

Copy link
Copy Markdown
Member

@copilot resolve the merge conflicts in this pull request

@greptile-apps

greptile-apps Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 4/5

Not ready to merge: directly constructed proxy objects can still terminate the Python process on first use.

One actionable non-security failure remains in the C-extension proxy construction path.

Files Needing Attention: multidict/_multidict.c

T-Rex T-Rex Logs

What T-Rex did

  • T-Rex produced a validation proof for a posted P1 finding, supported by the Runtime validation harness source and the current candidate execution output.
  • T-Rex produced a second finding-proof for another posted P1 finding.
  • T-Rex executed the general contract validation harness and reported PASS on multidict-direct-new, cimultidict-direct-new, multidict-subclass-skips-init, and cimultidict-subclass-skips-init, followed by a segmentation fault when len() was called on the direct __new__ proxy instances, confirming unsafe direct proxy behavior while the new initialization path works.

View all artifacts

T-Rex Ran code and verified through T-Rex

Comments Outside Diff (1)

  1. multidict/_multidict.c, line 1192 (link)

    P1 Uninitialized proxy backing pointer crashes reads

    MultiDictProxy.__new__(MultiDictProxy) and CIMultiDictProxy.__new__(CIMultiDictProxy) still produce instances whose md pointer is unset. Calling len() immediately dereferences that pointer and terminates the interpreter with SIGSEGV. Initialize proxies to a valid backing mapping in tp_new, or reject direct construction before proxy methods dereference md.

    Artifacts

    Runtime validation harness source

    • This exact harness executes each C-extension construction case in an isolated child process so segmentation-fault exit codes are captured without terminating the validation run.

    Current candidate execution output

    • This captured command output shows all four new `MultiDict`/`CIMultiDict` initialization cases pass while both uninitialized proxy `len()` calls segfault with exit code `-11`.

    View 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

Comment thread CHANGES/1378.bugfix.rst Resolved
@asvetlov

asvetlov commented Sep 5, 2026

Copy link
Copy Markdown
Member

@aiolibsbot rr

@aiolibsbot

Copy link
Copy Markdown
Contributor

@asvetlov: @copilot resolve the merge conflicts in this pull request

Conflicts resolved. Merge commit 366da84 brings in master through 09063b3. Tree clean, no conflict markers present.

@aiolibsbot

Copy link
Copy Markdown
Contributor

PR Review — Fix segfault from an uninitialised MultiDict/CIMultiDict created via __new__

Correct, minimal fix for a real segfault. Merge-ready; three non-blocking suggestions.

What is solid here, specifically:

  • The no-leak argument in the PR body holds up under inspection. tp_new sets keys = &empty_htkeys, and both tp_init paths that follow (md_init at _multidict.c:570 and md_clone_from_ht via _multidict_clone_fast) call md_clear, which short-circuits on the empty_htkeys sentinel rather than freeing it. No double-allocation, no leak.
  • Deriving is_ci from the type with PyType_IsSubtype is the right call: cimultidict_slots has no Py_tp_new of its own (line 1073), so CIMultiDict inherits this one, and the derivation is what keeps it case-insensitive.
  • The new function mirrors the existing istr_new (_multilib/istr.h:31) module-lookup pattern exactly, so it reads as native to the file rather than bolted on.
  • Scope discipline is real, not just claimed: MultiDictProxy still carries {Py_tp_new, PyType_GenericNew} at line 1323, matching the follow-up note in the description.
  • Test gating is right. @pytest.mark.c_extension is deselected by --no-c-extensions, which ci-cd.yml:379 passes on the pure-Python leg, so the C-only test will not fail there.

On @Vizonex's changes-requested: the spelling blocker looks cleared. @asvetlov's fragment suggestion was applied verbatim in 39487b5, and dereferenced landed in docs/spelling_wordlist.txt:35 via #1418, which this branch picked up in the master merge (366da84). segfault is unlisted but already appears in merged CHANGES/1405.misc.rst, and NULL is skipped by sphinxcontrib-spelling's acronym filter.

Remaining points, all non-blocking:

  • Pure-Python MultiDict still raises AttributeError for the same construction (__slots__, fields set only in __init__), so the backends now diverge; pin the current behaviour with a test and link the follow-up issue.
  • The Sub subclass in the new test never checks case-insensitivity, so the PyType_IsSubtype subclass path it exists to protect is not actually asserted.
  • multidict_copy (line 237) still allocates via PyType_GenericNew, so the new invariant is guaranteed at one allocation site but not the other; a shared multidict_alloc_empty helper would consolidate it.

I did not build the extension myself; compilation is evidenced by CodSpeed's 248-benchmark run and Greptile's T-Rex build on this head.


🟢 Suggestions

1. Backends now diverge on `__new__`-without-`__init__`; pin it with a test or file the follow-up
multidict/_multidict_py.py:616

Verified: MultiDict here uses __slots__ = ("_keys", "_used", "_version") and only assigns them in __init__, so MultiDict.__new__(MultiDict) leaves all three unset and the first method call raises AttributeError. After this PR the C extension returns a usable empty mapping for the same construction.

Why it matters: AGENTS.md states the two implementations "must stay behaviourally identical", and the same code now works on the wheel build and raises on the pure-Python leg (PyPy, MULTIDICT_NO_EXTENSIONS=1, platforms without a wheel). The PR body calls the divergence out, which satisfies the "do not silently leave the implementations divergent" half of the rule, but there is no follow-up issue linked and nothing in the suite records the current pure-Python behaviour.

The scoping decision itself looks defensible: a Python-level __new__ on MultiDict would add a call to every construction on a hot path, which is a worse trade than the C-side tp_new (free, since tp_alloc already ran). Suggested minimum before merge:

  • Add a companion test asserting AttributeError (or pytest.raises) for MultiDict.__new__(MultiDict) on the pure-Python module, so the divergence is documented in the suite rather than only in the PR body.
  • Link the follow-up issue number in the description so the parity question does not get lost.
    __slots__ = ("_keys", "_used", "_version")

    def __init__(self, arg: MDArg[_V] = None, /, **kwargs: _V):
        self._used = 0
2. Subclass case exercises `len`/`get` but not the `is_ci` derivation it is there to protect
tests/test_multidict.py:1474-1481

The trickiest line in the new tp_new is bool is_ci = PyType_IsSubtype(type, state->CIMultiDictType) (multidict/_multidict.c:599). The test covers case-insensitivity only for the exact CIMultiDict type (lines 1469-1472), and the Sub block only asserts len(s) == 0 and s.get("missing") is None.

Why it matters: PyType_IsSubtype is precisely what makes a subclass of CIMultiDict come out case-insensitive. If someone later simplified it to Py_IS_TYPE(type, state->CIMultiDictType), every CIMultiDict subclass would silently become case-sensitive and this test would still pass. The subclass path is the one the exact-type assertions cannot cover.

Two lines close it:

    s = Sub()
    assert len(s) == 0
    assert s.get("missing") is None
    s["A"] = "1"
    assert (s["a"] == "1") is (cls_name == "CIMultiDict")

That also keeps both parametrized legs meaningful rather than adding a third if cls_name == ... branch.

    class Sub(cls):  # type: ignore[valid-type, misc]
        def __init__(self) -> None:
            pass

    s = Sub()
    assert len(s) == 0
    assert s.get("missing") is None
3. The "valid empty state" invariant now lives in two allocation sites
multidict/_multidict.c:586-608

multidict_tp_new establishes the invariant "an allocated MultiDictObject always has non-NULL state/keys", but multidict_copy at line 237 still allocates through PyType_GenericNew(Py_TYPE(self), NULL, NULL) and bypasses it, relying on md_clone_from_ht to fill the struct in.

Not a defect today: I checked md_clone_from_ht (_multilib/hashtable.h:355) and its md_clear call short-circuits on md->keys == NULL, and PyMem_Malloc between the alloc and the fill-in cannot trigger a GC pass, so the tracked-but-uninitialised window is safe. But this is the exact shape of the bug being fixed here: one allocation path guarantees the invariant, another does not, and md_clear's NULL branch exists only to tolerate the second.

Structural remedy, if you want it in a follow-up alongside the proxy fix: extract the PyType_GetModuleByDef + tp_alloc + md_init(..., 0) body into a multidict_alloc_empty(PyTypeObject* type) helper, call it from both multidict_tp_new and multidict_copy, and the NULL-keys tolerance in md_clear becomes provably dead rather than load-bearing.

Also worth noting for the record: the md_init(self, state, is_ci, 0) < 0 branch is unreachable with minused == 0 (md_init only allocates when minused > USABLE_FRACTION(HT_MINSIZE)), so it is defensive-only. Keeping it matches the other call sites; no change needed.

    MultiDictObject* self = (MultiDictObject*)type->tp_alloc(type, 0);
    if (self == NULL) {
        return NULL;
    }
    if (md_init(self, state, is_ci, 0) < 0) {

Checklist

  • Memory safety: no NULL deref, no leak, no double-free on the new path
  • Error paths handled (module lookup failure, tp_alloc failure, md_init failure)
  • Dual-backend parity (AGENTS.md) — suggestion #1
  • New behaviour covered by tests, both parametrized legs meaningful — suggestion #2
  • CHANGES fragment: correct category, past tense, signed, spell-check clean
  • No backward-incompatible change to public API or construction protocol
  • Diff matches the PR description; no scope creep
  • Change leaves the surrounding construction code no messier — suggestion #3

Automated review by Kōan (Claude) HEAD=366da84 6 min 37s

@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 (8f0f754) to head (c125f0a).

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #1378   +/-   ##
=======================================
  Coverage   99.86%   99.86%           
=======================================
  Files          29       29           
  Lines        3763     3784   +21     
  Branches      280      281    +1     
=======================================
+ Hits         3758     3779   +21     
  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.

@aiolibsbot

Copy link
Copy Markdown
Contributor

Rebase with requested adjustments

Branch fix/uninitialized-container-proxy was rebased onto master and review feedback was applied.

Warning

Force-push safety check — the rewrite of fix/uninitialized-container-proxy needs attention.

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

  • 9ebfe5c Fix segfault from uninitialised MultiDict/CIMultiDict via __new__
  • 642a95d Merge branch 'master' into fix/uninitialized-container-proxy

Previous PR head: 366da849e709758b1415d8280b727dde1e88206e — everything it contained is recoverable: git fetch origin 366da849e709758b1415d8280b727dde1e88206e && git switch -c koan-prerebase-366da849e709 FETCH_HEAD

Changes applied

  • Two edits applied.
  • Replaced bare d["k"] subscript with d.__getitem__("k") inside pytest.raises(KeyError) (tests/test_multidict.py:1502), per CodeQL "Statement has no effect" (alert 273). Call form matches the existing md.items().__contains__(...) style in this file and keeps the same __getitem__ coverage.
  • Added subclass case-insensitivity assertion to test_new_without_init_is_valid_empty per automated-review suggestion Python MultiDict constructor discards generator content #2: s["A"] = "1" then assert s.get("a") == ("1" if cls_name == "CIMultiDict" else None). Locks in the PyType_IsSubtype(type, state->CIMultiDictType) derivation at multidict/_multidict.c:599; a regression to Py_IS_TYPE would now fail. Used .get() with a value comparison rather than the reviewer's literal assert (s["a"] == "1") is (cls_name == "CIMultiDict"), which would raise KeyError on the MultiDict leg instead of evaluating to False. Single expression, no untaken branch, both parametrized legs meaningful.

Not changed (and why)

  • asvetlov's CHANGES/1378.bugfix.rst suggestion (initializes): already applied verbatim in 39487b5; fragment on HEAD already reads initializes. dereferenced whitelisting landed separately via Add 'dereferenced' to spelling whitelist #1418, merged in 366da84.
  • Vizonex's CHANGES_REQUESTED review ("as long as the spelling mistakes are changed"): covered by the two commits above; no code change outstanding.
  • Vizonex's C-API capsule comment (_multidict.c:610): discussion, not a change request. Already answered inline.
  • Automated-re

Stats

3 files changed, 65 insertions(+), 1 deletion(-)
Actions performed
  • Already-solved check: negative (confidence=high, reasoning=Master still uses PyType_GenericNew for the container types and has no test or CHANGES fragment fo)
  • Resolved merge conflicts (1 round(s))
  • Rebased fix/uninitialized-container-proxy onto upstream/master
  • Applied review feedback
  • Pre-push CI check: previous run passed
  • Force-pushed fix/uninitialized-container-proxy 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

@bdraco

bdraco commented Sep 5, 2026

Copy link
Copy Markdown
Member

It has no write access so commits land on its fork and have to be cherry picked or merged in by a human

@asvetlov

asvetlov commented Sep 5, 2026

Copy link
Copy Markdown
Member

@aiolibsbot rv

@asvetlov
asvetlov merged commit b36706a into aio-libs:master Sep 5, 2026
55 of 57 checks passed
@asvetlov

asvetlov commented Sep 5, 2026

Copy link
Copy Markdown
Member

@devdanzin thanks!

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.

Segfault calling MultiDict().setdefault()

6 participants