Skip to content

Speed up the argument binding of the C extension - #1549

Merged
asvetlov merged 3 commits into
aio-libs:masterfrom
asvetlov:parse2-fast-binding
Sep 24, 2026
Merged

asvetlov merged 3 commits into
aio-libs:masterfrom
asvetlov:parse2-fast-binding

Conversation

@asvetlov

Copy link
Copy Markdown
Member

What do these changes do?

Three changes to the argument handling of the C extension, no behaviour
change in any of them.

parse2() compiled to a single outlined clone shared by all eleven call
sites and was inlined nowhere, so md.get(key) paid a call into the
keyword machinery it never used. The all-positional case now binds in
the inline wrapper, five instructions at the call site, and the rest
moved to a COLD parse2_slow(). Since the keyword walk is out of line
anyway, it takes the tuple through PyTuple_GET_SIZE() and
PyTuple_GET_ITEM(); all eleven methods are
METH_FASTCALL | METH_KEYWORDS, so kwnames is a tuple or NULL and
the error branches of the checked calls were unreachable.

Parameter names are now interned in the module state and matched against
kwnames by identity before falling back to a comparison, which is what
find_keyword() in CPython's Python/getargs.c does. A call written as
get(key=k) settles on a pointer compare; the memcmp() it replaces was
45% of the keyword path. The fallback is not optional: get(**{"key": k})
builds names that never reach the intern table, and there is a test for
exactly that.

Finally, multidict_get() built the implicit None default on every
call and carried a flag to release it again, although it is only
reachable when the key is absent. It now does the lookup directly and
produces the constant on the miss path, where it is the return value.
setdefault() keeps the old shape, since it has to hand the default to
md_set_default() inside the critical section.

Instruction counts against 9682ba1, callgrind, 200k calls:

case master this branch
md.get(key) 506,599,099 492,590,531 -2.77%
md.get(key, default=None) 560,167,840 538,574,218 -3.85%
md.getone(key=key) 553,395,042 531,801,895 -3.90%
md.get(key, None) 508,367,864 498,974,074 -1.85%
md.getone(key) 501,769,613 493,572,776 -1.63%
md.getall(key) 576,882,245 569,485,981 -1.28%
md.add(key, value) 752,475,828 743,272,580 -1.22%

Only the C extension is touched; the pure-Python implementation is
unchanged.

Are there changes in behavior for the user?

No. The same calls succeed, the same ones raise, and the messages are
identical. A behaviour matrix of 27 argument combinations compared
against the pure-Python backend is unchanged by this branch.

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

No, though two of the assumptions are worth knowing about. The tuple
macros rely on every parse2() caller staying
METH_FASTCALL | METH_KEYWORDS, and the identity match relies on the
module state holding interned names, so PyUnicode_InternFromString()
there is load bearing rather than incidental.

Related issue number

None. Follow-up to #1545.

Checklist

  • I think the code is well written
  • Unit tests for the changes exist
  • Documentation reflects the changes - N/A, no documented behaviour changes
  • If you provide code modification, please add yourself to CONTRIBUTORS.txt - N/A, no such file in this repo
  • Add a new news fragment into the CHANGES/ folder
  • 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.

Agent run details (optional, for reviewers)

Both legs ran in their own venv, and the pure-Python leg in its own tree
copy, so neither picked up a stale .so.

C extension:   pytest tests -q                    2444 passed, 120 skipped
pure Python:   MULTIDICT_NO_EXTENSIONS=1 pytest -q --no-c-extensions
                                                  1188 passed, 11 skipped, 1191 deselected
lint:          pre-commit run --all-files         all hooks passed
docs:          make doc-spelling                  build succeeded

Measurement notes: callgrind, PYTHONHASHSEED=0, warm __pycache__,
200k iterations. Cross-rebuild noise was measured at about 0.01% by
building identical source twice and comparing, so the deltas above are
well clear of it.

One rejected variant, recorded so it is not retried: screening the name
comparison with an inline first-character check before
PyUnicode_CompareWithASCIIString() regressed the keyword paths by 0.5
to 0.8%. The common keyword forms hit on the first name tried, so there
is no memcmp() to skip and the screen is pure overhead. Identity
matching was the change that actually paid.

multidict_get() materialised the implicit None on every call, then
carried a decref_default flag to release it again, even though the
default is only reachable when the key is absent. Do the lookup
directly and produce the constant on the miss path, where it is the
return value.

