|
| 1 | +# Copyright 2023–2026 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Pytest configuration and fixtures for post-training unit tests.""" |
| 16 | + |
| 17 | +import faulthandler |
| 18 | +import os |
| 19 | +import sys |
| 20 | +import threading |
| 21 | + |
| 22 | +import pytest |
| 23 | + |
| 24 | + |
| 25 | +_DUMP_PATH = ( |
| 26 | + os.environ.get("HANG_DUMP_FILE") |
| 27 | + or os.environ.get("GITHUB_STEP_SUMMARY") |
| 28 | + or "/tmp/hang_watchdog_dump.txt" |
| 29 | +) |
| 30 | +_DUMP_FH = open(_DUMP_PATH, "a", buffering=1) |
| 31 | +os.environ["HANG_DUMP_FILE"] = _DUMP_PATH |
| 32 | +_DUMP_AFTER_SECS = float(os.environ.get("HANG_DUMP_AFTER_SECS", "300")) |
| 33 | +_EXIT_AFTER_SECS = float(os.environ.get("HANG_EXIT_AFTER_SECS", "900")) |
| 34 | +faulthandler.enable(file=_DUMP_FH, all_threads=True) |
| 35 | + |
| 36 | + |
| 37 | +def _dump(header): |
| 38 | + for sink in (_DUMP_FH, sys.__stderr__): |
| 39 | + try: |
| 40 | + sink.write("\n" + header + "\n") |
| 41 | + sink.flush() |
| 42 | + faulthandler.dump_traceback(file=sink, all_threads=True) |
| 43 | + sink.flush() |
| 44 | + except Exception: |
| 45 | + pass |
| 46 | + |
| 47 | + |
| 48 | +@pytest.fixture(autouse=True) |
| 49 | +def _hang_watchdog(request): |
| 50 | + """Watchdog fixture to detect and dump stack traces for hanging tests.""" |
| 51 | + node = request.node.nodeid |
| 52 | + stop = threading.Event() |
| 53 | + |
| 54 | + def _watch(): |
| 55 | + waited = 0.0 |
| 56 | + while not stop.wait(_DUMP_AFTER_SECS): |
| 57 | + waited += _DUMP_AFTER_SECS |
| 58 | + _dump( |
| 59 | + f"===== HANG WATCHDOG: {node!r} still running after {int(waited)}s;" |
| 60 | + " all threads: =====" |
| 61 | + ) |
| 62 | + if waited >= _EXIT_AFTER_SECS: |
| 63 | + _dump("===== HANG WATCHDOG: aborting process for CI =====") |
| 64 | + os._exit(99) |
| 65 | + |
| 66 | + t = threading.Thread(target=_watch, name="hang-watchdog", daemon=True) |
| 67 | + t.start() |
| 68 | + try: |
| 69 | + yield |
| 70 | + finally: |
| 71 | + stop.set() |
0 commit comments