Skip to content

Speed up adding many values for the same key - #1466

Merged
bdraco merged 13 commits into
masterfrom
speed-up-duplicate-key-insert
Sep 17, 2026
Merged

bdraco merged 13 commits into
masterfrom
speed-up-duplicate-key-insert

Conversation

@bdraco

@bdraco bdraco commented Sep 15, 2026 •

Copy link
Copy Markdown
Member

What do these changes do?

Adding many values under one key got slower with every value, since each insert walked past all earlier values for that key on the same probe sequence; resizes rebuilt the table the same way. Once the perturb shift reaches 0 the probe sequence only depends on the slot, so large tables now remember the last slot used from that point and the next insert resumes there. Both the C extension and the pure Python implementation are changed.

The C lookup loop is unswitched by index size by hand so the extra check stays cheap.

Memory is only spent where the problem exists. The hint array is a separate allocation made the first time a table sees a long probe after the perturb shift reaches 0, which in practice means many values for one key. Multidicts without that pattern, including large ones with distinct keys, only pay for one pointer in the keys header, 8 bytes at any size; none of 120 random distinct key multidicts with 1000 to 50000 entries allocated it. Tables that do allocate use 2 bytes per slot below 2**16 slots and 4 bytes from there on, only for tables of 1024 slots or more. The raw allocator is used so allocating can't suspend the critical section on free threaded builds, and if it fails probing just continues without hints. copy() does not copy the hints. The pure Python implementation follows the same rules with a dict created on the first long probe.

Are there changes in behavior for the user?

No, only performance. The benchmarks added in #1465 cover it.

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

No, the change is contained in the slot lookup used for inserts and table rebuilds.

Related issue number

N/A

Checklist

  • I think the code is well written
  • Unit tests for the changes exist
  • Documentation reflects the changes N/A
  • If you provide code modification, please add yourself to CONTRIBUTORS.txt N/A
  • 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
Benchmark and test details

Local pytest --codspeed wall time with the benchmarks from #1465, run time per iteration:

benchmark master this PR
test_create_multidict_with_items_same_key[cs-c] 598us 11.9us
test_create_multidict_with_items_same_key[ci-c] 620us 40.1us
test_create_multidict_with_items_same_key[cs-py] 20.6ms 1.23ms
test_multidict_add_same_key[cs-c] 987us 109us
test_multidict_add_same_key[ci-c] 1.01ms 137us
test_multidict_add_same_key[cs-py] 33.3ms 2.59ms
test_create_multidict_with_many_items[cs-c] 40.7us 42.3us
test_create_multidict_with_many_items[cs-py] 2.16ms 2.17ms

Callgrind instruction counts against master (gcc, arm64 Linux, PYTHONHASHSEED=1): 5000 distinct keys through the constructor +1.5%, 5000 add() calls +0.004%, CIMultiDict of 16 headers +0.04%; 20000 values for one key 2.2B instructions on master, 6.8M here.

sys.getsizeof():

entries master distinct keys one repeated key
60 2960 2968 2968
342 23984 23992 26040
1000 47888 47896 51992
5000 191248 191256 207640

Tests pass on 3.10 and 3.14 with the C extension (release and MULTIDICT_DEBUG_BUILD=1), on 3.14t with a debug build, and with MULTIDICT_NO_EXTENSIONS=1 --no-c-extensions. The new tests fail on both backends if the hint is deliberately corrupted.

Drafted with Claude Code; reviewed by @bdraco.

@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 15, 2026
@codspeed

codspeed Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Merging this PR will improve performance by ×5.2

⚠️ 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 improved benchmarks
✅ 258 untouched benchmarks

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ test_create_multidict_with_items_same_key[cs-py] 954.2 ms 47.7 ms ×20
⚡ test_create_multidict_with_items_same_key[ci-py] 956 ms 49.2 ms ×19
⚡ test_multidict_add_same_key[cs-py] 1,497.9 ms 182.8 ms ×8.2
⚡ test_multidict_add_same_key[ci-py] 1,499.4 ms 184.3 ms ×8.1
⚡ test_create_multidict_with_items_same_key[cs-c] 1,848.6 µs 581.2 µs ×3.2
⚡ test_multidict_add_same_key[cs-c] 3.2 ms 1.5 ms ×2.2
⚡ test_create_multidict_with_items_same_key[ci-c] 2.9 ms 1.6 ms +81.6%
⚡ test_multidict_add_same_key[ci-c] 4.5 ms 2.8 ms +64.83%

