Skip to content

Pass native method receivers outside FuncArgs - #9829

Closed
youknowdot wants to merge 10 commits into
RustPython:mainfrom
youknowdot:perf/native-receiver-20261113
Closed

youknowdot wants to merge 10 commits into
RustPython:mainfrom
youknowdot:perf/native-receiver-20261113

Conversation

@youknowdot

@youknowdot youknowdot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Follow-up to #9758 and #9758 (comment). Based on its reviewed head 6344672b; #9758 is unchanged. This draft depends on #9758 and should be rebased onto main after that PR merges.

  • Pass every native receiver as Option<&PyObject> outside FuncArgs.
  • Store a single Option<PyObjectRef> on native functions, without receiver-kind tags, prepend operations or receiver-vector allocation at invocation.
  • Select method adapters at registration, leaving ordinary functions and static methods' explicit arguments unchanged.
  • Preserve ordinary/native-method metadata and argument errors; retain safe Rust payload validation without repeating descriptor Python-class checks.

Receiver / raw-argument audit

Audited the complete tree at 6344672b before implementation.

Boundary / assumption Treatment
PyNativeFn, IntoPyNativeFn, PyNativeFnInternal, static_raw_func, Context::new_raw_method_def Unified borrowed PyObject receiver ABI.
PyNativeFunction call/vectorcall and NativeFunctionSelf Remove Module/Bound transport variants and manual traversal; forward zelf.as_deref() and unchanged user args.
PyMethodDescriptor call/vectorcall Preserve missing-receiver/type/keyword validation ordering; extract the receiver before forming native user args.
Four CallMethodDescriptor{Noargs,O,Fast,FastWithKeywords} frame specializations Split the already-checked receiver from the argument vector.
#[pymethod], #[pyclassmethod], #[pystaticmethod], raw method expansion Explicit method adapter for instance/class methods; ordinary adapter for static methods; raw methods use the unified ABI. No current raw=true methods were found.
&self, &Py<S>, PyRef<S>, PyObjectRef, custom TryFromObject self Borrow/convert the separate receiver. Preserve NativeFunctionOrMethod's special conversion for builtin-method prefix payloads and PyPayload::try_downcast_from validation hooks.
Ordinary OwnedParam/BorrowedParam/RefParam, BorrowedArgs functions Continue reading explicit Python arguments, never treating their first parameter as a hidden receiver. Module adapter downcasts the ABI receiver.
PyMethodDef, HeapMethodDef, define_methods!, VirtualMachine::new_method Explicit method registration; remove module-only heap constructor. WASM write/flush use the updated method helper.
Manual slot_new_wrapper and C-API type __new__ registration Use method adapter. PyType::__new__ still binds the explicit subtype argument from FuncArgs; it is distinct from the hidden defining-class receiver.
_ast deepcopy/replace/reduce, struct-sequence reduce, _thread except-hook reduce, cross-interpreter FIND_CLASS Convert manual registrations. FIND_CLASS binds self despite empty flags, so selection must not depend on flags.
type.__subclasshook__(FuncArgs) Add an explicit ignored class receiver; keep arbitrary user args ignored.
Explicit-self FuncArgs methods Adapter handles receiver; bodies unchanged: contextvars.run, socket recv_into/recvfrom_into/sendto/setsockopt, ssl_wasm load_cert_chain/_wrap_socket, frame_locals_proxy.update, str.format, _ThreadHandle.join, _io exit/readinto/write, both os ScandirIterator.exit, winreg PyHkey.exit, _zoneinfo.init_subclass, typevar class_getitem/init_subclass.
Slot wrappers PyWrapper, PyMethodWrapper, vectorcall_wrapper Already separate object and args; preserve. types/slot.rs new-wrapper prepend is an explicit __new__ class argument, not native hidden-self transport.
Python PyBoundMethod and generic/instrumented frame calls Preserve Python-callable receiver insertion. This is not the native-function ABI.
Callee.instance_arg / binder offset / shape skipping Remove. Preserve method-level outer validation for one custom/legacy parser so the single-element tuple override does not change existing errors.
C-API NOARGS/O/VARARGS/VARARGS+KEYWORDS/FASTCALL/FASTCALL+KEYWORDS Pass ABI receiver directly, remove take_self_arg, has_self, and Cow. Static C adapters pass NULL as before. PyModule_AddFunctions uses ordinary heap build_function.
Other raw FuncArgs consumers Reviewed constructors, datetime pickle-state, collections default factory, ctypes foreign-ABI arguments, functools cache-key indexing, and descriptor pow arguments; these are explicit Python arguments, not hidden receivers.

A descriptor's Python subtype check does not prove its Rust payload type: safe manual constructors can pair any descriptor class with an adapter. The remaining checked payload downcast is necessary to avoid undefined behavior. There is no extra Python isinstance check on the normal method adapter path.

C-API static-method registration correction

The audit found one existing metadata bug that cannot be described as unchanged: PyType_FromSlots registered C METH_STATIC functions as method descriptors. Calling one through the class exposed the user's first explicit argument to the descriptor's receiver protocol (and zero-argument calls failed). These now use an actual staticmethod around a function bound to the defining class, while the C adapter still receives self=NULL.

This intentionally corrects the C-API static entry's __dict__ type, class access result, receiver/descriptor metadata and related repr/inspection behavior. Tests cover class, instance and raw staticmethod calls, explicit type arguments, zero arguments, module snapshot, wrapper identity and C self=NULL. Ordinary static builtins retain their existing registration and metadata.

Validation

Verified head: 1f002314f10557b30d8c508fbf4c204b4dd70262. This remains a draft because it depends on unmerged #9758; that PR is unchanged. Rebase onto main is deferred until #9758 merges, as requested.

  • CI: 27 successful checks, one comparison workflow skipped, no failures or pending checks. Linux/macOS workspace tests each passed 1,571 tests, followed by the separate C-API suite (152 passed, 2 ignored). Cross-platform Rust/Python jobs, strict Clippy, Miri, WASI and cross-target checks passed. CI logs were checked for this exact commit, not an earlier head.
  • Separate local C-API validation: the outlined implementation passed 152 tests, 2 ignored; cd crates/capi && cargo clippy --locked --all-targets -- -D warnings passed with its own Cargo configuration. cargo fmt --all --check and normal commit hooks passed. No hook bypass was used.
  • Python: the final local run of test_binascii test_inspect test_builtin test_importlib test_descr test_capi passed 2,172 tests, 155 skips. All four existing signature/binascii unittest wrappers passed with actual CPython 3.15.2 and RustPython; no dependency was added.
  • C-extension limitation: test_capi includes 10 module skips because _testcapi/_testlimitedcapi are unavailable locally. These skips are not claimed as extension coverage; the separate Rust/PyO3 C-API suite is the actual C-API validation.
  • Compatibility: all 2,616 native callable metadata entries and 31 invalid-call results match the exact 6344672b baseline, including both final build configurations below. This covers receiver/module/name/qualname/objclass/doc/text signature, repr, reduce and inspection results; the separate equality/hash probe is unchanged. Existing CPython differences in some error wording, bound-method hashing and one binascii doc body remain baseline gaps, not fixes claimed here.
  • One unreproduced failure is retained: an earlier outlined six-module run failed the threaded cross-package circular-import test once with KeyError: circ_a. Subsequent focused fresh-process runs (20 per binary), complete test_importlib runs (6 per binary), and another 100 repeated test cases per binary all passed on both baseline and outlined builds. The final complete local suite and CI also passed. This is not asserted to be a confirmed baseline failure; no assertion, marker or test logic was changed to hide it.

Performance

The initial implementation regressed unbound/module measurements and was not accepted. Receiver extraction now avoids a receiver-containing argument vector, and the four descriptor handlers share an outlined implementation instead of expanding duplicate code inside the forced-inline opcode dispatcher. The non-instrumented dispatch body is about 17% smaller in the optimized dev build.

Direct l.append(x) specializes to CALL_LIST_APPEND, which already bypasses the native adapter on the baseline. The cached bound-method case exercises the receiver transport changed here; the unbound case uses CALL_METHOD_DESCRIPTOR_O. Both forms are reported.

Exact 6344672b versus this head, identical build settings within each comparison: Rust 1.100, opt-level 3, debug-info 0, one Cargo job, no incremental. Every sample is a fresh process pinned to one CPU, 3,000,000 iterations following 300,000 warmup calls; append loops clear every 1,024 iterations. ABBA/BAAB blocks balance ordering. Medians include loop overhead. Both wall and process-CPU time were recorded.

Optimized dev, debug assertions enabled (10 blocks, 20 samples per binary/case)

Case Baseline CPU ns Changed CPU ns CPU change Wall change
Cached bound append 355.99 329.55 -7.43% -7.88%
Direct l.append(x) 250.10 254.34 +1.70% +1.02%
Unbound list.append(l, x) 436.40 447.67 +2.58% +2.46%
Cached math.sqrt(x) 271.66 244.18 -10.12% -10.73%

Optimized dev, debug assertions disabled (12 blocks, 24 samples per binary/case)

Case Baseline CPU ns Changed CPU ns CPU change Wall change
Cached bound append 242.33 221.53 -8.59% -10.49%
Direct l.append(x) 184.16 185.63 +0.80% +3.43%
Unbound list.append(l, x) 285.76 274.87 -3.81% -3.77%
Cached math.sqrt(x) 146.98 138.22 -5.96% -5.88%

The assertions-disabled configuration is still an optimized dev profile, not a release/LTO build. No repository profile, payload check, conversion hook or unsafe cast was changed for these measurements.

The assertions-enabled unbound median is +2.58% and is not hidden. Its paired-block mean is +1.72%, with a 95% Student-t interval of -0.07% to +3.51%, so that run does not resolve a small slowdown from noise. With assertions disabled, unbound's paired interval is -5.91% to -1.79%, indicating an improvement; cached unbound append also improves by 3.78% at the CPU median. Bound and module calls improve in both configurations. Direct append's paired interval includes zero in both configurations; it is an existing intrinsic path, not the receiver adapter.

The five-block assertions-disabled A/A control uses the same baseline binary on both sides. Its CPU/wall median differences were unbound +2.19%/-0.12%, direct +1.27%/+1.10%, sqrt +1.40%/+4.20%. These controls put small positive medians in context; the result is not a claim that every noisy sample or configuration is faster. Python-call/empty-loop controls were also measured.

Build provenance was checked as well as metadata: a bound-call receiver-refcount probe shows the baseline's extra reference (+1) disappears in all accepted changed binaries (+0). One additional-profile attempt was rejected because a shared target reused the other worktree's VM; none of its numbers is reported above. The accepted run rebuilt all RustPython outputs between worktrees and verified the VM source path and runtime receiver behavior. A private helper-fusion experiment worsened performance and was reverted, not published. A proposed unsafe cast change was rejected because assembly showed the allegedly duplicate check was already optimized away.

CI CodSpeed reports unchanged benchmarks against main, but that different baseline does not replace the focused comparisons above.

AI assistance

OpenAI Codex assisted with the receiver-site audit, implementation, tests, local validation, performance investigation and this description. A second AI review checked the diff. The exact model version is not exposed by this session and is not guessed. Validation above records actual executions, including their limitations.

youknowdot and others added 9 commits November 13, 2026 18:30
Assisted-by: OpenAI Codex:GPT-6.1
Add explicit pyfunction(with_module) support for a leading PyRef<PyModule> or &Py<PyModule>, reusing the existing bound native call path. Keep this opt-in: _imp.exec_builtin and exec_dynamic take ordinary module arguments of the same type. Generate binascii decoder signatures from FromArgs metadata, preserve their docs, and remove manual registration.

Assisted-by: Codex:unknown
Remove the three inline docstring overrides from the module-bound decoder functions. Import their complete CPython 3.15.1 documentation into the shared database, including the missing base32 and base85 entries, and cover the parameter documentation in the existing binascii snippet.

Assisted-by: Codex:unknown
Replace the with_module opt-in and BIND_MODULE flag with a structural
module receiver carried in Callee. Infer leading owned or borrowed module
parameters in pyfunction through a distinct adapter, and keep one typed
receiver in PyNativeFunction while preserving positional method binding.

Update C-API adapters and _imp target-module calls, document the canonical
receiver spelling, and cover module injection and callable metadata. The
binascii decoders retain generated signatures and rustpython-doc bodies.

Assisted-by: Codex:unknown
PyNativeFn now takes Option<&Py<PyModule>> after &VirtualMachine, and
Callee returns to its lifetime-free form without a module field.
HeapMethodDef::build_function always binds a positional receiver;
build_module_function creates a module-bound function and is used by
PyModule_AddFunctions. Module-function adapters expect the module
instead of raising SystemError.

Assisted-by: Grok
Assisted-by: Claude
A leading PyRef<PyModule> in a #[pyfunction] is now a compile error, as
PyModuleRef already was; PyRef<PyModule> in later positions stays an
ordinary Python argument. The owned-receiver ModuleFunction adapters are
removed. binascii.a2b_base64, binascii.a2b_base32, _imp.exec_builtin and
_imp.exec_dynamic take &Py<PyModule> receivers.

Assisted-by: Grok
Assisted-by: Claude
Unify native calls around a borrowed PyObject receiver and leave FuncArgs
for explicit Python arguments. Select method adapters at registration,
preserve descriptor checks and legacy argument validation, and convert
manual registrations plus all six C-API calling conventions.

Correct C-API static-method registration so an explicit first argument is
not consumed as a descriptor receiver. Add receiver borrowing, metadata,
argument-validation and C-API regressions.

OpenAI Codex assisted with the audit, implementation, tests and review.
The execution environment does not expose an exact model version.

Assisted-by: Codex:unavailable
Replace the PyO3 payload class with a zero-sized C type spec and preserve the receiver/static metadata checks. Use the equivalent Self spelling requested by strict Clippy.

OpenAI Codex assisted with implementation and test review. The exact model version is unavailable in this session.

Assisted-by: Codex:unavailable
@coderabbitai

coderabbitai Bot commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@codspeed

codspeed Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 62 untouched benchmarks
⏩ 4 skipped benchmarks1


Comparing youknowdot:perf/native-receiver-20261113 (1f00231) with main (9a82f61)

Open in CodSpeed

Footnotes

  1. 4 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

Extract receiver values directly from the frame stack. Share descriptor guards and invocation in an outlined helper rather than duplicating them in the forced-inline opcode dispatcher. Preserve generic Python call handling and all fallback checks.

Use one-item iterators in regression tests to satisfy strict Clippy.

OpenAI Codex assisted with the implementation, tests, performance investigation and review. The exact model version is unavailable in this session.

Assisted-by: Codex:unavailable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants