Skip to content

Add a tool for diffing the code the C extension compiles to - #1529

Merged
asvetlov merged 2 commits into
aio-libs:masterfrom
asvetlov:claude/merge-insert-order-ifdefs
Sep 23, 2026
Merged

asvetlov merged 2 commits into
aio-libs:masterfrom
asvetlov:claude/merge-insert-order-ifdefs

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

What do these changes do?

Adds tools/codegen_diff.py, which reports the functions GCC emits
differently before and after a change to the C extension. It builds
multidict/_multidict.c from a baseline ref and from the working tree
against the same interpreter headers, normalizes the fields that move
when code is relocated, and compares function by function.

The normalization is the point, in both directions. Without it a raw
objdump diff is unusable, because one instruction-length change shifts
every later label and untouched functions look modified. Normalizing too
much is the opposite failure: immediate operands and memory
displacements are deliberately left alone, so that a store moving to
another structure field is reported rather than folded away. The
disassembly is taken with relocations, because in a relocatable object
the target of an external call lives only in the relocation record.
--self-test compiles a pair of sources for each of those and checks
the difference is reported.

What remains is churn that is not a behavior change: a helper that gets
smaller frees inlining budget, and a stack slot that moves changes a
displacement. The report carries the two numbers that separate those
from a real difference, the instruction count and whether the set of
called symbols moved.

--probe compiles a caller-supplied translation unit instead of the
extension, which is how a helper that GCC always inlines, and that
therefore has no standalone copy in the object, gets looked at on its
own.

Are there changes in behavior for the user?

No, it is a development tool. Nothing imports it, nothing in CI runs
it, and it is not packaged.

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

It is stdlib Python with no new dependency, and nothing depends on it,
so it can be deleted if it stops earning its place. Two limits are worth
knowing up front: it assumes GCC on x86-64, and it hardcodes gcc and
objdump rather than honouring CC. Teaching it clang would mostly be
a matter of the normalization rules.

Related issue number

None. The tooling was rebuilt by hand for #1518, #1526 and #1528; this
puts it in the tree instead.

Checklist

  • I think the code is well written
  • Unit tests for the changes exist (N/A: development tool, not imported or packaged; --self-test is the executable check, see below)
  • Documentation reflects the changes (the module docstring is the documentation, including when a reported difference is benign)
  • 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 Opus 5 via Claude Code; reviewed by @asvetlov.

Agent run details (optional, for reviewers)

The tool was checked against a change whose answer was already known by
hand, #1528, by running it with that commit's parent as the baseline:

python3.14  (GIL):  4 of 155 functions differ
  _md_add_with_hash_steal_refs  156 -> 156 insns, 10 changed lines, call targets unchanged
  _md_merge                     548 -> 548 insns,  4 changed lines, call targets unchanged
  _md_update                    672 -> 672 insns,  6 changed lines, call targets unchanged
  md_extend_self                411 -> 411 insns,  8 changed lines, call targets unchanged

python3.14t (free-threaded): 13 of 158 functions differ
  _md_add_with_hash_steal_refs  174 -> 169 insns, CALL TARGETS DIFFER
  _md_add_for_upd               257 -> 251 insns, call targets unchanged
  md_extend_self                265 -> 253 insns, call targets unchanged
  ... plus their cold halves, and callers that keep their instruction count

The three insert-path functions are picked out, the free-threaded ones
shedding instructions, and _md_add_with_hash_steal_refs is flagged
CALL TARGETS DIFFER because it drops a Py_DECREF call site, which is
the real change. The rest keep both their instruction count and their
call targets: stack slots and block layout moving, not behavior.

Note that is four GIL functions where #1528's own description says
three. That PR was written with an earlier version of this tool, which
normalized memory displacements and so folded away the inlined copy in
_md_update. Its conclusion still holds, since all four keep their
instruction count and call targets, but the count it quotes was an
undercount caused by one of the bugs this branch fixes.

Two further checks: against an identical tree it reports 0 of 183 and 0
of 188 functions on the two builds, and --self-test passes its four
cases, which are an immediate operand, a structure offset, an external
call target, and an unchanged pair that must report nothing.

-fkeep-static-functions was evaluated as a way to avoid hand-written
probe wrappers and rejected: on this tree it emits two extra standalone
functions but still not _md_add_for_upd_steal_refs, so the wrapper is
still needed. It is exposed as --keep-static since it is occasionally
useful.

The compile drops -Werror and the warning flags. This object is only
ever disassembled, and inheriting -Werror would fail the run on a
warning the real build already accepts.