Tip

Curious why performance improved? Comment @codspeedbot explain why performance improved on this PR, or directly use the CodSpeed MCP with your agent.


Comparing speed-up-duplicate-key-insert (67f3ced) with master (684b085)

Open in CodSpeed

@aiolibsbot

aiolibsbot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Previous review — superseded by a newer review below.

@codecov

codecov Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (684b085) to head (67f3ced).

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1466   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           37        37           
  Lines         5792      5851   +59     
  Branches       489       499   +10     
=========================================
+ Hits          5792      5851   +59     
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 15, 2026 06:10
@bdraco

bdraco commented Sep 15, 2026 •

Copy link
Copy Markdown
Member Author
  1. Tails add about 16-17% memory to every table with 1024+ slots, and the PR doesn't mention it
    multidict/_multilib/htkeys.h:301-308

Most multidict have < 60 keys so has no effect on common case. Not worth the complexity. This PR is concerned about making the pathological case survivable

@aiolibsbot

aiolibsbot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Previous review — superseded by a newer review below.

@greptile-apps

greptile-apps Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

Safe to merge.

Reviews (10) · Last reviewed commit: "Merge remote-tracking branch 'origin/mas..."

Comment thread multidict/_multilib/htkeys.h Resolved
@aiolibsbot

Copy link
Copy Markdown
Contributor

@bdraco: > 1. Tails add about 16-17% memory to every table with 1024+ slots, and the PR doesn't mention it

Agreed. Tables under 1024 slots get no C tails (HT_LOG_TAILS_MINSIZE). Common case pays nothing. Dropped from this review.

@aiolibsbot

aiolibsbot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Previous review — superseded by a newer review below.

@asvetlov asvetlov 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.

@bdraco I think we need to discuss this change.

The speedup of tests is impressive.
But the price is high; every large multidict gets an additional tails array.
If it were for small dicts, I don't care too much; the memory usage is still relatively low.
Instead, the PR makes memory consumption for big multidicts worse.
The optimization works only for big multidicts with multiple values for the same key. If the multidict has no duplicates or few duplicates, we reserve extra memory and pay the price anyway.

I'm curious: is there any metric that confirms the fact that most huge multidicts have a massive amount of duplicates?

Anyway, the patch demonstrates a non-trivial approach that I never considered.

@bdraco

bdraco commented Sep 15, 2026

Copy link
Copy Markdown
Member Author

Please check aiohttp security queue

@bdraco

bdraco commented Sep 15, 2026 •

Copy link
Copy Markdown
Member Author

Switched to lazy allocation so the common case with unique keys only RAM cost is for the null pointer

@aiolibsbot

Copy link
Copy Markdown
Contributor

@bdraco: Please check aiohttp security queue

Out of scope here. This review covers #1466 only. The aiohttp security queue needs its own task.

@aiolibsbot

aiolibsbot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Previous review — superseded by a newer review below.

@aiolibsbot

aiolibsbot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Previous review — superseded by a newer review below.

@bdraco

bdraco commented Sep 15, 2026 •

Copy link
Copy Markdown
Member Author
  • multidict_sizeof reads self->keys several times without a critical section. The tails check adds two more reads to an existing free threaded race.

Its pre-existing
if (self->keys != &empty_htkeys) size += htkeys_sizeof(self->keys); was original code.

But simple enough to wrap it. Makes me wish we had RAII

@bdraco

bdraco commented Sep 15, 2026

Copy link
Copy Markdown
Member Author

nearly 0230 here so have to wait till tomorrow to address anything else.

@aiolibsbot

Copy link
Copy Markdown
Contributor

@bdraco: > * multidict_sizeof reads self->keys several times without a critical section. The tails check ...

Agreed, race predated this PR. Fixed in e21f628. Keys now read once. Read happens under critical section (_multidict.c:1267-1275). Finding resolved.

@aiolibsbot

aiolibsbot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Previous review — superseded by a newer review below.

@bdraco

bdraco commented Sep 15, 2026

Copy link
Copy Markdown
Member Author

probably should rename it now

@aiolibsbot

Copy link
Copy Markdown
Contributor

@bdraco: probably should rename it now

Rename landed in 4508fbe. Commit only renames, no logic changes. git grep -i tail finds nothing left in multidict, tests, docs or benchmarks. Python constants match the C names.

@aiolibsbot

aiolibsbot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Previous review — superseded by a newer review below.

