Skip to content

Commit e634ec6

Browse files
authored
Preserve native profile events without monitoring dispatch changes (#9912)
Extract the native profile corrections from bd76a91, adapting specialized calls to the existing main dispatch without changing shared bytecode. Preserve independently bound descriptor events and exercise warmed calls across profile toggles. Assisted-by: Codex:unknown
1 parent b1665f0 commit e634ec6

5 files changed

Lines changed: 185 additions & 35 deletions

File tree

‎Lib/test/test_profile.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,6 @@ def do_profiling(cls):
5252
results.append('\n'.join(output))
5353
return results
5454

55-
@unittest.expectedFailure # TODO: RUSTPYTHON; print_callees output differs from CPython
5655
def test_cprofile(self):
5756
results = self.do_profiling()
5857
expected = self.get_expected_output()

‎crates/vm/src/builtins/descriptor.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ impl Representable for PyMethodDescriptor {
171171
Ok(format!(
172172
"<method '{}' of '{}' objects>",
173173
zelf.method.name,
174-
zelf.common.typ.name()
174+
zelf.common.typ.slot_name()
175175
))
176176
}
177177
}

‎crates/vm/src/frame.rs‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3984,7 +3984,24 @@ impl ExecutingFrame<'_> {
39843984
self.localsplus.promote_stack();
39853985
break Ok(None);
39863986
}
3987-
let result = self.execute_instruction(op, arg, &mut do_extend_arg, vm);
3987+
// Native-call specializations bypass PyCallable's legacy profile
3988+
// events. Use the generic call only while tracing, without rewriting
3989+
// shared bytecode or touching the specialization's inline caches.
3990+
let result = if tracing
3991+
&& matches!(
3992+
op,
3993+
Instruction::CallListAppend
3994+
| Instruction::CallLen
3995+
| Instruction::CallIsinstance
3996+
| Instruction::CallMethodDescriptorNoargs
3997+
| Instruction::CallMethodDescriptorO
3998+
| Instruction::CallMethodDescriptorFast
3999+
| Instruction::CallMethodDescriptorFastWithKeywords
4000+
) {
4001+
self.execute_call_vectorcall(arg.into(), vm)
4002+
} else {
4003+
self.execute_instruction(op, arg, &mut do_extend_arg, vm)
4004+
};
39884005
// Skip inline cache entries if instruction fell through (no jump).
39894006
// `cache_entries()` is a table lookup, so it is done here rather
39904007
// than before dispatch: computing it up front kept the count live

‎crates/vm/src/protocol/callable.rs‎

Lines changed: 76 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
use crate::{
2-
builtins::{PyBoundMethod, PyFunction},
2+
builtins::{builtin_func::PyNativeFunction, descriptor::PyMethodDescriptor},
33
function::{FuncArgs, IntoFuncArgs},
4-
types::{GenericMethod, PyTypeFlags, VectorCallFunc},
5-
{PyObject, PyObjectRef, PyResult, VirtualMachine},
4+
types::{GenericMethod, GetDescriptor, PyTypeFlags, VectorCallFunc},
5+
{AsObject, PyObject, PyObjectRef, PyResult, VirtualMachine},
66
};
77

