Repository navigation
Add a public C API capsule, with optional Cython support - #1480
Conversation
Covers type checks and constructors for MultiDict, CIMultiDict, MultiDictProxy, CIMultiDictProxy and istr, getversion() and len() for the first four, and add(), clear(), setdefault() and single-item access (in, [], del, pop()) for the mutable types. GetItem, Pop and SetDefault follow the PyDict_GetItemRef / PyDict_SetDefaultRef design, reporting a missing key through the return code rather than an exception.
Visits every (key, value) pair, or just the entries for one key (the getall() equivalent), through a callback rather than building a list. Also moves MultiDict_Size ahead of MultiDict_Contains/GetItem in the getters group, trims a redundant note from the visitor callback docs, and parametrizes tests/test_capi.py to cut duplicate wrong-type and type-check tests.
Ships multidict/__init__.pxd so third-party Cython code can cimport multidict, and multidict/_testcyapi.pyx, a Cython mirror of _testcapi.c that exercises the capsule from tests/test_capi.py's existing suite through a new api fixture parametrized across both the C and Cython bindings. Cython is never a real dependency of multidict: pyproject.toml's [build-system] requires still only lists setuptools, so an ordinary install or a cibuildwheel-isolated release build never sees Cython and multidict._testcyapi is silently skipped. Opting in locally needs pip install -r requirements/cython.txt followed by pip install -e . --no-build-isolation (or make install-dev-cython); a new CI job exercises this path. Set MULTIDICT_TEST_REQUIRE_CYAPI=1 to turn a missing _testcyapi into a hard test failure instead of a skip, for that job. Also adds docs/cyapi.rst, extends AGENTS.md's "Public C API" section, and updates the CHANGES fragment for the capsule feature.
Merging this PR will degrade performance by 9.07%
|
| Benchmark | BASE |
HEAD |
Efficiency | |
|---|---|---|---|---|
| 👁 | test_keys_view_is_disjoint[cs-c] |
73.7 µs | 81.1 µs | -9.07% |
Comparing asvetlov:worktree-capsule-capi-core (67f867f) with master (7d74f3e)
|
@Vizonex this PR is heavily based on your previous work. |
|
This comment has been minimized.
This comment has been minimized.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #1480 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 38 40 +2
Lines 6455 6761 +306
Branches 591 594 +3
==========================================
+ Hits 6455 6761 +306
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
…se pathlib multidict/_testcapi.c's istr_type/md_type/cimd_type/mdproxy_type/ cimdproxy_type each leaked one reference to the returned type object per call: the capsule's *_GetType functions already return a new reference, and wrapping that in another Py_NewRef incremented it a second time without ever releasing the first (caught by automated review on the open PR). tests/test_capi.py's test_get_type and test_istr_type now loop each getter and assert the refcount is unchanged, so a regression here fails the suite instead of only showing up as slow memory growth. Also: - MANIFEST.in excludes the Cython-generated multidict/_testcyapi.c/ .html, which otherwise leaks into the sdist whenever the optional Cython build has been run locally beforehand. - CHANGES/1478.feature.rst is a short two-line summary crediting Vizonex's original C API work alongside this PR's, matching the precedent in CHANGES/1183.feature.rst. - tests/test_get_include.py and multidict.get_include() use pathlib instead of os.path. - ci-cd.yml's test-cython-capi, asan and tsan jobs now collect coverage like the rest of the matrix instead of passing --no-cov, closing the one branch in test_capi.py (whether Cython was opted into the build) that no coverage-collecting job ever exercised. tsan's custom free-threaded CPython build ignores coverage.exceptions.CoverageWarning, since coverage's C tracer can fail to load against a from-source build like that and pytest.ini's filterwarnings=error would otherwise turn the fallback into a hard failure.
…idict into worktree-capsule-capi-core
Master's own MANIFEST.in cleanup (merged into this branch) dropped the explicit \`include multidict/*.c\` line as redundant with \`graft multidict\`; update the comment on the new _testcyapi.c/.html excludes to point at the line that actually matches hand-written .c files now.
Mirrors .gitignore's Cython-generated multidict/*.html and _testcyapi.c entries, and adds .venv*/ so ad-hoc dev virtualenvs like .venv-capi/.venv-purepy2 (hundreds of MB of installed packages, not source) don't end up in context.
MultiDict_CAPI now starts with an api_version field, set to MultiDict_CAPI_VERSION (currently 1) when the capsule is created. The struct's existing append-only growth already protects a client built against an older header running against a newer multidict runtime; this guards the opposite direction, where a client built against a newer header (expecting fields a smaller, older-allocated struct never had) would otherwise read past the end of the struct. MultiDict_GetCAPI() checks the imported capsule's api_version against MultiDict_CAPI_VERSION and, on mismatch, sets a RuntimeError and returns NULL instead of handing back an unsafe pointer. The check lives in a small internal helper, _MultiDict_CheckAPIVersion, so it can be exercised directly from multidict/_testcapi.c against a deliberately-corrupted copy of the struct without needing a second capsule or a real version bump to test against.
Both sanitizer jobs are already the slowest legs in the matrix; collecting coverage on top of that isn't worth the extra time. The test-cython-capi job keeps it, since that's the one build that actually exercises the Cython-available branch in test_capi.py's fixture setup.
Every wrapper function declared in the .pxd takes a MultiDict_CAPI* as its first argument, so third-party Cython code (and our own _testcyapi.pyx) had to import multidict, call MultiDict_GetCAPI(), and thread the result through every single call by hand. capi() does that once and caches the pointer, so callers can just write e.g. MultiDict_New(capi(), 2). It has to be a plain `cdef extern` C function with a `static` local for the cache rather than a Cython-level cdef inline function sharing a module-level cdef variable: multidict/__init__.pxd has no compiled .pyx of its own (multidict/__init__.py is plain Python), so there's no multidict.__pyx_capi__ for Cython to link such a variable against across cimporting modules -- confirmed by trying the Cython-level version first and hitting exactly that AttributeError at import time. _testcyapi.pyx now uses capi() instead of its own module-level MultiDict_GetCAPI() call, and docs/cyapi.rst's example and notes are updated to match.
Tried it again directly: a cdef variable at the top level of a package's __init__.pxd compiles fine, but every cimporting module generates a runtime multidict.__pyx_capi__ lookup for it (confirmed in the generated C -- the reading function is a genuine static-inline function, but the variable it touches is an indirect pointer resolved via PyObject_GetAttrString at that module's own import time), which fails since multidict/__init__.py is plain Python and never populates that attribute. Expands the comment with what was actually observed.
Vizonex
left a comment
There was a problem hiding this comment.
Glad to see us coming back to this. I had worked several months on this on in particular and was quite disappointed to not see any further progress. The problem with last time was that we were having trouble triggering the tests but hopefully this time this won't be a problem. This should speedup aiohttp with parsing and writing requests and I don't think this will be a burden for new contributors.
Drops the capi() caching helper added in 273d679/a231c8b along with its per-subinterpreter-safety follow-up (never committed). Back to the original design: multidict/__init__.pxd mirrors multidict_capi.h 1:1 with an explicit MultiDict_CAPI *capi first parameter, and _testcyapi.pyx fetches it once into a module-level _capi and threads it through by hand.
MultiDict_ForEach's key is a raw PyObject* where NULL means "visit every item", which has no object equivalent that wouldn't also risk colliding with an actual None key. MultiDict_ForEachAll and MultiDict_ForEachKey split the two cases into their own signatures in multidict/__init__.pxd so ordinary Cython callers never touch a raw pointer or a NULL sentinel; _testcyapi.pyx's md_foreach now uses them. Also drops two comments that just restated the code they sit above.
…ename master (aio-libs#1505, aio-libs#1510) replaced the MD_HASH_MARK-based keyed walk with a bitmap-tracked finder and dropped the md_ prefix from _multilib's private names, since the directory is already namespaced. Follow both: md_readonly_finder_t/_init/_find_next/_cleanup become the unified finder_t/finder_init/find_next/finder_cleanup (the bitmap approach needs no separate readonly variant, since it never marks the table), and md_deferred_decref_t/_init/_release become deferred_decref_t/_init/ _release. Also updates two comments left stale by the same upstream change: capsule.h's and docs/capi.rst's reentrancy notes described a keyed walk that could hide matches by reentering marked entries. The bitmap finder never marks the table; the actual guard against reentrant mutation is the version check both md_next and find_next already perform, raising "MultiDict is changed during iteration" instead.
Mirrors the labeling CPython's own C API documentation uses for dict: a short "Thread safety" section defines the two levels this API actually needs (Atomic for calls touching no state shared with any other MultiDict instance; Safe for concurrent use on the same object for calls that read or mutate self's contents through a lock-free path or self's own critical section), then every function gets a one-line note under its signature. MultiDict_GetVersion gets its own precise wording instead of the canned phrase: it reads self->version without taking a lock or an atomic load, so it is a best-effort change-detection hint rather than a synchronized read.
…idict into worktree-capsule-capi-core
… fix master (aio-libs#1514) made md_version() an atomic relaxed read, matching md_len(). Update the note and the Atomic bucket's definition in the new Thread safety section accordingly, since it previously described this counter as a best-effort, unsynchronized read that is no longer accurate.
Vizonex
left a comment
There was a problem hiding this comment.
Nothing to complain about now. I like this and I hope other developers will enjoy using it too. I had some ideas for ls-hpack which is another C Library that packs http2 frames and utilizing multidict with it would enhance it's speed so know that I have some ideas for this C-API outside of aiohttp in general.
|
I'm sure the codspeed problem might be from the updated patches and bug fixes. But as far as I'm aware That should be an ignorable problem caused by branches not being updated |
|
Were very close, |
Upstream's aio-libs#1522 replaced finder_t/find_next()/finder_cleanup() with a single md_walk() callback, and aio-libs#1518 renamed md_version() to load_version(). _md_foreach_key() now calls md_walk() directly, since its visitor signature already matches MultiDict_ItemVisitor, and MultiDict_GetVersion() calls load_version(). No behavior change.
|
ok, let's merge |
|
aiohttp probably should stay with conditional logic for a while; use CAPI if available with fallback to python method calls |
|
@asvetlov Thank you. I have been waiting for this for over a year now, glad to see our work finally accomplished. |
<!-- Thank you for your contribution! --> ## What do these changes do? The `ForEach` visitor received the key and the value but not the identity, the canonical key a multidict actually looks entries up by. On a `CIMultiDict` that is the internal lower-cased form, so a visitor wanting to group or compare entries by it had to derive it again itself, duplicating work the walk had already done. `MultiDict_ItemVisitor` now takes `(void *user_data, PyObject *identity, PyObject *key, PyObject *value)`. `user_data` stays first so existing call sites keep their shape, and the identity goes next to the key and value it belongs with rather than at the end. `MultiDict_CyItemVisitor` gains it in the same position, keeping its own `user_data`-last order. The internal `md_item_visitor_t` in `_multilib/walk.h` is widened to match, along with `md_walk_all`, `md_walk_with_hash` and their two in-tree visitors. The two walks source it differently. `md_walk_with_hash` passes the identity it was already handed, which every matched entry compares equal to by the walk's own predicate, so the keyed path does no extra work. `md_walk_all` reads `entry->identity` and holds a reference across the visitor call, the same way it already does for the value, since `_md_ensure_key()` and the visitor can both run Python code that frees the entry. The capsule is unreleased: it landed in #1480, after v6.9.1, and `MultiDict_CAPI_VERSION` is still 1, so no client can have been built against the narrower signature. That is why the typedef changes in place instead of growing a parallel entry point at the end of the struct with a version bump. ## Are there changes in behavior for the user? No, for Python-level users. A C or Cython client of the capsule has to take the extra parameter, but the capsule has not shipped in a release yet, so there is nothing to migrate. ## Is it a substantial burden for the maintainers to support this? No. Both walks already have the identity in hand, so the wider signature costs nothing on the keyed path and one reference pair per entry on the all-entries path. One benchmark row does move, and it is worth a reviewer's attention. `d.pop(key)` gets slower on GIL builds: measured on `CPython 3.14.7`, MultiDict 428.8 to 441.5 instructions (+2.96%) and CIMultiDict 713.5 to 726.2 (+1.78%). Every other row is bit-identical, and the free-threaded build is unaffected. The cause is not the walk; it is GCC's inlining budget in `hashtable.h`. Widening `_md_getall_visit` by one parameter is enough to tip `htkeysiter_init` out of line inside `md_pop_one`, which `objdump` confirms as a new `call <htkeysiter_init>` on the GIL build and not on the free-threaded one. An `ALWAYS_INLINE` on `htkeysiter_init` removes it, and wins well beyond `pop` because GCC already outlines that helper in several places on master. That belongs in its own pull request, with its own numbers, and is left out of this one deliberately. `docs/benchmark.rst` is not regenerated here on purpose. The `dict` control rows in this environment reproduce the committed tables exactly on both builds (`d.pop(key)` 476.4 against a published 476 on the GIL build, 587.4 against 587 free-threaded), but every `multidict` row differs by a few percent (446 published against 428.8 measured on the GIL build, 562 against 548.8 free-threaded). The interpreter matches and the compiler does not, so regenerating would rewrite every `multidict` row for toolchain reasons unrelated to this change. Calling the one moved row out in prose seemed better than that. ## Related issue number None; this came out of a session looking at the `ForEach` walks. ## Checklist - [x] I think the code is well written - [x] Unit tests for the changes exist - [x] Documentation reflects the changes - [ ] If you provide code modification, please add yourself to `CONTRIBUTORS.txt` - [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` <details> <summary>Agent run details (optional, for reviewers)</summary> Tests, each in its own virtualenv against its own copy of the tree, so a stale `.so` cannot make a leg lie: ``` CPython 3.13.12, C extension 2542 passed, 21 skipped CPython 3.13.12, MULTIDICT_NO_EXTENSIONS=1 --no-c-extensions 1180 passed, 17 skipped, 1189 deselected CPython 3.14.7t, free-threaded 2531 passed, 32 skipped CPython 3.10.17, oldest supported 2542 passed, 21 skipped ``` Every leg that has a C extension built the Cython harness too and ran with `MULTIDICT_TEST_REQUIRE_CYAPI=1`, so the `_testcyapi` half of `tests/test_capi.py` is a hard failure rather than a skip. Lint: `pre-commit run --all-files` passes, including `clang-format` and both `mypy` hooks. `make doc-spelling` passes. Benchmarks: `benchmarks/callgrind_driver.py`, bracketed (`pytest-codspeed` installed so the instrumented region is delimited), `PYTHONHASHSEED=0`, on `CPython 3.14.7` and `3.14.7t`, base and branch each built from a clean `git archive` of its own commit. Only the `d.pop(key)` GIL rows move; the numbers are in the section above. </details> Drafted with Claude Opus 5 in Claude Code. Left as a draft for @asvetlov to review before it goes out.
<!-- Thank you for your contribution! --> ## What do these changes do? The `ForEach` visitor gained the entry's identity in #1552, but not the hash the mapping stores alongside it. A visitor that buckets or groups entries by identity therefore had to hash it again, work both walks had already done. `MultiDict_ItemVisitor` now takes `(void *user_data, PyObject *identity, Py_hash_t hash, PyObject *key, PyObject *value)`, with the hash next to the identity it belongs to. `MultiDict_CyItemVisitor` gains it in the same position, keeping its own `user_data`-last order. The internal `md_item_visitor_t` in `_multilib/walk.h` is widened to match, along with `md_walk_all`, `md_walk_with_hash` and their two in-tree visitors. `md_walk_with_hash` passes the hash it was already handed; every matched entry's own `entry->hash` equals it, since that is the first half of the walk's match predicate. `md_walk_all` reads `entry->hash` before the visitor call, alongside the identity and value it already reads there, since `_md_ensure_key()` and the visitor can both run Python code that frees the entry. The capsule is unreleased: it landed in #1480, after v6.9.1, and `MultiDict_CAPI_VERSION` is still 1, so no client can have been built against the narrower signature. That is why the typedef changes in place instead of growing a parallel entry point at the end of the struct with a version bump. ## Are there changes in behavior for the user? No, for Python-level users. A C or Cython client of the capsule has to take the extra parameter, but the capsule has not shipped in a release yet, so there is nothing to migrate. ## Is it a substantial burden for the maintainers to support this? No. Both walks have the hash in hand already, so the wider signature costs neither a lookup nor a reference. This one does not move the benchmarks. On the GIL build no C-extension row changed at all; on the free-threaded build the three that did move (`update` on `CIMultiDict` -0.24% and on `MultiDict` +0.08%, `popitem` on `CIMultiDict` -0.02%) sit well inside the noise floor the untouched pure-Python rows show across the same pair of runs, which reaches 1.8%. `docs/benchmark.rst` is unchanged accordingly. ## Related issue number None; this follows #1552 directly. ## Checklist - [x] I think the code is well written - [x] Unit tests for the changes exist - [x] Documentation reflects the changes - [ ] If you provide code modification, please add yourself to `CONTRIBUTORS.txt` - [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` <details> <summary>Agent run details (optional, for reviewers)</summary> Tests, each in its own virtualenv against its own copy of the tree, so a stale `.so` cannot make a leg lie: ``` CPython 3.13.12, C extension 2699 passed, 21 skipped CPython 3.13.12, MULTIDICT_NO_EXTENSIONS=1 --no-c-extensions 1258 passed, 17 skipped, 1268 deselected CPython 3.14.7t, free-threaded 2687 passed, 33 skipped CPython 3.10.17, oldest supported 2699 passed, 21 skipped ``` Every leg with a C extension built the Cython harness too and ran with `MULTIDICT_TEST_REQUIRE_CYAPI=1`, so the `_testcyapi` half of `tests/test_capi.py` is a hard failure rather than a skip. The `md_foreach` harnesses now return `(identity, hash, key, value)`, and the tests assert the hash against `hash(identity)`, which on a `CIMultiDict` is the lower-cased form's hash and not the key's. Lint: `pre-commit run --all-files` passes, including `clang-format` and both `mypy` hooks. `make doc-spelling` passes. Benchmarks: `benchmarks/callgrind_driver.py`, `PYTHONHASHSEED=0`, on CPython 3.14.7 and 3.14.7t, base (pinned at the merge base cd92a6c) and branch each built from a clean copy of its own tree in its own virtualenv. Numbers in the section above. </details> Drafted with Claude Opus 5 in Claude Code. Left as a draft for @asvetlov to review before it goes out. --------- Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
<!-- Thank you for your contribution! --> ## What do these changes do? Prepares the news fragments for 7.0.0. The public C API (#1480) and the watchers API (#1551) are new in this release, so the fragments describing later changes to them describe states that never shipped. They are folded into the entries that added the APIs: the visitor's identity and hash (#1552, #1561) into `1478`, and the 32-watcher limit, the watcher registration race fix and the failing-callback report (#1574, #1583, #1585) into `1551`. The `MultiDict_SetDefault(NULL)` half of `1553` is dropped for the same reason. Intermediate header names that never shipped are removed as well: `1510` no longer mentions `deferred_decref.h`, which #1530 merged into `reflist.h`, and `1513` names `debug.h` directly, so `1576` goes. `1572`, a fix to a tool added this cycle, is folded into `1529`. `1560` and the last sentence of `1556` go too, since the release refresh of the benchmark tables supersedes those intermediate ones. Finally, the fragments that did not lead with a past-tense verb or described the change as "now ..." are rewritten per `AGENTS.md`. The benchmark table refresh from `RELEASE.md` step 2 is still to be added to this branch before it leaves draft. ## Are there changes in behavior for the user? No. ## Is it a substantial burden for the maintainers to support this? No. ## Related issue number N/A ## Checklist - [x] I think the code is well written - [ ] Unit tests for the changes exist (N/A, changelog only) - [x] Documentation reflects the changes - [ ] If you provide code modification, please add yourself to `CONTRIBUTORS.txt` (N/A) - [ ] Add a new news fragment into the `CHANGES/` folder (N/A, edits existing fragments; the benchmark refresh will add a `doc` fragment) - [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); pending review by @asvetlov before leaving draft. <details> <summary>Agent run details (optional, for reviewers)</summary> `python -Im towncrier build --draft --version 7.0.0` renders cleanly. The symlinked pairs `1512` -> `1492` and `1562` -> `1555`, and both `1535` fragments, are intentional and left alone. </details>
What do these changes do?
Adds a public C API capsule (
multidict._multidict.CAPI, reachedthrough
multidict_capi.h/multidict_capi_struct.h) so other Cextensions can create and manipulate
MultiDict,CIMultiDict,their proxies, and
istrdirectly, without going through thePython-level API. Covers type checks and constructors for all four
mapping types plus
istr,getversion()andlen(), andadd(),clear(),setdefault(), and single-item access (in,[],del,pop()) for the mutable types.GetItem,Pop, andSetDefaultfollow thePyDict_GetItemRef/PyDict_SetDefaultRefdesign, reporting a missing key through the return code rather than
an exception.
MultiDict_ForEachvisits every item, or just theitems for one key, through a callback, without allocating a list.
The same capsule is also reachable from Cython:
multidict/__init__.pxdlets third-party Cython code
cimport multidict, mirrored by amultidict/_testcyapi.pyxtest harness. Cython is optional and nevera real dependency of
multidictitself; an ordinary or release buildnever sees it, and a dedicated CI job exercises the opt-in path.
Are there changes in behavior for the user?
No behavior change for existing Python-level usage. This adds a new,
opt-in C API surface for other C extensions and Cython code to use.
Is it a substantial burden for the maintainers to support this?
The struct only ever grows at the end, so older clients keep working
against newer
multidictbuilds. The Cython binding is test-only andopt-in, so it adds no ongoing dependency burden.
Related issue number
Supersedes and closes #1183, #1190, #1191 (earlier C API drafts).
Checklist
CONTRIBUTORS.txtCHANGES/foldermake doc-spellingpasses and any new technical words are added todocs/spelling_wordlist.txtAgent run details (optional, for reviewers)
Tests:
pytest -qon both the accelerated build (with and without theCython opt-in) and the pure-Python build (
MULTIDICT_NO_EXTENSIONS=1);tests/test_capi.py'sapifixture runs every case against both theC and Cython bindings when Cython is opted in.
Lint:
pre-commit run --all-files(ruff, mypy for 3.13/3.11, yamllint,clang-format, GitHub Actions validators) clean.
Docs: strict Sphinx HTML build and
doc-spellingclean.Drafted with Claude Code (Sonnet 5); reviewed by asvetlov.