Repository navigation
Speed up adding many values for the same key - #1466
Conversation
Merging this PR will improve performance by ×5.2
|
| 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)
|
|
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
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 |
|
|
|
Agreed. Tables under 1024 slots get no C tails ( |
|
|
asvetlov
left a comment
There was a problem hiding this comment.
@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.
|
Please check aiohttp security queue |
|
Switched to lazy allocation so the common case with unique keys only RAM cost is for the null pointer |
|
|
|
|
Its pre-existing But simple enough to wrap it. Makes me wish we had RAII |
|
nearly 0230 here so have to wait till tomorrow to address anything else. |
|
|
|
probably should rename it now |
|
|
asvetlov
left a comment
There was a problem hiding this comment.
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
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. |
The access is already guarded by the critical section on every insert path ( |
|
|
|
#1473 demonstrates a different approach: linear probe after the first match instead of keeping the perturbation probe. |
Thanks. Much simpler design. 👍 If it doesn't regress performance, I'd prefer that. Guess we need to wait for codspeed to decide |
Verified. |
Reviewed at 67f3ced. No correctness blocker found. Hint invariant holds: deletes write My earlier blocker on |
PR Review — Speed up adding many values for the same keyMerge-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 On @asvetlov's two review questions:
What is left, all non-blocking:
✅ Resolved since last review (1)Previously-flagged issues verified fixed
🟢 Suggestions
1. The log2size < 8 fast path silently depends on HT_LOG_RESUME_SLOTS_MINSIZE >= 8
|
|
Thanks |
) <!-- 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>
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**16slots 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
CONTRIBUTORS.txtN/ACHANGES/foldermake doc-spellingpasses and any new technical words are added todocs/spelling_wordlist.txtBenchmark and test details
Local
pytest --codspeedwall time with the benchmarks from #1465, run time per iteration:test_create_multidict_with_items_same_key[cs-c]test_create_multidict_with_items_same_key[ci-c]test_create_multidict_with_items_same_key[cs-py]test_multidict_add_same_key[cs-c]test_multidict_add_same_key[ci-c]test_multidict_add_same_key[cs-py]test_create_multidict_with_many_items[cs-c]test_create_multidict_with_many_items[cs-py]Callgrind instruction counts against master (gcc, arm64 Linux,
PYTHONHASHSEED=1): 5000 distinct keys through the constructor +1.5%, 5000add()calls +0.004%,CIMultiDictof 16 headers +0.04%; 20000 values for one key 2.2B instructions on master, 6.8M here.sys.getsizeof():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 withMULTIDICT_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.