Lint: pre-commit run --all-files passes (ruff check, ruff format, both
mypy legs, clang-format). make doc-spelling passes.

@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 23, 2026
@asvetlov
asvetlov marked this pull request as ready for review September 23, 2026 10:25
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 23, 2026 10:25
@codspeed

codspeed Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Merging this PR will improve performance by 13.97%

⚡ 1 improved benchmark
✅ 309 untouched benchmarks

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ test_create_multidict_with_dict[ci-c] 99.9 µs 87.7 µs +13.97%

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:claude/merge-insert-order-ifdefs (5831701) with master (e50bed4)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

Safe to merge.

Reviews (2) · Last reviewed commit: "Compare only the operands that a relocat..."

Comment thread tools/codegen_diff.py Resolved
Comment thread tools/codegen_diff.py Resolved
Comment thread tools/codegen_diff.py Resolved
Comment thread tools/codegen_diff.py Resolved
@greptile-apps

This comment has been minimized.

Refactors of the C extension are often meant to change no behaviour,
and the strongest evidence for that is that GCC emits the same code.
A raw objdump diff cannot show it: one instruction-length change shifts
every later address and label, so untouched functions look modified.

The script builds the extension from a baseline ref and from the
working tree against the same interpreter headers, normalises the
addresses, RIP-relative displacements and intra-symbol branch offsets
away, and then compares function by function.

Some churn is expected rather than suspicious, so the report carries
the two numbers needed to triage it: the instruction count, and whether
the set of symbols a function calls has moved. Shrinking an inline
helper frees inlining budget and can perturb a function the change
never touched, which shows up as an unchanged call-target set.

A helper GCC always inlines has no standalone copy to compare, so
--probe compiles a caller-supplied translation unit instead, which is
how such a helper gets looked at on its own.
Three ways the comparison could report "no difference" for code that
really did change:

Normalising every hexadecimal operand folded away immediate values and
memory displacements, so `v == 1` and `v == 2` compared equal, and so
did a store to one structure field and a store to the next one. Only
the address column, RIP-relative displacements and branch offsets
inside a symbol move when code is relocated, so only those are
normalised now.

Disassembling a relocatable object without relocations hides the target
of an external call: the symbol lives in the relocation record, and
without it a call to alpha and a call to beta are the same
instruction. Disassemble with -r and count relocation symbols as call
targets.

A --probe file compiled where it lies resolved its quoted includes
against the working tree for both builds, because GCC searches the
directory of the including file before any -I. Copy it into a scratch
directory, which has nothing to shadow with.

--self-test compiles a pair of sources for each of these and checks the
difference is reported, plus an unchanged pair that must not be.

Leaving displacements alone means more functions get reported, since a
stack slot that moves now counts. The instruction count and call-target
columns are what separate that from a real change.
@asvetlov
asvetlov force-pushed the claude/merge-insert-order-ifdefs branch from 45c57a7 to 5831701 Compare September 23, 2026 10:59
@asvetlov

Copy link
Copy Markdown
Member Author

All three findings were real. I reproduced each one against a minimal pair of
sources before changing anything, and each now has a regression case in
--self-test.

Immediate operands and memory displacements were normalized away. Confirmed:
cmp $0x1,%edi and cmp $0x2,%edi compared equal, and so did
mov %rsi,(%rdi) and mov %rsi,0x8(%rdi), a store to one structure field and a
store to the next. The broad hexadecimal rule was the worse of the two, since
structure offsets are exactly what this tool gets pointed at. Only the fields a
relocation is allowed to change are normalized now: the address column,
RIP-relative displacements, and branch offsets inside a symbol.

External call targets were invisible. Confirmed: with objdump -d, a
function calling alpha and the same function calling beta both disassemble to
jmp 9 <h+0x9>, because the symbol only exists in the relocation record.
Switched to objdump -dr and relocation symbols now count as call targets.

--probe resolved quoted includes against the working tree for both builds.
Correct, and it only bites when the probe file sits inside the repository, which
is where anyone would naturally put it. The probe is now copied into a scratch
directory per build, which has nothing to shadow with.

One consequence worth flagging for reviewers: leaving displacements alone means
more functions get reported, because a stack slot that moves now counts as a
difference. Replaying #1528 with the fixed tool gives 4 of 155 functions on the
GIL build rather than the 3 that PR's description quotes; the extra one is
_md_update, which also inlines the insert path and was being folded away. The
conclusion there is unaffected, since all four keep their instruction count and
their call targets, but the number in #1528 was an undercount caused by this bug.

