File: test_threadsafety.py

package info (click to toggle)
python-mapbox-earcut 2.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 236 kB
  • sloc: cpp: 681; python: 355; makefile: 4
file content (419 lines) | stat: -rw-r--r-- 13,959 bytes parent folder | download
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
"""
Thread safety tests for free-threaded Python (PEP 703).

These tests validate that the mapbox_earcut library is safe to use
with multiple threads when running Python with the GIL disabled.
"""

import sys
from concurrent.futures import ThreadPoolExecutor
import threading
from typing import Any, Callable, List, Optional, Tuple, Union

import mapbox_earcut as earcut
import numpy as np
from numpy.typing import NDArray
import pytest


def run_threaded(
    func: Callable[..., Any],
    num_threads: int = 8,
    pass_count: bool = False,
    pass_barrier: bool = False,
    outer_iterations: int = 1,
    prepare_args: Optional[Callable[[], List[Any]]] = None,
) -> None:
    """
    Runs a function many times in parallel.

    This helper is adapted from NumPy's testing utilities and is designed
    to expose race conditions and thread safety issues.

    Args:
        func: The function to run in parallel
        num_threads: Number of threads to spawn
        pass_count: If True, pass thread index as first argument to func
        pass_barrier: If True, pass a threading.Barrier as argument to func
        outer_iterations: Number of times to repeat the entire test
        prepare_args: Optional function that returns a list of arguments
    """
    for _ in range(outer_iterations):
        with ThreadPoolExecutor(max_workers=num_threads) as tpe:
            if prepare_args is None:
                args = []
            else:
                args = prepare_args()
            if pass_barrier:
                barrier = threading.Barrier(num_threads)
                args.append(barrier)
            else:
                barrier = None
            if pass_count:
                all_args = [(func, i, *args) for i in range(num_threads)]
            else:
                all_args = [(func, *args) for i in range(num_threads)]

            futures = []
            try:
                for arg in all_args:
                    futures.append(tpe.submit(*arg))
            finally:
                if len(futures) < num_threads and barrier is not None:
                    barrier.abort()
            for f in futures:
                f.result()


# Basic thread safety tests


def test_parallel_triangulate_float32_simple() -> None:
    """Test that multiple threads can triangulate simple polygons simultaneously."""
    results: List[Optional[NDArray[np.uint32]]] = [None] * 8

    def closure(i: int, b: threading.Barrier) -> None:
        # Create per-thread data to avoid sharing arrays
        verts = np.array([[0, 0], [1, 0], [1, 1]], dtype=np.float32).reshape(-1, 2)
        rings = np.array([3])

        # Synchronize all threads to maximize chance of race condition
        _ = b.wait()

        # Perform triangulation
        result = earcut.triangulate_float32(verts, rings)

        # Store result
        results[i] = result

    run_threaded(closure, num_threads=8, pass_barrier=True, pass_count=True)

    # Verify all threads got correct results
    expected = np.array([1, 2, 0])
    for i, result in enumerate(results):
        assert result is not None, f"Thread {i} didn't produce a result"
        assert result.dtype == np.uint32
        assert result.shape == (3,)
        assert np.array_equal(result, expected), f"Thread {i} got incorrect result"


def test_parallel_triangulate_float64_simple() -> None:
    """Test that multiple threads can triangulate with float64 simultaneously."""
    results: List[Optional[NDArray[np.uint32]]] = [None] * 8

    def closure(i: int, b: threading.Barrier) -> None:
        verts = np.array([[0, 0], [1, 0], [1, 1]], dtype=np.float64).reshape(-1, 2)
        rings = np.array([3])
        _ = b.wait()
        result = earcut.triangulate_float64(verts, rings)
        results[i] = result

    run_threaded(closure, num_threads=8, pass_barrier=True, pass_count=True)

    expected = np.array([1, 2, 0])
    for result in results:
        assert result is not None
        assert np.array_equal(result, expected)


def test_parallel_triangulate_int32_simple() -> None:
    """Test that multiple threads can triangulate with int32 simultaneously."""
    results: List[Optional[NDArray[np.uint32]]] = [None] * 8

    def closure(i: int, b: threading.Barrier) -> None:
        verts = np.array([[0, 0], [1, 0], [1, 1]], dtype=np.int32).reshape(-1, 2)
        rings = np.array([3])
        _ = b.wait()
        result = earcut.triangulate_int32(verts, rings)
        results[i] = result

    run_threaded(closure, num_threads=8, pass_barrier=True, pass_count=True)

    expected = np.array([1, 2, 0])
    for result in results:
        assert result is not None
        assert np.array_equal(result, expected)