Callgrind, 200k calls: md.get(key) on a present key drops 1.19%, and
md.get(key, None) 0.20%. The saving is not only Py_GetConstant(): the
flag, its branch and the Py_CLEAR() go with it.

setdefault() keeps the old shape; it has to hand the default to
md_set_default() inside the critical section, so there is no miss path
to defer the constant to.
Two changes to how FASTCALL arguments are bound.

parse2() compiled to a single outlined clone shared by all eleven call
sites, so md.get(key) paid a call into the keyword machinery it never
used. Guard the all-positional case in the inline wrapper and leave the
rest to a COLD parse2_slow(); the wrapper now costs five instructions at
the call site. While the keyword walk is out of line anyway, take the
tuple through PyTuple_GET_SIZE()/PyTuple_GET_ITEM(): all eleven methods
are METH_FASTCALL|METH_KEYWORDS, so kwnames is a tuple or NULL and the
error branches of the checked calls were unreachable.

The names are now compared by identity first. Both sides are interned,
the parameter names in the module state and the keyword names the
compiler puts in kwnames, so a call written as get(key=k) settles on a
pointer compare instead of memcmp(), which was 45% of the keyword path.
Names that never reach the intern table, as built by get(**{"key": k}),
still need the comparison, so it stays as a fallback; this mirrors
find_keyword() in CPython's Python/getargs.c.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 23, 2026
@codspeed

codspeed Bot commented Sep 23, 2026

Copy link
Copy Markdown

Merging this PR will improve performance by 9.06%

⚠️ Different runtime environments detected

Some benchmarks with significant performance changes were compared across different runtime environments,
which may affect the accuracy of the results.

Open the report in CodSpeed to investigate

⚡ 1 improved benchmark
✅ 309 untouched benchmarks

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ test_multidict_get_miss[cs-c] 78.3 µs 71.8 µs +9.06%

Tip

Curious why performance improved? Comment @codspeedbot explain why performance improved on this PR, or directly use the CodSpeed MCP with your agent.


Comparing asvetlov:parse2-fast-binding (fb8541a) with master (9682ba1)

Open in CodSpeed

@codecov

codecov Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (9682ba1) to head (fb8541a).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1549   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           40        40           
  Lines         6876      6890   +14     
  Branches       596       596           
=========================================
+ Hits          6876      6890   +14     
Flag Coverage Δ
CI-GHA 100.00% <100.00%> (ø)
pytest 100.00% <100.00%> (ø)

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 marked this pull request as ready for review September 24, 2026 06:21
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 24, 2026 06:21
@greptile-apps

greptile-apps Bot commented Sep 24, 2026

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 4/5

Do not merge until the published benchmark tables satisfy the repository requirement.

Reviews (1) · Last reviewed commit: "Rename the news fragments to the assigne..."

Comment thread multidict/_multilib/parser.h Resolved
@asvetlov
asvetlov merged commit 443d745 into aio-libs:master Sep 24, 2026
62 checks passed
@asvetlov
asvetlov deleted the parse2-fast-binding branch September 24, 2026 06:37
asvetlov added a commit to asvetlov/multidict that referenced this pull request Sep 24, 2026
Takes master's copies of hashtable.h, atomic_helpers.h and the 1546
fragment: aio-libs#1546 landed there, so the copies this branch carried are
redundant and master's also has aio-libs#1539, aio-libs#1549 and aio-libs#1550 on top.
asvetlov added a commit to asvetlov/multidict that referenced this pull request Sep 24, 2026
aio-libs#1539, aio-libs#1549 and aio-libs#1550 landed since these were collected, and the add
row moved most: 876 to 765 on the GIL build, 1,035 to 939 free-threaded.

Also restore the note that d.add() starts from an empty mapping and
inserts 200 keys. Without it the lead-in describes every row as running
against a 200-key mapping, which is true of the other two but not of
that one.
asvetlov added a commit that referenced this pull request Sep 24, 2026
…1553)

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

## What do these changes do?

`setdefault()` called without an explicit default built the implicit
`None` on every call, then carried a flag to release it again, although
only the call that actually inserts consumes it. `md_set_default()` now
reads a `NULL` *value* as `None`, so the method simply forwards what it
parsed and the flag, its branch and the `Py_CLEAR()` all go away.

