mirror of
https://github.com/RustPython/RustPython.git
synced 2026-10-29 03:04:38 +08:00
* Add deterministic profiler and canonical Python 3.15 tools
Use the merged operation critical sections with interpreter-bound profiler
entry checks and short payload borrows. Trace owned code references for GC.
Import the canonical tracing and offline profiling output closure via the
repository updater, retaining existing test markers.
Assisted-by: dot:GPT-6.1
* Clarify standalone profiling license cross-reference
Preserve license terms and copyright notices; point to the reproduced
Apache text below instead of CPython's original OpenSSL section above.
Assisted-by: dot:GPT-6.1
* Defer unsupported sampling package from profiler extraction
Keep the deterministic tracing profiler and its canonical tools together.
Defer the entirely new sampling production, tests, assets and their license
as one closure until native record and binary-collector support is ready.
Retain canonical pstats for deterministic empty-profile handling; its
upstream sampled-file sorting issue is not patched here.
Assisted-by: dot:GPT-6.1
* Stage profiling root as a namespace until sampling is available
Omit the whole newly added canonical package initializer rather than
advertise an absent sampling module or hand-edit canonical __all__.
Explicit profiling.tracing and cProfile imports remain available.
The namespace root intentionally lacks canonical metadata/automatic exports.
This addresses test___all__ failures in the prior Linux, macOS and Windows
CI runs. No test assertions, skips or canonical file contents are changed.
Assisted-by: dot:GPT-6.1
* Match canonical static builtin profiler labels and metadata
Normalize the raw builtin receiver instead of its call-argument accessor.
Snapshot static method module metadata at construction, matching CPython,
so explicit module mutation and deletion remain observable. Avoid a
profiler-time fallback that would obscure deleted metadata.
Correct float.__getformat__ to CPython's classmethod calling convention,
including subclass binding, rather than special-casing its profiler label.
Assisted-by: dot:GPT-6.1
* Support collision-safe frozen package containers
Generate empty frozen packages only for source namespace directories with
real frozen descendants. Preserve genuine modules and packages across
frozen-library registrations while retaining real-real replacement order.
Record the container marker in FrozenModule and its library envelope;
legacy module/package encodings remain unchanged. This is closed-tree
frozen packaging, not full PEP 420 namespace merging.
Add structural codec, mock generator, and registration-priority checks.
* Revert frozen package containers before restoring canonical profiling root
The container implementation changed filesystem namespace precedence.
Restore the existing importer and frozen envelope unchanged; the following
offline sampling closure restores the canonical regular package root.
This reverses d5a8049234.
Assisted-by: dot:GPT-6.1
* Restore canonical profiling package with offline sampling codec
Provide native records, status constants and genuine uncompressed binary
reader/writer APIs for canonical offline tools. Keep the unsupported live
process capability absent and preserve existing canonical test gates.
Restore the complete selected sampling production/test/assets closure via
update_lib, including its asyncio frame-schema dependency. The prior frozen
container extension is reverted separately; canonical packages work with
both filesystem and frozen imports without changing namespace semantics.
Assisted-by: dot:GPT-6.1
* Keep platform-dependent C long normalization explicit
Allow only the c_long-to-i32 conversion lint: Windows uses the same type,
while LP64 requires the existing truncation to match CPython normalization.
No runtime behavior or test assertions change.
Assisted-by: dot:GPT-6.1
* Include profiling notices in library and desktop packages
Bundle a byte-identical copy of the root profiling notice in rustpython-pylib
and include the root notice in configured desktop resources. Avoid a symlink
so Windows checkouts preserve the actual notice text. Terms are unchanged.
Assisted-by: dot:GPT-6.1
* Keep profiling asset license notice in pylib crate
* Serve frozen profiling assets through native resource readers
* Preserve canonical profiling asset line endings on checkout
---------
Co-authored-by: youknowdot <dot@youknowone.org>
152 lines
4.8 KiB
Python
Vendored
152 lines
4.8 KiB
Python
Vendored
"""Thin Python wrapper around C binary writer for profiling data."""
|
|
|
|
import time
|
|
|
|
import _remote_debugging
|
|
|
|
from .collector import Collector
|
|
|
|
# Compression type constants (must match binary_io.h)
|
|
COMPRESSION_NONE = 0
|
|
COMPRESSION_ZSTD = 1
|
|
|
|
CAPTURE_FEATURES = {
|
|
"all_threads": 1 << 0,
|
|
"native": 1 << 1,
|
|
"gc": 1 << 2,
|
|
"opcodes": 1 << 3,
|
|
"blocking": 1 << 4,
|
|
}
|
|
|
|
|
|
def encode_capture_config(capture_config):
|
|
if capture_config is None:
|
|
return -1
|
|
return sum(
|
|
bit for name, bit in CAPTURE_FEATURES.items()
|
|
if capture_config.get(name, False)
|
|
)
|
|
|
|
|
|
def _resolve_compression(compression):
|
|
"""Resolve compression type from string or int.
|
|
|
|
Args:
|
|
compression: 'auto', 'zstd', 'none', or int (0/1)
|
|
|
|
Returns:
|
|
int: Compression type constant
|
|
"""
|
|
if isinstance(compression, int):
|
|
return compression
|
|
|
|
compression = compression.lower()
|
|
if compression == 'none':
|
|
return COMPRESSION_NONE
|
|
elif compression == 'zstd':
|
|
return COMPRESSION_ZSTD
|
|
elif compression == 'auto':
|
|
# Auto: use zstd if available, otherwise none
|
|
if _remote_debugging.zstd_available():
|
|
return COMPRESSION_ZSTD
|
|
return COMPRESSION_NONE
|
|
else:
|
|
raise ValueError(f"Unknown compression type: {compression}")
|
|
|
|
|
|
class BinaryCollector(Collector):
|
|
"""High-performance binary collector using C implementation.
|
|
|
|
This collector writes profiling data directly to a binary file format
|
|
with optional zstd compression. All I/O is performed in C for maximum
|
|
throughput.
|
|
|
|
The binary format uses string/frame deduplication and varint encoding
|
|
for efficient storage.
|
|
"""
|
|
|
|
def __init__(self, filename, sample_interval_usec, *, skip_idle=False,
|
|
compression='auto', mode=None, capture_config=None):
|
|
"""Create a new binary collector.
|
|
|
|
Args:
|
|
filename: Path to output binary file
|
|
sample_interval_usec: Sampling interval in microseconds
|
|
skip_idle: If True, skip idle threads (not used in binary format)
|
|
compression: 'auto', 'zstd', 'none', or int (0=none, 1=zstd)
|
|
mode: Profiling mode, or None if unknown
|
|
capture_config: Mapping of capture feature names to booleans, or
|
|
None if the capture configuration is unknown
|
|
"""
|
|
self.filename = filename
|
|
self.sample_interval_usec = sample_interval_usec
|
|
self.skip_idle = skip_idle
|
|
|
|
compression_type = _resolve_compression(compression)
|
|
start_time_us = int(time.monotonic() * 1_000_000)
|
|
self._writer = _remote_debugging.BinaryWriter(
|
|
filename, sample_interval_usec, start_time_us,
|
|
compression=compression_type,
|
|
mode=-1 if mode is None else mode,
|
|
capture_features=encode_capture_config(capture_config),
|
|
)
|
|
|
|
def collect(self, stack_frames, timestamp_us=None):
|
|
"""Collect profiling data from stack frames.
|
|
|
|
This passes stack_frames directly to the C writer which handles
|
|
all encoding and buffering.
|
|
|
|
Args:
|
|
stack_frames: List of InterpreterInfo objects from _remote_debugging
|
|
timestamp_us: Optional timestamp in microseconds. If not provided,
|
|
uses time.monotonic() to generate one.
|
|
"""
|
|
if timestamp_us is None:
|
|
timestamp_us = int(time.monotonic() * 1_000_000)
|
|
self._writer.write_sample(stack_frames, timestamp_us)
|
|
|
|
def collect_failed_sample(self):
|
|
"""Record a failed sample attempt (no-op for binary format)."""
|
|
pass
|
|
|
|
def set_stats(self, sample_interval_usec, duration_sec, sample_rate,
|
|
error_rate=None, missed_samples=None, **kwargs):
|
|
"""Persist measured statistics for later replay."""
|
|
self._writer.set_stats(
|
|
duration_sec, sample_rate, error_rate, missed_samples
|
|
)
|
|
|
|
def export(self, filename=None):
|
|
"""Finalize and close the binary file.
|
|
|
|
Args:
|
|
filename: Ignored (binary files are written incrementally)
|
|
"""
|
|
self._writer.finalize()
|
|
return True
|
|
|
|
@property
|
|
def total_samples(self):
|
|
return self._writer.total_samples
|
|
|
|
def get_stats(self):
|
|
"""Get encoding statistics.
|
|
|
|
Returns:
|
|
Dict with encoding statistics including repeat/full/suffix/pop-push
|
|
record counts, frames written/saved, and compression ratio.
|
|
"""
|
|
return self._writer.get_stats()
|
|
|
|
def __enter__(self):
|
|
return self
|
|
|
|
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
"""Context manager exit - finalize unless there was an error."""
|
|
if exc_type is None:
|
|
self._writer.finalize()
|
|
else:
|
|
self._writer.close()
|
|
return False
|