Skip to content

Populate a new hash table entry the same way on both builds - #1528

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

asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:claude/merge-insert-order-ifdefs

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

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

  • 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)
  • 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)

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.

The free-threaded build has to publish an entry's identity last,
because that 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
own field order was arbitrary; letting it adopt the free-threaded one
leaves a single body and removes the conditional from both insert
helpers.

The free-threaded arm also called store_value(), which loads the old
value and releases it. A newly inserted entry is carved out of the
zeroed tail past every live entry, so the old value is always NULL and
both the load and the Py_XDECREF() were dead; publish_value() is what
the code meant, and an assert now states the precondition. That leaves
store_value() with no callers, so it goes too.

GIL-build code generation changes: four stores swap places and the
dead load and decref disappear. The free-threaded build keeps the
order it had and loses only that dead pair.
@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

✅ 310 untouched benchmarks


Comparing asvetlov:claude/merge-insert-order-ifdefs (0736bc2) with master (a794a6e)

Open in CodSpeed

@asvetlov
asvetlov marked this pull request as ready for review September 23, 2026 07:27
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 23, 2026 07:27
@greptile-apps

greptile-apps Bot commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

Safe to merge: the affected native insertion operations produced the same checked results before and after the change, and focused coverage passed.

What we checked:

  • Authored the executable init-order check script and the orchestration command for unified init-order validation. T-Rex
  • Ran the parent native extension check and captured the before-state results in the before log. T-Rex
  • Rebuilt the changed HEAD as an editable MULTIDICT_DEBUG_BUILD=1 native extension, then executed the unified init-order validation and captured the after-state results in the after log, including the loaded .so path and pytest outcome. T-Rex
  • Compared the parent and changed HEAD checks and confirmed identical results. T-Rex

Reviews (1) · Last reviewed commit: "Populate a new hash table entry the same..."

@asvetlov
asvetlov merged commit 9475056 into aio-libs:master Sep 23, 2026
61 checks passed
@asvetlov
asvetlov deleted the claude/merge-insert-order-ifdefs branch September 23, 2026 07:42
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