Skip to content

Explain why md_clear() keeps Py_CLEAR() on the GIL build - #1526

Merged
asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:claude/py-clear-accessors
Sep 23, 2026
Merged

asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:claude/py-clear-accessors

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

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

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

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.

@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 22, 2026
@asvetlov
asvetlov force-pushed the claude/py-clear-accessors branch from ba2056a to 673247f Compare September 22, 2026 22:47
@asvetlov
asvetlov marked this pull request as ready for review September 22, 2026 22:48
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 22, 2026 22:48
@greptile-apps

greptile-apps Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

Safe to merge.

Reviews (2) · Last reviewed commit: "Explain why md_clear() keeps Py_CLEAR() ..."

@codspeed

codspeed Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 310 untouched benchmarks


Comparing asvetlov:claude/py-clear-accessors (6b5b46a) with master (a794a6e)

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 (a794a6e) to head (6b5b46a).

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1526   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           38        38           
  Lines         6455      6455           
  Branches       591       591           
=========================================
  Hits          6455      6455           
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.

The accessor refactor left three raw entry-field accesses in
md_clear()'s non-free-threaded arm. Py_CLEAR() skips the store when
the field is already NULL, which reset_identity() and reset_value()
cannot express, and that arm compiles only on the GIL build, where an
accessor carries no ordering anyway. Record both reasons at the site so
the conversion is not attempted again.
@asvetlov
asvetlov force-pushed the claude/py-clear-accessors branch from 673247f to 6b5b46a Compare September 22, 2026 23:50
@asvetlov
asvetlov merged commit 7d74f3e into aio-libs:master Sep 23, 2026
61 checks passed
@asvetlov
asvetlov deleted the claude/py-clear-accessors branch September 23, 2026 07:46
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