Skip to content

Drop two module state lookups that were already answered - #1536

Merged
asvetlov merged 2 commits into
aio-libs:masterfrom
asvetlov:claude/drop-answered-state-lookups
Sep 23, 2026
Merged

asvetlov merged 2 commits into
aio-libs:masterfrom
asvetlov:claude/drop-answered-state-lookups

Conversation

@asvetlov

Copy link
Copy Markdown
Member

What do these changes do?

Two places in the C extension asked for the module state although it was
already at hand.

MultiDict.__init__() and CIMultiDict.__init__() called
get_mod_state_by_def(), which is PyType_GetModuleByDef() plus
PyModule_GetState(), even though tp_new() stores that same pointer in
self->state before either of them can run. They read the field now. The
two proxy tp_init()s are left alone: MultiDictProxy's tp_new is
PyType_GenericNew, so self->md is still NULL there and the lookup is
the only way to get the state.

The istr object had a mod_state * field that was written on every
creation and never read; the only field ever read off an istr is
canonical. Dropping it also takes eight bytes off every istr.

This is C-extension-only. The pure-Python backend has no module state, so
there is nothing to mirror there.

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

N/A

Checklist

  • I think the code is well written
  • Unit tests for the changes exist
  • Documentation reflects the changes
  • 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 via Claude Code; reviewed by @asvetlov.

Agent run details (optional, for reviewers)

Measured with callgrind, instructions retired per operation, PYTHONHASHSEED=0,
GC collected then disabled, each case run at N and 2N iterations with the totals
subtracted so startup and loop overhead cancel. CPython 3.14.7, GIL build.

benchmark before after delta
MultiDict subclass from a 10-key dict 3980.9 3937.9 -43 (-1.1%)
CIMultiDict subclass from a 10-key dict 4844.9 4801.9 -43 (-0.9%)
istr('Content-Type') 2605.9 2604.9 -1
CIMultiDict(dict) 4104.9 4104.9 0
MultiDict(dict) 3117.9 3117.9 0
CIMultiDict.__getitem__ (str key) 346.9 346.9 0
CIMultiDict.__getitem__ (istr key) 327.9 327.9 0
MultiDict.__getitem__ 268.9 268.9 0
CIMultiDict.getall 1359.0 1359.0 0

The 43 instructions are the PyType_GetModuleByDef() and
PyModule_GetState() call pair. Only the subclass path reaches tp_init():
a call on the exact type goes through tp_vectorcall, and CPython does not
copy tp_vectorcall to a Python subclass, so those fall back to
type_call() -> tp_new + tp_init. istr.__basicsize__ goes from 80 to 72.

Tests, CPython 3.14.7:

pytest -q                                           2338 passed, 107 skipped
MULTIDICT_NO_EXTENSIONS=1 pytest -q --no-c-extensions  1125 passed, 17 skipped
pytest -q -m hypothesis                              142 passed, 5 skipped
make doc-spelling                                    build succeeded
PYENV_VERSION=3.13.2 pre-commit run --all-files      all passed

MultiDict.__init__() and CIMultiDict.__init__() resolved the module
state from the type with PyType_GetModuleByDef() and
PyModule_GetState(), although tp_new() had already stored that same
pointer in self->state before either of them ran. Read the field
instead.

The istr object carried a mod_state pointer of its own, written on
every creation and never read anywhere; the only field read off an
istr is canonical. Drop it, which also takes eight bytes off every
istr.
@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 improve performance by 11.13%

⚠️ Different runtime environments detected

Some benchmarks with significant performance changes were compared across different runtime environments,
which may affect the accuracy of the results.

Open the report in CodSpeed to investigate

⚡ 1 improved benchmark
✅ 309 untouched benchmarks

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ test_create_multidict_with_dict[ci-c] 99.4 µs 89.4 µs +11.13%

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/drop-answered-state-lookups (8a19265) with master (fdceefa)

Open in CodSpeed

@codecov

codecov Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (3e5aa5b) to head (8a19265).
⚠️ Report is 2 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1536   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           40        40           
  Lines         6820      6823    +3     
  Branches       596       596           
=========================================
+ Hits          6820      6823    +3     
Flag Coverage Δ
CI-GHA 100.00% <100.00%> (ø)
pytest 100.00% <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 marked this pull request as ready for review September 23, 2026 18:17
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 23, 2026 18:17
@asvetlov
asvetlov merged commit 88026da into aio-libs:master Sep 23, 2026
61 of 62 checks passed
@asvetlov
asvetlov deleted the claude/drop-answered-state-lookups branch September 23, 2026 18:19
@greptile-apps

greptile-apps Bot commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

Safe to merge: no actionable issues were found in the changed construction paths.

What we checked:

  • Built the C extension in debug mode and exercised explicit new() followed by init() for MultiDict and CIMultiDict, validating concrete instances, inherited subclasses, and subclasses that skip super().init() before base initialization. T-Rex
  • Ran the PR validation and the base run, and observed that all three allocation/initialization paths passed and exited with code 0, with multidict_tp_new storing state before return and tp_init reading that state in the exercised paths. T-Rex

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

