Skip to content

Commit bd76a91

Browse files
youknowdotcodex
authored andcommitted
Preserve native profile events in observed dispatch
Restrict legacy c events to native functions and method descriptors, binding each descriptor event independently. Route native-call specializations through a local observed CALL with adaptive writes suppressed, without changing the unobserved dispatch body or shared bytecode. Preserve full static type names in descriptor repr and remove the profile output expected failure. Assisted-by: Codex:unknown
1 parent f028f83 commit bd76a91

5 files changed

Lines changed: 192 additions & 36 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: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2887,6 +2887,21 @@ fn exec_iframe<'a>(
28872887
}
28882888
}
28892889

2890+
// Legacy profiling must observe calls even after native-call specialization.
2891+
#[cold]
2892+
fn legacy_profile_call(op: Instruction) -> bool {
2893+
matches!(
2894+
op,
2895+
Instruction::CallListAppend
2896+
| Instruction::CallLen
2897+
| Instruction::CallIsinstance
2898+
| Instruction::CallMethodDescriptorNoargs
2899+
| Instruction::CallMethodDescriptorO
2900+
| Instruction::CallMethodDescriptorFast
2901+
| Instruction::CallMethodDescriptorFastWithKeywords
2902+
)
2903+
}
2904+
28902905
/// Execute an InterpreterFrame's bytecode directly, without a FrameObject.
28912906
#[inline(always)]
28922907
pub(crate) fn run_iframe(
@@ -4116,10 +4131,22 @@ impl ExecutingFrame<'_> {
41164131
)
41174132
} else {
41184133
let unit = unsafe { bytecode::CodeUnits::read_unit_from(units_ptr, idx) };
4134+
let (op, mode) = if OBSERVED && tracing && legacy_profile_call(unit.op) {
4135+
(
4136+
Opcode::Call.as_instruction(),
4137+
// The physical-path opcode callback runs below. Avoid
4138+
// adaptive cache writes for this virtual legacy call.
4139+
DispatchMode::Monitored {
4140+
opcode_traced: true,
4141+
},
4142+
)
4143+
} else {
4144+
(unit.op, DispatchMode::Physical)
4145+
};
41194146
(
4120-
unit.op,
4147+
op,
41214148
unit.arg,
4122-
DispatchMode::Physical,
4149+
mode,
41234150
if OBSERVED { unit.op.cache_entries() } else { 0 },
41244151
)
41254152
};

‎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: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -680,3 +680,89 @@ def original(frame, event, arg):
680680
set_hook(old)
681681
assert not any(name == "suppressed_after_change" for name, _ in changed_events)
682682
assert (("later", "call") in changed_events) == replace_hook
683+
684+
# Legacy profiling excludes constructors and callable instances, and binds a
685+
# method descriptor independently for each event (legacy_tracing.c).
686+
def check_profile_callables():
687+
class Constructor:
688+
pass
689+
690+
class CallableInstance:
691+
def __call__(self):
692+
pass
693+
694+
import _lsprof
695+
696+
# cProfile's table width includes the profiler's disable descriptor label.
697+
assert (
698+
repr(_lsprof.Profiler.disable)
699+
== "<method 'disable' of '_lsprof.Profiler' objects>"
700+
)
701+
702+
events = []
703+
704+
def record(frame, event, arg):
705+
if event.startswith("c_") and arg is not sys.setprofile:
706+
events.append((event, arg))
707+
708+
def capture(func):
709+
events.clear()
710+
sys.setprofile(record)
711+
try:
712+
func()
713+
except TypeError:
714+
pass
715+
finally:
716+
sys.setprofile(None)
717+
return list(events)
718+
719+
assert capture(Constructor) == []
720+
assert capture(list) == []
721+
assert capture(CallableInstance()) == []
722+
assert capture(lambda: list.append()) == []
723+
assert capture(lambda: list.append(1, 2)) == []
724+
receiver = []
725+
result = capture(lambda: list.append(receiver, 1))
726+
assert [event for event, _ in result] == ["c_call", "c_return"]
727+
assert all(type(arg) is type(len) and arg.__self__ is receiver for _, arg in result)
728+
assert result[0][1] is not result[1][1]
729+
result = capture(lambda: list.append(receiver))
730+
assert [event for event, _ in result] == ["c_call", "c_exception"]
731+
assert all(type(arg) is type(len) and arg.__self__ is receiver for _, arg in result)
732+
result = capture(lambda: len(1))
733+
assert result == [("c_call", len), ("c_exception", len)]
734+
735+
def native_calls():
736+
values = []
737+
for value in range(20):
738+
values.append(value)
739+
len(values)
740+
isinstance(value, int)
741+
values.count(value)
742+
"aaa".replace("a", "b")
743+
values.sort(reverse=True)
744+
values.clear()
745+
746+
native_calls() # Warm native-call specializations before profiling.
747+
result = capture(native_calls)
748+
assert len(result) == 280
749+
assert [event for event, _ in result] == ["c_call", "c_return"] * 140
750+
751+
# Enabling profiling inside an unprofiled native call must not invent an
752+
# unmatched c_return, even when sys.settrace was already active.
753+
events.clear()
754+
755+
def enable_profile(value):
756+
sys.setprofile(record)
757+
return value
758+
759+
sys.settrace(lambda *args: None)
760+
try:
761+
sorted([1], key=enable_profile)
762+
finally:
763+
sys.setprofile(None)
764+
sys.settrace(None)
765+
assert not any(arg is sorted for _, arg in events)
766+
767+
768+
check_profile_callables()

0 commit comments

Comments
 (0)