88
impl PyObject {
@@ -111,22 +111,69 @@ impl PyObject {
111111
if !vm.use_tracing.get() {
112112
return vc(self, args, nargs, kwnames, vm);
113113
}
114-
let is_python_callable = self.downcast_ref::<PyFunction>().is_some()
115-
|| self.downcast_ref::<PyBoundMethod>().is_some();
116-
if is_python_callable {
117-
vc(self, args, nargs, kwnames, vm)
114+
let first_arg = self.profile_first_arg(args[..nargs].first(), vm);
115+
let Some(callable) = self.profile_callable(first_arg.as_ref(), vm)? else {
116+
return vc(self, args, nargs, kwnames, vm);
117+
};
118+
vm.trace_event(TraceEvent::CCall, Some(callable))?;
119+
let result = vc(self, args, nargs, kwnames, vm);
120+
if result.is_ok() {
121+
self.profile_event(TraceEvent::CReturn, first_arg.as_ref(), vm)?;
118122
} else {
119-
let callable = self.to_owned();
120-
vm.trace_event(TraceEvent::CCall, Some(callable.clone()))?;
121-
let result = vc(self, args, nargs, kwnames, vm);
122-
if result.is_ok() {
123-
vm.trace_event(TraceEvent::CReturn, Some(callable))?;
124-
} else {
125-
let _ = vm.trace_event(TraceEvent::CException, Some(callable));
126-
}
127-
result
123+
let _ = self.profile_event(TraceEvent::CException, first_arg.as_ref(), vm);
124+
}
125+
result
126+
}
127+
128+
#[cold]
129+
fn profile_event(
130+
&self,
131+
event: TraceEvent,
132+
first_arg: Option<&PyObjectRef>,
133+
vm: &VirtualMachine,
134+
) -> PyResult<()> {
135+
if let Some(callable) = self.profile_callable(first_arg, vm)? {
136+
vm.trace_event(event, Some(callable))?;
137+
}
138+
Ok(())
139+
}
140+
141+
#[cold]
142+
fn profile_first_arg(
143+
&self,
144+
first_arg: Option<&PyObjectRef>,
145+
vm: &VirtualMachine,
146+
) -> Option<PyObjectRef> {
147+
// Only method descriptors need a receiver for legacy profile callbacks.
148+
// Keep it available for binding independently at call and return.
149+
if self.class().is(vm.ctx.types.method_descriptor_type) {
150+
first_arg.cloned()
151+
} else {
152+
None
128153
}
129154
}
155+
156+
// CPython legacy_tracing.c: sys_profile_call_or_return. This filter is
157+
// specific to sys.setprofile, not sys.monitoring's general CALL events.
158+
#[cold]
159+
fn profile_callable(
160+
&self,
161+
first_arg: Option<&PyObjectRef>,
162+
vm: &VirtualMachine,
163+
) -> PyResult<Option<PyObjectRef>> {
164+
if vm.tracing_is_suppressed() || vm.is_none(&vm.profile_func.borrow()) {
165+
return Ok(None);
166+
}
167+
if self.downcast_ref::<PyNativeFunction>().is_some() {
168+
return Ok(Some(self.to_owned()));
169+
}
170+
if self.class().is(vm.ctx.types.method_descriptor_type)
171+
&& let Some(first_arg) = first_arg
172+
{
173+
return PyMethodDescriptor::descr_get(self, Some(first_arg), None, vm).map(Some);
174+
}
175+
Ok(None)
176+
}
130177
}
131178

132179
#[derive(Debug)]
@@ -165,24 +212,21 @@ impl<'a> PyCallable<'a> {
165212
if !vm.use_tracing.get() {
166213
return (self.call)(self.obj, args, vm);
167214
}
168-
// Python functions get 'call'/'return' events from with_frame().
169-
// Bound methods delegate to the inner callable, which fires its own events.
170-
// All other callables (built-in functions, etc.) get 'c_call'/'c_return'/'c_exception'.
171-
let is_python_callable = self.obj.downcast_ref::<PyFunction>().is_some()
172-
|| self.obj.downcast_ref::<PyBoundMethod>().is_some();
173-
if is_python_callable {
174-
(self.call)(self.obj, args, vm)
215+
let first_arg = self.obj.profile_first_arg(args.args.first(), vm);
216+
let Some(callable) = self.obj.profile_callable(first_arg.as_ref(), vm)? else {
217+
return (self.call)(self.obj, args, vm);
218+
};
219+
vm.trace_event(TraceEvent::CCall, Some(callable))?;
220+
let result = (self.call)(self.obj, args, vm);
221+
if result.is_ok() {
222+
self.obj
223+
.profile_event(TraceEvent::CReturn, first_arg.as_ref(), vm)?;
175224
} else {
176-
let callable = self.obj.to_owned();
177-
vm.trace_event(TraceEvent::CCall, Some(callable.clone()))?;
178-
let result = (self.call)(self.obj, args, vm);
179-
if result.is_ok() {
180-
vm.trace_event(TraceEvent::CReturn, Some(callable))?;
181-
} else {
182-
let _ = vm.trace_event(TraceEvent::CException, Some(callable));
183-
}
184-
result
225+
let _ = self
226+
.obj
227+
.profile_event(TraceEvent::CException, first_arg.as_ref(), vm);
185228
}
229+
result
186230
}
187231

188232
/// Use automatic vectorcall if available, else fall back to FuncArgs.

‎extra_tests/snippets/stdlib_sys.py‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -618,3 +618,93 @@ def original(frame, event, arg):
618618
set_hook(old)
619619
assert not any(name == "suppressed_after_change" for name, _ in changed_events)
620620
assert (("later", "call") in changed_events) == replace_hook
621+
622+
623+
# Legacy profiling excludes constructors and callable instances, and binds a
624+
# method descriptor independently for each event (legacy_tracing.c).
625+
def check_profile_callables():
626+
class Constructor:
627+
pass
628+
629+
class CallableInstance:
630+
def __call__(self):
631+
pass
632+
633+
import _lsprof
634+
635+
# cProfile's table width includes the profiler's disable descriptor label.
636+
assert (
637+
repr(_lsprof.Profiler.disable)
638+
== "<method 'disable' of '_lsprof.Profiler' objects>"
639+
)
640+
641+
events = []
642+
643+
def record(frame, event, arg):
644+
if event.startswith("c_") and arg is not sys.setprofile:
645+
events.append((event, arg))
646+
647+
def capture(func):
648+
events.clear()
649+
sys.setprofile(record)
650+
try:
651+
func()
652+
except TypeError:
653+
pass
654+
finally:
655+
sys.setprofile(None)
656+
return list(events)
657+
658+
assert capture(Constructor) == []
659+
assert capture(list) == []
660+
assert capture(CallableInstance()) == []
661+
assert capture(lambda: list.append()) == []
662+
assert capture(lambda: list.append(1, 2)) == []
663+
receiver = []
664+
result = capture(lambda: list.append(receiver, 1))
665+
assert [event for event, _ in result] == ["c_call", "c_return"]
666+
assert all(type(arg) is type(len) and arg.__self__ is receiver for _, arg in result)
667+
assert result[0][1] is not result[1][1]
668+
result = capture(lambda: list.append(receiver))
669+
assert [event for event, _ in result] == ["c_call", "c_exception"]
670+
assert all(type(arg) is type(len) and arg.__self__ is receiver for _, arg in result)
671+
result = capture(lambda: len(1))
672+
assert result == [("c_call", len), ("c_exception", len)]
673+
674+
def native_calls():
675+
values = []
676+
for value in range(20):
677+
values.append(value)
678+
len(values)
679+
isinstance(value, int)
680+
values.count(value)
681+
"aaa".replace("a", "b")
682+
values.sort(reverse=True)
683+
values.sort()
684+
values.clear()
685+
686+
native_calls() # Warm native-call specializations before profiling.
687+
for _ in range(3):
688+
result = capture(native_calls)
689+
assert len(result) == 320
690+
assert [event for event, _ in result] == ["c_call", "c_return"] * 160
691+
native_calls() # Disable/re-enable must preserve warmed call sites.
692+
693+
# Enabling profiling inside an unprofiled native call must not invent an
694+
# unmatched c_return, even when sys.settrace was already active.
695+
events.clear()
696+
697+
def enable_profile(value):
698+
sys.setprofile(record)
699+
return value
700+
701+
sys.settrace(lambda *args: None)
702+
try:
703+
sorted([1], key=enable_profile)
704+
finally:
705+
sys.setprofile(None)
706+
sys.settrace(None)
707+
assert not any(arg is sorted for _, arg in events)
708+
709+
710+
check_profile_callables()

0 commit comments

Comments
 (0)