Skip to content

Track md_finder_t's visited entries out of band instead of marking hashes - #1442

Closed
asvetlov wants to merge 3 commits into
aio-libs:masterfrom
asvetlov:finder-refactor
Closed

asvetlov wants to merge 3 commits into
aio-libs:masterfrom
asvetlov:finder-refactor

Conversation

@asvetlov

Copy link
Copy Markdown
Member

What do these changes do?

md_finder_t (the getall()/popall()/key-replacement lookup helper used
when a key has duplicate entries) used to deduplicate a repeated slot in
the hash probe sequence by temporarily ORing a sentinel bit into the
entry's hash, then restoring it once the lookup finished. It now keeps
its own small buffer of entry indices it has already returned instead:
an 8-element array embedded in the finder, falling back to a
heap-allocated, growable one for keys with more duplicates than that.
The finder also now holds its own reference to the key identity instead
of borrowing the caller's.

Are there changes in behavior for the user?

No.

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

No, it is an internal-only rework of one C helper with no new public
surface.

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 (N/A: no CONTRIBUTORS.txt 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
Agent run details (optional, for reviewers)

Tests: pytest -q (1839 passed) against the default C-extension build, a
debug build (MULTIDICT_DEBUG_BUILD=1, asserts enabled), and the
pure-Python leg (MULTIDICT_NO_EXTENSIONS=1); two tests added exercising
more than 8 duplicate keys for getall() and for d[key] = value
replacement (the C extension's fixed inline buffer overflows past 8, so
both need coverage). The pure-Python implementation has no equivalent
probe-sequence construct, so it needed no changes.

Lint: pre-commit run (ruff, clang-format, mypy) passes.

Docs: make doc-spelling passes.

Drafted with Claude Code (Sonnet 5); reviewed by asvetlov.

…shes

getall()/replace() used to dedupe a probe sequence's repeated slots by
temporarily ORing a sentinel bit into the entry's hash and restoring it
afterward. md_finder_t now keeps its own small buffer of already-returned
entry indices instead (an 8-element inline array, falling back to a
heap-allocated one for keys with more duplicates), so a lookup's
bookkeeping never touches state another reader could observe. It also
holds its own reference to the key identity rather than borrowing the
caller's.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 11, 2026
Comment thread multidict/_multilib/hashtable.h Resolved
@codspeed

codspeed Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

Merging this PR will degrade performance by 48.17%

⚠️ 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

❌ 8 regressed benchmarks
✅ 240 untouched benchmarks

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ test_cimultidict_getall_istr_hit[c] 34.6 ms 91 ms -61.95%
❌ test_multidict_getall_str_hit[ci-c] 36.5 ms 93.8 ms -61.15%
❌ test_multidict_getall_str_hit[cs-c] 35.7 ms 91.5 ms -60.95%
❌ test_multidict_getall_str_hit_nonascii[cs-c] 25.2 ms 53.5 ms -52.93%
❌ test_cimultidict_getall_istr_hit_nonascii[c] 26.1 ms 55.1 ms -52.56%
❌ test_multidict_getall_str_hit_nonascii[ci-c] 28.1 ms 56 ms -49.86%
❌ test_multidict_getall_str_miss[cs-c] 662.1 µs 738.5 µs -10.35%
❌ test_multidict_getall_str_miss[ci-c] 1.5 ms 1.7 ms -10.11%

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing asvetlov:finder-refactor (64d08fb) with master (88a0a85)

Open in CodSpeed

Comment thread multidict/_multilib/hashtable.h Resolved
Comment thread multidict/_multilib/hashtable.h Resolved
The comment only mentioned the unadvanced-iterator case; htkeysiter_next()
documents that the probe sequence can revisit a slot non-consecutively
too, and the visited check has to guard against any of those, not just
the immediate one.
entry->hash = finder->hash;
}
if (finder->visited != finder->visited_embedded) {
PyMem_Free(finder->visited);

@Vizonex Vizonex Sep 11, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Honestly believe a smarter mechanism should be used unless I'm missing something here. Memory Leaks were common a problem last time (for reference the fixes that I and other contributors made in 6.6.4). A better system for taking care of freeing memory should be necessary. Like a Boolean flag saying that memory was heap allocated.

@Vizonex Vizonex left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just have one little concern about this but other than that I support this Pull Request.

@codecov

codecov Bot commented Sep 11, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (88a0a85) to head (64d08fb).

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1442   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           29        29           
  Lines         4139      4153   +14     
  Branches       306       307    +1     
=========================================
+ Hits          4139      4153   +14     
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

Copy link
Copy Markdown
Member Author

Withdrawing this for now: the visited-entry tracking that replaces the in-place hash marking has a real performance regression I haven't resolved (O(N^2) blowup on lookups with many duplicate keys for the same key, up to ~18x slower at 500 duplicates, and it already regresses the existing 10-duplicate getall benchmark). Will revisit with a proper fix later rather than land this as-is.

@asvetlov asvetlov closed this Sep 11, 2026
@asvetlov
asvetlov deleted the finder-refactor branch September 11, 2026 18:06
asvetlov added a commit that referenced this pull request Sep 13, 2026
…e reads (#1448)

<!-- Thank you for your contribution! -->

## What do these changes do?

`getall()`/`popall()` (via `md_find_next()`/`md_finder_cleanup()`) and
`update()`/`extend()`/`merge()` (via `md_post_update()`) mark and unmark
a matching entry's hash while holding `self`'s critical section. That
excludes other mutators but not a lock-free reader: `__contains__` and
`get()`/`getone()`/`__getitem__` load the same field with an atomic op
and no lock at all. The mark/unmark writes were plain, non-atomic
stores, racing that atomic load under the free-threaded build. This
routes them through the existing `_md_entry_store_hash()` helper,
matching the pattern `_md_replace()`/`_md_update()` already use for the
same mark bit.

Note this is unrelated to and much cheaper than the approach tried in
#1442 (which replaced the marking scheme entirely and was withdrawn for
a large performance regression): the fix here keeps the existing
in-place marking and only makes the one racy write atomic, at the cost
of a relaxed atomic store in place of a plain one.

## Are there changes in behavior for the user?

No. This only affects the free-threaded build's internal memory-model
correctness; there is no change to observable behavior.

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

No, it's a small, self-contained fix mirroring the existing atomic-op
pattern already used elsewhere in `hashtable.h`.

## 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
- [ ] If you provide code modification, please add yourself to
`CONTRIBUTORS.txt` (N/A: no `CONTRIBUTORS.txt` 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`

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

Tests: `pytest -q` against the default C-extension build (1839 passed),
a free-threaded debug build (`MULTIDICT_DEBUG_BUILD=1` on CPython
3.14.7 free-threaded, 1834 passed, 5 skipped), and the pure-Python leg
(`MULTIDICT_NO_EXTENSIONS=1`, `pytest -q --no-c-extensions`, 926
passed). New test:

`tests/test_multidict.py::test_getall_update_vs_lock_free_reads_thread_safety`,
marked `c_extension`, races `getall()`/`update()` against lock-free
`contains()`/`get()` on never-deleted keys.

Lint: `pre-commit run` (ruff, clang-format, mypy) passed on the changed
files.

Docs: `make doc-spelling` passed with no wordlist additions needed.

Drafted with Claude Code (Sonnet 5); reviewed by asvetlov.

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

2 participants