Skip to content

Lay out the common branch in line in lookup and identity - #1550

Merged
asvetlov merged 2 commits into
aio-libs:masterfrom
asvetlov:claude/read-path-branch-layout
Sep 24, 2026
Merged

asvetlov merged 2 commits into
aio-libs:masterfrom
asvetlov:claude/read-path-branch-layout

Conversation

@asvetlov

Copy link
Copy Markdown
Member

What do these changes do?

Two branches on the hot path were being laid out with the frequent case behind
a taken branch, so the common path jumped out of line and back.

The DKIX_DUMMY check in the four single-key lookup probe loops
(_md_contains_locked, _md_contains_lockfree, _md_get_one_locked,
_md_get_one_lockfree) now carries UNLIKELY. A dummy slot only appears once
something has been deleted, so a pure lookup almost never walks over one.

_key_to_identity() has its first test inverted so the exact-str case is the
fallthrough. Left as written, GCC put that case out of line and gave the
straight line to PyUnicode_FromObject(), which only runs for a str
subclass.

The same UNLIKELY is deliberately not added to the probe loops of the
deleting methods. Deleting is what creates dummy slots, so those loops hit them
often; measured there it costs 0.85% on __delitem__ and 0.5% on update().
Three other candidates were measured and rejected for the same reason: the
resize check in _md_add_with_hash_steal_refs(), an UNLIKELY on the
md_calc_identity_hash() error return, and ALWAYS_INLINE on
htkeys_get_index(). Numbers for those are in the footer.

This is C only. The pure-Python backend has no equivalent notion of branch
layout, so there is nothing to mirror there.

Are there changes in behavior for the user?

No. Both hunks are pure code layout; the conditions tested and the values
returned are unchanged.

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

No. It is five lines of annotation plus one inverted if.

Related issue number

None.

Checklist

  • I think the code is well written
  • Unit tests for the changes exist - N/A, no behavior change; the existing suite covers both paths
  • Documentation reflects the changes - N/A
  • 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
Agent run details (optional, for reviewers)

Measured with callgrind on a GIL build, PYTHONHASHSEED=0, 20 keys, base
9682ba1. Instructions per operation, so it is not wall clock and does not
need a quiet machine. Every number below was reproduced in a second
independent run.

case                          m_base     m_new    delta
md:getitem                    1040.9    1037.9   -0.29%
md:ctor_items                 5143.7    5123.2   -0.40%
md:ctor_dict                  5641.1    5621.6   -0.34%
md:delitem                    1174.6    1173.7   -0.08%
md:setitem_new                1536.1    1535.1   -0.07%
md:setdefault                 1394.9    1393.9   -0.07%
md:add                        1548.8    1547.8   -0.06%
md:getall                     1618.0    1617.0   -0.06%
md:popall                     1710.6    1709.6   -0.06%
ci:getitem                    1633.0    1631.0   -0.12%
ci:ctor_items                16045.8   16005.3   -0.25%
ci:delitem                    1781.5    1780.5   -0.05%
ciistr:getitem                1037.0    1036.0   -0.10%
ciistr:ctor_items             5326.0    5304.6   -0.40%
ciistr:ctor_dict              5784.5    5764.0   -0.35%
ci:ctor_dict                 16544.3   16564.9   +0.12%
ciistr:update                 7658.9    7679.0   +0.26%

The last two rows are regressions and reproduce exactly. Both are a flat +20
instructions per call rather than a per-item cost, and both look like inlining
shifting around the +112 bytes of text this adds; the wins on the neighbouring
constructor rows are larger. Everything not listed moved by less than 0.05%.
Nothing here is near the couple-of-percent threshold that would require
regenerating docs/benchmark.rst.

Free-threaded 3.14.7t, same method: __getitem__ -0.07%, __contains__
-0.05%, getone() -0.07%.

Rejected candidates, same harness:

UNLIKELY on DKIX_DUMMY in the write probe loops   __delitem__ +0.85%, update +0.5%
UNLIKELY on the insert resize check               +0.03% to +0.15%, never better
UNLIKELY on md_calc_identity_hash() < 0           __delitem__ +0.85%
ALWAYS_INLINE htkeys_get_index (3.14t)            getitem +0.64%, add +0.64%, setitem +0.79%

The third is worth recording: wrapping a call in UNLIKELY() marks the whole
statement cold, so GCC stops inlining the callee there.
multidict_mp_as_subscript went from having md_calc_identity() inlined to a
plain call, and got smaller (1445 to 1307 bytes) while getting slower.

Tests, all on this branch:

C extension, CPython 3.13.2          2451 passed, 109 skipped
pure Python, CPython 3.14.7          1186 passed, 11 skipped, 1189 deselected
free-threaded CPython 3.14.7t        2529 passed, 23 skipped, 147 deselected
pytest -q -m hypothesis               142 passed, 5 skipped
make doc-spelling                    build succeeded
pre-commit (via commit hook)         passed

The pure-Python leg ran from its own tree and its own virtualenv, so no stale
.so could be picked up by the C half of the matrix.

Drafted with Claude Opus 5 in Claude Code. Left as a draft for @asvetlov to review before it goes out.

Two branches in the hot path were laid out with the frequent case behind
a taken branch.

In the single-key lookup probe loops the DKIX_DUMMY check now carries
UNLIKELY. A dummy slot only exists once something has been deleted, so a
pure lookup almost never sees one. The same hint is deliberately not
added to the probe loops of the deleting methods: there it costs 0.85%
on __delitem__, because deleting is what creates the dummies.

In _key_to_identity() the test is inverted so the exact-str case falls
through. As written, GCC put it out of line behind a taken branch and
gave the straight line to the str subclass call instead.
@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 not alter performance

✅ 310 untouched benchmarks


Comparing asvetlov:claude/read-path-branch-layout (49423f1) with master (9682ba1)

Open in CodSpeed

@asvetlov
asvetlov marked this pull request as ready for review September 24, 2026 06:28
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 24, 2026 06:28
@greptile-apps

greptile-apps Bot commented Sep 24, 2026

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

No blocking issues identified; safe to merge based on the reviewed changes.

What we checked:

  • Ran the tombstone collision probe using the C backend on the base revision and the PR changes; both runs exited with code 0, ruling out the tested collision-and-tombstone failure path for these scenarios. T-Rex
  • Compared the C backend results with the pure-Python backend for the probe; both runs exited 0 and produced identical behavioral results for this test, while noting that some differences exist in other contexts (such as a MultiDict subclass with an overridden hash), which are outside this narrow probe. T-Rex

Reviews (1) · Last reviewed commit: "Rename the news fragment to the assigned..."

@asvetlov
asvetlov merged commit d3d9375 into aio-libs:master Sep 24, 2026
62 checks passed
@asvetlov
asvetlov deleted the claude/read-path-branch-layout 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
<!-- 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