From 74e2c092b97dbe82edfa90f37ccc2af49571f2d2 Mon Sep 17 00:00:00 2001 From: Ivona Stojanovic Date: Fri, 23 Oct 2026 11:21:33 -0700 Subject: [PATCH 1/4] Release consumed profile pages during replay Replay maps the whole profile into memory and asks the kernel to load every page up front. Those pages stay resident until the reader is closed, so memory usage grows with the size of the capture, even though replay only needs one block at a time. Stop preloading the file and let pages load on demand as replay reads them. On Linux, release the string and frame tables once they have been parsed, and release each sample block once it has been replayed. Only pages that have been fully consumed are released. Because the mapping is read-only, a released page is read back from the file if it is needed again. --- Modules/_remote_debugging/binary_io.h | 1 + Modules/_remote_debugging/binary_io_reader.c | 43 ++++++++++++-------- 2 files changed, 27 insertions(+), 17 deletions(-) diff --git a/Modules/_remote_debugging/binary_io.h b/Modules/_remote_debugging/binary_io.h index 4f740d953f5dcc..b3c1d4459e5709 100644 --- a/Modules/_remote_debugging/binary_io.h +++ b/Modules/_remote_debugging/binary_io.h @@ -459,6 +459,7 @@ typedef struct { #if USE_MMAP uint8_t *mapped_data; size_t mapped_size; + size_t page_size; #else FILE *fp; uint8_t *file_data; diff --git a/Modules/_remote_debugging/binary_io_reader.c b/Modules/_remote_debugging/binary_io_reader.c index 24079f26a137eb..7aca214453f521 100644 --- a/Modules/_remote_debugging/binary_io_reader.c +++ b/Modules/_remote_debugging/binary_io_reader.c @@ -435,6 +435,26 @@ reader_parse_frame_table(BinaryReader *reader, const uint8_t *data, size_t file_ return 0; } +#if defined(__linux__) && defined(MADV_DONTNEED) +static size_t +reader_discard_mapped_pages(BinaryReader *reader, size_t start, size_t end) +{ + start = _Py_SIZE_ROUND_UP(start, reader->page_size); + end = _Py_SIZE_ROUND_DOWN(end, reader->page_size); + if (start >= end) { + return start; + } + (void)madvise(reader->mapped_data + start, end - start, MADV_DONTNEED); + return end; +} +#else +static inline size_t +reader_discard_mapped_pages(BinaryReader *reader, size_t start, size_t end) +{ + return end; +} +#endif + BinaryReader * binary_reader_open(PyObject *path) { @@ -475,32 +495,19 @@ binary_reader_open(PyObject *path) goto error; } - /* Map the file into memory. - * MAP_POPULATE (Linux-only) pre-faults all pages at mmap time, which: - * - Catches issues (e.g., file truncation) immediately rather than as SIGBUS during reads - * - Eliminates page faults during subsequent reads for better performance - */ -#ifdef __linux__ - reader->mapped_data = mmap(NULL, reader->mapped_size, PROT_READ, - MAP_PRIVATE | MAP_POPULATE, fd, 0); -#else reader->mapped_data = mmap(NULL, reader->mapped_size, PROT_READ, MAP_PRIVATE, fd, 0); -#endif if (reader->mapped_data == MAP_FAILED) { reader->mapped_data = NULL; PyErr_SetFromErrno(PyExc_IOError); Py_fclose(fp); goto error; } + reader->page_size = (size_t)sysconf(_SC_PAGESIZE); /* Hint sequential access pattern - failures are non-fatal */ (void)madvise(reader->mapped_data, reader->mapped_size, MADV_SEQUENTIAL); - /* Pre-fetch pages into memory - failures are non-fatal. - * Complements MAP_POPULATE on Linux, provides benefit on macOS. */ - (void)madvise(reader->mapped_data, reader->mapped_size, MADV_WILLNEED); - /* Use transparent huge pages for large files to reduce TLB misses. * Only beneficial for files >= 32MB where TLB pressure matters. */ #ifdef MADV_HUGEPAGE @@ -512,9 +519,6 @@ binary_reader_open(PyObject *path) /* Add file descriptor-level hints for better kernel I/O scheduling */ #if defined(__linux__) && defined(POSIX_FADV_SEQUENTIAL) (void)posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL); - if (reader->mapped_size > (64 * 1024 * 1024)) { - (void)posix_fadvise(fd, 0, 0, POSIX_FADV_WILLNEED); - } #endif if (Py_fclose(fp) != 0) { @@ -647,6 +651,8 @@ binary_reader_open(PyObject *path) if (reader_parse_frame_table(reader, data, file_size) < 0) { goto error; } + (void)reader_discard_mapped_pages( + reader, (size_t)reader->string_table_offset, file_size); return reader; @@ -1600,6 +1606,7 @@ replay_blocks(BinaryReader *reader, RemoteDebuggingState *state, { ByteBuffer section = {reader->sample_data, reader->sample_data_size, 0}; size_t offset = 0; + size_t discarded = 0; while (offset < section.size) { DecodedBlock block; if (decode_block(reader, §ion, &offset, &block) < 0 || @@ -1607,6 +1614,8 @@ replay_blocks(BinaryReader *reader, RemoteDebuggingState *state, &block, replayed) < 0) { return -1; } + discarded = reader_discard_mapped_pages( + reader, discarded, FILE_HEADER_PLACEHOLDER_SIZE + offset); } return 0; } From a29bbacf87ba2aeb5da97ea1e9b1af85395ca7f8 Mon Sep 17 00:00:00 2001 From: Ivona Stojanovic Date: Mon, 23 Nov 2026 22:51:42 +0000 Subject: [PATCH 2/4] Read profile samples block by block on Windows On Windows, opening a profile reads the whole file into memory and keeps it there until the reader is closed. Memory usage therefore grows with the size of the capture, even though replay only needs one block at a time. Read only the header and the tables that follow the samples when the profile is opened. The tables are parsed into their own structures, so the bytes read for them are released straight away. During replay, read the samples through a small reusable window that always holds at least one complete block, keeping the unread bytes and refilling the rest from the file as blocks are consumed. Memory used for samples is then bounded by the window size rather than by the length of the capture. --- .../test_binary_format.py | 27 ++ ...-11-24-17-56-46.gh-issue-159207.3PCgei.rst | 4 + Modules/_remote_debugging/binary_io.h | 4 +- Modules/_remote_debugging/binary_io_reader.c | 231 +++++++++++++----- 4 files changed, 198 insertions(+), 68 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2026-11-24-17-56-46.gh-issue-159207.3PCgei.rst diff --git a/Lib/test/test_profiling/test_sampling_profiler/test_binary_format.py b/Lib/test/test_profiling/test_sampling_profiler/test_binary_format.py index 67b2708129b797..e1a1083d0dbe07 100644 --- a/Lib/test/test_profiling/test_sampling_profiler/test_binary_format.py +++ b/Lib/test/test_profiling/test_sampling_profiler/test_binary_format.py @@ -1227,6 +1227,33 @@ 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) + 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() diff --git a/Misc/NEWS.d/next/Library/2026-11-24-17-56-46.gh-issue-159207.3PCgei.rst b/Misc/NEWS.d/next/Library/2026-11-24-17-56-46.gh-issue-159207.3PCgei.rst new file mode 100644 index 00000000000000..79c184fc4d9ac1 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-24-17-56-46.gh-issue-159207.3PCgei.rst @@ -0,0 +1,4 @@ +Reduce the memory used by :mod:`profiling.sampling` when replaying binary +profiles on Linux and Windows. Profiles are now read one block at a time +instead of being loaded into memory in full, so memory use stays small even +for very long captures. diff --git a/Modules/_remote_debugging/binary_io.h b/Modules/_remote_debugging/binary_io.h index b3c1d4459e5709..b89bb9bbedf67d 100644 --- a/Modules/_remote_debugging/binary_io.h +++ b/Modules/_remote_debugging/binary_io.h @@ -462,8 +462,10 @@ typedef struct { 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 */ diff --git a/Modules/_remote_debugging/binary_io_reader.c b/Modules/_remote_debugging/binary_io_reader.c index 7aca214453f521..24c270cd4ff37c 100644 --- a/Modules/_remote_debugging/binary_io_reader.c +++ b/Modules/_remote_debugging/binary_io_reader.c @@ -35,6 +35,13 @@ #define FRAME_INFO_CACHE_SIZE 1024 +#if !USE_MMAP +/* A block on disk is at most MAX_BLOCK_SIZE plus a small header */ +#define MAX_STORED_BLOCK_SIZE (MAX_BLOCK_SIZE + 1024) +/* Replay reads samples through a window that fits any block */ +#define SAMPLE_WINDOW_SIZE (2 * MAX_BLOCK_SIZE) +#endif + /* ============================================================================ * BINARY READER IMPLEMENTATION * ============================================================================ */ @@ -304,10 +311,10 @@ reader_validate_count(const char *what, uint32_t count, } static inline int -reader_parse_string_table(BinaryReader *reader, const uint8_t *data, size_t file_size) +reader_parse_string_table(BinaryReader *reader, const uint8_t *data, + size_t size, size_t offset) { - if (reader_validate_count("string", reader->strings_count, - file_size - (size_t)reader->string_table_offset, + if (reader_validate_count("string", reader->strings_count, size - offset, MIN_STRING_ENTRY_SIZE) < 0) { return -1; } @@ -318,15 +325,14 @@ reader_parse_string_table(BinaryReader *reader, const uint8_t *data, size_t file return -1; } - size_t offset = (size_t)reader->string_table_offset; for (uint32_t i = 0; i < reader->strings_count; i++) { size_t prev_offset = offset; - uint32_t str_len = decode_varint_u32(data, &offset, file_size); + uint32_t str_len = decode_varint_u32(data, &offset, size); if (offset == prev_offset) { PyErr_SetString(PyExc_ValueError, "Malformed varint in string table"); return -1; } - if (offset > file_size || str_len > file_size - offset) { + if (offset > size || str_len > size - offset) { PyErr_SetString(PyExc_ValueError, "String table overflow"); return -1; } @@ -342,7 +348,8 @@ reader_parse_string_table(BinaryReader *reader, const uint8_t *data, size_t file } static inline int -reader_parse_frame_table(BinaryReader *reader, const uint8_t *data, size_t file_size) +reader_parse_frame_table(BinaryReader *reader, const uint8_t *data, + size_t size, size_t offset) { /* Check for integer overflow in allocation size calculation. */ #if SIZEOF_SIZE_T < 8 @@ -352,8 +359,7 @@ reader_parse_frame_table(BinaryReader *reader, const uint8_t *data, size_t file_ } #endif - if (reader_validate_count("frame", reader->frames_count, - file_size - (size_t)reader->frame_table_offset, + if (reader_validate_count("frame", reader->frames_count, size - offset, MIN_FRAME_ENTRY_SIZE) < 0) { return -1; } @@ -365,34 +371,33 @@ reader_parse_frame_table(BinaryReader *reader, const uint8_t *data, size_t file_ return -1; } - size_t offset = (size_t)reader->frame_table_offset; for (uint32_t i = 0; i < reader->frames_count; i++) { FrameEntry *frame = &reader->frames[i]; size_t prev_offset; prev_offset = offset; - frame->filename_idx = decode_varint_u32(data, &offset, file_size); + frame->filename_idx = decode_varint_u32(data, &offset, size); if (offset == prev_offset) { PyErr_SetString(PyExc_ValueError, "Malformed varint in frame table (filename)"); return -1; } prev_offset = offset; - frame->funcname_idx = decode_varint_u32(data, &offset, file_size); + frame->funcname_idx = decode_varint_u32(data, &offset, size); if (offset == prev_offset) { PyErr_SetString(PyExc_ValueError, "Malformed varint in frame table (funcname)"); return -1; } prev_offset = offset; - frame->lineno = decode_varint_i32(data, &offset, file_size); + frame->lineno = decode_varint_i32(data, &offset, size); if (offset == prev_offset) { PyErr_SetString(PyExc_ValueError, "Malformed varint in frame table (lineno)"); return -1; } prev_offset = offset; - int32_t end_lineno_delta = decode_varint_i32(data, &offset, file_size); + int32_t end_lineno_delta = decode_varint_i32(data, &offset, size); if (offset == prev_offset) { PyErr_SetString(PyExc_ValueError, "Malformed varint in frame table (end_lineno_delta)"); return -1; @@ -405,14 +410,14 @@ reader_parse_frame_table(BinaryReader *reader, const uint8_t *data, size_t file_ } prev_offset = offset; - frame->column = decode_varint_i32(data, &offset, file_size); + frame->column = decode_varint_i32(data, &offset, size); if (offset == prev_offset) { PyErr_SetString(PyExc_ValueError, "Malformed varint in frame table (column)"); return -1; } prev_offset = offset; - int32_t end_column_delta = decode_varint_i32(data, &offset, file_size); + int32_t end_column_delta = decode_varint_i32(data, &offset, size); if (offset == prev_offset) { PyErr_SetString(PyExc_ValueError, "Malformed varint in frame table (end_column_delta)"); return -1; @@ -425,7 +430,7 @@ reader_parse_frame_table(BinaryReader *reader, const uint8_t *data, size_t file_ } /* Read opcode byte */ - if (offset >= file_size) { + if (offset >= size) { PyErr_SetString(PyExc_ValueError, "Unexpected end of frame table (opcode)"); return -1; } @@ -435,7 +440,7 @@ reader_parse_frame_table(BinaryReader *reader, const uint8_t *data, size_t file_ return 0; } -#if defined(__linux__) && defined(MADV_DONTNEED) +#if USE_MMAP && defined(__linux__) && defined(MADV_DONTNEED) static size_t reader_discard_mapped_pages(BinaryReader *reader, size_t start, size_t end) { @@ -455,6 +460,43 @@ reader_discard_mapped_pages(BinaryReader *reader, size_t start, size_t end) } #endif +#if !USE_MMAP +/* Checked fread with GIL release - returns 0 on success, -1 on error */ +static int +fread_checked_allow_threads(void *data, size_t size, FILE *fp) +{ + size_t nread; + Py_BEGIN_ALLOW_THREADS + nread = fread(data, 1, size, fp); + Py_END_ALLOW_THREADS + if (nread != size) { + int err = errno; + if (ferror(fp) && err != 0) { + errno = err; + PyErr_SetFromErrno(PyExc_IOError); + } + else { + PyErr_Format(PyExc_ValueError, + "Unexpected end of file: read %zu of %zu bytes", + nread, size); + } + return -1; + } + return 0; +} + +static int +reader_read_at(BinaryReader *reader, size_t offset, uint8_t *buffer, + size_t size) +{ + if (FSEEK64(reader->fp, (file_offset_t)offset, SEEK_SET) != 0) { + PyErr_SetFromErrno(PyExc_IOError); + return -1; + } + return fread_checked_allow_threads(buffer, size, reader->fp); +} +#endif + BinaryReader * binary_reader_open(PyObject *path) { @@ -529,7 +571,8 @@ binary_reader_open(PyObject *path) uint8_t *data = reader->mapped_data; size_t file_size = reader->mapped_size; #else - /* Use stdio on Windows */ + /* Use stdio on Windows. Read the header and tables now, samples during + * replay. */ reader->fp = Py_fopen(path, "rb"); if (!reader->fp) { goto error; @@ -553,46 +596,17 @@ binary_reader_open(PyObject *path) PyErr_SetString(PyExc_ValueError, "File too small for header"); goto error; } - if (FSEEK64(reader->fp, 0, SEEK_SET) != 0) { - PyErr_SetFromErrno(PyExc_IOError); - goto error; - } - - reader->file_data = PyMem_Malloc(reader->file_size); - if (!reader->file_data) { - PyErr_NoMemory(); - goto error; - } - - size_t nread = fread(reader->file_data, 1, reader->file_size, reader->fp); - if (nread != reader->file_size) { - int err = errno; - if (ferror(reader->fp) && err != 0) { - errno = err; - PyErr_SetFromErrno(PyExc_IOError); - } - else { - PyErr_Format(PyExc_ValueError, - "Unexpected end of file: read %zu of %zu bytes", - nread, reader->file_size); - } + uint8_t data[FILE_HEADER_PLACEHOLDER_SIZE]; + size_t file_size = reader->file_size; + if (reader_read_at(reader, 0, data, + Py_MIN(file_size, sizeof(data))) < 0) { goto error; } - - uint8_t *data = reader->file_data; - size_t file_size = reader->file_size; #endif - /* Parse header and footer */ if (reader_parse_header(reader, data, file_size) < 0) { goto error; } - if (reader_parse_footer(reader, data, file_size) < 0) { - goto error; - } - if (reader_parse_profile_stats(reader, data, file_size) < 0) { - goto error; - } /* Validate table offsets are within file bounds */ if (reader->string_table_offset > file_size) { @@ -640,19 +654,45 @@ binary_reader_open(PyObject *path) goto error; #endif } - reader->sample_data = data + FILE_HEADER_PLACEHOLDER_SIZE; reader->sample_data_size = (size_t)reader->string_table_offset - FILE_HEADER_PLACEHOLDER_SIZE; - /* Parse string and frame tables */ - if (reader_parse_string_table(reader, data, file_size) < 0) { + /* Tables, statistics and footer follow the samples. The footer is + * always the last bytes of the file. */ + size_t tail_offset = Py_MIN((size_t)reader->string_table_offset, + file_size - FILE_FOOTER_SIZE); + size_t tail_size = file_size - tail_offset; +#if USE_MMAP + reader->sample_data = data + FILE_HEADER_PLACEHOLDER_SIZE; + const uint8_t *tail = data + tail_offset; +#else + reader->table_data = PyMem_Malloc(tail_size); + if (!reader->table_data) { + PyErr_NoMemory(); goto error; } - if (reader_parse_frame_table(reader, data, file_size) < 0) { + if (reader_read_at(reader, tail_offset, reader->table_data, + tail_size) < 0) { goto error; } - (void)reader_discard_mapped_pages( - reader, (size_t)reader->string_table_offset, file_size); + const uint8_t *tail = reader->table_data; +#endif + if (reader_parse_footer(reader, tail, tail_size) < 0 || + reader_parse_profile_stats(reader, tail, tail_size) < 0 || + reader_parse_string_table( + reader, tail, tail_size, + (size_t)reader->string_table_offset - tail_offset) < 0 || + reader_parse_frame_table( + reader, tail, tail_size, + (size_t)reader->frame_table_offset - tail_offset) < 0) { + goto error; + } +#if USE_MMAP + (void)reader_discard_mapped_pages(reader, tail_offset, file_size); +#else + PyMem_Free(reader->table_data); + reader->table_data = NULL; +#endif return reader; @@ -1599,23 +1639,81 @@ replay_block(BinaryReader *reader, RemoteDebuggingState *state, return result; } +/* Set section and offset to the block at sample offset pos */ +#if USE_MMAP +static int +reader_load_samples(BinaryReader *reader, size_t pos, ByteBuffer *section, + size_t *offset) +{ + *section = (ByteBuffer){reader->sample_data, reader->sample_data_size, 0}; + *offset = pos; + return 0; +} +#else +static int +reader_load_samples(BinaryReader *reader, size_t pos, ByteBuffer *section, + size_t *offset) +{ + ByteBuffer *window = &reader->sample_window; + if (pos == 0) { + /* A new replay starts at the first block */ + if (buffer_reserve(window, SAMPLE_WINDOW_SIZE) < 0) { + return -1; + } + if (FSEEK64(reader->fp, FILE_HEADER_PLACEHOLDER_SIZE, SEEK_SET) != 0) { + PyErr_SetFromErrno(PyExc_IOError); + return -1; + } + window->size = 0; + reader->sample_window_start = 0; + } + + size_t start = reader->sample_window_start; + size_t end = start + window->size; + size_t needed = Py_MIN(MAX_STORED_BLOCK_SIZE, + reader->sample_data_size - pos); + if (end - pos < needed) { + /* Keep the unread bytes and refill the rest */ + size_t kept = end - pos; + memmove(window->data, window->data + (pos - start), kept); + size_t size = Py_MIN(SAMPLE_WINDOW_SIZE - kept, + reader->sample_data_size - end); + if (fread_checked_allow_threads(window->data + kept, size, + reader->fp) < 0) { + return -1; + } + reader->sample_window_start = pos; + window->size = kept + size; + } + *section = (ByteBuffer){window->data, window->size, 0}; + *offset = pos - reader->sample_window_start; + return 0; +} +#endif + static int replay_blocks(BinaryReader *reader, RemoteDebuggingState *state, PyObject *collector, PyObject *progress_callback, Py_ssize_t *replayed) { - ByteBuffer section = {reader->sample_data, reader->sample_data_size, 0}; - size_t offset = 0; + size_t pos = 0; size_t discarded = 0; - while (offset < section.size) { + while (pos < reader->sample_data_size) { + ByteBuffer section; + size_t offset; + if (reader_load_samples(reader, pos, §ion, &offset) < 0) { + return -1; + } + size_t block_start = offset; DecodedBlock block; if (decode_block(reader, §ion, &offset, &block) < 0 || replay_block(reader, state, collector, progress_callback, &block, replayed) < 0) { return -1; } + pos += offset - block_start; discarded = reader_discard_mapped_pages( - reader, discarded, FILE_HEADER_PLACEHOLDER_SIZE + offset); + reader, discarded, FILE_HEADER_PLACEHOLDER_SIZE + pos); } return 0; } @@ -1852,11 +1950,10 @@ binary_reader_close(BinaryReader *reader) Py_fclose(reader->fp); reader->fp = NULL; } - if (reader->file_data) { - PyMem_Free(reader->file_data); - reader->file_data = NULL; - reader->file_size = 0; - } + PyMem_Free(reader->table_data); + reader->table_data = NULL; + buffer_clear(&reader->sample_window); + reader->file_size = 0; #endif #ifdef HAVE_ZSTD From 0cb3bbc926dd7ab9e4e642f25f9b1c4a7e35e1ad Mon Sep 17 00:00:00 2001 From: Ivona Stojanovic Date: Wed, 25 Nov 2026 19:29:06 +0000 Subject: [PATCH 3/4] fixup! Read profile samples block by block on Windows --- InternalDocs/profiling_binary_format.md | 40 ++++++++++++------- .../test_binary_format.py | 15 ++++--- ...-11-24-17-56-46.gh-issue-159207.3PCgei.rst | 6 +-- Modules/_remote_debugging/binary_io_reader.c | 10 ++++- 4 files changed, 46 insertions(+), 25 deletions(-) diff --git a/InternalDocs/profiling_binary_format.md b/InternalDocs/profiling_binary_format.md index b467514ca228e3..68598427d870f2 100644 --- a/InternalDocs/profiling_binary_format.md +++ b/InternalDocs/profiling_binary_format.md @@ -120,11 +120,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. +are grouped into blocks, and each block holds at most 1 MiB of decoded data +and takes at most 1 MiB on disk. 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. ### Block Format @@ -659,16 +660,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 buffer is 2 MiB, twice the +maximum block size, or the size of the sample data if that is smaller, so a +complete block always fits. 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. diff --git a/Lib/test/test_profiling/test_sampling_profiler/test_binary_format.py b/Lib/test/test_profiling/test_sampling_profiler/test_binary_format.py index e1a1083d0dbe07..31c010ba54fc4c 100644 --- a/Lib/test/test_profiling/test_sampling_profiler/test_binary_format.py +++ b/Lib/test/test_profiling/test_sampling_profiler/test_binary_format.py @@ -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. @@ -1246,6 +1251,9 @@ def collect(self, stack_frames, timestamps_us): samples = [[make_interpreter(0, [make_thread(1, stack)])] for stack in stacks] filename = self.create_binary_file(samples) + 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() @@ -1648,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: @@ -2050,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): diff --git a/Misc/NEWS.d/next/Library/2026-11-24-17-56-46.gh-issue-159207.3PCgei.rst b/Misc/NEWS.d/next/Library/2026-11-24-17-56-46.gh-issue-159207.3PCgei.rst index 79c184fc4d9ac1..b80c2f7d2a3e93 100644 --- a/Misc/NEWS.d/next/Library/2026-11-24-17-56-46.gh-issue-159207.3PCgei.rst +++ b/Misc/NEWS.d/next/Library/2026-11-24-17-56-46.gh-issue-159207.3PCgei.rst @@ -1,4 +1,4 @@ Reduce the memory used by :mod:`profiling.sampling` when replaying binary -profiles on Linux and Windows. Profiles are now read one block at a time -instead of being loaded into memory in full, so memory use stays small even -for very long captures. +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. diff --git a/Modules/_remote_debugging/binary_io_reader.c b/Modules/_remote_debugging/binary_io_reader.c index 24c270cd4ff37c..e627feeb53bd49 100644 --- a/Modules/_remote_debugging/binary_io_reader.c +++ b/Modules/_remote_debugging/binary_io_reader.c @@ -36,7 +36,7 @@ #define FRAME_INFO_CACHE_SIZE 1024 #if !USE_MMAP -/* A block on disk is at most MAX_BLOCK_SIZE plus a small header */ +/* The block parser limits stored columns to MAX_BLOCK_SIZE */ #define MAX_STORED_BLOCK_SIZE (MAX_BLOCK_SIZE + 1024) /* Replay reads samples through a window that fits any block */ #define SAMPLE_WINDOW_SIZE (2 * MAX_BLOCK_SIZE) @@ -1018,6 +1018,7 @@ reader_parse_block_header(BinaryReader *reader, const ByteBuffer *section, } size_t decoded_total = 0; + size_t stored_total = 0; for (unsigned column = 0; column < COLUMN_COUNT; column++) { ColumnDescriptor *descriptor = &header->columns[column]; /* Decoded size (varint) and encoding (1 byte) */ @@ -1058,7 +1059,11 @@ reader_parse_block_header(BinaryReader *reader, const ByteBuffer *section, if (descriptor->decoded_size > MAX_BLOCK_SIZE - decoded_total) { return block_error("decoded columns exceed the block limit"); } + if (descriptor->stored_size > MAX_BLOCK_SIZE - stored_total) { + return block_error("stored columns exceed the block limit"); + } decoded_total += descriptor->decoded_size; + stored_total += descriptor->stored_size; } /* Each sample needs at least one byte of stream index and residual */ @@ -1657,7 +1662,8 @@ reader_load_samples(BinaryReader *reader, size_t pos, ByteBuffer *section, ByteBuffer *window = &reader->sample_window; if (pos == 0) { /* A new replay starts at the first block */ - if (buffer_reserve(window, SAMPLE_WINDOW_SIZE) < 0) { + if (buffer_reserve(window, Py_MIN(SAMPLE_WINDOW_SIZE, + reader->sample_data_size)) < 0) { return -1; } if (FSEEK64(reader->fp, FILE_HEADER_PLACEHOLDER_SIZE, SEEK_SET) != 0) { From afee9841b726980a42f7e8f904118f79b65e6e04 Mon Sep 17 00:00:00 2001 From: Pablo Galindo Salgado Date: Wed, 25 Nov 2026 21:49:47 +0000 Subject: [PATCH 4/4] gh-159207: Clarify the size limit for stored sample columns --- InternalDocs/profiling_binary_format.md | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/InternalDocs/profiling_binary_format.md b/InternalDocs/profiling_binary_format.md index 68598427d870f2..f38c8dd3306448 100644 --- a/InternalDocs/profiling_binary_format.md +++ b/InternalDocs/profiling_binary_format.md @@ -119,13 +119,12 @@ network streams. ## Sample Data -Sample data begins at offset 64 and extends to `string_table_offset`. Samples -are grouped into blocks, and each block holds at most 1 MiB of decoded data -and takes at most 1 MiB on disk. 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 @@ -675,9 +674,9 @@ 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 buffer is 2 MiB, twice the -maximum block size, or the size of the sample data if that is smaller, so a -complete block always fits. When the buffer runs low, the bytes not yet +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