Skip to content

Reject arguments passed both positionally and by name - #1545

Merged
asvetlov merged 2 commits into
aio-libs:masterfrom
asvetlov:parse2-argument-binding
Sep 23, 2026
Merged

asvetlov merged 2 commits into
aio-libs:masterfrom
asvetlov:parse2-argument-binding

Conversation

@asvetlov

Copy link
Copy Markdown
Member

What do these changes do?

parse2() in _multilib/parser.h enumerated the shapes the keyword
tuple could take, and the shapes where a keyword repeats an argument
already bound positionally were not among them. The surplus arguments
were dropped rather than rejected, so md.get("a", "b", key="c")
quietly returned the value for "a", and add() was worse:
md.add("a", key="k", value="v") read its value out of the first
keyword slot and stored ("a", "k").

The enumeration is replaced by a walk over the keyword tuple that binds
each name and rejects one that is already bound, mirroring how CPython
binds arguments for an equivalent def, down to reporting the leftmost
offending keyword. That also corrects the arity messages, whose two
minargs labels were swapped: methods with an optional second argument
claimed to take exactly one, and add() claimed to take a range.

The two parameter names are distinct, so the walk compares the one still
unbound first. Without that, get(key, default=...) pays a second
PyUnicode_CompareWithASCIIString(), which measured as +4.3% on that
call; ordering it this way brings it back to +0.87%.

Only the C extension is affected. The pure-Python implementation already
raised TypeError for every one of these and is unchanged; it served as
the oracle for the expected messages.

Are there changes in behavior for the user?

Yes. Calls that were silently accepted now raise TypeError, matching
the pure-Python backend, and md.add("a", key="k", value="v") no longer
stores a wrong value. The wording of some existing TypeError messages
changed as a result.

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

No. parse2() is shorter than it was, and the error precedence follows
one rule instead of a case per keyword-tuple shape.

Related issue number

None.

Checklist

  • I think the code is well written
  • Unit tests for the changes exist
  • Documentation reflects the changes - N/A, no documented behaviour describes these messages
  • If you provide code modification, please add yourself to CONTRIBUTORS.txt - N/A, no such file 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

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

Agent run details (optional, for reviewers)

Both legs were run in their own venv, and the pure-Python leg in its own
tree copy, so neither picked up a stale .so.

C extension:   pytest tests -q                      2422 passed, 118 skipped
pure Python:   MULTIDICT_NO_EXTENSIONS=1 pytest -q --no-c-extensions
                                                    1178 passed, 11 skipped, 1181 deselected
lint:          pre-commit run --all-files           all hooks passed
docs:          make doc-spelling                    build succeeded

Reverting parser.h alone and rebuilding fails 38 of the new cases, all
on the -c legs; the -py legs pass unchanged, which is what confirms
the pure-Python backend was already correct.

Behaviour was compared against the pure-Python backend across 27
argument combinations. Before: 16 differed. After: 3 differ, all of them
pre-existing conventions rather than this bug. The C messages do not
count self (but 3 were given against but 4 were given), and
pure-Python pop() delegates to popone(), so that name appears in its
message. The tests are written to hold on both backends, which is why
the arity assertions match a shape rather than an exact string.

Instruction counts, callgrind, PYTHONHASHSEED=0, 200k iterations,
against the same build before and after:

getone(key)                 496,903,250 -> 497,123,146   +0.04%
getone(key=key)             546,524,905 -> 548,748,507   +0.41%
get(key, None)              503,107,618 -> 503,717,635   +0.12%
get(key, default=None)      552,320,495 -> 557,134,602   +0.87%
add(key, value)             746,356,393 -> 747,363,225   +0.13%

Run-to-run noise on this harness is about 0.01%.

parse2() special-cased each shape of the keyword tuple, and the cases
where a name repeated an argument already bound positionally were not
among them. The surplus arguments were dropped instead of rejected, so
md.get("a", "b", key="c") returned a value for "a", and add() was worse:
md.add("a", key="k", value="v") read the value out of the first keyword
slot and stored ("a", "k").

Replace the special cases with a walk over the keyword tuple that binds
each name and rejects one that is already bound, mirroring how CPython
binds arguments for an equivalent def, including reporting the leftmost
offending keyword. This also fixes the arity messages: the labels for
the two minargs values were swapped, so methods with an optional second
argument claimed to take exactly one, and add() claimed to take a range.

The two names are distinct, so the walk compares the one still unbound
first; that keeps the common get(key, default=...) form at the single
string comparison it used to cost.

The pure-Python implementation already behaved this way and is unchanged.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 23, 2026
@codspeed

codspeed Bot commented Sep 23, 2026

Copy link
Copy Markdown

Merging this PR will improve performance by 14.24%

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

⚡ 1 improved benchmark
✅ 309 untouched benchmarks

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ test_create_multidict_with_dict[ci-c] 100.3 µs 87.8 µs +14.24%

Tip

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


Comparing asvetlov:parse2-argument-binding (84d627a) with master (372d632)

Open in CodSpeed

@codecov

codecov Bot commented Sep 23, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (937fd76) to head (84d627a).
⚠️ Report is 7 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1545   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           40        40           
  Lines         6820      6842   +22     
  Branches       596       596           
=========================================
+ Hits          6820      6842   +22     
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 23, 2026 19:53
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 23, 2026 19:53
@greptile-apps

greptile-apps Bot commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

Safe to merge; no actionable issues were found in the changed argument-binding behavior.

What we checked:

  • T-Rex exercised every affected two-argument public method on MultiDict and CIMultiDict with edge-case bindings, ran 136 focused calls against the native extension and the pure-Python implementation, and found behavioral_differences=0 with 208 passing tests. T-Rex
  • The cross-backend validation for parse2 was executed using trex-artifacts/parse2_cross_backend_validation.py and the results were compared with trex-artifacts/compare_parse2_backend_output.py, using native output parse2-cross-backend-01-before.log and pure-Python output parse2-cross-backend-02-after.log; the comparison reported behavioral_differences=0, with 104 message-only differences due to normal TypeError wording differences rather than changes to call acceptance, error ordering, return values, or state. T-Rex

Reviews (1) · Last reviewed commit: "Rename the news fragments to the assigne..."

@asvetlov
asvetlov merged commit 1a408f3 into aio-libs:master Sep 23, 2026
62 checks passed
@asvetlov
asvetlov deleted the parse2-argument-binding branch September 23, 2026 20:02
asvetlov added a commit that referenced this pull request Sep 24, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

Three changes to the argument handling of the C extension, no behaviour
change in any of them.

`parse2()` compiled to a single outlined clone shared by all eleven call
sites and was inlined nowhere, so `md.get(key)` paid a call into the
keyword machinery it never used. The all-positional case now binds in
the inline wrapper, five instructions at the call site, and the rest
moved to a `COLD parse2_slow()`. Since the keyword walk is out of line
anyway, it takes the tuple through `PyTuple_GET_SIZE()` and
`PyTuple_GET_ITEM()`; all eleven methods are
`METH_FASTCALL | METH_KEYWORDS`, so `kwnames` is a tuple or `NULL` and
the error branches of the checked calls were unreachable.

Parameter names are now interned in the module state and matched against
`kwnames` by identity before falling back to a comparison, which is what
`find_keyword()` in CPython's `Python/getargs.c` does. A call written as
`get(key=k)` settles on a pointer compare; the `memcmp()` it replaces
was
45% of the keyword path. The fallback is not optional: `get(**{"key":
k})`
builds names that never reach the intern table, and there is a test for
exactly that.

Finally, `multidict_get()` built the implicit `None` default on every
call and carried a flag to release it again, although it is only
reachable when the key is absent. It now does the lookup directly and
produces the constant on the miss path, where it is the return value.
`setdefault()` keeps the old shape, since it has to hand the default to
`md_set_default()` inside the critical section.

Instruction counts against `9682ba1`, callgrind, 200k calls:

| case | master | this branch | |
| --- | --- | --- | --- |
| `md.get(key)` | 506,599,099 | 492,590,531 | -2.77% |
| `md.get(key, default=None)` | 560,167,840 | 538,574,218 | -3.85% |
| `md.getone(key=key)` | 553,395,042 | 531,801,895 | -3.90% |
| `md.get(key, None)` | 508,367,864 | 498,974,074 | -1.85% |
| `md.getone(key)` | 501,769,613 | 493,572,776 | -1.63% |
| `md.getall(key)` | 576,882,245 | 569,485,981 | -1.28% |
| `md.add(key, value)` | 752,475,828 | 743,272,580 | -1.22% |

Only the C extension is touched; the pure-Python implementation is
unchanged.

## Are there changes in behavior for the user?

No. The same calls succeed, the same ones raise, and the messages are
identical. A behaviour matrix of 27 argument combinations compared
against the pure-Python backend is unchanged by this branch.

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

No, though two of the assumptions are worth knowing about. The tuple
macros rely on every `parse2()` caller staying
`METH_FASTCALL | METH_KEYWORDS`, and the identity match relies on the
module state holding interned names, so `PyUnicode_InternFromString()`
there is load bearing rather than incidental.

## Related issue number

None. Follow-up to #1545.

## Checklist

- [x] I think the code is well written
- [x] Unit tests for the changes exist
- [x] Documentation reflects the changes - N/A, no documented behaviour
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 (Opus 5); reviewed by @asvetlov.

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

Both legs ran in their own venv, and the pure-Python leg in its own tree
copy, so neither picked up a stale `.so`.

```
C extension:   pytest tests -q                    2444 passed, 120 skipped
pure Python:   MULTIDICT_NO_EXTENSIONS=1 pytest -q --no-c-extensions
                                                  1188 passed, 11 skipped, 1191 deselected
lint:          pre-commit run --all-files         all hooks passed
docs:          make doc-spelling                  build succeeded
```

Measurement notes: callgrind, `PYTHONHASHSEED=0`, warm `__pycache__`,
200k iterations. Cross-rebuild noise was measured at about 0.01% by
building identical source twice and comparing, so the deltas above are
well clear of it.

One rejected variant, recorded so it is not retried: screening the name
comparison with an inline first-character check before
`PyUnicode_CompareWithASCIIString()` regressed the keyword paths by 0.5
to 0.8%. The common keyword forms hit on the first name tried, so there
is no `memcmp()` to skip and the screen is pure overhead. Identity
matching was the change that actually paid.

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