Skip to content

Drop dead code - #1469

Merged
asvetlov merged 2 commits into
aio-libs:masterfrom
asvetlov:drop-dead-code
Sep 16, 2026
Merged

asvetlov merged 2 commits into
aio-libs:masterfrom
asvetlov:drop-dead-code

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 16, 2026 •

Copy link
Copy Markdown
Member

PyMem_Malloc never suspends an acquired critical section.
The code for this guard was added by oversight by #1441; it is never executed.

@asvetlov asvetlov added the bot:chronographer:skip This PR does not need to include a change note label Sep 16, 2026
@asvetlov

Copy link
Copy Markdown
Member Author

The dead code was never published; the removal doesn't require a changelog.

@codspeed

codspeed Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 260 untouched benchmarks


Comparing asvetlov:drop-dead-code (482d406) with master (838ebf7)1

Open in CodSpeed

Footnotes

  1. No successful run was found on master (f4218f8) during the generation of this report, so 838ebf7 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@greptile-apps

greptile-apps Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

Safe to merge; no blocking issues remain.

The prior documentation finding was resolved by greptile-apps[bot] without explanation. The current change removes the obsolete claim, and no new issues require action.

Reviews (2): Last reviewed commit: "Drop misleading comment" | Re-trigger Greptile

Comment thread multidict/_multilib/hashtable.h Resolved
@asvetlov
asvetlov merged commit 445f9f9 into aio-libs:master Sep 16, 2026
61 checks passed
@asvetlov
asvetlov deleted the drop-dead-code branch September 16, 2026 08:02
asvetlov added a commit that referenced this pull request Sep 20, 2026
)

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

## What do these changes do?

An automated review of #1484 flagged `md_readonly_find_next()`'s
allocation
as a potential use-after-free, reasoning that a blocking
`PyMem_Malloc()`
call could transiently suspend the held critical section. That mechanism
does not exist: per #1469, `PyMem_Malloc()` never suspends an acquired
critical section on the free-threaded build, so the finding was a false
positive there.

Chasing the same claim through the rest of `hashtable.h` turned up two
real issues. `md_clone_from_ht()` still carried the exact
retry-on-staleness loop #1469 already proved dead in `_md_resize()`,
just
never cleaned up here; this drops it the same way. `_md_del_at()`,
`_md_del_at_for_upd()` and `_md_replace()` have a real suspension risk
(a decref of the old key/value can run a finalizer or weakref callback),
but their comments wrongly attributed it to "the same allocator lock as
`PyMem_Malloc()`", pointing at a comment that no longer exists anywhere
in
the file after #1469; reworded those to name the actual mechanism.

## Are there changes in behavior for the user?

No.

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

No; this only touches internal comments and removes unreachable code in
one free-threaded-only helper.

## Related issue number

Related to #1484 and #1469, not closing either.

## Checklist

- [x] I think the code is well written
- [ ] Unit tests for the changes exist -- N/A, no behavior change; the
      touched paths are already exercised by the existing suite on both
      backends