@asvetlov

asvetlov commented Sep 15, 2026 •

Copy link
Copy Markdown
Member

@bdraco are you refering to https://github.com/aio-libs/aiohttp/security/advisories/GHSA-r7v6-hxr5-4cpr?
No, perhaps GHSA-xgw8-8ccx-rmqh

@asvetlov asvetlov 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.

There my brief review

In Free-threaded mode, we use atomic readers/writers.
Why does _htkeys_find_empty_slot_resume avoid it?

The resume slots are not copied by multidict cloning.
Perhaps it is good, I don't know

Comment thread multidict/_multidict.c Resolved
Comment thread multidict/_multilib/htkeys.h Resolved
@bdraco

bdraco commented Sep 15, 2026

Copy link
Copy Markdown
Member Author

The resume slots are not copied by multidict cloning.
Perhaps it is good, I don't know

That's an intentional trade-off. If there is never another long probe, the copy allocates nothing, and if there is one, rebuilding is cheap. So the common case doesn't pay for another allocation.

@bdraco

bdraco commented Sep 15, 2026

Copy link
Copy Markdown
Member Author

In Free-threaded mode, we use atomic readers/writers.
Why does _htkeys_find_empty_slot_resume avoid it?

The access is already guarded by the critical section on every insert path (multidict_add) and the lock free reads never read resume_slots so there shouldn't be anything to protect with atomics unless I missed somthing.

Comment thread multidict/_multilib/htkeys.h Resolved
@aiolibsbot

Copy link
Copy Markdown
Contributor

@bdraco: > In Free-threaded mode, we use atomic readers/writers.

Guard holds only without suspension. Commit 3d2876d switched to PyMem_Calloc. hashtable.h:574-584 says PyMem_Malloc may suspend. Add paths hold keys across call (hashtable.h:910-920). Revert to PyMem_RawCalloc, or document why safe.

@aiolibsbot

aiolibsbot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Previous review — superseded by a newer review below.

Comment thread multidict/_multilib/htkeys.h Resolved
Comment thread multidict/_multilib/htkeys.h Resolved
@asvetlov

Copy link
Copy Markdown
Member

#1473 demonstrates a different approach: linear probe after the first match instead of keeping the perturbation probe.
I really don't know what is better. Let me see on benchmarks and sleep on it

@bdraco

bdraco commented Sep 16, 2026

Copy link
Copy Markdown
Member Author

#1473 demonstrates a different approach: linear probe after the first match instead of keeping the perturbation probe. I really don't know what is better. Let me see on benchmarks and sleep on it

Thanks. Much simpler design. 👍 If it doesn't regress performance, I'd prefer that. Guess we need to wait for codspeed to decide

@asvetlov

Copy link
Copy Markdown
Member

@bdraco it seems like the probe from #1473 behaves worse than already applied for pathological cases.
I suggest applying your fix from this PR.
Could you please fix CI and make it green?

@aiolibsbot

Copy link
Copy Markdown
Contributor

@bdraco: Switched to lazy allocation so the common case with unique keys only RAM cost is for the null pointe...

Verified. htkeys_t grows one pointer, 8 bytes per table at any size. Allocation gated on log2_size >= 10 plus 32 probe steps past perturb == 0. Distinct-key tables never reach that gate. test_duplicate_key_hints_only_allocated_when_needed asserts it on both backends.

@aiolibsbot

Copy link
Copy Markdown
Contributor

@asvetlov: @bdraco it seems like the probe from #1473 behaves worse than already applied for pathological cases...

Reviewed at 67f3ced. No correctness blocker found. Hint invariant holds: deletes write DKIX_DUMMY, slots go back to DKIX_EMPTY only in htkeys_new() and the in-place shrink, and htkeys_build_indices() zeroes hints before rebuilding. That shrink path is covered by test_add_many_duplicate_keys_after_delete.

My earlier blocker on PyMem_Malloc is withdrawn, settled by your #1469. Remaining items are nits. PR body still says "raw allocator"; one line to update.

@aiolibsbot

Copy link
Copy Markdown
Contributor

PR Review — Speed up adding many values for the same key

Merge-ready. My previous blocker is withdrawn, and nothing in the current tree replaces it.

