Skip to content

WIP: add nanobind leak detector #204

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
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
64 changes: 64 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import os
import sys

from io import StringIO
from typing import Generator

import pytest

Expand All @@ -7,3 +11,63 @@
def setup_test_environment():
"""Set up test environment variables for all tests."""
os.environ.setdefault("LAUNCHPAD_ENV", "TEST")


class NanobindLeakDetector:
"""Captures stderr and detects nanobind leak messages."""

def __init__(self):
self.original_stderr = sys.stderr
self.captured_stderr = StringIO()
self.leak_detected = False
self.leak_messages: list[str] = []

def start_capture(self):
"""Start capturing stderr."""
sys.stderr = self.captured_stderr

def stop_capture_and_check(self):
"""Stop capturing stderr and check for nanobind leaks."""
# Restore original stderr
sys.stderr = self.original_stderr

# Get captured content
captured_content = self.captured_stderr.getvalue()

# Check for nanobind leak messages
lines = captured_content.split("\n")
leak_lines = [line for line in lines if "nanobind: leaked" in line.lower()]

if leak_lines:
self.leak_detected = True
self.leak_messages.extend(leak_lines)

# Write captured content to original stderr so it's still visible
if captured_content:
self.original_stderr.write(captured_content)

# Reset for next capture
self.captured_stderr = StringIO()


@pytest.fixture(autouse=True)
def nanobind_leak_detector() -> Generator[NanobindLeakDetector, None, None]:
"""Fixture that detects nanobind memory leaks during test execution."""
detector = NanobindLeakDetector()

# Start capturing before the test
detector.start_capture()

try:
yield detector
finally:
detector.stop_capture_and_check()

if detector.leak_detected:
leak_summary = "\n".join(f" • {msg}" for msg in detector.leak_messages)
pytest.fail(
f"❌ NANOBIND MEMORY LEAK DETECTED ❌\n\n"
f"This change caused nanobind memory leaks, which can lead to dangerous memory issues.\n"
f"Please review your code to ensure that all LIEF objects are properly cleaned up.\n\n"
f"Leak messages detected:\n{leak_summary}\n\n"
)
5 changes: 5 additions & 0 deletions tests/unit/test_large_audio_file_insight.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ def test_generate_with_large_audio_files(self):
treemap_type=TreemapType.ASSETS,
hash_md5="hash1",
)
import sys

print("DEBUG: About to write to stderr", file=sys.stdout)
print("nanobind: leaked telkins", file=sys.stderr)
print("DEBUG: Just wrote to stderr", file=sys.stdout)
Comment on lines +23 to +27
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This appears to be test code that intentionally triggers the nanobind leak detector by printing a fake leak message to stderr. These debug print statements should be removed before merging as they will cause the test to fail with a false positive leak detection. If this was added to verify the detector's functionality, consider moving it to a dedicated test case for the detector itself rather than leaving it in an unrelated test.

Suggested change
import sys
print("DEBUG: About to write to stderr", file=sys.stdout)
print("nanobind: leaked telkins", file=sys.stderr)
print("DEBUG: Just wrote to stderr", file=sys.stdout)
import sys

Spotted by Diamond

Is this helpful? React 👍 or 👎 to let us know.

large_audio_2 = FileInfo(
full_path="assets/large_wav.wav",
path="assets/large_wav.wav",
Expand Down