Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 25 additions & 16 deletions InternalDocs/profiling_binary_format.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,12 +119,12 @@ network streams.

## Sample Data

Sample data begins at offset 64 and extends to `string_table_offset`. Samples
are grouped into blocks of at most 1 MiB of decoded data. Within a block,
samples use delta compression to minimize redundancy when consecutive samples
from the same thread have identical or similar call stacks. Each block can be
decoded on its own once the string and frame tables are loaded, so a reader
only needs to decode one block at a time.
Sample data begins at offset 64 and extends to `string_table_offset`. Each
block has a header followed by its columns. The columns together take at most
1 MiB on disk and at most 1 MiB when decoded. Within a block, samples use
delta compression to minimize redundancy when consecutive samples from the
same thread have identical or similar call stacks. Once the reader loads the
string and frame tables, it can decode each block on its own.

### Block Format

Expand Down Expand Up @@ -659,16 +659,25 @@ patterns benefit from kernel read-ahead.

The implementation uses `madvise()` to hint the access pattern to the kernel:
`MADV_SEQUENTIAL` indicates the file will be read linearly, enabling
aggressive read-ahead. `MADV_WILLNEED` requests pre-faulting of pages.
On Linux, `MAP_POPULATE` pre-faults all pages at mmap time rather than on
first access, moving page fault overhead from the parsing loop to the
initial mapping for more predictable performance. For large files (over
32 MB), `MADV_HUGEPAGE` requests transparent huge pages (2 MB instead of
4 KB) to reduce TLB pressure when accessing large amounts of data.

On Windows, the implementation falls back to standard file I/O with full
file buffering. Profiling data files are typically small enough (tens to
hundreds of megabytes) that this is acceptable.
aggressive read-ahead. For large files (over 32 MB), `MADV_HUGEPAGE` requests
transparent huge pages (2 MB instead of 4 KB) to reduce TLB pressure when
accessing large amounts of data. Pages are not loaded up front, only when
replay reaches them.

On Linux, the reader also gives back memory it no longer needs. Once the
string and frame tables have been parsed, and after each sample block has
been replayed, it uses `MADV_DONTNEED` to tell the kernel those pages can be
dropped. The mapping is read-only, so if a dropped page is needed again, the
kernel reads it back from the file. This keeps the memory used for sample
data small, however large the file is.

On Windows, the reader uses standard file I/O instead. When a file is opened,
it only reads the header and the part after the sample data, which holds the
string and frame tables, the statistics and the footer. During replay,
samples are read into a reusable buffer. The reader requests the smaller of
2 MiB and the sample section size. A complete block, including its header,
fits in this buffer. When the buffer runs low, the bytes not yet
replayed are moved to the start and the rest is filled from the file.

The writer buffers samples in the current block and writes each completed
block with a single call, so individual samples never cause a write.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,11 @@ def write_binary_file(self, samples, interval=1000, compression="none",
collector.export(None)
return filename, collector

def _read_offset(self, filename, hdr_off):
with open(filename, "rb") as raw:
raw.seek(hdr_off)
return struct.unpack("=Q", raw.read(8))[0]

def read_block_columns(self, filename):
"""Return the header flags and (decoded size, encoding) per column.

Expand Down Expand Up @@ -1227,6 +1232,36 @@ def collect(self, stack_frames, timestamps_us):
):
self.assertIs(first_frame, second_frame)

def test_reader_replays_large_file_twice(self):
"""Replaying more sample data than the reader buffers is exact."""
class StackCollector:
def __init__(self):
self.stacks = []

def collect(self, stack_frames, timestamps_us):
for interp in stack_frames:
for thread in interp.threads:
stack = list(thread.frame_info)
self.stacks.extend([stack] * len(timestamps_us))

# Deep, shifting stacks give about 2.5 MB of sample data, more than
# the reader reads at once on platforms without mmap.
frames = [make_frame("deep.py", line, "f") for line in range(1356)]
stacks = [frames[i % 1100:i % 1100 + 256] for i in range(5000)]
samples = [[make_interpreter(0, [make_thread(1, stack)])]
for stack in stacks]
filename = self.create_binary_file(samples)
Comment thread
ivonastojanovic marked this conversation as resolved.
Resolved
sample_size = (self._read_offset(filename, self.HDR_OFF_STR_TABLE)
- self.FILE_HEADER_PLACEHOLDER_SIZE)
self.assertGreater(sample_size, 2 * 1024 * 1024)
with BinaryReader(filename) as reader:
first = StackCollector()
second = StackCollector()
self.assertEqual(reader.replay_samples(first), len(samples))
self.assertEqual(reader.replay_samples(second), len(samples))
self.assertEqual(first.stacks, stacks)
self.assertEqual(second.stacks, stacks)

def test_writer_repeat_run_spans_interleaved_streams(self):
"""A thread's repeat run continues across other threads' samples."""
filename = self.temp_filename()
Expand Down Expand Up @@ -1621,11 +1656,6 @@ def test_replay_rejects_trailing_partial_sample_header(self):
MIN_STRING_ENTRY_SIZE = 1
MIN_FRAME_ENTRY_SIZE = 7

def _read_offset(self, filename, hdr_off):
with open(filename, "rb") as raw:
raw.seek(hdr_off)
return struct.unpack("=Q", raw.read(8))[0]

def _patch_footer_count(self, filename, ftr_off, value):
size = os.path.getsize(filename)
with open(filename, "r+b") as raw:
Expand Down Expand Up @@ -2023,6 +2053,8 @@ def test_replay_rejects_invalid_zstd_column(self):
("zstd frame size does not match the decoded size",
frame, len(instructions) + 1),
("zstd decompression error: ", bad_checksum, len(instructions)),
("Invalid sample block: stored columns exceed the block limit",
b"\x00" * (self.MAX_BLOCK_SIZE + 1), len(instructions)),
]
for message, stored, decoded_size in cases:
with self.subTest(message):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Reduce the memory used by :mod:`profiling.sampling` when replaying binary
profiles on Linux and Windows. Sample data is now read one block at a time
instead of being loaded into memory in full, so the memory used for samples
stays small even for very long captures.
5 changes: 4 additions & 1 deletion Modules/_remote_debugging/binary_io.h
Original file line number Diff line number Diff line change
Expand Up @@ -459,10 +459,13 @@ typedef struct {
#if USE_MMAP
uint8_t *mapped_data;
size_t mapped_size;
size_t page_size;
#else
FILE *fp;
uint8_t *file_data;
size_t file_size;
uint8_t *table_data;
ByteBuffer sample_window;
size_t sample_window_start;
#endif

/* Decompression state */
Expand Down
Loading
Loading