The hint mechanism holds up under scrutiny. Once perturb reaches 0 the probe order depends only on the slot, and the "never empty again" invariant the hints rest on is genuinely airtight: deletes write DKIX_DUMMY (hashtable.h:1025, 1035, 2403), and the only two places slots revert to DKIX_EMPTY are htkeys_new() (fresh table, hints NULL) and the in-place shrink at hashtable.h:671, which is immediately followed by htkeys_build_indices() zeroing the hints. That shrink path is exercised by test_add_many_duplicate_keys_after_delete, which trips _md_resize_for_insert into _md_shrink with a live hint array and then asserts the full getall() result. The lazy allocation is real: distinct-key tables pay one pointer in the keys header and never reach the log2_size >= 10 plus 32-step gate. copy() dropping the hints is deliberate and correct; md_clone_from_ht() resets the field right after the memcpy. Widths line up at every boundary (uint16_t up to log2_size 15 where slot+1 tops out at 32768, uint32_t to 31, nothing at 32+).

On @asvetlov's two review questions:

  • Atomics. resume_slots is touched only by writers holding md's critical section, plus __sizeof__, which this PR moves under the section. The lock-free read paths (iter_hash, __contains__) never read it, and the index reads inside the helper still go through htkeys_get_index()/LOAD_INDEX, which stay atomic-relaxed on free-threaded builds. So no atomics are needed for the hint array itself.
  • Allocator. My prior review blocked on PyMem_Malloc suspending the critical section. That premise is repudiated by your own #1469 ("PyMem_Malloc never suspends an acquired critical section"), which this branch has merged. Finding withdrawn; the code is consistent with master's position.

What is left, all non-blocking:

  • PR body still says "The raw allocator is used"; the code calls PyMem_Malloc. Fix the sentence, not the code.
  • htkeys_find_empty_slot()'s log2size < 8 fast path silently relies on HT_LOG_RESUME_SLOTS_MINSIZE >= 8; a static_assert would pin it.
  • Pure-Python build_indices() does not clear resume_slots the way the C version does. Harmless today, a trap if an in-place rebuild is ever added there.
  • The hand-unswitched _HT_FIND_EMPTY_SLOT macro is an independent optimization bundled in, and the distinct-key constructor is still +1.5% instructions with it.
  • Leftover pre-existing comments in hashtable.h still claim PyMem_Malloc can suspend a critical section, contradicting #1469; worth a cleanup PR.

✅ Resolved since last review (1)

Previously-flagged issues verified fixed
  • multidict/_multilib/htkeys.h:431 Still open: PyMem_Calloc can pause the critical section while callers hold raw keys pointers

🟢 Suggestions

1. The log2size < 8 fast path silently depends on HT_LOG_RESUME_SLOTS_MINSIZE >= 8
multidict/_multilib/htkeys.h:514-519

The log2size < 8 loop deliberately omits the perturb == 0 check, which is correct today only because htkeys_resume_slots_bytes() returns 0 below HT_LOG_RESUME_SLOTS_MINSIZE (10), so those tables could never own a hint array anyway.

That coupling is invisible at both ends. If someone later lowers HT_LOG_RESUME_SLOTS_MINSIZE to, say, 6 to widen the optimization, tables of 64..128 slots would get hints through htkeys_build_indices() (which does call the helper at every size) but never through htkeys_find_empty_slot(), so inserts and rebuilds would disagree about where a chain resumes. Nothing crashes, but the two paths diverge and the reason is nowhere in the file.

Cheapest fix is a compile-time assertion next to the constant or this branch:

