Skip to content
Open
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
55 changes: 55 additions & 0 deletions src/crawlee/_utils/_macos_memory.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
from __future__ import annotations

import ctypes
from functools import cache
from typing import TYPE_CHECKING

if TYPE_CHECKING:
from psutil import Process

_RUSAGE_INFO_V0 = 0


class _RUsageInfoV0(ctypes.Structure):
"""Layout of Apple's `rusage_info_v0` in `sys/resource.h`."""

_fields_ = (
('ri_uuid', ctypes.c_uint8 * 16),
('ri_user_time', ctypes.c_uint64),
('ri_system_time', ctypes.c_uint64),
('ri_pkg_idle_wkups', ctypes.c_uint64),
('ri_interrupt_wkups', ctypes.c_uint64),
('ri_pageins', ctypes.c_uint64),
('ri_wired_size', ctypes.c_uint64),
('ri_resident_size', ctypes.c_uint64),
('ri_phys_footprint', ctypes.c_uint64),
('ri_proc_start_abstime', ctypes.c_uint64),
('ri_proc_exit_abstime', ctypes.c_uint64),
)


@cache
def _load_libproc() -> ctypes.CDLL:
"""Load the process accounting API once per process."""
libproc = ctypes.CDLL('/usr/lib/libproc.dylib')
libproc.proc_pid_rusage.argtypes = (ctypes.c_int, ctypes.c_int, ctypes.c_void_p)
libproc.proc_pid_rusage.restype = ctypes.c_int
return libproc


def _get_memory_footprint(pid: int) -> int:
"""Return the memory charged to a live process, or zero if no reading is available."""
usage = _RUsageInfoV0()
result = _load_libproc().proc_pid_rusage(pid, _RUSAGE_INFO_V0, ctypes.byref(usage))
if result != 0 or usage.ri_proc_exit_abstime:
return 0
return int(usage.ri_phys_footprint)


def get_used_memory(process: Process) -> int:
"""Use the macOS footprint, which excludes clean mappings such as shared libraries."""
try:
footprint = _get_memory_footprint(process.pid)
except OSError:
footprint = 0
return footprint or int(process.memory_info().rss)
55 changes: 55 additions & 0 deletions src/crawlee/_utils/_windows_memory.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
from __future__ import annotations

import ctypes
import mmap
import sys
from ctypes import wintypes

_PROCESS_QUERY_INFORMATION = 0x0400
_PROCESS_VM_READ = 0x0010
_ERROR_BAD_LENGTH = 24
_SHARED_PAGE = 1 << 8
_SHARE_COUNT_MASK = 0b111

if sys.platform == 'win32':
_kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
_open_process = _kernel32.OpenProcess
_open_process.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD)
_open_process.restype = wintypes.HANDLE
_close_handle = _kernel32.CloseHandle
_close_handle.argtypes = (wintypes.HANDLE,)
_close_handle.restype = wintypes.BOOL
_query_working_set = _kernel32.K32QueryWorkingSet
_query_working_set.argtypes = (wintypes.HANDLE, ctypes.c_void_p, wintypes.DWORD)
_query_working_set.restype = wintypes.BOOL

def get_proportional_memory(pid: int, rss: int) -> int:
"""Return the process's private resident memory plus its share of shared pages."""
handle = _open_process(_PROCESS_QUERY_INFORMATION | _PROCESS_VM_READ, 0, pid)
if not handle:
raise ctypes.WinError(ctypes.get_last_error())

try:
# The working set can grow between the RSS read and the query.
capacity = rss // mmap.PAGESIZE + 1
for _ in range(3):
entries = (ctypes.c_size_t * (capacity + 1))()
if _query_working_set(handle, entries, ctypes.sizeof(entries)):
break
error = ctypes.get_last_error()
if error != _ERROR_BAD_LENGTH:
raise ctypes.WinError(error)
capacity = max(capacity * 2, entries[0])
else:
raise ctypes.WinError(error)
finally:
_close_handle(handle)

# QueryWorkingSet writes the entry count first, followed by one pointer-sized word per page.
pages = memoryview(entries).cast('B').cast('P')[1 : entries[0] + 1]
page_count = 0.0
for flags in pages:
# Windows exposes at most seven sharers, so heavily shared pages can still be overcounted.
share_count = (flags >> 5) & _SHARE_COUNT_MASK if flags & _SHARED_PAGE else 1
page_count += 1 / max(share_count, 1)
return round(page_count * mmap.PAGESIZE)
27 changes: 20 additions & 7 deletions src/crawlee/_utils/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,27 @@ def _get_used_memory(process: psutil.Process) -> int:
return int(memory.rss)

return int(process.memory_info().rss)
elif sys.platform == 'win32':
from crawlee._utils._windows_memory import get_proportional_memory

def _get_used_memory(process: psutil.Process) -> int:
"""Count each resident page in proportion to the number of processes sharing it."""
rss = int(process.memory_info().rss)
try:
proportional_memory = get_proportional_memory(process.pid, rss)
except OSError:
# Reading the working set needs more permissions than reading RSS.
return rss
return proportional_memory or rss
elif sys.platform == 'darwin':
from crawlee._utils._macos_memory import get_used_memory as _get_used_memory
else:

def _get_used_memory(process: psutil.Process) -> int:
"""Get the used memory metric of a single process.

`Resident Set Size (RSS)` is the non-swapped physical memory a process has used; it includes shared memory, so
a process tree that shares memory gets overestimated. It is the only metric available outside of Linux.
a process tree that shares memory gets overestimated.

Raises:
psutil.Error: If the process refuses inspection or is gone.
Expand Down Expand Up @@ -161,9 +175,9 @@ class MemoryUsageInfo(BaseModel):
]
"""Memory usage of the current Python process and its children.

This is a best-effort estimate - a process that cannot be inspected is left out of the sum, and the metric used
may be RSS, which counts memory shared between the processes repeatedly. When only some of the processes expose
PSS, the sum mixes both metrics, so the memory those processes share with the rest of the tree is counted twice.
This is an estimate. It uses proportional resident memory on Linux and Windows and the process footprint on
macOS. When those readings are unavailable, it uses RSS, which counts shared memory in every process that maps
it. Processes that cannot be inspected are left out of the sum.
"""

# Workaround for Pydantic and type checkers when using Annotated with default_factory
Expand Down Expand Up @@ -262,9 +276,8 @@ def get_cpu_info(cpu_load: proclimits.CpuLoad | None = None) -> CpuInfo:
def get_memory_info() -> MemoryInfo:
"""Retrieve the current memory usage of the process and its children.

It utilizes the `psutil` library. The reported `current_size` is best-effort - processes that cannot be inspected
are left out of the sum, and PSS may be substituted by RSS for some or all of the processes. The system-wide
figures come from the limit applying to this process whenever one restricts how much memory it may use.
The reported `current_size` uses the platform's memory estimate for each process. The system-wide figures
come from the memory limit when one applies to this process.
"""
logger.debug('Calling get_memory_info()...')
_log_resource_limits()
Expand Down
117 changes: 113 additions & 4 deletions tests/unit/_utils/test_system.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from __future__ import annotations

import ctypes
import logging
import mmap
import sys
from multiprocessing import get_context, resource_tracker, synchronize
from multiprocessing.shared_memory import SharedMemory
Expand All @@ -12,13 +14,17 @@
import psutil
import pytest

from crawlee._utils import system
from crawlee._utils import _macos_memory, system
from crawlee._utils.byte_size import ByteSize
from crawlee._utils.log import LoggerOnce
from crawlee._utils.system import get_cpu_info, get_memory_info

if sys.platform == 'win32':
from crawlee._utils import _windows_memory

if TYPE_CHECKING:
from collections.abc import Callable
from ctypes import Array
from multiprocessing.context import ForkContext, ForkServerContext, SpawnContext

HOST_TOTAL_BYTES = 8 * 1024**3
Expand Down Expand Up @@ -98,6 +104,10 @@ def measured_current_process(monkeypatch: pytest.MonkeyPatch) -> None:
"""Make the real current process report a fixed memory usage of 100 bytes, whichever metric is used."""
monkeypatch.setattr(psutil.Process, 'memory_full_info', lambda _process: SimpleNamespace(pss=100))
monkeypatch.setattr(psutil.Process, 'memory_info', lambda _process: SimpleNamespace(rss=100))
if sys.platform == 'win32':
monkeypatch.setattr(system, 'get_proportional_memory', lambda _pid, rss: rss)
elif sys.platform == 'darwin':
monkeypatch.setattr(_macos_memory, '_get_memory_footprint', lambda _pid: 0)


@pytest.fixture
Expand All @@ -124,7 +134,7 @@ def test_get_memory_info_returns_valid_values() -> None:
assert memory_info.current_size < memory_info.total_size


@pytest.mark.skipif(sys.platform != 'linux', reason='PSS is read only on Linux, elsewhere RSS is used directly')
@pytest.mark.skipif(sys.platform != 'linux', reason='This test covers Linux PSS readings from psutil')
@pytest.mark.parametrize(
('memory_full_info', 'expected_size', 'expected_warning', 'pss_stays_available'),
[
Expand Down Expand Up @@ -159,7 +169,7 @@ def test_get_used_memory_falls_back_to_rss_when_pss_is_unavailable(
assert system._PssAvailability.is_available == pss_stays_available


@pytest.mark.skipif(sys.platform != 'linux', reason='PSS is read only on Linux, elsewhere RSS is used directly')
@pytest.mark.skipif(sys.platform != 'linux', reason='This test covers Linux PSS readings from psutil')
def test_get_used_memory_does_not_report_a_vanished_process_as_a_pss_denial(
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
Expand All @@ -174,7 +184,7 @@ def test_get_used_memory_does_not_report_a_vanished_process_as_a_pss_denial(
assert not [record.getMessage() for record in caplog.records if 'PSS' in record.getMessage()]


@pytest.mark.skipif(sys.platform != 'linux', reason='PSS is read only on Linux, elsewhere RSS is used directly')
@pytest.mark.skipif(sys.platform != 'linux', reason='This test covers Linux PSS readings from psutil')
def test_get_used_memory_stops_asking_for_pss_once_it_is_known_to_be_missing(
monkeypatch: pytest.MonkeyPatch,
) -> None:
Expand All @@ -189,6 +199,105 @@ def test_get_used_memory_stops_asking_for_pss_once_it_is_known_to_be_missing(
memory_full_info.assert_called_once()


@pytest.mark.skipif(sys.platform != 'win32', reason='Windows working set API')
@pytest.mark.parametrize(
'working_set_grows',
[pytest.param(False, id='fits'), pytest.param(True, id='grows')],
)
def test_windows_working_set_counts_only_a_share_of_each_shared_page(
monkeypatch: pytest.MonkeyPatch, *, working_set_grows: bool
) -> None:
"""Private pages count in full and shared pages count according to their share count."""
working_set = [4, 0, 0x100 | (2 << 5), 0x100 | (4 << 5), 0x100]
rss_pages = 1 if working_set_grows else 4

def read_working_set(_handle: int, entries: Array[ctypes.c_size_t], _size: int) -> int:
if len(entries) < len(working_set):
entries[0] = working_set[0]
return 0
entries[: len(working_set)] = working_set
return 1

monkeypatch.setattr(_windows_memory, '_open_process', Mock(return_value=42))
query_working_set = Mock(side_effect=read_working_set)
monkeypatch.setattr(_windows_memory, '_query_working_set', query_working_set)
monkeypatch.setattr(ctypes, 'get_last_error', Mock(return_value=24))
close_handle = Mock()
monkeypatch.setattr(_windows_memory, '_close_handle', close_handle)
process = Mock(spec=psutil.Process)
process.pid = 1234
process.memory_info.return_value.rss = rss_pages * mmap.PAGESIZE

assert system._get_used_memory(process) == 11 * mmap.PAGESIZE // 4
assert query_working_set.call_count == (2 if working_set_grows else 1)
close_handle.assert_called_once_with(42)


@pytest.mark.skipif(sys.platform != 'win32', reason='Windows working set API')
@pytest.mark.parametrize(
'working_set_result',
[
pytest.param(Mock(side_effect=PermissionError), id='access denied'),
pytest.param(Mock(return_value=0), id='empty working set'),
],
)
def test_windows_memory_falls_back_to_rss(monkeypatch: pytest.MonkeyPatch, working_set_result: Mock) -> None:
"""An unreadable or empty working set falls back to the process's RSS."""
monkeypatch.setattr(system, 'get_proportional_memory', working_set_result)
process = Mock(spec=psutil.Process)
process.pid = 1234
process.memory_info.return_value.rss = 2048

assert system._get_used_memory(process) == 2048


@pytest.mark.parametrize(
('result', 'footprint', 'exit_time', 'expected_size'),
[
pytest.param(0, 2048, 0, 2048, id='footprint available'),
pytest.param(0, 0, 0, 4096, id='empty footprint'),
pytest.param(-1, 2048, 0, 4096, id='read failed'),
pytest.param(0, 2048, 1, 4096, id='process exited'),
],
)
def test_macos_memory_uses_the_footprint_when_available(
monkeypatch: pytest.MonkeyPatch, result: int, footprint: int, exit_time: int, expected_size: int
) -> None:
"""Use the live process footprint and fall back to RSS if the reading cannot be used."""
process = Mock(spec=psutil.Process)
process.pid = 1234
process.memory_info.return_value.rss = 4096

def read_usage(pid: int, flavor: int, buffer: ctypes.c_void_p) -> int:
assert pid == process.pid
assert flavor == 0
usage = ctypes.cast(buffer, ctypes.POINTER(_macos_memory._RUsageInfoV0)).contents
usage.ri_phys_footprint = footprint
usage.ri_proc_exit_abstime = exit_time
return result

monkeypatch.setattr(_macos_memory, '_load_libproc', lambda: SimpleNamespace(proc_pid_rusage=read_usage))

assert _macos_memory.get_used_memory(process) == expected_size
assert process.memory_info.called == (expected_size == 4096)


def test_macos_memory_falls_back_to_rss_if_libproc_cannot_load(monkeypatch: pytest.MonkeyPatch) -> None:
"""RSS remains available when the macOS process accounting library cannot be loaded."""
process = Mock(spec=psutil.Process)
process.pid = 1234
process.memory_info.return_value.rss = 4096
monkeypatch.setattr(_macos_memory, '_load_libproc', Mock(side_effect=OSError))

assert _macos_memory.get_used_memory(process) == 4096


@pytest.mark.skipif(sys.platform != 'darwin', reason='macOS process accounting API')
def test_macos_reads_the_current_process_footprint() -> None:
"""The native call returns the memory footprint of a live process."""
assert _macos_memory._get_memory_footprint(psutil.Process().pid) > 0


@pytest.mark.parametrize(
('error', 'expected_warning'),
[
Expand Down