def test_parallel_triangulate_int64_simple() -> None:
    """Test that multiple threads can triangulate with int64 simultaneously."""
    results: List[Optional[NDArray[np.uint32]]] = [None] * 8

    def closure(i: int, b: threading.Barrier) -> None:
        verts = np.array([[0, 0], [1, 0], [1, 1]], dtype=np.int64).reshape(-1, 2)
        rings = np.array([3])
        _ = b.wait()
        result = earcut.triangulate_int64(verts, rings)
        results[i] = result

    run_threaded(closure, num_threads=8, pass_barrier=True, pass_count=True)

    expected = np.array([1, 2, 0])
    for result in results:
        assert result is not None
        assert np.array_equal(result, expected)


# Complex polygon thread safety tests


def test_parallel_triangulate_square() -> None:
    """Test parallel triangulation of a square."""
    results: List[Optional[NDArray[np.uint32]]] = [None] * 16

    def closure(i: int, b: threading.Barrier) -> None:
        # Square polygon
        verts = np.array(
            [[0, 0], [10, 0], [10, 10], [0, 10]], dtype=np.float32
        ).reshape(-1, 2)
        rings = np.array([4])

        _ = b.wait()
        result = earcut.triangulate_float32(verts, rings)
        results[i] = result

    run_threaded(
        closure, num_threads=16, pass_barrier=True, pass_count=True, outer_iterations=3
    )

    # All results should have 6 indices (2 triangles)
    for result in results:
        assert result is not None
        assert result.dtype == np.uint32
        assert result.shape == (6,)


def test_parallel_triangulate_with_hole() -> None:
    """Test parallel triangulation of a polygon with a hole."""
    results: List[Optional[NDArray[np.uint32]]] = [None] * 8

    def closure(i: int, b: threading.Barrier) -> None:
        # Outer square
        outer = np.array([[0, 0], [10, 0], [10, 10], [0, 10]], dtype=np.float32)

        # Inner square (hole)
        inner = np.array([[2, 2], [8, 2], [8, 8], [2, 8]], dtype=np.float32)

        verts = np.vstack([outer, inner]).reshape(-1, 2)
        rings = np.array([4, 8])  # First ring ends at 4, second at 8

        _ = b.wait()
        result = earcut.triangulate_float32(verts, rings)
        results[i] = result

    run_threaded(closure, num_threads=8, pass_barrier=True, pass_count=True)

    # All results should be consistent
    first_result = results[0]
    assert first_result is not None
    for result in results[1:]:
        assert result is not None
        assert result.shape == first_result.shape
        assert np.array_equal(result, first_result)


def test_parallel_triangulate_complex_shape() -> None:
    """Test parallel triangulation with a more complex polygon."""
    results: List[Optional[NDArray[np.uint32]]] = [None] * 12

    def closure(i: int, b: threading.Barrier) -> None:
        # Hexagon
        angles = np.linspace(0, 2 * np.pi, 7)[:-1]  # 6 points
        verts = np.column_stack([np.cos(angles), np.sin(angles)]).astype(np.float64)
        rings = np.array([6])

        _ = b.wait()
        result = earcut.triangulate_float64(verts, rings)
        results[i] = result

    run_threaded(
        closure, num_threads=12, pass_barrier=True, pass_count=True, outer_iterations=2
    )

    # Hexagon should produce 12 indices (4 triangles)
    for result in results:
        assert result is not None
        assert result.shape == (12,)


# Stress tests


def test_high_contention_same_shape() -> None:
    """
    Stress test with many threads processing the same shape.

    This test runs many threads all triangulating the same geometry
    to maximize the chance of exposing race conditions.
    """
    num_threads = 32
    results: List[Optional[NDArray[np.uint32]]] = [None] * num_threads

    def closure(i: int, b: threading.Barrier) -> None:
        verts = np.array([[0, 0], [5, 0], [5, 5], [0, 5]], dtype=np.float32).reshape(
            -1, 2
        )
        rings = np.array([4])

        _ = b.wait()
        result = None
        # Run multiple times in each thread
        for _ in range(10):
            result = earcut.triangulate_float32(verts, rings)
        results[i] = result

    run_threaded(
        closure,
        num_threads=num_threads,
        pass_barrier=True,
        pass_count=True,
        outer_iterations=5,
    )

    # Verify all results are consistent
    for result in results:
        assert result is not None
        assert result.shape == (6,)


