Skip to content
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
21 changes: 10 additions & 11 deletions ci/tools/run-tests
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,14 @@ 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.
# Each attempt writes its own JUnit file; a restart skips tests completed without failure.
# Other pytest exit codes are returned unchanged unless pytest passed and log folding failed.
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"
local attempt=0 junit rc fold_rc fold_failed=0
rm -f "${done_file}"
while true; do
junit="${TEST_RESULTS_DIR}/${junit_base}.xml"
if [[ ${attempt} -gt 0 ]]; then
Expand All @@ -45,15 +45,14 @@ run_pytest_with_restarts() {
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}
if [[ ${fold_rc} -ne 0 ]]; then
fold_failed=${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
# A fold failure in any attempt fails the run, as the old pipefail pipeline did.
if [[ ${rc} -eq 0 && ${fold_failed} -ne 0 ]]; then
echo "Folding the pytest log failed (exit ${fold_failed})" >&2
return "${fold_failed}"
fi
return "${rc}"
fi
Expand Down
37 changes: 13 additions & 24 deletions cuda_core/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,8 @@ 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)
if report.when in ("setup", "call") and sticky_oom.is_oom_failure(report, call):
_stop_if_driver_is_stuck_in_oom(item)
return report


Expand All @@ -109,48 +110,36 @@ def pytest_terminal_summary(terminalreporter):
# 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()
_unfinished_nodeids = set()


def _stop_if_driver_is_stuck_in_oom(item, call, report):
def _stop_if_driver_is_stuck_in_oom(item):
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():
if 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)
_unfinished_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)
if report.failed or report.outcome == "rerun":
_unfinished_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:
return
sticky_oom.record_finished(nodeid, failed=nodeid in _failed_nodeids)
# The stuck driver may cause non-OOM failures before detection. Leave all
# failures for the fresh process, where deterministic failures recur.
# The trigger must also rerun even if an in-process rerun passed.
if nodeid != _sticky_oom_nodeid and nodeid not in _unfinished_nodeids:
sticky_oom.record_finished(nodeid)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved


def pytest_collection_modifyitems(config, items):
Expand Down
29 changes: 12 additions & 17 deletions cuda_core/tests/helpers/sticky_oom.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

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
that skips tests already completed without failure. 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.

Expand All @@ -31,8 +31,6 @@
# 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
Expand Down Expand Up @@ -62,25 +60,22 @@ def process_is_stuck_in_oom():
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 _exception_is_oom(exc):
# For a group of errors, classify the phase as OOM only if all are OOMs.
if isinstance(exc, BaseExceptionGroup):
return all(_exception_is_oom(child) for child in exc.exceptions)
return OOM_MARKER in str(exc)


def record_finished(nodeid, failed=False):
"""Append a finished test to the resume file, if CI asked for one.
def is_oom_failure(report, call):
"""Classify a failed phase from its exception, not its rendered traceback."""
return report.failed and call.excinfo is not None and _exception_is_oom(call.excinfo.value)

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.
"""

def record_finished(nodeid):
"""Record a test completed without failure, if CI asked for a resume file."""
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")

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

import os
import pathlib
import subprocess
import sys
from types import SimpleNamespace

import pytest
from helpers import sticky_oom


@pytest.mark.parametrize(
("probe_confirms_sticky_oom", "failure_repeats"),
[(True, False), (True, True), (False, False)],
ids=["clears", "repeats", "no-restart"],
)
@pytest.mark.agent_authored(model="gpt-6.2-sol")
def test_sticky_oom_retries_non_oom_failure(tmp_path, probe_confirms_sticky_oom, failure_repeats):
# Run the actual hooks in separate processes with no live driver probes.
test_file = tmp_path / "test_retry.py"
test_file.write_text(
f"""\
import os

from helpers import oom_diagnostics, sticky_oom

restarting = os.environ["STICKY_OOM_TEST_RESTART"] == "1"
sticky_oom.IS_WINDOWS = True
sticky_oom.process_is_stuck_in_oom = lambda: {probe_confirms_sticky_oom!r}
oom_diagnostics.record_if_oom = lambda *args: None

def test_already_passed():
assert not restarting, "a completed test should be skipped"

def test_non_oom():
if not restarting or {failure_repeats!r}:
raise AssertionError("non-OOM failure") # Not CUDA_ERROR_OUT_OF_MEMORY

def test_trigger():
if not restarting:
raise RuntimeError("CUDA_ERROR_OUT_OF_MEMORY: restart trigger")
""",
encoding="utf-8",
)
done_file = tmp_path / "finished.txt"
tests_dir = pathlib.Path(__file__).parent
env = {
**os.environ,
sticky_oom.DONE_FILE_ENV: str(done_file),
"PYTEST_ADDOPTS": "",
"PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1",
"PYTHONPATH": os.pathsep.join(filter(None, (str(tests_dir), os.environ.get("PYTHONPATH")))),
}

def run_pytest(restart):
return subprocess.run( # noqa: S603 - trusted interpreter and test-owned arguments
[sys.executable, "-m", "pytest", "--noconftest", "-p", "conftest", "-q", test_file.name],
capture_output=True,
cwd=tmp_path,
env={**env, "STICKY_OOM_TEST_RESTART": str(int(restart))},
text=True,
timeout=30,
)

first = run_pytest(restart=False)
expected = sticky_oom.STICKY_OOM_EXIT_CODE if probe_confirms_sticky_oom else pytest.ExitCode.TESTS_FAILED
assert first.returncode == expected, first.stdout + first.stderr
assert "non-OOM failure" in first.stdout
assert "CUDA_ERROR_OUT_OF_MEMORY: restart trigger" in first.stdout
assert done_file.read_text(encoding="utf-8").splitlines() == ["test_retry.py::test_already_passed"]

if probe_confirms_sticky_oom:
second = run_pytest(restart=True)
expected = pytest.ExitCode.TESTS_FAILED if failure_repeats else pytest.ExitCode.OK
assert second.returncode == expected, second.stdout + second.stderr
assert ("non-OOM failure" in second.stdout) is failure_repeats
finished = ["test_retry.py::test_already_passed", "test_retry.py::test_trigger"]
if not failure_repeats:
finished.append("test_retry.py::test_non_oom")
assert sorted(done_file.read_text(encoding="utf-8").splitlines()) == sorted(finished)


@pytest.mark.parametrize(
("second_error", "is_oom"),
[(sticky_oom.OOM_MARKER, True), ("unrelated failure", False)],
ids=["oom-only", "mixed"],
)
@pytest.mark.agent_authored(model="gpt-6.2-sol")
def test_sticky_oom_classifies_grouped_failures(second_error, is_oom):
with pytest.raises(ExceptionGroup) as excinfo:
raise ExceptionGroup("teardown", [RuntimeError(sticky_oom.OOM_MARKER), RuntimeError(second_error)])

report = SimpleNamespace(failed=True)
call = SimpleNamespace(excinfo=excinfo)
assert sticky_oom.is_oom_failure(report, call) is is_oom
Loading