Skip to content

Route every shared hash table field through named accessors - #1518

Merged
asvetlov merged 3 commits into
aio-libs:masterfrom
asvetlov:claude/freethreading-accessors
Sep 22, 2026
Merged

asvetlov merged 3 commits into
aio-libs:masterfrom
asvetlov:claude/freethreading-accessors

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

What do these changes do?

Every field of the hash table that code on both builds touches is now
read and written through a named inline accessor in a new
_multilib/freethreading.h header, instead of each call site picking
between an atomic and a plain access behind #ifdef Py_GIL_DISABLED.
Under free-threading an accessor forwards to atomic_helpers.h,
otherwise it is the plain access the GIL already makes safe.
atomic_helpers.h gained GIL-build versions of the primitives it was
missing, which is what makes that possible.

#ifdef Py_GIL_DISABLED across the extension drops from 39 to 25, and in
hashtable.h from 31 to 16. _md_del_at() is the clearest case: it had
carried the same fifteen lines of bookkeeping twice, once per build.
htkeys.h's LOAD_INDEX/STORE_INDEX macros become ordinary inline
functions for the same reason.

An accessor earns its place only by unifying the two builds, so code that
compiles solely under Py_GIL_DISABLED keeps naming atomic_helpers.h
directly. The lock-free reader protocol is all of that, and it is
byte-for-byte unchanged.

No access changes type: each site keeps the operation and memory order it
already had, and reads made under md's critical section stay plain.

Are there changes in behavior for the user?

No. Both builds compile to byte-identical machine code.

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

No; it removes duplication rather than adding any. Adding a new mutation
no longer means remembering which fields are shared and what ordering
each needs.

Related issue number

None.

Checklist

  • I think the code is well written
  • Unit tests for the changes exist (N/A, no behaviour change; the existing suite is the test)
  • Documentation reflects the changes (N/A, internal C headers only)
  • If you provide code modification, please add yourself to CONTRIBUTORS.txt
  • 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; reviewed by @asvetlov.

Agent run details (optional, for reviewers)

Codegen, compared per function against master with objdump -d --no-show-raw-insn and addresses normalised: 0 of 240 functions differ
on the GIL build, 0 of 254 on the free-threaded build.
The build is
deterministic, so this is a real byte-for-byte result, and it is the main
evidence that nothing changed.

Tests, GIL build (CPython 3.14.2): 2170 passed, 21 skipped.
Tests, free-threaded build (3.14.7t): 2159 passed, 32 skipped.
Tests, free-threaded debug build (MULTIDICT_DEBUG_BUILD=1, so
ASSERT_CONSISTENT runs): 2159 passed, 32 skipped.

ASan + UBSan (MULTIDICT_DEBUG_BUILD=1 MULTIDICT_ASAN_BUILD=1,
LD_PRELOAD=libasan.so, PYTHONMALLOC=malloc, -k "not test_leak"):
2159 passed, clean.

ThreadSanitizer: CI's own TSan leg passes on this commit. An earlier
local TSan run against a superseded revision of the branch is not quoted
here, since it does not describe the code being proposed.

make doc-spelling passes; accessor added to
docs/spelling_wordlist.txt. pre-commit run passes.

Two things noticed and deliberately left alone, for the maintainer to
decide on:

  1. _md_add_with_hash_steal_refs() and _md_add_for_upd_steal_refs()
    hold the only two remaining access-mode #ifdefs. Their free-threaded
    arm calls store_value(), which loads the old value and Py_XDECREFs
    it, on an entry that is always freshly zeroed memory, so both are dead
    work. publish_value() would do, and the arms could then merge, at
    the cost of reordering four stores on the GIL build.
  2. Py_CLEAR(entry->identity) is not reset_identity(): it skips the
    store when the field is already NULL. Converting it changed the
    emitted code across 34 inlined functions, so those sites keep the raw
    field.

@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 22, 2026
@codspeed

codspeed Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 298 untouched benchmarks