def test_mixed_operations() -> None:
    """Test mixing different data types in parallel."""
    results: List[Optional[NDArray[np.uint32]]] = [None] * 16

    def closure(i: int, b: threading.Barrier) -> None:
        # Each thread uses a different dtype based on its index
        dtypes = [np.float32, np.float64, np.int32, np.int64]
        funcs: List[Callable[[Any, Any], NDArray[np.uint32]]] = [
            earcut.triangulate_float32,
            earcut.triangulate_float64,
            earcut.triangulate_int32,
            earcut.triangulate_int64,
        ]

        dtype = dtypes[i % 4]
        func = funcs[i % 4]

        verts = np.array([[0, 0], [1, 0], [1, 1]], dtype=dtype).reshape(-1, 2)
        rings = np.array([3])

        _ = b.wait()
        result = func(verts, rings)
        results[i] = result

    run_threaded(
        closure, num_threads=16, pass_barrier=True, pass_count=True, outer_iterations=10
    )

    expected = np.array([1, 2, 0])
    for result in results:
        assert result is not None
        assert np.array_equal(result, expected)


def test_varying_sizes() -> None:
    """Test with varying polygon sizes across threads."""
    results: List[Optional[NDArray[np.uint32]]] = [None] * 20

    def closure(i: int, b: threading.Barrier) -> None:
        # Create polygons of different sizes based on thread index
        num_sides = 3 + (i % 8)  # 3 to 10 sides
        angles = np.linspace(0, 2 * np.pi, num_sides + 1)[:-1]
        verts = np.column_stack([np.cos(angles), np.sin(angles)]).astype(np.float32)
        rings = np.array([num_sides])

        _ = b.wait()
        result = earcut.triangulate_float32(verts, rings)
        results[i] = result

    run_threaded(
        closure, num_threads=20, pass_barrier=True, pass_count=True, outer_iterations=3
    )

    # Verify results exist and have reasonable sizes
    for i, result in enumerate(results):
        assert result is not None
        num_sides = 3 + (i % 8)
        # n-sided polygon should produce (n-2) triangles = (n-2)*3 indices
        expected_indices = (num_sides - 2) * 3
        assert result.shape == (expected_indices,), (
            f"Thread {i}: {num_sides}-sided polygon should produce {expected_indices} indices"
        )


# Error handling thread safety tests


def test_parallel_invalid_rings() -> None:
    """Test that multiple threads can handle invalid input simultaneously."""
    exceptions: List[Optional[ValueError]] = [None] * 8

    def closure(i: int, b: threading.Barrier) -> None:
        verts = np.array([[0, 0], [1, 0], [1, 1]], dtype=np.float32).reshape(-1, 2)
        rings = np.array([5])  # Invalid: larger than verts

        _ = b.wait()
        try:
            _ = earcut.triangulate_float32(verts, rings)
            exceptions[i] = None
        except ValueError as e:
            exceptions[i] = e

    run_threaded(closure, num_threads=8, pass_barrier=True, pass_count=True)

    # All threads should have raised ValueError
    for i, exc in enumerate(exceptions):
        assert exc is not None, f"Thread {i} should have raised ValueError"
        assert isinstance(exc, ValueError)


def test_parallel_mixed_valid_invalid() -> None:
    """Test mixing valid and invalid inputs across threads."""
    results: List[Optional[Tuple[str, Union[NDArray[np.uint32], ValueError]]]] = [
        None
    ] * 16

    def closure(i: int, b: threading.Barrier) -> None:
        verts = np.array([[0, 0], [1, 0], [1, 1]], dtype=np.float32).reshape(-1, 2)

        # Even threads: valid input, Odd threads: invalid input
        if i % 2 == 0:
            rings = np.array([3])
        else:
            rings = np.array([5])  # Invalid

        _ = b.wait()
        try:
            result = earcut.triangulate_float32(verts, rings)
            results[i] = ("success", result)
        except ValueError as e:
            results[i] = ("error", e)

    run_threaded(
        closure, num_threads=16, pass_barrier=True, pass_count=True, outer_iterations=5
    )

    # Verify results match expectations
    for i, result in enumerate(results):
        assert result is not None
        status, value = result
        if i % 2 == 0:
            assert status == "success", f"Thread {i} should have succeeded"
            assert isinstance(value, np.ndarray)
            assert value.shape == (3,)
        else:
            assert status == "error", f"Thread {i} should have raised error"
            assert isinstance(value, ValueError)


# Helper functions


def is_free_threaded() -> bool:
    """Check if Python is running with free-threading enabled."""
    return getattr(sys, "_is_gil_enabled", lambda: True)() is False


pytestmark = pytest.mark.skipif(
    not is_free_threaded(),
    reason="Thread safety tests are most relevant for free-threaded Python",
)