From 264e9dd62a7b022c5f73c4e707829d720833f807 Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Mon, 23 Nov 2026 14:59:34 -0800 Subject: [PATCH 1/3] test(cuda.core): make the OOM probe work after context teardown and keep its report The first OOM often surfaces in a teardown, after init_cuda has popped the context, so the probe found no context and skipped every check. Borrow device 0's primary context in that case, write the report beside the --junitxml file so CI uploads it, and do not let a report without a context consume the once-per-session latch. --- cuda_core/tests/helpers/oom_diagnostics.py | 197 +++++++++++++++++---- cuda_core/tests/test_helpers.py | 88 ++++++++- 2 files changed, 249 insertions(+), 36 deletions(-) diff --git a/cuda_core/tests/helpers/oom_diagnostics.py b/cuda_core/tests/helpers/oom_diagnostics.py index b80cfef58200..c765a2bb0ca3 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,10 @@ 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 + context_restore_error: str | None = None mem_free: int | None = None mem_total: int | None = None @@ -177,10 +190,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 +233,59 @@ 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. 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=f"cuCtxGetCurrent: {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(context_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(context_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(context_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 +370,7 @@ 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" + 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 +418,23 @@ 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}") 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 +492,56 @@ 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. + """ + xmlpath = getattr(config.option, "xmlpath", None) + if xmlpath: + return pathlib.Path(os.path.abspath(os.path.expanduser(os.path.expandvars(xmlpath)))).parent + return config.rootpath + + 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 +555,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 +584,43 @@ 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 + self._artifact_path = pathlib.Path(directory) / self._filename + if snapshot.has_context: + self._probed = True + self._probed_nodeid = nodeid + + destination = self._artifact_path + try: + destination.parent.mkdir(parents=True, exist_ok=True) + with destination.open("a" if self._artifact_written else "w", encoding="utf-8") as f: + if self._artifact_written: + f.write("\n\n") + f.write(report) + 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})" _default_recorder = OomDiagnosticsRecorder() @@ -517,14 +638,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 +673,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..bcc3e11ccc94 100644 --- a/cuda_core/tests/test_helpers.py +++ b/cuda_core/tests/test_helpers.py @@ -23,10 +23,13 @@ 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 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 +143,11 @@ 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), pluginmanager=types.SimpleNamespace(get_plugin=lambda _: None), ) return types.SimpleNamespace(nodeid=nodeid, config=config) @@ -153,6 +157,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 +235,49 @@ 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") def test_oom_diagnostics_report_names_the_failing_test_and_verdict(tmp_path): # build_report is what actually assembles the artifact text; exercise it @@ -375,6 +424,43 @@ def test_oom_diagnostics_probe_basics_is_live_and_cheap(init_cuda): assert snapshot.capped_pool_create_ok is None +def _current_context(): + return int(handle_return(driver.cuCtxGetCurrent())) + + +@pytest.mark.agent_authored(model="claude-opus-5-5") +def test_oom_diagnostics_probe_borrows_and_restores_the_primary_context(init_cuda, monkeypatch): + # The real probes are replaced: only the context handling is under test, + # and the full probe reserves a ~2x-device-memory VA window. + seen = [] + + def fake_probe(): + seen.append(_current_context()) + return ProbeSnapshot(has_context=True) + + monkeypatch.setattr("helpers.oom_diagnostics._probe_current_context", fake_probe) + dev = handle_return(driver.cuDeviceGet(0)) + primary = int(handle_return(driver.cuDevicePrimaryCtxRetain(dev))) + handle_return(driver.cuDevicePrimaryCtxRelease(dev)) + current = _current_context() + + snapshot = run_probe() + assert not snapshot.borrowed_primary_context + assert seen == [current] + + popped = handle_return(driver.cuCtxPopCurrent()) + try: + assert _current_context() == 0 + snapshot = run_probe() + assert _current_context() == 0 + finally: + handle_return(driver.cuCtxPushCurrent(popped)) + + assert snapshot.borrowed_primary_context + assert snapshot.context_restore_error is None + assert seen[1] == primary + + # --------------------------------------------------------------------------- # GL helper tests # --------------------------------------------------------------------------- From aabf2fcd3793bf73aac7bd5e45ec36281b459f8e Mon Sep 17 00:00:00 2001 From: Ralf Juengling Date: Mon, 23 Nov 2026 15:11:25 -0800 Subject: [PATCH 2/3] test(cuda.core): name failed context borrows, anchor and preserve OOM artifacts Follow-ups from review of the OOM probe context change: - A failed borrow of device 0's primary context (cuDeviceGet, retain or push) is recorded in a dedicated borrow_error field, printed on its own log line and named in the verdict, instead of being attributed to cuCtxGetCurrent. - Document that the borrow is always device 0. - Resolve a relative --junitxml against the invocation directory, not the current one, which a test may have changed. - Pick an unused artifact name rather than truncating a report left by an earlier pytest invocation sharing the results directory (tests/ and tests/cython). Co-Authored-By: Claude Sonnet 5.5 --- cuda_core/tests/helpers/oom_diagnostics.py | 46 ++++++++++++++--- cuda_core/tests/test_helpers.py | 59 ++++++++++++++++++++++ 2 files changed, 97 insertions(+), 8 deletions(-) diff --git a/cuda_core/tests/helpers/oom_diagnostics.py b/cuda_core/tests/helpers/oom_diagnostics.py index c765a2bb0ca3..f0ffec4bf89d 100644 --- a/cuda_core/tests/helpers/oom_diagnostics.py +++ b/cuda_core/tests/helpers/oom_diagnostics.py @@ -146,6 +146,9 @@ class ProbeSnapshot: # 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 @@ -244,28 +247,30 @@ def run_probe(): 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. See :func:`_probe_current_context` for the probes. + 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=f"cuCtxGetCurrent: {ctx_err}") + 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(context_error=f"cuDeviceGet(0): {dev_err}") + 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(context_error=f"cuDevicePrimaryCtxRetain(dev 0): {retain_err}") + 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(context_error=f"cuCtxPushCurrent(primary context of dev 0): {push_err}") + snapshot = ProbeSnapshot(borrow_error=f"cuCtxPushCurrent(primary context of dev 0): {push_err}") else: try: snapshot = _probe_current_context() @@ -370,6 +375,11 @@ def classify(snapshot: ProbeSnapshot) -> str: specific enough to act on. """ if not snapshot.has_context: + 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: @@ -427,6 +437,8 @@ def format_probe_log(snapshot: ProbeSnapshot) -> str: if not snapshot.has_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) if snapshot.borrowed_primary_context: lines.append( @@ -496,14 +508,32 @@ 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. + 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: - return pathlib.Path(os.path.abspath(os.path.expanduser(os.path.expandvars(xmlpath)))).parent + 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 _unused_path(path): + """``path``, or ``stem.N.suffix`` if it exists. + + 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. + """ + candidate = path + n = 0 + while candidate.exists(): + n += 1 + candidate = path.with_name(f"{path.stem}.{n}{path.suffix}") + return candidate + + class OomDiagnosticsRecorder: """Captures the OOM reason checker on the first CUDA OOM that can be probed. @@ -605,7 +635,7 @@ def capture(self, nodeid, phase, exc_text, directory, snapshot=None): if not self._captured: self._captured = True self._nodeid = nodeid - self._artifact_path = pathlib.Path(directory) / self._filename + self._artifact_path = _unused_path(pathlib.Path(directory) / self._filename) if snapshot.has_context: self._probed = True self._probed_nodeid = nodeid diff --git a/cuda_core/tests/test_helpers.py b/cuda_core/tests/test_helpers.py index bcc3e11ccc94..20344f6e6941 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,12 +22,16 @@ 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 @@ -148,6 +154,7 @@ def _fake_item(rootpath, nodeid="tests/test_x.py::test_a", xmlpath=None): 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) @@ -278,6 +285,58 @@ def test_oom_diagnostics_artifact_lands_beside_the_junit_file(tmp_path, monkeypa 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") + + +@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 -> Date: Mon, 23 Nov 2026 19:16:18 -0800 Subject: [PATCH 3/3] test(cuda.core): keep OOM artifact name selection inside the write error handling Picking an unused artifact name called Path.exists() outside the OSError handler, so an inaccessible results directory raised out of pytest_runtest_makereport and lost the report. Create the file exclusively instead, retrying numbered names on FileExistsError, so every filesystem error is reported with the diagnostics. Until a write succeeds the artifact stays unwritten, and a later report creates a new file rather than appending. --- cuda_core/tests/helpers/oom_diagnostics.py | 42 +++++++++------- cuda_core/tests/test_helpers.py | 58 ++++++++++++++++++++++ 2 files changed, 83 insertions(+), 17 deletions(-) diff --git a/cuda_core/tests/helpers/oom_diagnostics.py b/cuda_core/tests/helpers/oom_diagnostics.py index f0ffec4bf89d..7db10b5768fa 100644 --- a/cuda_core/tests/helpers/oom_diagnostics.py +++ b/cuda_core/tests/helpers/oom_diagnostics.py @@ -519,19 +519,25 @@ def artifact_directory(config): return config.rootpath -def _unused_path(path): - """``path``, or ``stem.N.suffix`` if it exists. +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. + 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 candidate.exists(): - n += 1 - candidate = path.with_name(f"{path.stem}.{n}{path.suffix}") - return candidate + 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: @@ -635,22 +641,24 @@ def capture(self, nodeid, phase, exc_text, directory, snapshot=None): if not self._captured: self._captured = True self._nodeid = nodeid - self._artifact_path = _unused_path(pathlib.Path(directory) / self._filename) if snapshot.has_context: self._probed = True self._probed_nodeid = nodeid - destination = self._artifact_path + # 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: - destination.parent.mkdir(parents=True, exist_ok=True) - with destination.open("a" if self._artifact_written else "w", encoding="utf-8") as f: - if self._artifact_written: - f.write("\n\n") - f.write(report) - self._artifact_written = True - return f"{report}\n(diagnostics also written to {destination})" + 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 {destination}: {exc!r})" + return f"{report}\n(could not write {self._artifact_path}: {exc!r})" _default_recorder = OomDiagnosticsRecorder() diff --git a/cuda_core/tests/test_helpers.py b/cuda_core/tests/test_helpers.py index 20344f6e6941..ec42acfb51db 100644 --- a/cuda_core/tests/test_helpers.py +++ b/cuda_core/tests/test_helpers.py @@ -312,6 +312,64 @@ def test_oom_diagnostics_does_not_overwrite_an_earlier_invocations_artifact(tmp_ 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