Skip to content

Pass the entry identity to the ForEach visitor - #1552

Merged
asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:claude/foreach-identity-arg
Sep 24, 2026
Merged

asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:claude/foreach-identity-arg

Conversation

@asvetlov

Copy link
Copy Markdown
Member

What do these changes do?

The ForEach visitor received the key and the value but not the identity,
the canonical key a multidict actually looks entries up by. On a
CIMultiDict that is the internal lower-cased form, so a visitor wanting
to group or compare entries by it had to derive it again itself,
duplicating work the walk had already done.

MultiDict_ItemVisitor now takes
(void *user_data, PyObject *identity, PyObject *key, PyObject *value).
user_data stays first so existing call sites keep their shape, and the
identity goes next to the key and value it belongs with rather than at the
end. MultiDict_CyItemVisitor gains it in the same position, keeping its
own user_data-last order. The internal md_item_visitor_t in
_multilib/walk.h is widened to match, along with md_walk_all,
md_walk_with_hash and their two in-tree visitors.

The two walks source it differently. md_walk_with_hash passes the
identity it was already handed, which every matched entry compares equal
to by the walk's own predicate, so the keyed path does no extra work.
md_walk_all reads entry->identity and holds a reference across the
visitor call, the same way it already does for the value, since
_md_ensure_key() and the visitor can both run Python code that frees
the entry.

The capsule is unreleased: it landed in #1480, after v6.9.1, and
MultiDict_CAPI_VERSION is still 1, so no client can have been built
against the narrower signature. That is why the typedef changes in place
instead of growing a parallel entry point at the end of the struct with a
version bump.

Are there changes in behavior for the user?

No, for Python-level users. A C or Cython client of the capsule has to
take the extra parameter, but the capsule has not shipped in a release
yet, so there is nothing to migrate.

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

No. Both walks already have the identity in hand, so the wider signature
costs nothing on the keyed path and one reference pair per entry on the
all-entries path.

One benchmark row does move, and it is worth a reviewer's attention.
d.pop(key) gets slower on GIL builds: measured on CPython 3.14.7,
MultiDict 428.8 to 441.5 instructions (+2.96%) and CIMultiDict 713.5 to
726.2 (+1.78%). Every other row is bit-identical, and the free-threaded
build is unaffected. The cause is not the walk; it is GCC's inlining
budget in hashtable.h. Widening _md_getall_visit by one parameter is
enough to tip htkeysiter_init out of line inside md_pop_one, which
objdump confirms as a new call <htkeysiter_init> on the GIL build and
not on the free-threaded one.

An ALWAYS_INLINE on htkeysiter_init removes it, and wins well beyond
pop because GCC already outlines that helper in several places on
master. That belongs in its own pull request, with its own numbers, and
is left out of this one deliberately.

docs/benchmark.rst is not regenerated here on purpose. The dict
control rows in this environment reproduce the committed tables exactly
on both builds (d.pop(key) 476.4 against a published 476 on the GIL
build, 587.4 against 587 free-threaded), but every multidict row
differs by a few percent (446 published against 428.8 measured on the
GIL build, 562 against 548.8 free-threaded). The interpreter matches
and the compiler does not, so regenerating would rewrite every
multidict row for toolchain reasons unrelated to this change. Calling
the one moved row out in prose seemed better than that.

Related issue number

None; this came out of a session looking at the ForEach walks.

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
Agent run details (optional, for reviewers)

Tests, each in its own virtualenv against its own copy of the tree, so a
stale .so cannot make a leg lie:

CPython 3.13.12, C extension      2542 passed, 21 skipped
CPython 3.13.12, MULTIDICT_NO_EXTENSIONS=1 --no-c-extensions
                                  1180 passed, 17 skipped, 1189 deselected
CPython 3.14.7t, free-threaded    2531 passed, 32 skipped
CPython 3.10.17, oldest supported 2542 passed, 21 skipped

Every leg that has a C extension built the Cython harness too and ran with
MULTIDICT_TEST_REQUIRE_CYAPI=1, so the _testcyapi half of
tests/test_capi.py is a hard failure rather than a skip.

Lint: pre-commit run --all-files passes, including clang-format and
both mypy hooks. make doc-spelling passes.

Benchmarks: benchmarks/callgrind_driver.py, bracketed (pytest-codspeed
installed so the instrumented region is delimited), PYTHONHASHSEED=0, on
CPython 3.14.7 and 3.14.7t, base and branch each built from a clean
git archive of its own commit. Only the d.pop(key) GIL rows move; the
numbers are in the section above.