Comparing asvetlov:claude/freethreading-accessors (d320b9e) with master (d647f3e)

Open in CodSpeed

@codecov

codecov Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1518   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           38        38           
  Lines         6381      6406   +25     
  Branches       579       579           
=========================================
+ Hits          6381      6406   +25     
Flag Coverage Δ
CI-GHA 100.00% <ø> (ø)
pytest 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 force-pushed the claude/freethreading-accessors branch 4 times, most recently from 8a59123 to 7979562 Compare September 22, 2026 21:14
Every field of the hash table that code on *both* builds touches now has
a named inline accessor in the new freethreading.h. The header is split
once, the way atomic_helpers.h is: the free-threaded arm forwards to
that header's atomics, the GIL arm is the plain access each name
describes, and each arm is a complete set on its own. Each accessor
keeps the operation and memory order its call sites already had, so
neither build changes behaviour.

Fifteen `#ifdef Py_GIL_DISABLED` blocks in hashtable.h existed only to
pick between an atomic and a plain access and collapse to a single body;
the file goes from 31 of them to 16. _md_del_at() is the clearest case,
having carried the same fifteen lines of bookkeeping twice, once per
build.

atomic_helpers.h loses the three GIL-mode definitions it had, so a name
beginning `atomic_` now always means a real atomic and the choice
between an atomic and a plain access is made in one place.
_unicode_hash() makes that choice inline, since htkeys.h cannot include
freethreading.h.

Code that only ever compiles under Py_GIL_DISABLED gains nothing from an
accessor, so the lock-free reader protocol keeps naming atomic_helpers.h
directly and is unchanged.

Each field is reached with exactly one memory order, so the accessor
names do not carry an order suffix; the free-threaded arm shows which
order a field uses. A field needing a second order would get a second
accessor, and that is when the names should start saying which is which.

entry_publish_identity()/entry_publish_value() skip
PyUnstable_EnableTryIncRef() on the GIL build: it has nothing to do
there, and unlike PyUnstable_TryIncRef() it is a real out-of-line call
on 3.14+, so leaving it in would have added a PLT call per insert to a
build that never made one before.

Py_CLEAR() and Py_VISIT() sites keep the raw field: they need an lvalue,
and Py_CLEAR() is not entry_reset_*() rewritten, since it skips the
store when the field is already NULL.

The two _md_entry_clear_*() helpers are not carried over; they have had
no caller since they were written.
LOAD_INDEX()/STORE_INDEX() were macros so that the atomic and plain
spellings could differ per build. Ordinary functions can do that too,
one pair per slot width, generated the same way atomic_helpers.h
generates its own width-specific helpers, with the build split around
the generator rather than around each use.

They stay in htkeys.h rather than moving to freethreading.h: htkeys.h
calls them itself, from htkeysiter and htkeys_build_indices(), so they
cannot live in a header that includes it.
@asvetlov
asvetlov force-pushed the claude/freethreading-accessors branch from 7979562 to d320b9e Compare September 22, 2026 21:26
@asvetlov
asvetlov marked this pull request as ready for review September 22, 2026 21:32
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 22, 2026 21:32
@greptile-apps

greptile-apps Bot commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

No merge-blocking issue was identified in the exercised GIL-build behavior; free-threaded behavior remains unexecuted in this environment.

What we checked:

  • Ran the multidict-gil-accessor-probe.py, and both the parent run and PR-head run completed with exit code 0 and identical passing behavior, with the after run loading the built extension. T-Rex
  • Verified that no repository source files were modified; the authored probe and command captures are confined to trex-artifacts. T-Rex
  • Ran the free-threaded environment check script and recorded that only CPython 3.11.6 interpreters are available, and each reports Py_GIL_DISABLED with no sys._is_gil_enabled, blocking free-threaded invocation. T-Rex
  • Documented the blocker condition by inspecting the environment-check log and interpreter results. T-Rex

Reviews (1) · Last reviewed commit: "Add a news fragment for the accessor ref..."

