|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +"""Run fork-safety scenarios in a fresh interpreter. |
| 5 | +
|
| 6 | +Forking the pytest worker copies everything earlier tests left behind (DuckDB |
| 7 | +thread pools, large allocator reservations), which makes fork() itself fail |
| 8 | +with ENOMEM on memory-constrained CI runners. A fresh interpreter gives each |
| 9 | +scenario a small, clean parent. |
| 10 | +""" |
| 11 | + |
| 12 | +from __future__ import annotations |
| 13 | + |
| 14 | +import multiprocessing |
| 15 | +import subprocess |
| 16 | +import sys |
| 17 | +import textwrap |
| 18 | + |
| 19 | +import pytest |
| 20 | + |
| 21 | +requires_fork = pytest.mark.skipif( |
| 22 | + "fork" not in multiprocessing.get_all_start_methods(), reason="requires the fork start method" |
| 23 | +) |
| 24 | + |
| 25 | +_CHILD_JOIN_TIMEOUT_S = 20 |
| 26 | +_SCRIPT_TIMEOUT_S = 90 |
| 27 | + |
| 28 | +_PRELUDE = f""" |
| 29 | +import asyncio |
| 30 | +import multiprocessing |
| 31 | +import sys |
| 32 | +
|
| 33 | +
|
| 34 | +async def ping(): |
| 35 | + return "pong" |
| 36 | +
|
| 37 | +
|
| 38 | +def run_forked_child(target): |
| 39 | + ctx = multiprocessing.get_context("fork") |
| 40 | + queue = ctx.Queue() |
| 41 | + child = ctx.Process(target=target, args=(queue,)) |
| 42 | + child.start() |
| 43 | + child.join(timeout={_CHILD_JOIN_TIMEOUT_S}) |
| 44 | + if child.is_alive(): |
| 45 | + child.kill() |
| 46 | + child.join() |
| 47 | + sys.exit("forked child hung") |
| 48 | + if child.exitcode != 0: |
| 49 | + sys.exit(f"forked child exited with code {{child.exitcode}}") |
| 50 | + return queue.get(timeout=5) |
| 51 | +""" |
| 52 | + |
| 53 | + |
| 54 | +def run_fork_probe(body: str) -> None: |
| 55 | + """Run ``body`` after a prelude that defines ``ping()`` and ``run_forked_child(target)``. |
| 56 | +
|
| 57 | + ``target`` receives a queue and must put its result on it. The probe fails if |
| 58 | + the script exits non-zero, which includes a forked child that hangs. |
| 59 | + """ |
| 60 | + script = _PRELUDE + textwrap.dedent(body) |
| 61 | + result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=_SCRIPT_TIMEOUT_S) |
| 62 | + assert result.returncode == 0, f"fork probe failed:\n{result.stderr}" |
0 commit comments