Drafted with Claude Opus 5 in Claude Code. Left as a draft for @asvetlov to review before it goes out.

The public C API and Cython API visitor callbacks got the key and the
value but not the identity, the canonical key the mapping actually
looks entries up by. On a CIMultiDict that is the internal lower-cased
form, so a visitor that wanted to group or compare entries had to
derive it again itself.

Widen MultiDict_ItemVisitor, MultiDict_CyItemVisitor and the internal
md_item_visitor_t to take it. The capsule is unreleased (it landed
after v6.9.1 and MultiDict_CAPI_VERSION is still 1), so no client can
have been built against the narrower signature and the typedef changes
in place rather than needing a parallel entry point.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 24, 2026
@codspeed

codspeed Bot commented Sep 24, 2026

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 310 untouched benchmarks


Comparing asvetlov:claude/foreach-identity-arg (48c2390) with master (8b5dd23)

Open in CodSpeed

@asvetlov
asvetlov marked this pull request as ready for review September 24, 2026 06:56
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 24, 2026 06:56
@codecov

codecov Bot commented Sep 24, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (9682ba1) to head (48c2390).
⚠️ Report is 4 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1552   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           40        41    +1     
  Lines         6876      6962   +86     
  Branches       596       605    +9     
=========================================
+ Hits          6876      6962   +86     
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.

@greptile-apps

greptile-apps Bot commented Sep 24, 2026

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 4/5

Not safe to merge until the existing C callback contract is preserved and the news fragment meets the repository requirement.

Reviews (1) · Last reviewed commit: "Pass the entry identity to the ForEach v..."

Comment thread multidict/multidict_capi_struct.h Resolved
Comment thread CHANGES/1552.feature.rst Resolved
@greptile-apps

greptile-apps Bot commented Sep 24, 2026

Copy link
Copy Markdown
Contributor

Comments Outside Diff

These findings sit on lines the diff does not cover, so they could not be posted inline. Each one leaves this list once its file changes.

  • P1 Unversioned ForEach callback change silently breaks C clients in both directions ▶

    • Bug
      • An old-header client does not continue to work correctly against the new runtime: its value callback argument becomes the identity. A new-header client is not rejected by the older runtime and receives mismatched callback arguments. Clients that use the missing fourth argument may have more severe behavior, but that was not exercised.
    • Cause
      • multidict/multidict_capi_struct.h:21-24 changes MultiDict_ItemVisitor from three arguments to four while retaining MultiDict_CAPI_VERSION 1 and the existing MultiDict_ForEach slot at lines 61-63. multidict/multidict_capi.h:13-23 therefore accepts both combinations.
    • Fix
      • Preserve the existing ForEach slot and its three-argument callback; introduce a separately versioned four-argument slot and bump the C API version so new clients reject runtimes lacking it.

@asvetlov
asvetlov merged commit cd92a6c into aio-libs:master Sep 24, 2026
62 checks passed
@asvetlov
asvetlov deleted the claude/foreach-identity-arg branch September 24, 2026 07:51
asvetlov added a commit that referenced this pull request Sep 24, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

The `ForEach` visitor gained the entry's identity in #1552, but not
the hash the mapping stores alongside it. A visitor that buckets or
groups entries by identity therefore had to hash it again, work both
walks had already done.

`MultiDict_ItemVisitor` now takes
`(void *user_data, PyObject *identity, Py_hash_t hash, PyObject *key,
PyObject *value)`, with the hash next to the identity it belongs to.
`MultiDict_CyItemVisitor` gains it in the same position, keeping its
own `user_data`-last order. The internal `md_item_visitor_t` in
`_multilib/walk.h` is widened to match, along with `md_walk_all`,
`md_walk_with_hash` and their two in-tree visitors.

`md_walk_with_hash` passes the hash it was already handed; every
matched entry's own `entry->hash` equals it, since that is the first
half of the walk's match predicate. `md_walk_all` reads `entry->hash`
before the visitor call, alongside the identity and value it already
reads there, since `_md_ensure_key()` and the visitor can both run
Python code that frees the entry.

The capsule is unreleased: it landed in #1480, after v6.9.1, and
`MultiDict_CAPI_VERSION` is still 1, so no client can have been built
against the narrower signature. That is why the typedef changes in
place instead of growing a parallel entry point at the end of the
struct with a version bump.