The constant lives in the module state rather than coming from
`Py_GetConstant()` at the point of use, because the substitution happens
just before the critical section is taken. On 3.13+ either would do; on
3.10 to 3.12 the `pythoncapi_compat` shim initialises its table lazily
and calls `PyLong_FromLong()`, so a first call landing under the lock
could collect.

Instruction counts against `cd92a6c`, callgrind, 200k calls:

| case | master | this branch | |
| --- | --- | --- | --- |
| `d.setdefault(key)`, present key | 491,825,979 | 486,878,820 | -1.01%
|
| `d.setdefault(key, default)`, present key | 494,626,107 | 493,681,201
| -0.19% |
| `d.setdefault(key)`, inserting | 290,700,236 | 290,812,020 | +0.04% |

The inserting call is unchanged, as expected: it still stores the same
constant, just one that was not built for the occasion.

Only the C extension is touched; the pure-Python implementation is
unchanged.

## Are there changes in behavior for the user?

Not at the Python level; `setdefault()` returns and stores exactly what
it did before.

The public C API gains a little: `MultiDict_SetDefault()` forwards
straight to `md_set_default()`, so it now accepts `NULL` for
*default_value* and reads it as `None`, where the documentation
previously called the argument required. `docs/capi.rst` says so, and
both `_testcapi.c` and `_testcyapi.pyx` exercise it.

`MultiDict_CAPI_VERSION` stays at 1 deliberately. It exists to stop a
client built against a newer header from running on an older runtime,
and version 1 has not shipped: the capsule landed after v6.9.1, so there
is no released runtime that would reject a `NULL` default. Bumping would
announce a boundary no client can be on the wrong side of.

The Cython wrapper cannot express a `NULL` object, but passing `None` is
read identically, so `default_value` just gained a `None` default, which
incidentally makes its signature match the Python method.

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

No. It removes a local variable and a branch from the method, adds one
field to the module state next to the interned names already there, and
leaves `md_set_default()`'s behaviour for a non-`NULL` default
untouched.

## Related issue number

None. Follow-up to #1549, which did the same for `get()`.

## 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` - N/A, no such file 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>

Both legs ran in their own venv, and the pure-Python leg in its own tree
copy, so neither picked up a stale `.so`. The C leg ran with
`MULTIDICT_TEST_REQUIRE_CYAPI=1` after building Cython, so the
`_testcyapi` half of `test_capi.py` was a hard requirement rather than a
skip.

```
C extension:   MULTIDICT_TEST_REQUIRE_CYAPI=1 pytest tests -q
                                                  2691 passed, 33 skipped
pure Python:   MULTIDICT_NO_EXTENSIONS=1 pytest -q --no-c-extensions
                                                  1264 passed, 11 skipped, 1268 deselected
lint:          pre-commit run --all-files         all hooks passed
docs:          make doc-spelling                  build succeeded
```

Two tests cover the new `NULL` path through both harnesses, one
inserting and one finding an existing key. The Python-level paths were
already covered by `test_mutable_multidict.py`, which asserts
`setdefault("key") == "one"` and `setdefault("noexist") is None`.

Measurement notes: callgrind, `PYTHONHASHSEED=0`, warm `__pycache__`,
200k iterations, rebuilt from the same tree for each side. Cross-rebuild
noise on this harness measures at about 0.01%, which is what the
inserting row is showing.

</details>
asvetlov added a commit that referenced this pull request Sep 24, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

The `istr` section already tells people to build their keys once and
reuse them, but not what that buys. This adds the instruction counts,
for both builds, next to the plain `str` equivalents, and points out
that a key which is not already lower case saves more still, since it
has to be copied into a lower-cased string whose hash is not cached.

Numbers come from `benchmarks/callgrind_driver.py
--include-multidict-only`,
the same harness and machine as the tables in `docs/benchmark.rst`.

#1546 has landed, so this is down to its own two files. The figures were
re-measured against master afterwards, since #1539, #1549 and #1550 also
moved them; `d.add()` shifted most, 876 to 765 on the GIL build.

## Are there changes in behavior for the user?

No, documentation only.

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

No, though the table joins `docs/benchmark.rst` in needing a refresh
when the figures move.

## Related issue number

None.

## Checklist

- [x] I think the code is well written — N/A, documentation only
- [ ] Unit tests for the changes exist — N/A
- [x] Documentation reflects the changes
- [ ] 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 Opus 5 in Claude Code; reviewed by @asvetlov.

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
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.

1 participant