Repository navigation
Expand file tree
/
Copy pathtest_leaks.py
More file actions
143 lines (110 loc) · 4.14 KB
/
Copy pathtest_leaks.py
File metadata and controls
143 lines (110 loc) · 4.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
import contextlib
import gc
import multiprocessing as mp
import platform
try:
import psutil
except ImportError:
HAVE_PSUTIL = False
else:
HAVE_PSUTIL = True
import pytest
from helpers.child_processes import child_timeout_sec, kill_subprocesses, noop, run_child, warmup_multiprocessing
CHILD_TIMEOUT_SEC = child_timeout_sec()
NBYTES = 64
USING_FDS = platform.system() == "Linux"
skip_if_unrunnable = pytest.mark.skipif(
not USING_FDS or not HAVE_PSUTIL, reason="mempool allocation handle is not using fds or psutil is unavailable"
)
pytestmark = pytest.mark.thread_unsafe(reason="Tests number of fds which is shared.")
@pytest.mark.flaky(reruns=2)
@skip_if_unrunnable
def test_alloc_handle(ipc_memory_resource):
"""Check for fd leaks in allocation_handle."""
mr = ipc_memory_resource
if not hasattr(mr, "allocation_handle"):
pytest.skip("allocation handles are pool-only")
with CheckFDLeaks():
[mr.allocation_handle for _ in range(10)]
def exec_success(obj, number=1):
"""Successfully run a child process."""
for _ in range(number):
run_child(noop, obj)
def exec_launch_failure(obj, number=1):
"""
Unsuccessfully try to launch a child process. This fails after
the child starts.
"""
for _ in range(number):
process = mp.Process(target=child_main_bad, args=(obj,))
process.start()
process.join(timeout=CHILD_TIMEOUT_SEC)
survivors = kill_subprocesses(process)
assert not survivors, "child did not exit within timeout"
assert process.exitcode != 0
def child_main_bad():
"""Fails when passed arguments."""
def exec_reduce_failure(obj, number=1):
"""
Unsuccessfully try to launch a child process. This fails before
the child starts but after the resource-owning object is serialized.
"""
for _ in range(number):
fails_to_reduce = Irreducible()
with contextlib.suppress(RuntimeError):
mp.Process(target=noop, args=(obj, fails_to_reduce)).start()
class Irreducible:
"""A class that cannot be serialized."""
def __reduce__(self):
raise RuntimeError("Irreducible")
def _get_alloc_handle(mr, _stream):
if not hasattr(mr, "allocation_handle"):
pytest.skip("allocation handles are pool-only")
return mr.allocation_handle
def _get_mr(mr, _stream):
return mr
def _get_buffer(mr, stream):
return mr.allocate(NBYTES, stream=stream)
def _get_buffer_desc(mr, stream):
return mr.allocate(NBYTES, stream=stream).ipc_descriptor
@pytest.mark.flaky(reruns=2)
@skip_if_unrunnable
@pytest.mark.parametrize(
"getobject",
[_get_alloc_handle, _get_mr, _get_buffer, _get_buffer_desc],
ids=["alloc_handle", "mr", "buffer", "buffer_desc"],
)
@pytest.mark.parametrize("launcher", [exec_success, exec_launch_failure, exec_reduce_failure])
def test_pass_object(ipc_device, ipc_memory_resource, launcher, getobject):
"""Check for fd leaks when an object is sent as a subprocess argument."""
mr = ipc_memory_resource
stream = ipc_device.default_stream
with CheckFDLeaks():
obj = getobject(mr, stream)
stream.sync()
try:
launcher(obj, number=2)
finally:
del obj
class CheckFDLeaks:
"""
Context manager to check for file descriptor leaks.
Ensures the number of open file descriptors is the same before and after the block.
"""
def __init__(self):
self.process = psutil.Process()
def __enter__(self):
warmup_multiprocessing()
gc.collect()
self.initial_fds = self.process.num_fds()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
# Only the success path is checked: a failing block has already
# reported its own error, and its cleanup may legitimately be partial.
if exc_type is None:
gc.collect()
final_fds = self.process.num_fds()
assert final_fds == self.initial_fds, f"file descriptors leaked: {self.initial_fds} -> {final_fds}"
return False