Skip to content
48 changes: 47 additions & 1 deletion ci/tools/run-tests
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,52 @@ fold_pytest_log() {
python "${CI_TOOLS_DIR}/fold_pytest_sections.py"
}

# Windows drivers can get stuck in CUDA_ERROR_OUT_OF_MEMORY for the rest of a process
# (NVBugs 7092346, NVIDIA/cuda-python#3472). cuda_core/tests/conftest.py then stops pytest
# with this exit code; run_pytest_with_restarts reruns the unfinished tests in a fresh
# process. Mirrors STICKY_OOM_EXIT_CODE in cuda_core/tests/helpers/sticky_oom.py.
STICKY_OOM_EXIT_CODE=75
MAX_STICKY_OOM_RESTARTS=3

# Usage: run_pytest_with_restarts <junit-basename> <pytest command...>
# Each attempt writes its own JUnit file; a restart skips tests earlier attempts finished.
# Any other pytest exit code is returned unchanged.
run_pytest_with_restarts() {
local junit_base="${1}"
shift
local done_file="${TEST_RESULTS_DIR}/${junit_base}-finished.txt"
local attempt=0 junit rc
rm -f "${done_file}" "${done_file}.failed"
while true; do
junit="${TEST_RESULTS_DIR}/${junit_base}.xml"
if [[ ${attempt} -gt 0 ]]; then
junit="${TEST_RESULTS_DIR}/${junit_base}-restart${attempt}.xml"
fi
set +e
CUDA_CORE_TEST_DONE_FILE="${done_file}" "$@" --junitxml "${junit}" | fold_pytest_log
rc=${PIPESTATUS[0]} fold_rc=${PIPESTATUS[1]}
set -e
if [[ ${fold_rc} -ne 0 && ${rc} -eq 0 ]]; then
rc=${fold_rc}
fi
if [[ ${rc} -ne ${STICKY_OOM_EXIT_CODE} ]]; then
# Earlier attempts' failures are not rerun: they must still fail the run.
if [[ ${attempt} -gt 0 && ${rc} -eq 0 && -s "${done_file}.failed" ]]; then
echo "Tests failed in an earlier attempt (listed in ${done_file}.failed)" >&2
cat "${done_file}.failed" >&2
return 1
fi
return "${rc}"
fi
attempt=$((attempt + 1))
if [[ ${attempt} -gt ${MAX_STICKY_OOM_RESTARTS} ]]; then
echo "Driver stuck in CUDA_ERROR_OUT_OF_MEMORY (NVBugs 7092346); giving up after ${MAX_STICKY_OOM_RESTARTS} restarts" >&2
return "${rc}"
fi
echo "Driver stuck in CUDA_ERROR_OUT_OF_MEMORY (NVBugs 7092346); restarting pytest (${attempt}/${MAX_STICKY_OOM_RESTARTS}) to run the unfinished tests"
done
}

# JUnit XML, one file per suite. The test workflows upload this directory as an
# artifact: a machine-readable record of the run for follow-up tooling.
TEST_RESULTS_DIR="$(pwd)/test-results"
Expand Down Expand Up @@ -187,7 +233,7 @@ elif [[ "${test_module}" == "core" || "${test_module}" == nightly-* ]]; then
echo "Installed packages before core tests:"
pip list
echo "Running core tests"
${SANITIZER_CMD} pytest -rsxXfE -v --randomly-dont-reorganize --exclude-warning-annotations "${PYTEST_PARALLEL_ARGS[@]}" --junitxml "${TEST_RESULTS_DIR}/junit-core.xml" tests/ | fold_pytest_log
run_pytest_with_restarts junit-core ${SANITIZER_CMD} pytest -rsxXfE -v --randomly-dont-reorganize --exclude-warning-annotations "${PYTEST_PARALLEL_ARGS[@]}" tests/
# Compiled Cython tests require the bindings used to build them. Older
# toolkit rows intentionally exercise published floor bindings instead.
if [[ "${SKIP_CYTHON_TEST}" == 0 ]]; then
Expand Down
73 changes: 73 additions & 0 deletions cuda_core/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
pytest_plugins = ["cuda_python_test_helpers._pytest_plugin"]
# END SYNCED PYTEST PLUGIN BOOTSTRAP