- [x] Documentation reflects the changes
- [ ] If you provide code modification, please add yourself to
`CONTRIBUTORS.txt` -- N/A, no such file 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`

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

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

Tests (isolated venvs, this branch rebased onto current upstream
master):

- C extension, default build: `pytest tests -q` -- 2059 passed
- Free-threaded debug build (`MULTIDICT_DEBUG_BUILD=1`): `pytest tests
-q -k "not test_leak" --no-cov` -- 2049 passed
- Free-threaded debug build under ASan+UBSan (`MULTIDICT_ASAN_BUILD=1`):
same command under `LD_PRELOAD=libasan.so ASAN_OPTIONS=detect_leaks=0`
-- 2049 passed, no sanitizer reports
- Pure Python (`MULTIDICT_NO_EXTENSIONS=1`, `pytest --no-c-extensions
--no-cov`): 1037 passed

Lint: `make doc-spelling` passes; pre-commit hooks (clang-format,
changelog filename/role checks) passed on commit.

</details>

---------

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

## What do these changes do?

Add a watchers C API, so another C extension can be notified when a
`MultiDict` or `CIMultiDict` changes. It follows CPython's
`PyDict_AddWatcher` family, with two deliberate differences.

The callback gets **two context pointers**: `watcher_data`, fixed when
the
callback is registered, and `user_data`, belonging to one watched
multidict. That is the point of the API: one registered callback can
serve
any number of multidicts and still know, on every event, what owns the
one
that changed. CPython does not need this because its dict watchers are
static functions inside the interpreter.

Events are **delivered after the operation finishes**, not mid-mutation.
Several of the update paths run with the table deliberately inconsistent
(`_md_del_at_for_upd_deferred` leaves an entry half-deleted but still
reachable until `md_post_update` sweeps it, and
`_md_replace`/`_md_update`
carry a `reflist_t` of not-yet-decref'd objects), so calling out to a
client there is the shape behind #1469 and #1489. Events are recorded
into
a per-multidict log instead, which only allocates, and delivered once
the
critical section is released.

The events are multi-value aware, since `add()` on a key that is already
present is an append rather than a modification, and one `__setitem__`
can
both replace a pair and delete several. Each event that concerns a key
carries the identity alongside it, already lowercased for a
`CIMultiDict`,
so a watcher matching `"content-length"` needs no `lower()` of its own,
and
the identity's hash with it, so a watcher keeping its own table does not
have to hash the key again.

C-extension only, like the rest of the capsule API: `_multidict_py.py`
and
`_abc.py` are untouched, and `tests/test_capi.py` skips on the
pure-Python
leg as it already does.

`MultiDict_CAPI_VERSION` stays at 1: version 1 has not shipped, since
7.0
is unreleased, so no client can exist that was built against a capsule
without these entry points.

One thing a reviewer may want to overrule:

- `MultiDictObject` grows one pointer, `md_watch_t *watch`, NULL until
the
first `MultiDict_Watch()`. `tp_basicsize` goes 56 to 64 on GIL 3.12+, 64
  to 72 on 3.10/3.11 and 88 to 96 free-threaded, but what the allocator
  reserves is what actually costs. Measured as RSS over a million empty
  multidicts:

  | build | `tp_basicsize` | bytes per instance |
  | --- | --- | --- |
  | 3.10.17 | 64 -> 72 | 80.4 -> 96.4 |
  | 3.11.13 | 64 -> 72 | 80.4 -> 96.2 |
  | 3.13.2 | 56 -> 64 | 96.2 -> 96.4 |
  | 3.14.7t | 88 -> 96 | 112.1 -> 112.1 |

  So only 3.10 and 3.11 pay, and they pay 16 rather than 8: pymalloc's
  size classes are 16 bytes apart, and those are the versions that still
  carry an explicit `weaklist` pointer, which puts the object on a class
  boundary. Everywhere else the rounding absorbs it.

  The alternative (an occupancy bitmask in the existing padding after
`is_ci`, which is free, plus a side table in `mod_state`) saves those 16
bytes on two versions, at the price of a keyed lookup at every recording
  site and, on free-threaded builds, a lock over globally shared state
  taken inside the per-object critical section.

## Are there changes in behavior for the user?

No. Nothing fires until a client registers a watcher and watches a
multidict, and no Python-level API changes.

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

The four entry points are small and the event set is fixed. The ongoing
cost is that every new mutation path has to record its events; a debug
build asserts the log is empty at dealloc, which catches a missed flush.

## 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 such file 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`

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

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

Branched from `9682ba1`, with `upstream/master` merged in at `7b84e1b`.
Everything below was re-run on the merge commit.

Tests, all green:

- C extension, 3.14t, `MULTIDICT_TEST_REQUIRE_CYAPI=1 pytest -q` — 2793
passed, 35 skipped
- Pure Python, `MULTIDICT_NO_EXTENSIONS=1 pytest -q --no-c-extensions` —
1272 passed, 11 skipped
- ASan + UBSan on GIL 3.13.2, `MULTIDICT_DEBUG_BUILD=1
MULTIDICT_ASAN_BUILD=1`,
  `LD_PRELOAD=libasan.so ASAN_OPTIONS=detect_leaks=0 PYTHONMALLOC=malloc
python -m pytest tests -q -k "not test_leak"` — 2637 passed, no reports
- TSan on 3.14.7t-tsan: an 8-thread stress of a watched multidict
(add/setitem/extend/update/popall/getall in a loop) delivers 47,987
events
with zero ThreadSanitizer reports, and `tests/test_capi.py` gives 126
passed,
also with zero reports. The whole suite was run under TSan before the
merge
  and was clean apart from two pure-Python deadlock tests,
  `test_pure_python_reciprocal_view_ops_no_deadlock` and
`test_pure_python_reciprocal_raw_iterator_ops_no_deadlock`, which fail
the
same way on the base commit: they exercise `_multidict_py.py`, which
this
branch does not touch, and TSan's slowdown trips their 40-second
timeout.
- `make doc-spelling`, `make lint` (full pre-commit) — pass

Perf, callgrind on GIL 3.13.2 with `PYTHONHASHSEED=0`, `__pycache__`
warmed
first, 2000 iterations over 16 keys per case, base and head each built
from a
clean `git archive` of its own commit. `delitem` is the one row the
`hash`
field moved, from +0.21% to +0.31%, about six instructions per delete at
the
recording site even though the multidict is not watched:

| case | base Ir | head Ir | delta |
| --- | ---: | ---: | ---: |
| ctor | 156,514,577 | 156,623,555 | +0.07% |
| getitem | 161,482,936 | 161,486,000 | +0.00% |
| contains | 160,617,767 | 160,620,968 | +0.00% |
| getall | 188,679,273 | 188,650,405 | -0.02% |
| add | 174,618,041 | 174,822,990 | +0.12% |
| setitem | 193,751,920 | 193,872,931 | +0.06% |
| extend | 157,940,969 | 158,070,000 | +0.08% |
| update | 188,320,260 | 188,573,291 | +0.13% |
| delitem | 187,412,355 | 187,991,366 | +0.31% |
| iterate | 149,685,057 | 149,687,945 | +0.00% |

`tools/codegen_diff.py --ref 7b84e1b`, with a `--probe` translation unit
wrapping the always-inlined helpers, agrees: `md_get_one`, `md_contains`
and
`md_len` do not appear in the report at all, and `md_get_all` is 535 ->
535
instructions with call targets unchanged. The read paths get no call.
The
write paths gain one `UNLIKELY` pointer test per mutation site,
branching to a
`COLD` recorder, plus one `md_watch_pending()` read inside the critical
section each mutator already holds.

Before the merge, CodSpeed reported one regression on this branch,
`test_multidict_extend_str[cs-c]` at -9.51%, with the other 309
benchmarks
unchanged. I do not think it was real, and here is why rather than just
asserting it:

- That comparison crossed a CPU **vendor** change, AMD EPYC 7763 to
Intel
  Xeon 6973P-C. CodSpeed's Simulation mode derives its cache model from
  the physical CPU, so the estimate moves on identical source.
- The control says the same: comparing two commits of this branch that
  differ **only in test files**, with no C change at all (`4a357c7` ->
  `66367ff`), CodSpeed reports 310 unchanged and zero regressions, and
  `test_multidict_extend_str[cs-c]` is flat there despite also being
  listed under a CPU difference.
- The three sibling extend benchmarks CodSpeed calls unchanged are the
  tell: a real 9.5% regression in `extend()` would move all four. Run
  locally under callgrind, reproducing each benchmark body exactly:

  | extend variant | base Ir | head Ir | delta |
  | --- | ---: | ---: | ---: |
  | `MultiDict` `[cs-c]` | 251,327,159 | 252,576,459 | +0.50% |
  | `CIMultiDict` `[ci-c]` | 281,511,710 | 282,361,010 | +0.30% |
  | `[cs-c]` with kwargs | 320,532,998 | 322,408,298 | +0.59% |
  | `[ci-c]` with kwargs | 366,117,561 | 367,392,861 | +0.35% |

  The one CodSpeed flagged measures +0.50% here, not -9.51%.

</details>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot:chronographer:skip This PR does not need to include a change note

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant