Repository navigation
Pass native method receivers outside FuncArgs - #9829
Closed
youknowdot wants to merge 10 commits into
Closed
youknowdot wants to merge 10 commits into
youknowdot wants to merge 10 commits into
Conversation
Assisted-by: OpenAI Codex:GPT-6.1
Assisted-by: OpenAI Codex
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
Contributor
|
Important Draft PR not reviewedDraft PRs are not automatically reviewed by default.
To automatically review draft PRs, update your CodeRabbit configuration: reviews:
auto_review:
drafts: true
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. |
Contributor
Merging this PR will not alter performance
Comparing Footnotes
|
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.Option<&PyObject>outsideFuncArgs.Option<PyObjectRef>on native functions, without receiver-kind tags, prepend operations or receiver-vector allocation at invocation.Receiver / raw-argument audit
Audited the complete tree at
6344672bbefore implementation.PyNativeFn,IntoPyNativeFn,PyNativeFnInternal,static_raw_func,Context::new_raw_method_defPyObjectreceiver ABI.PyNativeFunctioncall/vectorcall andNativeFunctionSelfzelf.as_deref()and unchanged user args.PyMethodDescriptorcall/vectorcallCallMethodDescriptor{Noargs,O,Fast,FastWithKeywords}frame specializations#[pymethod],#[pyclassmethod],#[pystaticmethod], raw method expansionraw=truemethods were found.&self,&Py<S>,PyRef<S>,PyObjectRef, customTryFromObjectselfNativeFunctionOrMethod's special conversion for builtin-method prefix payloads andPyPayload::try_downcast_fromvalidation hooks.OwnedParam/BorrowedParam/RefParam,BorrowedArgsfunctionsPyMethodDef,HeapMethodDef,define_methods!,VirtualMachine::new_methodwrite/flushuse the updated method helper.slot_new_wrapperand C-API type__new__registrationPyType::__new__still binds the explicit subtype argument fromFuncArgs; it is distinct from the hidden defining-class receiver._astdeepcopy/replace/reduce, struct-sequence reduce,_threadexcept-hook reduce, cross-interpreterFIND_CLASSFIND_CLASSbinds self despite empty flags, so selection must not depend on flags.type.__subclasshook__(FuncArgs)FuncArgsmethodsPyWrapper,PyMethodWrapper,vectorcall_wrappertypes/slot.rsnew-wrapper prepend is an explicit__new__class argument, not native hidden-self transport.PyBoundMethodand generic/instrumented frame callsCallee.instance_arg/ binder offset / shape skippingtake_self_arg,has_self, and Cow. Static C adapters pass NULL as before.PyModule_AddFunctionsuses ordinary heapbuild_function.FuncArgsconsumersA 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
isinstancecheck 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_FromSlotsregistered CMETH_STATICfunctions 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 actualstaticmethodaround a function bound to the defining class, while the C adapter still receivesself=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 Cself=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.cd crates/capi && cargo clippy --locked --all-targets -- -D warningspassed with its own Cargo configuration.cargo fmt --all --checkand normal commit hooks passed. No hook bypass was used.test_binascii test_inspect test_builtin test_importlib test_descr test_capipassed 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.test_capiincludes 10 module skips because_testcapi/_testlimitedcapiare unavailable locally. These skips are not claimed as extension coverage; the separate Rust/PyO3 C-API suite is the actual C-API validation.6344672bbaseline, 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.KeyError: circ_a. Subsequent focused fresh-process runs (20 per binary), completetest_importlibruns (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 toCALL_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 usesCALL_METHOD_DESCRIPTOR_O. Both forms are reported.Exact
6344672bversus 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)
l.append(x)list.append(l, x)math.sqrt(x)Optimized dev, debug assertions disabled (12 blocks, 24 samples per binary/case)
l.append(x)list.append(l, x)math.sqrt(x)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.