|
| 1 | +"""Shared helper for end-to-end memory-attribution tests. |
| 2 | +
|
| 3 | +Runs Scalene as a subprocess against a fixture, retries on empty output, |
| 4 | +and skips cleanly if no usable profile ever comes back. Factored out of |
| 5 | +``tests/test_line_attribution_nested.py`` and ``tests/test_memory_stacks_bigmem.py`` |
| 6 | +once a third family of tests started needing the same logic. |
| 7 | +
|
| 8 | +Not a test module — pytest ignores files whose basename starts with ``_``. |
| 9 | +""" |
| 10 | + |
| 11 | +from __future__ import annotations |
| 12 | + |
| 13 | +import json |
| 14 | +import subprocess |
| 15 | +import sys |
| 16 | +from pathlib import Path |
| 17 | +from typing import List, Optional |
| 18 | + |
| 19 | +import pytest |
| 20 | + |
| 21 | + |
| 22 | +def run_scalene_memory_profile( |
| 23 | + tmp_path: Path, |
| 24 | + fixture: Path, |
| 25 | + *, |
| 26 | + extra_args: Optional[List[str]] = None, |
| 27 | + timeout: int = 120, |
| 28 | + attempts: int = 3, |
| 29 | + require_memory_stacks: bool = False, |
| 30 | +) -> dict: |
| 31 | + """Profile *fixture* with ``--memory``; return the parsed JSON profile. |
| 32 | +
|
| 33 | + Retries on two known flake modes: |
| 34 | + - Scalene startup wedges (``DYLD_INSERT_LIBRARIES`` / ``sys.monitoring`` |
| 35 | + init under CI contention): caught via ``TimeoutExpired``. |
| 36 | + - Scalene runs but writes no samples for the fixture (program finished |
| 37 | + before a sampling interval): detected by the fixture path not being |
| 38 | + present in ``profile["files"]``. |
| 39 | +
|
| 40 | + If ``require_memory_stacks`` is set, an otherwise-valid profile whose |
| 41 | + ``memory_stacks`` is empty is also treated as a failed attempt. Used by |
| 42 | + tests that assert on the synchronous stack-capture output. |
| 43 | + """ |
| 44 | + extra = list(extra_args or []) |
| 45 | + fixture_name = fixture.name |
| 46 | + last: Optional[subprocess.CompletedProcess] = None |
| 47 | + for attempt in range(1, attempts + 1): |
| 48 | + out = tmp_path / f"{fixture.stem}_{attempt}.json" |
| 49 | + cmd = [ |
| 50 | + sys.executable, |
| 51 | + "-m", |
| 52 | + "scalene", |
| 53 | + "run", |
| 54 | + "--memory", |
| 55 | + "--no-browser", |
| 56 | + "-o", |
| 57 | + str(out), |
| 58 | + *extra, |
| 59 | + str(fixture), |
| 60 | + ] |
| 61 | + try: |
| 62 | + last = subprocess.run( |
| 63 | + cmd, |
| 64 | + check=False, |
| 65 | + capture_output=True, |
| 66 | + text=True, |
| 67 | + timeout=timeout, |
| 68 | + ) |
| 69 | + except subprocess.TimeoutExpired: |
| 70 | + continue |
| 71 | + if not (out.exists() and out.stat().st_size > 0): |
| 72 | + continue |
| 73 | + with open(out) as f: |
| 74 | + profile = json.load(f) |
| 75 | + files = profile.get("files", {}) |
| 76 | + if not any(fname.endswith(fixture_name) for fname in files): |
| 77 | + continue |
| 78 | + if require_memory_stacks and not profile.get("memory_stacks"): |
| 79 | + continue |
| 80 | + return profile |
| 81 | + pytest.skip( |
| 82 | + f"Scalene produced no usable profile for {fixture_name} after " |
| 83 | + f"{attempts} attempts (suspected subprocess startup flake). " |
| 84 | + f"last returncode={last.returncode if last else 'timeout'}, " |
| 85 | + f"last stderr={(last.stderr[-400:] if last else '')!r}" |
| 86 | + ) |
| 87 | + |
| 88 | + |
| 89 | +def fixture_lines(profile: dict, fixture_basename: str) -> List[dict]: |
| 90 | + """Return the per-line records for the file whose path ends in *fixture_basename*. |
| 91 | +
|
| 92 | + ``run_scalene_memory_profile`` only returns profiles where the fixture is |
| 93 | + present, so the guard here is for misuse (wrong basename) rather than |
| 94 | + flake. |
| 95 | + """ |
| 96 | + files = profile.get("files", {}) |
| 97 | + matches = [ |
| 98 | + fdata for fname, fdata in files.items() if fname.endswith(fixture_basename) |
| 99 | + ] |
| 100 | + assert matches, ( |
| 101 | + f"Fixture {fixture_basename!r} missing from profile: " |
| 102 | + f"files={list(files.keys())}" |
| 103 | + ) |
| 104 | + return matches[0]["lines"] |
| 105 | + |
| 106 | + |
| 107 | +def leaf_line(frames: List[dict]) -> Optional[int]: |
| 108 | + """Line number of the innermost (leaf) frame in a ``memory_stacks`` entry.""" |
| 109 | + return frames[-1]["line"] if frames else None |
| 110 | + |
| 111 | + |
| 112 | +def leaf_filename(frames: List[dict]) -> Optional[str]: |
| 113 | + """Filename of the innermost frame.""" |
| 114 | + return frames[-1].get("filename_or_module") if frames else None |
0 commit comments