Repository navigation
Compute the ASCII identity of a CIMultiDict key directly - #1527
Conversation
_ci_key_to_identity() called str.lower() on every plain str key. For an ASCII string that always allocates a fresh string, which then has to be hashed from scratch, and the call itself costs an attribute lookup and a vectorcall. An exact str that is ASCII is now handled inline: the key is scanned for an uppercase byte and, if it has none, it already is its own identity and is reused as-is, so there is no copy and _unicode_hash() gets the cached hash. A key that does have uppercase is lowered straight into a new string, still without the method call. The gate is deliberately PyUnicode_CheckExact: a str subclass may override lower(), and the identity of a subclass instance must keep coming from the override. istr, str subclasses and non-ASCII keys are unaffected. The pure-Python backend is left alone; its _CIMixin._identity() already is key.lower() and there is no cheaper spelling of it in Python.
f8339e9 to
6d7e5dd
Compare
Merging this PR will improve performance by 71.99%
|
6d7e5dd to
b5eff12
Compare
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #1527 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 38 40 +2
Lines 6455 6816 +361
Branches 591 596 +5
==========================================
+ Hits 6455 6816 +361
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:
|
The per-byte scan is the whole cost of the fast path for a key that is already lowercase, so it is worth doing in words. Both sums stay inside their own lane because every byte of an ASCII string is below 0x80, which makes the high bit of a lane the answer to the range test. The word test asks only whether some lane is uppercase, never which one, so it does not care what byte order the load produced, and the load is a memcpy because the data of a non-compact str need not be word aligned. The leftover is covered by one more word ending at the key's end rather than a byte loop. It overlaps the previous word when the length is not a multiple of eight, which costs nothing for a yes/no answer and keeps short keys off the slow path; scanning the leftover byte by byte is what made an eight-byte word lose to a four-byte one at realistic key lengths. Keys shorter than one word still take the byte loop, and that is also what lets the last word start at len - 8: a compact ASCII str is allocated as its header plus len + 1 bytes, so reading a word past either end is a genuine out-of-bounds read that AddressSanitizer reports. Instruction counts for the scan alone, one pass over twenty real HTTP header names: 1810 byte at a time, 1371 with a byte tail, 986 with the overlapping word. End to end that is a further -4% on lookups by an already-lowercase key.
b5eff12 to
c46c8a6
Compare
md_calc_identity() is inlined into every md_*() that takes a key, so it carries _ci_key_to_identity() along with it. Growing that function by the ASCII fast path pushed md_contains() and md_next() past the inliner's budget at their own call sites, and GCC stopped inlining them there. The cost landed on code the fast path cannot help: keys().isdisjoint() took 31% more instructions on a plain MultiDict, whose keys never reach the case-insensitive branch at all. Moving everything below the istr check behind a noinline call leaves _ci_key_to_identity() smaller than it was before the fast path, and the budget effect goes away. isdisjoint() lands within 2% of master on both multidict flavours, getall() by an istr key is 1.7% cheaper than master, and the fast path keeps all of its win: -46.6% for a lookup by an already-lowercase key and -17.2% for a mixed-case one. Counts are callgrind I refs with PYTHONHASHSEED pinned, differenced between two loop lengths so interpreter startup cancels.
|
<!-- Thank you for your contribution! --> ## What do these changes do? `docs/benchmark.rst` explained how to run the benchmarks but published no numbers, so the question a reader arrives with, what `MultiDict` costs compared with a plain `dict`, went unanswered, and the free-threaded build's overhead was undocumented. The page now carries per-operation tables for `dict`, `MultiDict` and `CIMultiDict` on the GIL build, the same on the free-threaded build, a free-threading overhead summary with `dict` as the control, and a pure-Python backend table. Fifteen rows, one per operation the two types share. The numbers are Callgrind instruction counts rather than wall clock, because they do not depend on scheduling or CPU frequency and so reproduce on a busy machine; a regression shows up as a changed integer. `benchmarks/callgrind_driver.py` measures each cell with four child processes, two round counts per arm. Differencing two non-zero round counts cancels interpreter startup, and subtracting an arm with the operation elided cancels the driving loop, which is worth a few hundred instructions per iteration and would otherwise compress every ratio toward 1. `benchmarks/render_tables.py` turns two runs into the tables and rewrites the block between markers in the page. Getting there needed the scripts restructured. The pyperf script built each benchmark out of `exec`'d source templates, which left nowhere to run setup between measured iterations and limited it to six non-destructive operations. `benchmarks/operations.py` now holds every operation as a setup/run/noop triple that all three entry points read, and the rebuild a destructive operation needs happens in setup, outside the measured region, so `pop()`, `clear()` and `del d[key]` can be measured without counting it. Both backends are covered: the tables carry `MultiDict` and `CIMultiDict` for the C extension and for the pure-Python implementation, imported directly from `multidict._multidict` and `multidict._multidict_py`, so one install measures both. `AGENTS.md` now asks for the tables to be refreshed in the same PR as any significant performance change, with the commands to do it. ## Are there changes in behavior for the user? No. Nothing outside `benchmarks/`, `docs/` and `AGENTS.md` is touched. ## Is it a substantial burden for the maintainers to support this? The tables need regenerating when performance moves, which is the point of them; `AGENTS.md` documents how. The measurement is deterministic, so it does not need a quiet machine, but it does need Valgrind and one virtualenv per interpreter build. ## Related issue number None. ## Checklist - [x] I think the code is well written - [ ] Unit tests for the changes exist — N/A, `benchmarks/` is not part of the test suite; `callgrind_driver.py --self-check` exercises every operation on every implementation instead - [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` <details> <summary>Agent run details (optional, for reviewers)</summary> Measured on CPython 3.14.7 and 3.14.7t, Valgrind 3.26.0, at dd9c64f. Verification: * `python benchmarks/callgrind_driver.py --self-check` — 95 cells build, run and end in the asserted state. * Full collection on both builds, twice, independently: all 75 published cells identical, reported drift 0. * `make doc` and `make doc-spelling` — both pass; Sphinx runs with `-W`. * `pre-commit run --files benchmarks/*.py docs/benchmark.rst AGENTS.md ...` — ruff check, ruff format and both mypy passes clean. * `benchmark.py --impl multidict_c -o c.json`, same for `multidict_py`, then `pyperf compare_to` — the wall-clock path still produces comparable output after the rewrite. The driver's self-checks earned their place during development: the bit-exactness check caught `ruff format` rewriting `operations.py` while a collection was in flight, and refused to emit numbers. Two measurement traps the driver guards against, both of which produce plausible wrong numbers rather than an error: * Handing Valgrind a wrapper script such as a `pyenv` shim. Valgrind defaults to `--trace-children=no` and detaches at the `exec`, so it reports a constant that never changes with the round count. * Leaving `PYTHONHASHSEED` unset. String hash randomisation changes the hash table's probe sequences per process and moved one case by 4.4%, which looks exactly like a real regression. Rebasing this branch onto current master mid-review changed the `CIMultiDict` rows substantially, since #1527 landed in between: `d[key]` went from 1,092 to 240 instructions, `key in d` from 1,076 to 226, and `cls(items)` from 219,466 to 62,942. The published tables are measured at this branch's base, not the older one. </details> Drafted with Claude Code (Opus 5); reviewed by @asvetlov.
<!-- Thank you for your contribution! --> ## What do these changes do? Adds `tools/check_inlining.py` and an `Inlining` CI job on 3.14 and 3.14t. The script compiles `_multidict.c` with the interpreter's flags plus the release flags from `setup.py`, disassembles it, and fails when an entry point a rule names (a slot, method or `MultiDict_*` C API function) reaches the rule's helper through any chain of out-of-line calls; the report shows the chain. The first rules come from the regressions in #1527, #1530, #1541, #1542, #1554, #1591 and #1604, each of which slowed a benchmark on code the change never touched. AGENTS.md now asks agents to run it, to add a rule whenever they fix an inlining regression or pin a helper, and never to weaken a rule without a measurement. CI builds with GCC 13.3. The two rules it failed on master at first (`md_calc_identity` out of line in `getall()` and `popall()` on free-threaded builds) were fixed by #1614; master now passes every rule with GCC 13 and GCC 15 on both builds. ## Are there changes in behavior for the user? No. ## Is it a substantial burden for the maintainers to support this? No. A PR that moves an inlining decision on purpose edits the matching rule. ## Related issue number N/A ## Checklist - [x] I think the code is well written - [ ] Unit tests for the changes exist (N/A, a CI-only tool; verified by reintroducing past regressions, see below) - [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 Code (Claude Opus 5.5); reviewed by @asvetlov. <details> <summary>Agent run details (optional, for reviewers)</summary> Master passes on 3.14.7 and 3.14.7t with GCC 14 and GCC 15. Each past regression reintroduced by hand was caught: - dropping `ALWAYS_INLINE` from `htkeysiter_init`: out-of-line copy reported, plus `md_contains` out of `isdisjoint` - dropping `NOINLINE` from the view, iterator and shell pool helpers (#1541/#1542): `md_contains` out of `isdisjoint` - dropping `NOINLINE` from `_ci_str_to_identity` (#1527): failures across getitem, getall, replace and `isdisjoint` on both builds GCC 13.5 (`gcc:13` Docker image): the two failures listed above. Lint: `pre-commit run` clean; `make doc-spelling` clean. </details>
What do these changes do?
_ci_key_to_identity()calledstr.lower()on every plainstrkey, so aCIMultiDictpaid an attribute lookup, a vectorcall, a string allocation anda from-scratch hash on every single lookup, insert and delete. For an ASCII
string CPython's
str.lower()isPyUnicode_New(len, 127)filled byPy_TOLOWER()per byte, and it has no shortcut for a string that is alreadylowercase, so even
d["content-type"]allocated and rehashed a copy.An exact
strthat is ASCII is now handled directly. The key is scanned for anuppercase byte, eight at a time, and if it has none it already is its own
identity, so it is reused as is: no copy, and
_unicode_hash()finds the key'scached
ob_shashinstead of hashing a fresh string. A key that does haveuppercase is lowered straight into a new string, still without the method call.
The gate is deliberately
PyUnicode_CheckExact. Astrsubclass may overridelower(), and the identity of a subclass instance has to keep coming from theoverride;
tests/test_mutable_multidict.pyandtests/test_multidict.pyalready depend on that, and there is a new test that pins it.
istr,strsubclasses and non-ASCII keys all take the path they took before.
Everything below the
istrcheck now sits behind anoinlinecall, andcompiler.hgains aNOINLINEmacro alongsideCOLDandALWAYS_INLINEforit. This is load-bearing, not cosmetic.
md_calc_identity()is inlined intoevery
md_*()that takes a key, so it carries_ci_key_to_identity()with it,and growing that function pushed
md_contains()andmd_next()past theinliner's budget at their own call sites. The cost landed on code the fast path
cannot help:
keys().isdisjoint()took 31% more instructions on a plainMultiDict, whose keys never reach the case-insensitive branch at all. Behindthe call,
_ci_key_to_identity()is smaller than it was before this change andthe effect is gone.
multidict/_multidict_py.pyis not touched. The dual-backend rule applies, butthere is nothing to mirror: the pure Python
_CIMixin._identity()already iskey.lower(), and no pure-Python spelling of the same idea is cheaper than themethod call it would replace.
Instruction counts, callgrind
I refswithPYTHONHASHSEEDpinned andinterpreter startup cancelled by differencing two loop lengths:
getall()byistr(control)istr(control)MultiDictlookup (control)MultiDictkeys().isdisjoint()(control)CodSpeed, against the benchmarks #1521 added: 41 improvements, 269 unchanged,
no regressions.
cimultidict_fetch_str_lower_case[c]cimultidict_insert_str_lower_case[c]cimultidict_fetch_str_mixed_case[c]cimultidict_insert_str_mixed_case[c]cimultidict_add_str_mixed_case[c]The existing
[ci-c]benchmarks move too, since their keys are digits and soalready lowercase:
multidict_extend_strx3.3,create_multidict_with_many_itemsx2.8,
multidict_setitem_str+95%,multidict_delitem_str+93%, and so on.An earlier push, before the last commit, reported four regressions of about
-11%, on
keys_view_is_disjoint[cs-c]and[ci-c]and oncimultidict_getall_istr_hitand its many-values variant. Those were theinliner-budget effect above rather than runner noise, and all four are back to
unchanged now. The report did carry an environment difference that listed them,
but a master-to-master comparison across the same CPU swap reports them
unchanged, so it never explained them. Fixing it also moved
getall_str_hit[ci-c]from +12% to +20% andgetall_str_hit_large_table[ci-c]from +10% to +15%.
Left out on purpose:
istr_new()also callslower(), butcanonicalhas tobe an exact
strwhile the object being lowered is theistr, so thereuse-the-key half is unavailable there and only the dispatch could be saved,
once per
istr, on the one type that already caches its identity.Are there changes in behavior for the user?
No. Identities are internal and are compared by content, never by pointer, and
the C extension keeps producing exactly what
str.lower()produced.Is it a substantial burden for the maintainers to support this?
No, it is one self-contained fast path in
identity.hwith no new state and nonew locking; it runs no Python code, so unlike the call it replaces it cannot
suspend a critical section.
Related issue number
N/A
Checklist
CONTRIBUTORS.txt- N/A, no such file in this repoCHANGES/foldermake doc-spellingpasses and any new technical words are added todocs/spelling_wordlist.txtRebased on top of #1521, which added the CodSpeed benchmarks this change is
meant to move, so the report here compares against a baseline that has them.
Drafted with Claude Code (Claude Opus 5); reviewed by @asvetlov.
Agent run details (optional, for reviewers)
Tests, full suite, all green:
--no-c-extensions-m hypothesisMULTIDICT_DEBUG_BUILD=1-m hypothesis-m hypothesisLint:
pre-commit runover the touched files, passed.make doc-spelling,build succeeded.
Mutation checks, to show the new tests are load-bearing:
PyUnicode_CheckExactrelaxed toPyUnicode_Checktest_str_subclass_lower_override_is_used, plus the pre-existingHacktestPy_TOLOWER()replaced with an unconditional| 0x20test_ascii_identity_matches_str_lower'A'off by onetest_ascii_identity_matches_str_lower'Z'off by onetest_ascii_identity_matches_str_lowertest_ascii_identity_matches_str_lowertest_ascii_identity_matches_str_lowerheap-buffer-overflow,READ of size 8in_ascii_has_upperThat last one is why a key shorter than one word takes a byte loop and the
final word ends at the key's end rather than starting past it: a compact ASCII
stris allocated as its header pluslen + 1bytes, so a word read pasteither end leaves the block.
How the inlining regression was found and fixed. CodSpeed flagged the four
benchmarks above; the four were reproduced locally under callgrind, and the
profile showed the cause directly. On master
md_contains()andmd_next()are inlined into
multidict_keysview_isdisjoint(); with the fast path inlinedthey appear as out-of-line
md_contains.part.0.constprop.0andmd_next, withhtkeysiter_init()split out too. Three shapes were then measured, asinstructions per
keys().isdisjoint()over 100 keys on a plainMultiDict:noinlinecallistrcheck behind itThe last shape is what is committed. Dropping
ALWAYS_INLINEfrom the scanhelpers changes nothing, because the helpers are not what crosses the budget;
the size of
_ci_key_to_identity()as a whole is.Portability of the word scan, since CI builds and tests s390x (big
endian), ppc64le, riscv64, armv7l, i686 and win32:
lane is uppercase, never which one. A standalone harness ran the shipped
word test with the word assembled both little and big endian and compared
both against a byte-at-a-time reference: 6,590,930 checks, 0 failures. It
covers every ASCII value in every lane against twelve adversarial fillers
(including
@,[,`,{,\x7f), every pair of ASCII values inevery adjacent lane pair, which is where a carry escaping a lane would
show, two million random ASCII words, and whole-scan runs for every length
up to 40 with the odd byte at every offset.
uint64_tarithmetic has the sameresult whatever the register width. On i686 clang emits the two adds as
addl/adcl, and the inter-half carry is harmless precisely because nocarry leaves a byte lane. The harness was also run with a 32-bit
Py_ssize_t. A four-byte word was considered for those targets andrejected: an i686 eight-byte word costs 1.68 times a four-byte one, but
needs half as many iterations, so for a twelve-byte key the four-byte word
is about a tenth cheaper on a scan that is itself under a tenth of a
lookup. That is well under a percent on the 32-bit tier, against a second
code path to write and test.
memcpyand not a cast throughuint64_t*, which would be both alignment and strict-aliasing UB. Everytarget inlines it; none falls back to a libc call, including strict
alignment MIPS, which uses an
lwl/lwrpair.riscv64, i686 and mips.
Scan shape: GCC does not auto-vectorise the byte loop, since the early
exit prevents it, so this is not work the compiler was already doing. Five
shapes were measured with callgrind on the scan alone, one pass over twenty
real HTTP header names (mean length 10.6):
The byte tail, not the word width, is what hurts: a twelve-byte key does one
word then four expensive scalar bytes, which is why the narrower word looked
better. Replacing the tail with one more word ending at the key's end removes
the effect and makes the eight-byte word the best shape at every length.
Also checked:
entry->identitycan now be the same object asentry->keyfor a
CIMultiDict, which is already the status quo for a plainMultiDictwith exact-
strkeys._md_ensure_key(),md_clear(), the resize and copypaths and
_md_check_consistency()all treat the two as independent ownedslots and never compare them,
md_traverse()not visitingidentityisharmless because
stris never GC-tracked, and there is a test asserting thetwo references are given back.