diff --git a/cuda_core/tests/helpers/oom_diagnostics.py b/cuda_core/tests/helpers/oom_diagnostics.py index b80cfef58200..7db10b5768fa 100644 --- a/cuda_core/tests/helpers/oom_diagnostics.py +++ b/cuda_core/tests/helpers/oom_diagnostics.py @@ -20,12 +20,21 @@ (``nvidia-smi``, NVML): see the PR #2458 review for why the previous version's ``nvidia-smi -q`` dump was dropped. -Capture is latched once per session, on the first failing OOM. A failing run -can report ~190 of these, all descending from one earlier event, and -re-running the probes on each would add noticeable time and bury the log. The -report is written via ``terminalreporter`` rather than ``print()`` so it -survives the stdout redirection these runs use, and ``pytest_terminal_summary`` -points at the artifact from the end of the run, where it is actually noticed. +The first OOM often surfaces in a teardown, after ``init_cuda`` has popped the +test's context, so when no context is current the probe makes device 0's +primary context current for its duration and pops it afterwards. + +Capture is latched once per session, on the first failing OOM that could be +probed. A failing run can report ~190 of these, all descending from one +earlier event, and re-running the probes on each would add noticeable time and +bury the log. A report that could not obtain any context is emitted once but +does not consume the latch, so a later OOM still gets a real probe. The report +is written via ``terminalreporter`` rather than ``print()`` so it survives the +stdout redirection these runs use, and ``pytest_terminal_summary`` points at +the artifact from the end of the run, where it is actually noticed. The +artifact lands beside the ``--junitxml`` file when one is given, which is the +directory CI uploads; it is written when captured, so it survives a later +crash that keeps pytest from writing the JUnit file or the summary. """ import os @@ -134,6 +143,13 @@ class ProbeSnapshot: has_context: bool = False context_error: str | None = None + # True when no context was current and the probe ran in device 0's + # primary context, pushed for the probe only. + borrowed_primary_context: bool = False + # Set when no context was current and making one current failed; names the + # failing call, which context_error (a cuCtxGetCurrent failure) does not. + borrow_error: str | None = None + context_restore_error: str | None = None mem_free: int | None = None mem_total: int | None = None @@ -177,10 +193,7 @@ def probe_basics(): snapshot = ProbeSnapshot() ctx_ok, ctx_err, ctx_values = _call(driver.cuCtxGetCurrent) - # cuCtxGetCurrent succeeds even with no bound context: it returns a null - # CUcontext, not None, so "no context" has to be checked via int(), not - # an identity check against None. - snapshot.has_context = bool(ctx_ok and ctx_values and ctx_values[0] is not None and int(ctx_values[0]) != 0) + snapshot.has_context = ctx_ok and _is_context(ctx_values) if not ctx_ok: snapshot.context_error = ctx_err if not snapshot.has_context: @@ -223,9 +236,61 @@ def probe_basics(): return snapshot, dev +def _is_context(ctx_values): + # cuCtxGetCurrent succeeds even with no bound context and returns a null + # CUcontext rather than None. + return bool(ctx_values and ctx_values[0] is not None and int(ctx_values[0]) != 0) + + def run_probe(): """Run the OOM reason checker once and return its :class:`ProbeSnapshot`. + If no context is current, device 0's primary context is retained and + pushed for the probe, then popped and released, so the caller's context + state is unchanged. Device 0 is always the one borrowed, so on a multi-GPU + host the memory figures may describe a different device than the failing + test used; the host virtual-address probes are process-wide either way. See :func:`_probe_current_context` for the probes. + """ + ctx_ok, ctx_err, ctx_values = _call(driver.cuCtxGetCurrent) + if not ctx_ok: + return ProbeSnapshot(context_error=ctx_err) + if _is_context(ctx_values): + return _probe_current_context() + + dev_ok, dev_err, dev_values = _call(driver.cuDeviceGet, 0) + if not dev_ok: + return ProbeSnapshot(borrow_error=f"cuDeviceGet(0): {dev_err}") + (dev,) = dev_values + retain_ok, retain_err, retain_values = _call(driver.cuDevicePrimaryCtxRetain, dev) + if not retain_ok: + return ProbeSnapshot(borrow_error=f"cuDevicePrimaryCtxRetain(dev 0): {retain_err}") + (ctx,) = retain_values + + restore_errors = [] + try: + push_ok, push_err, _ = _call(driver.cuCtxPushCurrent, ctx) + if not push_ok: + snapshot = ProbeSnapshot(borrow_error=f"cuCtxPushCurrent(primary context of dev 0): {push_err}") + else: + try: + snapshot = _probe_current_context() + snapshot.borrowed_primary_context = True + finally: + pop_ok, pop_err, _ = _call(driver.cuCtxPopCurrent) + if not pop_ok: + restore_errors.append(f"cuCtxPopCurrent: {pop_err}") + finally: + release_ok, release_err, _ = _call(driver.cuDevicePrimaryCtxRelease, dev) + if not release_ok: + restore_errors.append(f"cuDevicePrimaryCtxRelease(dev 0): {release_err}") + if restore_errors: + snapshot.context_restore_error = "; ".join(restore_errors) + return snapshot + + +def _probe_current_context(): + """Run the probe sequence in the current context. + Ordered from cheapest/most-general to most-specific so a probe that already answers the question skips the more expensive ones after it: @@ -310,7 +375,12 @@ def classify(snapshot: ProbeSnapshot) -> str: specific enough to act on. """ if not snapshot.has_context: - return "no current CUDA context; cannot narrow down the reason" + if snapshot.borrow_error is not None: + return ( + f"no current CUDA context and borrowing device 0's primary context failed ({snapshot.borrow_error}); " + "the driver could not set up a context, so this may be the same resource exhaustion" + ) + return "no current CUDA context and none could be made current; cannot narrow down the reason" if snapshot.mem_get_info_error is not None: return f"cuMemGetInfo itself failed ({snapshot.mem_get_info_error}); the device may be unavailable" @@ -358,12 +428,25 @@ def classify(snapshot: ProbeSnapshot) -> str: def format_probe_log(snapshot: ProbeSnapshot) -> str: """Render the raw probe results, independent of the verdict.""" lines = ["--- direct driver probe (bypasses cuda.core's error reporting) ---"] + if snapshot.context_restore_error is not None: + lines.append( + f"WARNING: restoring the context state after the probe failed ({snapshot.context_restore_error}); " + "later tests may see a different current context" + ) if not snapshot.has_context: - suffix = f" " if snapshot.context_error else " (no context)" + suffix = f" " if snapshot.context_error else " (no context)" lines.append(f"cuCtxGetCurrent(){suffix}") + if snapshot.borrow_error is not None: + lines.append(f"borrowing device 0's primary context -> ") return "\n".join(lines) - lines.append("cuCtxGetCurrent() -> ok") + if snapshot.borrowed_primary_context: + lines.append( + "cuCtxGetCurrent() -> no context; probing in device 0's primary context, " + "pushed for the probe and popped afterwards" + ) + else: + lines.append("cuCtxGetCurrent() -> ok") if snapshot.mem_get_info_error is not None: lines.append(f"cuMemGetInfo() -> ") @@ -421,26 +504,80 @@ def format_probe_log(snapshot: ProbeSnapshot) -> str: return "\n".join(lines) +def artifact_directory(config): + """Where the report goes: beside ``--junitxml`` if given, else the rootdir. + + CI uploads the JUnit directory as an artifact. The path is resolved the way + pytest's junitxml plugin resolves it, except that a relative path is + anchored at the invocation directory, not the current one: a test may have + changed directory by the time an OOM is captured. + """ + xmlpath = getattr(config.option, "xmlpath", None) + if xmlpath: + expanded = pathlib.Path(os.path.expanduser(os.path.expandvars(xmlpath))) + return pathlib.Path(os.path.normpath(config.invocation_params.dir / expanded)).parent + return config.rootpath + + +def _write_new_file(path, text): + """Write ``text`` to ``path``, or to ``stem.N.suffix`` if that exists; return the path used. + + Several pytest invocations (for example ``tests/`` and ``tests/cython``) + share one results directory; a later one must not truncate the report of + an earlier one. Exclusive creation picks the name without a separate + existence check, so every filesystem error surfaces as ``OSError`` here. + """ + path.parent.mkdir(parents=True, exist_ok=True) + candidate = path + n = 0 + while True: + try: + with candidate.open("x", encoding="utf-8") as f: + f.write(text) + return candidate + except FileExistsError: + n += 1 + candidate = path.with_name(f"{path.stem}.{n}{path.suffix}") + + class OomDiagnosticsRecorder: - """Captures the OOM reason checker the first time a CUDA OOM is seen, and only then.""" + """Captures the OOM reason checker on the first CUDA OOM that can be probed. + + The first OOM is always reported. If no context could be obtained for its + probe, the latch stays open and the next OOM whose probe gets a context is + reported as well; further OOMs without a context are not reported again. + """ def __init__(self, filename=DEFAULT_FILENAME): self._filename = filename self._lock = threading.Lock() self._captured = False + self._probed = False self._nodeid = None + self._probed_nodeid = None self._artifact_path = None self._artifact_written = False @property def captured(self): + """True once any report has been emitted.""" return self._captured + @property + def probed(self): + """True once a report with a probed context has been emitted; no more are captured.""" + return self._probed + @property def nodeid(self): - """Node id of the test that triggered capture, or None.""" + """Node id of the test that triggered the first report, or None.""" return self._nodeid + @property + def probed_nodeid(self): + """Node id of the test whose report has a probed context, or None.""" + return self._probed_nodeid + @property def artifact_path(self): """Where the report was written, or None if nothing was captured.""" @@ -454,14 +591,18 @@ def artifact_written(self): def matches(exc_text): return OOM_MARKER in exc_text - def build_report(self, nodeid, phase, exc_text, snapshot=None): + def build_report(self, nodeid, phase, exc_text, snapshot=None, earlier_nodeid=None): if snapshot is None: snapshot = run_probe() verdict = classify(snapshot) + if earlier_nodeid is None: + title = "first CUDA_ERROR_OUT_OF_MEMORY of this session" + else: + title = f"first probed CUDA_ERROR_OUT_OF_MEMORY (the probe at {earlier_nodeid} had no context)" return "\n".join( [ _BANNER, - "cuda_core OOM reason checker: first CUDA_ERROR_OUT_OF_MEMORY of this session", + f"cuda_core OOM reason checker: {title}", _BANNER, f"test: {nodeid}", f"phase: {phase}", @@ -479,27 +620,45 @@ def build_report(self, nodeid, phase, exc_text, snapshot=None): ) def capture(self, nodeid, phase, exc_text, directory, snapshot=None): - """Build and persist the report. Returns None if already captured. + """Build and persist the report. Returns None if nothing is reported. + + A later report is appended to the artifact, after the first one. ``snapshot`` lets callers (mainly tests) skip the live driver probe; - production callers leave it unset so :meth:`build_report` runs - :func:`run_probe`. + production callers leave it unset so :func:`run_probe` runs. """ + # Held throughout so concurrent test threads do not probe in parallel. with self._lock: - if self._captured: + if self._probed: + return None + if snapshot is None: + snapshot = run_probe() + if not snapshot.has_context and self._captured: return None - self._captured = True - report = self.build_report(nodeid, phase, exc_text, snapshot=snapshot) - destination = pathlib.Path(directory) / self._filename - self._nodeid = nodeid - self._artifact_path = destination - try: - destination.write_text(report, encoding="utf-8") - self._artifact_written = True - return f"{report}\n(diagnostics also written to {destination})" - except OSError as exc: - return f"{report}\n(could not write {destination}: {exc!r})" + earlier_nodeid = self._nodeid if self._captured else None + report = self.build_report(nodeid, phase, exc_text, snapshot=snapshot, earlier_nodeid=earlier_nodeid) + if not self._captured: + self._captured = True + self._nodeid = nodeid + if snapshot.has_context: + self._probed = True + self._probed_nodeid = nodeid + + # Until a write succeeds, the artifact path is the unnumbered name + # and a later report creates a new file rather than appending. + if not self._artifact_written: + self._artifact_path = pathlib.Path(directory) / self._filename + try: + if self._artifact_written: + with self._artifact_path.open("a", encoding="utf-8") as f: + f.write(f"\n\n{report}") + else: + self._artifact_path = _write_new_file(self._artifact_path, report) + self._artifact_written = True + return f"{report}\n(diagnostics also written to {self._artifact_path})" + except OSError as exc: + return f"{report}\n(could not write {self._artifact_path}: {exc!r})" _default_recorder = OomDiagnosticsRecorder() @@ -517,14 +676,14 @@ def record_if_oom(item, call, report, recorder=None, snapshot=None): if recorder is None: recorder = _default_recorder - if recorder.captured or not report.failed or call.excinfo is None: + if recorder.probed or not report.failed or call.excinfo is None: return None exc_text = str(call.excinfo.value) if not recorder.matches(exc_text): return None - text = recorder.capture(item.nodeid, call.when, exc_text, item.config.rootpath, snapshot=snapshot) + text = recorder.capture(item.nodeid, call.when, exc_text, artifact_directory(item.config), snapshot=snapshot) if text is None: return None @@ -552,7 +711,13 @@ def report_terminal_summary(terminalreporter, recorder=None): return None verb = "written to" if recorder.artifact_written else "could NOT be written to" - line = f"first CUDA OOM at {recorder.nodeid}; diagnostics {verb} {recorder.artifact_path}" + if recorder.probed_nodeid is None: + probed = "; no context could be probed" + elif recorder.probed_nodeid != recorder.nodeid: + probed = f"; probed at {recorder.probed_nodeid}" + else: + probed = "" + line = f"first CUDA OOM at {recorder.nodeid}{probed}; diagnostics {verb} {recorder.artifact_path}" terminalreporter.write_sep("=", "cuda_core OOM diagnostics", red=True) terminalreporter.write_line(line) return line diff --git a/cuda_core/tests/test_helpers.py b/cuda_core/tests/test_helpers.py index 5cbf9c40bf14..ec42acfb51db 100644 --- a/cuda_core/tests/test_helpers.py +++ b/cuda_core/tests/test_helpers.py @@ -3,6 +3,8 @@ # SPDX-License-Identifier: Apache-2.0 import ctypes +import os +import pathlib import sys import time import types @@ -20,13 +22,20 @@ OomDiagnosticsRecorder, ProbeSnapshot, classify, + format_probe_log, probe_basics, record_if_oom, report_terminal_summary, + run_probe, ) from helpers.oom_diagnostics import _round_up as oom_round_up # white-box test of the alignment guard +from helpers.oom_diagnostics import ( + artifact_directory as oom_artifact_directory, +) +from cuda.bindings import driver from cuda.core import Device +from cuda.core._utils.cuda_utils import handle_return from cuda_python_test_helpers import under_compute_sanitizer ENABLE_LOGGING = False # Set True for test debugging and development @@ -140,10 +149,12 @@ def _fake_call(exc_text, when="call"): return types.SimpleNamespace(excinfo=excinfo, when=when) -def _fake_item(rootpath, nodeid="tests/test_x.py::test_a"): +def _fake_item(rootpath, nodeid="tests/test_x.py::test_a", xmlpath=None): # get_plugin returns None so record_if_oom skips the terminal write. config = types.SimpleNamespace( rootpath=rootpath, + option=types.SimpleNamespace(xmlpath=xmlpath), + invocation_params=types.SimpleNamespace(dir=pathlib.Path(rootpath)), pluginmanager=types.SimpleNamespace(get_plugin=lambda _: None), ) return types.SimpleNamespace(nodeid=nodeid, config=config) @@ -153,6 +164,8 @@ def _fake_item(rootpath, nodeid="tests/test_x.py::test_a"): # first check, so harness tests never depend on -- or need to fake -- driver # call results. _NO_CONTEXT_SNAPSHOT = ProbeSnapshot(has_context=False) +# The smallest snapshot that counts as probed; its probe log stops at "VMM unsupported". +_PROBED_SNAPSHOT = ProbeSnapshot(has_context=True, mem_free=1 << 30, mem_total=1 << 30, small_alloc_ok=True) @pytest.mark.agent_authored(model="claude-sonnet-5") @@ -229,6 +242,159 @@ def test_oom_diagnostics_latch_to_the_first_oom(tmp_path): assert "first" in (tmp_path / DEFAULT_FILENAME).read_text(encoding="utf-8") +@pytest.mark.agent_authored(model="claude-opus-5-5") +def test_oom_diagnostics_report_without_context_keeps_the_latch_open(tmp_path): + recorder = OomDiagnosticsRecorder() + assert recorder.capture("first", "teardown", OOM_MARKER, tmp_path, snapshot=_NO_CONTEXT_SNAPSHOT) is not None + assert not recorder.probed + # A second unprobed report would only repeat the first. + assert recorder.capture("second", "call", OOM_MARKER, tmp_path, snapshot=_NO_CONTEXT_SNAPSHOT) is None + + text = recorder.capture("third", "call", OOM_MARKER, tmp_path, snapshot=_PROBED_SNAPSHOT) + assert "the probe at first had no context" in text + assert recorder.probed + assert recorder.capture("fourth", "call", OOM_MARKER, tmp_path, snapshot=_PROBED_SNAPSHOT) is None + + written = (tmp_path / DEFAULT_FILENAME).read_text(encoding="utf-8") + assert "test: first" in written + assert "test: third" in written + assert "second" not in written + assert "fourth" not in written + + lines = [] + reporter = types.SimpleNamespace(write_sep=lambda *_, **__: None, write_line=lines.append) + assert "first CUDA OOM at first; probed at third" in report_terminal_summary(reporter, recorder=recorder) + + +@pytest.mark.agent_authored(model="claude-opus-5-5") +def test_oom_diagnostics_artifact_lands_beside_the_junit_file(tmp_path, monkeypatch): + # CI uploads only the JUnit directory, which may not exist yet if the run + # crashes before pytest writes the JUnit file. + recorder = OomDiagnosticsRecorder() + monkeypatch.setattr("helpers.oom_diagnostics._default_recorder", recorder) + junit_dir = tmp_path / "test-results" + + record_if_oom( + _fake_item(tmp_path / "rootdir", xmlpath=str(junit_dir / "junit-core.xml")), + _fake_call(f"boom {OOM_MARKER}"), + _fake_report(True), + snapshot=_NO_CONTEXT_SNAPSHOT, + ) + + assert recorder.artifact_path == junit_dir / DEFAULT_FILENAME + assert OOM_MARKER in recorder.artifact_path.read_text(encoding="utf-8") + + +@pytest.mark.agent_authored(model="claude-sonnet-5-5") +def test_oom_diagnostics_relative_junit_path_is_anchored_at_the_invocation_dir(tmp_path, monkeypatch): + # A test may have changed directory by the time an OOM is captured. + invocation = tmp_path / "invocation" + elsewhere = tmp_path / "elsewhere" + invocation.mkdir() + elsewhere.mkdir() + monkeypatch.chdir(elsewhere) + item = _fake_item(invocation, xmlpath=os.path.join("test-results", "junit-core.xml")) + + assert oom_artifact_directory(item.config) == invocation / "test-results" + + +@pytest.mark.agent_authored(model="claude-sonnet-5-5") +def test_oom_diagnostics_does_not_overwrite_an_earlier_invocations_artifact(tmp_path): + # tests/ and tests/cython run as separate pytest processes into one directory. + first = OomDiagnosticsRecorder() + first.capture("first", "call", OOM_MARKER, tmp_path, snapshot=_PROBED_SNAPSHOT) + second = OomDiagnosticsRecorder() + second.capture("second", "call", OOM_MARKER, tmp_path, snapshot=_PROBED_SNAPSHOT) + + assert first.artifact_path == tmp_path / DEFAULT_FILENAME + assert second.artifact_path != first.artifact_path + assert "test: first" in first.artifact_path.read_text(encoding="utf-8") + assert "test: second" in second.artifact_path.read_text(encoding="utf-8") + + +def _deny_mkdir(self, *args, **kwargs): + raise PermissionError(13, "Permission denied", str(self)) + + +_CHMOD_CANNOT_DENY_TRAVERSAL = sys.platform == "win32" or (hasattr(os, "geteuid") and os.geteuid() == 0) + + +@pytest.mark.agent_authored(model="claude-opus-5-5") +@pytest.mark.parametrize( + "failure", + [ + pytest.param( + "untraversable_dir", + marks=pytest.mark.skipif(_CHMOD_CANNOT_DENY_TRAVERSAL, reason="chmod cannot deny traversal here"), + ), + "parent_is_a_file", + "permission_denied", + ], +) +def test_oom_diagnostics_unusable_artifact_directory_keeps_the_report(tmp_path, monkeypatch, failure): + # The capture runs inside pytest_runtest_makereport, where an escaping + # OSError becomes an INTERNALERROR and the report is lost. + locked = None + if failure == "untraversable_dir": + locked = tmp_path / "locked" + (locked / "test-results").mkdir(parents=True) + locked.chmod(0) + bad_dir = locked / "test-results" + elif failure == "parent_is_a_file": + blocker = tmp_path / "blocker" + blocker.write_text("") + bad_dir = blocker / "test-results" + else: + bad_dir = tmp_path / "test-results" + monkeypatch.setattr(pathlib.Path, "mkdir", _deny_mkdir) + recorder = OomDiagnosticsRecorder() + + try: + text = recorder.capture("first", "teardown", OOM_MARKER, bad_dir, snapshot=_NO_CONTEXT_SNAPSHOT) + finally: + if locked is not None: + locked.chmod(0o700) + + assert "test: first" in text + assert f"could not write {bad_dir / DEFAULT_FILENAME}" in text + assert recorder.artifact_path == bad_dir / DEFAULT_FILENAME + assert not recorder.artifact_written + + # A later report still gets a fresh file once the directory is usable. + monkeypatch.undo() + good_dir = tmp_path / "good" + text = recorder.capture("second", "call", OOM_MARKER, good_dir, snapshot=_PROBED_SNAPSHOT) + + assert recorder.artifact_written + assert recorder.artifact_path == good_dir / DEFAULT_FILENAME + assert "test: second" in recorder.artifact_path.read_text(encoding="utf-8") + + +@pytest.mark.agent_authored(model="claude-sonnet-5-5") +def test_oom_diagnostics_failed_borrow_names_the_failing_call(monkeypatch): + # No GPU needed: the driver calls are faked so that no context is current + # and the primary-context retain fails. + def fake_call(fn, *args): + if fn is driver.cuCtxGetCurrent: + return True, None, (0,) + if fn is driver.cuDeviceGet: + return True, None, (0,) + if fn is driver.cuDevicePrimaryCtxRetain: + return False, "CUDA_ERROR_OUT_OF_MEMORY", () + raise AssertionError(f"unexpected driver call {fn}") + + monkeypatch.setattr("helpers.oom_diagnostics._call", fake_call) + snapshot = run_probe() + + assert not snapshot.has_context + assert snapshot.context_error is None + assert "cuDevicePrimaryCtxRetain(dev 0): CUDA_ERROR_OUT_OF_MEMORY" in snapshot.borrow_error + log = format_probe_log(snapshot) + assert "cuCtxGetCurrent() (no context)" in log + assert "borrowing device 0's primary context ->