asvetlov added a commit to asvetlov/multidict that referenced this pull request Sep 23, 2026
aio-libs#1536 removed the mod_state pointer from istrobject, which this branch's
rewrite of istr_new() had carried into _istr_finish(). Dropped that store
there too; the rest of the merge is clean.
@asvetlov asvetlov mentioned this pull request Sep 23, 2026
5 of 6 tasks
asvetlov added a commit that referenced this pull request Sep 23, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

`istr(x)` went through `type_call()`, which packs the argument into a
tuple, and `istr_new()` then unpacked it again with
`PyArg_ParseTupleAndKeywords()`. The one-argument form, which is how an
`istr` gets built in practice, needs none of that.

`istr` now has a `tp_vectorcall` that handles that form directly, and
leaves `istr()` and the `encoding` / `errors` signature to a cold path
that rebuilds the tuple and calls `istr_new()` as before. Subclasses are
unaffected: CPython does not copy `tp_vectorcall` to a subclass, so
`class Sub(istr)` still goes through `type_call()` and `tp_new`.

There is one cost, and it is not in the `istr` path. `getall()` runs
nine
more instructions per call, because the added code moves where the
compiler draws its inlining line and `md_calc_identity()` lands out of
line in `_md_get_all_locked()`. The multidict side of the callgrind
profile is otherwise identical, and no attempt to place the new code
differently moved that number.

C-extension-only. The pure-Python `istr` is a plain `str` subclass with
no constructor of its own, so there is nothing to mirror there.

## Are there changes in behavior for the user?

No. Every constructor form was compared against `master` case by case,
including the `encoding` and `errors` arguments, the keyword forms, the
error messages for bad arguments, subclasses, `copy` and `pickle`; the
output is identical.

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

No.

## Related issue number

N/A

## Checklist

- [x] I think the code is well written
- [x] Unit tests for the changes exist
- [x] Documentation reflects the changes <!-- N/A, no user-visible API
change -->
- [ ] 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`

`master` was merged in after #1536 landed: that PR removed the
`mod_state` pointer from `istrobject`, which this branch's rewrite of
`istr_new()` had carried into `_istr_finish()`. The numbers above were
re-measured on the merged result.

Drafted with Claude Opus 5 via Claude Code; reviewed by @asvetlov.

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

Measured with callgrind, instructions retired per operation,
`PYTHONHASHSEED=0`,
GC collected then disabled, each case run at N and 2N iterations with
the totals
subtracted so startup and loop overhead cancel. Base and branch built
and
measured back to back in one session, with the base at 88026da. CPython
3.14.7, GIL build, GCC 15.2.

| benchmark | base | new | delta |
| --- | ---: | ---: | ---: |
| `istr('Content-Type')` | 2599.9 | 2105.9 | -494 (-19.0%) |
| `istr('content-type')` | 2599.9 | 2105.9 | -494 (-19.0%) |
| `istr(an_istr)` | 1105.9 | 353.9 | -752 (-68.0%) |
| `CIMultiDict.getall` | 1359.0 | 1368.0 | +9 (+0.7%) |
| `CIMultiDict(dict)` | 4104.9 | 4104.9 | 0 |
| `CIMultiDict(dict)`, mixed-case keys | 9077.9 | 9077.9 | 0 |
| `MultiDict(dict)` | 3117.9 | 3117.9 | 0 |
| `CIMultiDict()` | 955.9 | 955.9 | 0 |
| `MultiDict` subclass from a dict | 3937.9 | 3937.9 | 0 |
| `CIMultiDict` subclass from a dict | 4801.9 | 4801.9 | 0 |
| `CIMultiDict.__getitem__` (str key) | 346.9 | 346.9 | 0 |
| `CIMultiDict.__getitem__` (istr key) | 327.9 | 327.9 | 0 |
| `CIMultiDict.__getitem__` (mixed-case key) | 944.9 | 944.9 | 0 |
| `MultiDict.__getitem__` | 268.9 | 268.9 | 0 |
| `MultiDict.__contains__` | 251.9 | 251.9 | 0 |

On the `getall` regression: a function-level callgrind diff shows the
cost
moving from `identity.h:_md_get_all_locked` to a now separate
`md_calc_identity.isra.0`, which is the call overhead. `NOINLINE` on
each of
the new helpers, and on `istr_new` itself, was tried; every variant
still
reads 1368. Marking `md_calc_identity()` `ALWAYS_INLINE` does fix it
(1351)
and speeds construction up by 3% to 4%, but costs 2.6% on
`CIMultiDict.__getitem__` and 4.6% on the `istr`-key form, so it does
not
belong here.

Tests, CPython 3.14.7:

```
pytest -q                                              2353 passed, 98 skipped
MULTIDICT_NO_EXTENSIONS=1 pytest -q --no-c-extensions  1132 passed, 8 skipped
pytest -q -m hypothesis                                 142 passed, 5 skipped
ASan + UBSan, PYTHONMALLOC=malloc, -k "not test_leak"  2342 passed, 98 skipped
make doc-spelling                                      build succeeded
PYENV_VERSION=3.13.2 pre-commit run --all-files        all passed
```
</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