@asvetlov
asvetlov merged commit 1cdd934 into aio-libs:master Sep 22, 2026
61 checks passed
@asvetlov
asvetlov deleted the claude/freethreading-accessors branch September 22, 2026 21:54
asvetlov added a commit that referenced this pull request Sep 22, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

`get_mod_state_by_cls()` in `multidict/_multilib/state.h` has no call
sites anywhere in the tree, so it is removed. Module state is reached
through `get_mod_state()`, `get_mod_state_by_def()` and
`get_mod_state_by_def_checked()` everywhere in the extension. Dropping
the helper also leaves `PyType_GetModuleState()` with no remaining
user; no include becomes unnecessary, since `state.h` gets that
declaration from `Python.h`.

C extension only; the pure-Python backend has no equivalent and needs
no matching change.

## Are there changes in behavior for the user?

No. The helper was never reachable from Python.

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

No, it removes code.

## Related issue number

None. Split out of #1518 so that pull request stays one logical change.

## Checklist

- [x] I think the code is well written
- [ ] Unit tests for the changes exist — N/A, removal of dead code with
no behaviour to test
- [ ] Documentation reflects the changes — N/A, the helper was internal
and undocumented
- [ ] 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>

Verification that the helper is unreferenced:

```
$ grep -rn "get_mod_state_by_cls" .
CHANGES/1520.misc.rst:1:Removed ``get_mod_state_by_cls()``, an unused helper in the C extension
```

(only the news fragment, after the deletion). `grep -rn
"PyType_GetModuleState"` over `*.c`/`*.h` excluding the vendored
`pythoncapi_compat.h` returns nothing afterwards.