Not addressed: the confidence note also asks for coverage of new behavior. This
is a development tool that nothing imports, nothing in CI runs, and that is not
packaged, and coveralls reports No coverable files changed for the diff.
--self-test is the executable check instead.

@asvetlov

Copy link
Copy Markdown
Member Author

@aiolibsbot rr

@asvetlov
asvetlov merged commit 937fd76 into aio-libs:master Sep 23, 2026
62 checks passed
@asvetlov
asvetlov deleted the claude/merge-insert-order-ifdefs branch September 23, 2026 11:18
asvetlov added a commit to asvetlov/multidict that referenced this pull request Sep 23, 2026
aio-libs#1530 folded the deferred decref accumulator into `reflist_t` and
reworked the same region of `hashtable.h` that this branch moves out, so
both conflicting hunks resolve the same way: the block leaves
`hashtable.h`, and `bulk_update.h` is rebuilt from master's text rather
than the branch's older copy. `deferred_decref.h` is gone from the new
header's includes, replaced by `reflist.h`.

`tools/codegen_diff.py` arrived on master with aio-libs#1529 and now runs from
the tree: 0 of 191 functions differ on CPython 3.13.2 and 0 of 196 on
3.14.7t, against master.
asvetlov added a commit that referenced this pull request Sep 23, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

`hashtable.h` was 2735 lines covering three separate things: the table
itself, the single-key operations, and the multi-item `extend()`,
`update()` and `merge()` engine behind the constructors and the bulk
methods. The last of those was a contiguous block nothing else in the
file called into, whose only consumer is `_multidict.c`.

It moves verbatim into `multidict/_multilib/bulk_update.h`, along with
the `UpdateOp` enum: `_md_update()`, `_md_merge()`, the
`_md_post_update_*` family, `md_post_update()`, `md_update_from_ht()`,
`md_extend_self()`, `md_update_from_dict()`, `md_update_from_kwnames()`,
`md_update_from_seq()` and the sequence-parsing helpers beside it. The
new header includes `hashtable.h`, so `views.h`, `iter.h` and
`capsule.h` keep reaching only the hash table. This continues the split
started by #1510, #1513 and #1522.

Two things worth flagging for the reviewer.

`_list_getitem_ref()` and `_list_item_gone()` stay behind. `views.h`
uses them too, and it includes `hashtable.h` but not the new header, so
moving them would have left `views.h` compiling only by accident of the
include order in `_multidict.c`. They now have no user left in
`hashtable.h` itself, which deserves a proper home shared with the
open-coded two-element unpacking in `views.h`; that is its own change,
not this one.

The order the compiler sees does change, since the block now expands
after the rest of `hashtable.h` rather than in the middle of it.
`tools/codegen_diff.py` reports no difference at all, so nothing fell in
or out of line.

## Are there changes in behavior for the user?

No. The move is verbatim, and the pure Python implementation has no
header structure to mirror.

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

No, it shrinks `hashtable.h` by around 710 lines and keeps the bulk
paths separate from the table and its single-key API.

## Related issue number

N/A

## Checklist

- [x] I think the code is well written
- [ ] Unit tests for the changes exist: N/A, code move only; the moved
  functions are already covered through the constructors, `extend()`,
  `update()` and `merge()`
- [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`

<details>
<summary>Agent run details (optional, for reviewers)</summary>

Rebased onto master after #1529 and #1530 landed; #1530 reworked the
same region, so `bulk_update.h` was rebuilt from master's text rather
than carried over from the earlier push, and its includes now name
`reflist.h` instead of the removed `deferred_decref.h`.

Verbatim-move check: the moved text, with the retained
`_list_getitem_ref` block spliced back at its original offset,
reconstructs master's `hashtable.h` lines 1693-2416 exactly.

Codegen (`tools/codegen_diff.py --ref upstream/master`):
- CPython 3.13.2: 0 of 191 functions differ
- CPython 3.14.7t: 0 of 196 functions differ

Tests, `python -m pytest tests -q -k "not test_leak"`, each in its own
venv:
- 3.13.2 release build: 2326 passed, 107 skipped
- 3.13.2 debug build (`MULTIDICT_DEBUG_BUILD=1`, asserts on): 2326
  passed, 107 skipped
- 3.14.7t debug build: 2315 passed, 118 skipped
- Pure Python (`MULTIDICT_NO_EXTENSIONS=1`, `--no-c-extensions`): 1124
  passed, 17 skipped

Lint: `pre-commit run --all-files` passed; `make doc-spelling` passed.
</details>

Drafted with Claude Code (Opus 5); reviewed by @asvetlov.
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