from helpers import sticky_oom
from helpers.constants import POOL_SIZE
from helpers.memory import (
MEMPOOL_RESOURCE_CLASSES,
Expand Down Expand Up @@ -86,13 +87,85 @@ def pytest_runtest_makereport(item, call):
from helpers import oom_diagnostics

oom_diagnostics.record_if_oom(item, call, report)
_stop_if_driver_is_stuck_in_oom(item, call, report)
return report


def pytest_terminal_summary(terminalreporter):
from helpers import oom_diagnostics

oom_diagnostics.report_terminal_summary(terminalreporter)
if _sticky_oom_nodeid is not None:
terminalreporter.write_line("")
terminalreporter.write_line(
f"Driver stuck in CUDA_ERROR_OUT_OF_MEMORY after {_sticky_oom_nodeid} (NVBugs 7092346, "
f"#3472); stopped with exit code {sticky_oom.STICKY_OOM_EXIT_CODE} so CI can resume "
"in a fresh process."
)


# NVBugs 7092346: on Windows a host pinned pool can leave the process stuck in
# OOM. Stop the run at the first failing test that shows it and exit with a
# dedicated code; ci/tools/run-tests restarts and skips the finished tests.
# See helpers/sticky_oom.py.
_sticky_oom_nodeid = None
_failed_nodeids = set()
_rerun_nodeids = set()
# Tests whose current attempt failed with OOM, in any phase. Such a failure may
# be a symptom of the stuck driver, so the test runs again after a restart; a
# genuine OOM fails again there.
_oom_nodeids = set()


def _stop_if_driver_is_stuck_in_oom(item, call, report):
global _sticky_oom_nodeid
if _sticky_oom_nodeid is not None or not sticky_oom.is_affected_platform():
return
if sticky_oom.is_oom_failure(report, call) and sticky_oom.process_is_stuck_in_oom():
_sticky_oom_nodeid = item.nodeid
item.session.shouldstop = f"driver stuck in CUDA_ERROR_OUT_OF_MEMORY (NVBugs 7092346) at {item.nodeid}"


def pytest_runtest_logstart(nodeid, location):
# pytest-rerunfailures calls logstart and logfinish once per attempt.
_rerun_nodeids.discard(nodeid)
_oom_nodeids.discard(nodeid)


def pytest_runtest_logreport(report):
# Logged outcomes, not makereport's: pytest-rerunfailures relabels a failed
# attempt that it will rerun as "rerun" in between.
if report.outcome == "rerun":
_rerun_nodeids.add(report.nodeid)
elif report.failed:
_failed_nodeids.add(report.nodeid)
if sticky_oom.OOM_MARKER in report.longreprtext:
_oom_nodeids.add(report.nodeid)


def pytest_runtest_logfinish(nodeid, location):
# An attempt that is going to be rerun has not finished the test, and neither
# has the one that exposed the stuck driver or one that failed with OOM
# before the stuck state was detected (e.g. in a teardown, which has no
# current context to probe): all must run again.
if nodeid in _rerun_nodeids or nodeid in _oom_nodeids or nodeid == _sticky_oom_nodeid:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Major · Functional Correctness · Heavy lift

important: Keep a non-OOM failure when a teardown OOM makes the test rerun.

In cuda_core/tests/conftest.py:151-153, a test with a call-phase failure and a teardown OOM never reaches record_finished. Keeping the test unfinished is correct, since it must rerun after a restart. The call failure, however, stays only in the process-local _failed_nodeids. In the fresh process after the restart, the test can pass. The finished-test record then has no entry for the call failure, so the run can pass despite that failure. The PR states that a restart must not turn a genuine failure green.

Persist a non-OOM failure in a form that survives the restart. Keep that failure separate from completion. Leave the test unfinished so it reruns. Tests whose failures are only OOM should keep their current treatment.

return
sticky_oom.record_finished(nodeid, failed=nodeid in _failed_nodeids)


def pytest_collection_modifyitems(config, items):
finished = sticky_oom.finished_nodeids()
if not finished:
return
kept = [item for item in items if item.nodeid not in finished]
config.hook.pytest_deselected(items=[item for item in items if item.nodeid in finished])
items[:] = kept


def pytest_sessionfinish(session, exitstatus):
# Only a stop for this reason: an internal or usage error must not be retried.
if _sticky_oom_nodeid is not None and exitstatus in (pytest.ExitCode.TESTS_FAILED, pytest.ExitCode.INTERRUPTED):
session.exitstatus = sticky_oom.STICKY_OOM_EXIT_CODE


def _wrap_worker_cuda_test(func):
Expand Down
93 changes: 93 additions & 0 deletions cuda_core/tests/helpers/sticky_oom.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""Stop the run, and let CI resume it, when the driver is stuck in OOM (NVBugs 7092346).

On Windows (WDDM and MCDM), a host pinned memory pool that has had device
access granted can leave the process in a permanent error state: later driver
calls return ``CUDA_ERROR_OUT_OF_MEMORY`` even though no resource is exhausted,
and ``cuCtxSynchronize`` and ``cuMemGetInfo`` fail the same way. The state is
per process and the test that trips it is arbitrary, so marking tests xfail
would hide real failures and name the wrong tests (issue #3472).

This module detects that state after a failing test and makes pytest stop with
:data:`STICKY_OOM_EXIT_CODE`. ``ci/tools/run-tests`` then starts a fresh process
that skips the tests which already finished. Both halves are inert outside
Windows, and in a process that is healthy the probe returns False, so a
genuine out-of-memory failure still fails the run.

Remove this module and its wiring once the fixed driver is the minimum CI
driver.
"""

import os
import pathlib

from cuda.bindings import driver
from cuda_python_test_helpers import IS_WINDOWS

from .contexts import current_context_handle

# Not a pytest exit code (0-5) and not a signal. Mirrored in ci/tools/run-tests.
STICKY_OOM_EXIT_CODE = 75
DONE_FILE_ENV = "CUDA_CORE_TEST_DONE_FILE"
# Mirrored in ci/tools/run-tests.
FAILED_SUFFIX = ".failed"
OOM_MARKER = "CUDA_ERROR_OUT_OF_MEMORY"

_OOM = driver.CUresult.CUDA_ERROR_OUT_OF_MEMORY


def is_affected_platform():
"""True where NVBugs 7092346 can occur.

Linux is unaffected. TCC is unaffected too, but a healthy process never
passes :func:`process_is_stuck_in_oom`, so no driver-model check is needed.
"""
return IS_WINDOWS


def process_is_stuck_in_oom():
"""True if context-wide calls return OOM, which a genuine allocation failure never does.

Needs a current context; returns False without one, so the next failing
test (the cascade produces many) gets another chance. Never changes the
current context. A broken probe raises rather than reporting a healthy
driver; ``cuCtxGetCurrent`` still succeeds in the stuck state.
"""
if current_context_handle() == 0:
return False
(sync_err,) = driver.cuCtxSynchronize()
mem_err = driver.cuMemGetInfo()[0]
return sync_err == _OOM and mem_err == _OOM


def is_oom_failure(report, call):
"""True if ``report`` is a failed setup or call phase whose exception mentions OOM."""
if not report.failed or call.excinfo is None or call.when not in ("setup", "call"):
return False
return OOM_MARKER in str(call.excinfo.value)


def record_finished(nodeid, failed=False):
"""Append a finished test to the resume file, if CI asked for one.

A failed test is also listed in ``<resume file>.failed``, so that
``ci/tools/run-tests`` can fail the run even if the last attempt passes.
"""
path = os.environ.get(DONE_FILE_ENV)
if path:
# The failure first: if this raises, the test is not finished and reruns.
if failed:
with open(path + FAILED_SUFFIX, "a", encoding="utf-8") as f:
f.write(nodeid + "\n")
with open(path, "a", encoding="utf-8") as f:
f.write(nodeid + "\n")


def finished_nodeids():
"""Node IDs that earlier attempts of this run finished; empty on a first attempt."""
path = os.environ.get(DONE_FILE_ENV)
if not path or not pathlib.Path(path).is_file():
return set()
return {line.strip() for line in pathlib.Path(path).read_text(encoding="utf-8").splitlines() if line.strip()}
Loading