static_assert(HT_LOG_RESUME_SLOTS_MINSIZE >= 8,
              "htkeys_find_empty_slot()'s 8-bit index loop skips the "
              "perturb == 0 check");
    if (log2size < 8) {
        while (LOAD_INDEX(keys, 8, i) != DKIX_EMPTY) {
            perturb >>= HT_PERTURB_SHIFT;
            i = (i * 5 + perturb + 1) & mask;
        }
        return (Py_ssize_t)i;
2. The hand-unswitched probe loop is a separable optimization
multidict/_multilib/htkeys.h:490-499

The _HT_FIND_EMPTY_SLOT macro is a second, independent change riding along with the hint mechanism: htkeys_find_empty_slot() previously dispatched on index width once per probe through htkeys_get_index(), and hoisting that dispatch out of the loop is a win with or without resume slots.

Bundling it has two costs. The macro expands return from inside a caller's body, which is the kind of control flow the rest of this header avoids, and it triples the loop body so a future change to the probe sequence has to be made in four places. More practically, the PR's own callgrind numbers still show +1.5% instructions for 5000 distinct keys through the constructor, so the unswitching does not visibly pay for itself on the path it was meant to protect.

AGENTS.md asks for one logical change per PR. Splitting this out would let its callgrind delta be measured on its own, and if the win is inside the noise, the simpler single loop over htkeys_get_index() plus the perturb == 0 check is the version worth keeping.

/* Uses keys, mask, i and perturb from the caller and returns. */
#define _HT_FIND_EMPTY_SLOT(size)                           \
    while (LOAD_INDEX(keys, size, i) != DKIX_EMPTY) {       \

Checklist

  • Hint invariant: slots never revert to EMPTY except on rebuilds that clear the hints
  • resume_slots initialised to NULL in every constructor (htkeys_new, empty_htkeys, clone)
  • resume_slots freed on every keys-free path with a matching allocator family
  • Allocation failure degrades to probing without hints, no error state left behind
  • Every caller fills the slot returned by htkeys_find_empty_slot
  • Free-threaded safety: hints touched only under md's critical section, lock-free readers unaffected
  • uint16_t/uint32_t widths consistent across the size helper, reads and writes
  • sizeof accounting matches the allocation and is thread safe
  • Both backends behave identically, with matching constants
  • Tests cover lazy allocation, the 32-bit width, and the delete/shrink/update paths
  • CHANGES fragment present with a category consistent with past speedups
  • One logical change per PR — suggestion #2
  • No hardcoded secrets, injection, or unsafe operations
ℹ️ Triage summary

1 pre-existing finding(s) on unchanged code suppressed (freeze).


Automated review by Kōan (Claude) HEAD=67f3ced 10 min 54s

@bdraco

bdraco commented Sep 17, 2026

Copy link
Copy Markdown
Member Author

Thanks

@bdraco
bdraco merged commit a9aa239 into master Sep 17, 2026
61 checks passed
@bdraco
bdraco deleted the speed-up-duplicate-key-insert branch September 17, 2026 17:06
asvetlov added a commit that referenced this pull request Sep 21, 2026
)

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

## What do these changes do?

Moves the CodSpeed benchmark job to Python 3.14, and makes the `repr()`
and view inequality benchmarks repeat their operation 100 times, the way
the other benchmarks already loop. The benchmark job timeout goes from
10 to 15 minutes, since the job takes about 9.5 minutes.

The high "variability" figures on the CodSpeed dashboard (up to about
140%) come from benchmark redefinitions in #1494 and from the real
`add()` and `getall()` performance changes in #1466 and #1484, not from
run-to-run noise. A same-commit rerun on master (242e5bd) reported 266
of 266 benchmarks unchanged. The dashboard window will age out by
itself.

## Are there changes in behavior for the user?

No, only benchmarks and CI change. The reshaped benchmarks, and the move
to 3.14, will cause a one-time jump in their CodSpeed history.

## 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, this only changes
benchmarks and CI
- [ ] Documentation reflects the changes: N/A
- [ ] 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`

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

Measurement: valgrind is not available locally, so a small pytest plugin
emulated pytest-codspeed's simulation mode, including the
`gc.collect()`/`gc.disable()` and `random.seed(0)` that
`plugin._measure` does, followed by one warmup call and one measured
call. It recorded user-space retired instructions with
`perf_event_open`, pinned to P-cores. Each run allocated a different
number of dummy objects first, to mimic unrelated heap changes between
commits. The suite ran on CPython 3.15.0rc2 with `PYTHONHASHSEED=0`, 40
runs per variant, using the same seeds for both.

- master benchmarks: every benchmark within 3.6% max/min spread; the
worst was `test_items_view_not_equals[ci-py]`, followed by
`test_values_view_repr[ci-c]` at 2.4%.
- this branch: every benchmark within 3.3% spread; the looped benchmarks
all dropped below 2%.

An earlier revision also added a `gc_disabled` fixture, based on a
harness that did not replicate pytest-codspeed's own GC handling. It was
redundant and has been removed.

Tests (3.14.2): `pytest` passed (2059 passed, 21 skipped); `pytest
--no-c-extensions` passed (1037 passed); `pytest --codspeed
--codspeed-mode simulation` passed (269 benchmarks). 3.15 was tried
first but dropped: setup-python has no prebuilt 3.15 yet, so the job
compiled CPython and ran even longer.

Lint: `pre-commit run` on the changed files passed; `make doc-spelling`
passed.

</details>

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

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
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.

3 participants