## Are there changes in behavior for the user?

No, for Python-level users. A C or Cython client of the capsule has to
take the extra parameter, but the capsule has not shipped in a release
yet, so there is nothing to migrate.

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

No. Both walks have the hash in hand already, so the wider signature
costs neither a lookup nor a reference.

This one does not move the benchmarks. On the GIL build no
C-extension row changed at all; on the free-threaded build the three
that did move (`update` on `CIMultiDict` -0.24% and on `MultiDict`
+0.08%, `popitem` on `CIMultiDict` -0.02%) sit well inside the noise
floor the untouched pure-Python rows show across the same pair of
runs, which reaches 1.8%. `docs/benchmark.rst` is unchanged
accordingly.

## Related issue number

None; this follows #1552 directly.

## Checklist

- [x] I think the code is well written
- [x] Unit tests for the changes exist
- [x] Documentation reflects the changes
- [ ] 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>

Tests, each in its own virtualenv against its own copy of the tree, so
a stale `.so` cannot make a leg lie:

```
CPython 3.13.12, C extension      2699 passed, 21 skipped
CPython 3.13.12, MULTIDICT_NO_EXTENSIONS=1 --no-c-extensions
                                  1258 passed, 17 skipped, 1268 deselected
CPython 3.14.7t, free-threaded    2687 passed, 33 skipped
CPython 3.10.17, oldest supported 2699 passed, 21 skipped
```

Every leg with a C extension built the Cython harness too and ran with
`MULTIDICT_TEST_REQUIRE_CYAPI=1`, so the `_testcyapi` half of
`tests/test_capi.py` is a hard failure rather than a skip.

The `md_foreach` harnesses now return `(identity, hash, key, value)`,
and the tests assert the hash against `hash(identity)`, which on a
`CIMultiDict` is the lower-cased form's hash and not the key's.

Lint: `pre-commit run --all-files` passes, including `clang-format`
and both `mypy` hooks. `make doc-spelling` passes.

Benchmarks: `benchmarks/callgrind_driver.py`, `PYTHONHASHSEED=0`, on
CPython 3.14.7 and 3.14.7t, base (pinned at the merge base cd92a6c)
and branch each built from a clean copy of its own tree in its own
virtualenv. Numbers in the section above.

</details>

Drafted with Claude Opus 5 in Claude Code. Left as a draft for @asvetlov
to review before it goes out.

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
asvetlov added a commit that referenced this pull request Sep 26, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

Prepares the news fragments for 7.0.0.

The public C API (#1480) and the watchers API (#1551) are new in this
release, so the fragments describing later changes to them describe
states that never shipped. They are folded into the entries that added
the APIs: the visitor's identity and hash (#1552, #1561) into `1478`,
and the 32-watcher limit, the watcher registration race fix and the
failing-callback report (#1574, #1583, #1585) into `1551`. The
`MultiDict_SetDefault(NULL)` half of `1553` is dropped for the same
reason.

Intermediate header names that never shipped are removed as well: `1510`
no longer mentions `deferred_decref.h`, which #1530 merged into
`reflist.h`, and `1513` names `debug.h` directly, so `1576` goes.
`1572`, a fix to a tool added this cycle, is folded into `1529`. `1560`
and the last sentence of `1556` go too, since the release refresh of the
benchmark tables supersedes those intermediate ones.

Finally, the fragments that did not lead with a past-tense verb or
described the change as "now ..." are rewritten per `AGENTS.md`.

The benchmark table refresh from `RELEASE.md` step 2 is still to be
added to this branch before it leaves draft.

## Are there changes in behavior for the user?

No.

## 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
- [ ] Unit tests for the changes exist (N/A, changelog only)
- [x] Documentation reflects the changes
- [ ] If you provide code modification, please add yourself to
`CONTRIBUTORS.txt` (N/A)
- [ ] Add a new news fragment into the `CHANGES/` folder (N/A, edits
existing fragments; the benchmark refresh will add a `doc` fragment)
- [x] `make doc-spelling` passes and any new technical words are added
to `docs/spelling_wordlist.txt`

Drafted with Claude Code (Claude Opus 5.5); pending review by @asvetlov
before leaving draft.

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

`python -Im towncrier build --draft --version 7.0.0` renders cleanly.
The symlinked pairs `1512` -> `1492` and `1562` -> `1555`, and both
`1535` fragments, are intentional and left alone.
</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