Both backends, run after rebasing onto `1cdd934` (#1518):

C extension, CPython 3.14.7t

```
$ pip install -e . --force-reinstall --no-deps
$ python -m pytest tests -q
2187 passed, 23 skipped, 147 deselected in 90.67s

$ python -m pytest tests -q -m hypothesis
143 passed, 4 skipped, 2210 deselected in 58.40s
```

Pure Python

```
$ MULTIDICT_NO_EXTENSIONS=1 pip install -e . --force-reinstall --no-deps
$ MULTIDICT_NO_EXTENSIONS=1 python -m pytest tests -q --no-c-extensions
1104 passed, 1253 deselected in 107.44s
```

Docs

```
$ make doc-spelling
build succeeded.
```

`pre-commit run` over the changed files: clang-format and the
changelog `:user:` role check both pass.

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

## What do these changes do?

`finder.h` exported a resumable iterator, `finder_t` plus
`finder_init()`,
`find_next()` and `finder_cleanup()`, for walking every entry that
matches one
identity. Nothing needed it to be resumable: both drivers, `getall()`
and the
items view set algebra, collect every match into a list and only then
run a
user `__eq__` against it, because a re-entrant mutation must not happen
mid-walk. What the protocol did cost was a ~4.5 KB struct declared by
each
caller, a "not zero-initialized, cleanup only needs `nvisited_few`"
contract
for each to honour, and a `finder_cleanup()` on every error path;
`finder_collect()` carried a second failure label for that reason alone.

The header becomes `walk.h` and exports one function, `md_walk_key()`,
which
owns the probe walk and the visited-entry bitmap and calls a visitor per
match.
Its two consumers move next to their own callers: `getall()` into
`hashtable.h`
beside `popall()`, and the collect helper into `views.h` above the six
set
operations that use it. The algorithm, the dedup bitmap and the critical
section boundaries are unchanged.

Two small things worth flagging for the reviewer. The version check
moves from
the top of `find_next()` to just after the visitor call, which is the
same
check at the same point in the sequence, since the old consumer loop
called
`find_next()` once more even after the last match. And
`assert(finder->iter.keys == finder->md->keys)` is dropped: it sat
directly
above the `if` that handles exactly that condition, so a debug build
aborted
where a release build correctly raised `RuntimeError`.

`md_walk_key()` keeps `find_next()`'s plain field reads and does not
include
`freethreading.h`, per #1518's rule that reads made under `md`'s
critical
section stay plain.

This touches the C extension only. The pure-Python backend has no
equivalent:
its `getall()` and items view set algebra dedup by marking `entry.hash`
in the
table and restoring it afterwards, over the `iter_hash()` generator,
with no
finder object and no visited bitmap, so there is nothing to mirror.

## Are there changes in behavior for the user?

No behavior change. Keeping the walk's position in registers instead of
reloading it from the finder on every step does make things faster:
`getall()`
on a key with many values by about 30%, `CIMultiDict.getall()` by about
24%,
and `itemsview.isdisjoint()` by about 10%. Everything else measured
within
noise, nothing regressed.

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

No; it removes a caller-visible contract rather than adding one. A new
consumer
writes a visitor and cannot forget to release the bitmap.

## Related issue number

None.

## Checklist

- [x] I think the code is well written
- [x] Unit tests for the changes exist (N/A, no behavior change; the
existing
      suite is the test)
- [x] Documentation reflects the changes (N/A, internal C headers only)
- [ ] 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>

All runs on this branch, isolated venvs, against `1cdd934`.

Tests:

- C extension, CPython 3.14.2 (GIL): 2198 passed, 12 skipped
- C extension, CPython 3.14.7t (free-threaded): 2187 passed, 23 skipped
- Pure Python (`MULTIDICT_NO_EXTENSIONS=1`): 1098 passed, 6 skipped
- `MULTIDICT_DEBUG_BUILD=1` (`-O0 -UNDEBUG`, asserts live): 2198 passed
- `MULTIDICT_DEBUG_BUILD=1 MULTIDICT_ASAN_BUILD=1` under ASan/UBSan
(`LD_PRELOAD`, `PYTHONMALLOC=malloc`, `-k "not test_leak"`): 2187
passed,
  no sanitizer reports

Lint: `pre-commit run --all-files` clean (ruff, clang-format, yamllint,
mypy
3.11 and 3.13). `make doc-spelling` passes.

Code generation, `-O3` GIL build, before vs after:

- No `_visit` symbol survives in the `.so`; the visitors are inlined
into the
  walk and the walk into its two consumers.
- `_multidict_collect_matches` has exactly one indirect call, a
`call *0x78(%rax)` on `PyUnicode_Type`, which `finder_collect` had too.
No
  indirect call was introduced.
- Symbol inventory differs only by the rename: `finder_collect`,
`finder_collect.cold` and `_finder_spill` out;
`_multidict_collect_matches`,
  `_multidict_collect_matches.cold` and `_md_seen_spill` in.
- `.text` shrinks from 98144 to 97472 bytes.

Benchmarks, best of 8 runs each, GC disabled per round, CPython 3.14.2:

| case | before | after | delta |
| --- | ---: | ---: | ---: |
| `getall`, 100 values, 1k keys | 1335.8 ns | 860.9 ns | -35.6% |
| `getall`, 100 values, 20 keys | 1206.1 ns | 819.9 ns | -32.0% |
| `getall`, 5000 values | 57.3 us | 41.1 us | -28.2% |
| `CIMultiDict.getall`, 100 values | 2217.7 ns | 1687.8 ns | -23.9% |
| `itemsview.isdisjoint` | 1044.5 ns | 939.0 ns | -10.1% |
| `getall` hit, single value | 106.3 ns | 104.0 ns | -2.2% |
| `getall` miss | 69.2 ns | 65.9 ns | -4.8% |
| `(k, v) in itemsview`, duplicates | 1133.3 ns | 1119.2 ns | -1.2% |
| `itemsview & set` | 133.5 us | 132.5 us | -0.8% |
| `itemsview - set` | 27.1 us | 27.7 us | +2.1% |

The last four are inside this machine's run-to-run spread.

</details>

Drafted with Claude Opus 5; reviewed by @asvetlov.
asvetlov added a commit that referenced this pull request Sep 23, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

`_md_add_with_hash_steal_refs()` and `_md_add_for_upd_steal_refs()` each
carried an `#ifdef Py_GIL_DISABLED` whose only job was to write the same
four entry fields in a different order. Only the free-threaded order has
a reason behind it: `identity` is published last because it is the field
a lock-free reader checks first to decide whether a slot is populated.
The GIL build has no such reader, so its order was arbitrary; letting it
adopt the free-threaded one leaves a single body in both helpers.

The free-threaded arm also called `store_value()`, which loads the value
the entry already holds and releases it. A new entry is carved out of
the zeroed tail past every live one, so that value is always NULL and
both the load and the `Py_XDECREF()` were dead work; `publish_value()`
is what the arm meant. An `assert()` now states the precondition, and it
holds across the whole suite on the debug builds. That left
`store_value()` with no callers, so it goes too.

Code generation does change on the GIL build: four stores swap places,
which is why this was split out of #1518 rather than folded into it. The
free-threaded build keeps the store order it already had and loses only
the dead load and the dead decref.

## Are there changes in behavior for the user?

No.

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

No, it removes code.

## Related issue number

Follow-up to #1518, which introduced `_multilib/freethreading.h` and
deliberately left these two conditionals in place.

## Checklist

- [x] I think the code is well written
- [ ] Unit tests for the changes exist (N/A: no behavior change; the
      existing suite covers both helpers, and the new `assert()` checks
      the precondition the change relies on)
- [ ] Documentation reflects the changes (N/A: private header)
- [ ] 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 Opus 5 via Claude Code; reviewed by @asvetlov.

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

All runs on the rebased branch, against CPython 3.13.2 (GIL), 3.14.7t
(free-threaded) and a `--with-thread-sanitizer` 3.14.7t for the TSan
leg.

Tests:

```
make install-dev && pytest -q                     2210 passed, 21 skipped
MULTIDICT_DEBUG_BUILD=1 (GIL)                     2210 passed, 21 skipped
MULTIDICT_NO_EXTENSIONS=1, --no-c-extensions      1103 passed, 15 skipped
MULTIDICT_DEBUG_BUILD=1 (free-threaded)           2199 passed, 32 skipped
MULTIDICT_TSAN_BUILD=1, -k "not test_leak"        2188 passed, 23 skipped, 0 TSan warnings
```

The two debug legs run with `-UNDEBUG`, so the new
`assert(entry->identity == NULL && entry->key == NULL && entry->value ==
NULL)` is checked on every insert the suite performs, on both builds.
That is the evidence for the "entry is freshly zeroed" claim the
`publish_value()` switch rests on; the claim also follows from the code,
since `htkeys_new()` zeroes the entry region, `_md_resize()` sets
`nentries` to the number of entries it copied into a fresh table,
`_md_shrink()` zeroes the tail it frees up, and `md_clone_from_ht()`
copies the whole buffer including that zeroed tail.

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

Code generation was compared before and after with identical flags
(`-O3 -DNDEBUG -std=c11`), disassembled with `objdump -d
--no-show-raw-insn` and diffed per function. Normalising away
RIP-relative displacements, branch offsets and objdump's own header is
what makes the diff readable; without it, one instruction-length change
shifts every later label and buries the real differences. The harness
was validated by checking that the same object normalises identically
twice and that the same tree built twice compares equal.

On the GIL build, 3 of 157 functions differ:
`_md_add_with_hash_steal_refs()`
and the two that inline it, `md_extend_self()` and `_md_merge()`. Each
keeps
its instruction count and its set of call targets exactly; the only
change is
the four stores appearing in a different order, with the same registers
and
the same offsets.

On the free-threaded build, 8 of 163 differ. Three are the insert path
(`_md_add_with_hash_steal_refs()`, `_md_add_for_upd()`,
`md_extend_self()`),
each shedding 5 to 12 instructions and exactly one `Py_DECREF` call
site;
three more are the `.cold` halves of those same functions. The last two,
`_multidict_ctor_vectorcall()` and `multidict_keysview_repr()`, are not
on
the insert path: their call-target sets are identical before and after,
and
they change only because the optimiser flipped its decision about
inlining
`_Py_NewRef()` once the helpers next door got smaller.

Because a per-function diff cannot separate "the helper changed" from
"the
optimiser reacted to the helper changing", the two helpers were also
compiled
on their own, through `noinline` wrappers in a small translation unit
that
includes the headers. There the answer is unambiguous: the GIL object
differs
only by the store order, and the free-threaded object differs only by
the
disappearance of the `mov` that loaded the old value and of the
`Py_XDECREF(NULL)` branch that followed it.

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

## What do these changes do?

`md_clear()` holds the last three stores to a shared entry field that do
not go through `_multilib/freethreading.h`. #1518 left them alone on
purpose but recorded the reason only in its own PR footer, so this puts
it
at the site. Nothing else changes.

Keeping the raw access wins on two counts. `Py_CLEAR()` is not a decref
plus `reset_identity()`: it skips the store entirely when the field is
already NULL, which the accessors cannot express. And the block is the
`#else` arm of `#ifdef Py_GIL_DISABLED`, so it compiles only on the GIL
build, where every accessor is plain field access and there is no
ordering
for one to carry; the free-threaded build reaches none of it, since
`_md_retire()` owns that path. A `clear_identity()` would therefore
exist
solely for a single GIL-only call site, which fails the bar #1518 set
for
adding an accessor: it has to unify the two builds.

The two alternatives were built and measured rather than argued about;
the
numbers are in the footer.

## Are there changes in behavior for the user?

No. Both builds compile to byte-identical machine code.

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

No. It is four lines of comment.

## Related issue number

None. Split out of #1518, which reported these sites.

## Checklist

- [x] I think the code is well written
- [x] Unit tests for the changes exist (N/A, comment only; the existing
suite is the test)
- [x] Documentation reflects the changes (N/A, internal C header)
- [ ] 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`

Drafted with Claude Opus 5; reviewed by @asvetlov.

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

Codegen, `objdump -d --no-show-raw-insn` compared per function against
`master` at a794a6e with addresses, RIP displacements and intra-function
branch offsets normalised. The harness was checked two ways first: two
builds of the same tree are identical, and a throwaway comment inserted
at
the same spot is also identical, so it does not simply fail to notice
things.

| Variant | GIL build | Free-threaded build |
| --- | --- | --- |
| This PR (comment only) | 0 of 239 functions differ | 0 of 253 differ |
| `clear_identity()`/`clear_value()` accessors replicating `Py_CLEAR()`
exactly, including the skipped store | 23 of 239 differ | n/a,
unreachable there |
| Load, `reset_identity()`/`reset_value()`, then `Py_XDECREF` | 40 of
239 differ | n/a |

The accessor variant is worth a note: its inlined body is the same
instruction sequence, but GCC rotates the clearing loop differently, so
it
cannot be shown to be a no-op even though it is one. That is the whole
reason this PR does not take it.

Tests, all on this commit:

- GIL build, CPython 3.14.2, C extension: 2210 passed, 21 skipped.
- Free-threaded build, 3.14.7t, C extension: 2199 passed, 32 skipped.
- Pure Python, per the recipe #1523 just added: 1103 passed, 15 skipped,
1112 deselected.

No sanitizer or ThreadSanitizer run is quoted. The machine code is
unchanged, so there is nothing for them to say that CI's own legs do
not.

`make doc-spelling` passes. `pre-commit run` passes; clang-format leaves
the comment as written.

</details>
asvetlov added a commit to asvetlov/multidict that referenced this pull request Sep 23, 2026
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.
asvetlov added a commit that referenced this pull request Sep 23, 2026
<!-- Thank you for your contribution! -->

## 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

- [x] 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)
- [x] 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)
- [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 via Claude Code; reviewed by @asvetlov.

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

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.

</details>
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