Debian Codegraph @

tests/test_free_threading.py

raw ◀ ▶
1 Debian patch touch this file
1 import gc
2 import os
3 import select
4 import sys
5 import sysconfig
6 import threading
7 import time
8 import weakref
9
10 import pytest
11
12 import caio
13 from caio import python_aio
14
15 # os.open() defaults to text mode on Windows without this - \n <-> \r\n
16 # translation would corrupt any payload containing a raw \n byte.
17 _O_BINARY = getattr(os, "O_BINARY", 0)
18
19
20 def test_importing_caio_does_not_enable_gil():
21 """Every importable C backend must declare and support free threading."""
22 if not sysconfig.get_config_var("Py_GIL_DISABLED"):
23 pytest.skip("not a free-threaded build")
24 assert sys._is_gil_enabled() is False, (
25 "importing caio enabled the GIL; at least one C extension has not "
26 "declared free-threading support"
27 )
28
29
30 def test_high_concurrency_stress_no_data_races(tmp_path, submit_and_wait):
31 """Hammers python_aio's own bookkeeping (the _lock-protected
32 _in_progress counter and per-operation in_progress flag) with many
33 concurrent writes then reads dispatched across a real multi-worker
34 ThreadPool. Under a free-threaded interpreter these workers can run
35 truly in parallel instead of being serialized by the GIL, so a race in
36 that bookkeeping - two workers claiming the same slot, a result
37 crossing over to the wrong Operation - would show up here as a lost
38 write or a chunk read back with the wrong content, not just a
39 thread-timing fluke."""
40 count = 200
41 chunk = 4096
42 path = tmp_path / "stress.bin"
43 path.write_bytes(b"\x00" * (count * chunk))
44 fd = os.open(str(path), os.O_RDWR | _O_BINARY)
45 ctx = None
46 try:
•47 ctx = python_aio.Context(max_requests=count, pool_size=8)
48 expected = [bytes([i % 256]) * chunk for i in range(count)]
49
50 writes = (
51 python_aio.Operation.write(payload, fd, index * chunk)
52 for index, payload in enumerate(expected)
53 )
54 written = submit_and_wait(ctx, writes)
55 assert written == [chunk] * count
56
57 reads = (
58 python_aio.Operation.read(chunk, fd, index * chunk)
59 for index in range(count)
60 )
61 read_back = submit_and_wait(
62 ctx,
63 reads,
64 result_for=lambda operation, _result: operation.get_value(),
65 )
66 assert read_back == expected
67 finally:
68 os.close(fd)
69 if ctx is not None:
70 ctx.close()
71
72
73 def test_same_operation_is_claimed_once_across_contexts(workers):
74 """An Operation's one-shot claim must be synchronized by the Operation.
75
76 Context._execute() currently protects ``operation.in_progress`` with the
77 Context's lock. That only serializes submissions through the *same*
78 Context: two Contexts use two unrelated locks and can both observe False
79 before either stores True when the GIL is disabled.
80
81 Synchronizing each pair of submissions makes the race frequent enough to
82 be a useful regression test without depending on filesystem timing.
83 """
84 if getattr(sys, "_is_gil_enabled", lambda: True)():
85 pytest.skip("requires a free-threaded interpreter with the GIL disabled")
86
87 iterations = 20_000
88 contexts = (
89 python_aio.Context(max_requests=iterations * 2),
90 python_aio.Context(max_requests=iterations * 2),
91 )
92 start = workers.barrier(3)
93 finished = workers.barrier(3)
94 current = [None]
95 submitted = [0, 0]
96
97 def submitter(index, context):
98 for _ in range(iterations):
99 start.wait()
100 submitted[index] += context.submit(current[0])
101 finished.wait()
102
103 try:
104 workers.start_many(submitter, enumerate(contexts))
105
106 for _ in range(iterations):
107 current[0] = python_aio.Operation(
108 0, None, None, python_aio.OpCode.NOOP,
109 )
110 start.wait()
111 finished.wait()
112
113 workers.join()
114 assert sum(submitted) == iterations, (
115 f"{sum(submitted) - iterations} Operations were submitted twice"
116 )
117 finally:
118 workers.close()
119 for context in contexts:
120 context.close()
121 context.pool.join()
122
123
124 def _require_gil_disabled():
125 if getattr(sys, "_is_gil_enabled", lambda: True)():
126 pytest.skip("requires a free-threaded interpreter with the GIL disabled")
127
128
129 def _pump_contexts(contexts, predicate, timeout=10):
130 deadline = time.monotonic() + timeout
131 while not predicate():
132 if time.monotonic() >= deadline:
133 raise TimeoutError("contexts did not complete in time")
134 for context in contexts:
135 if hasattr(context, "flush"):
136 context.flush()
137 for context in contexts:
138 if hasattr(context, "process_events"):
139 context.process_events()
140 time.sleep(0.001)
141
142
143 def _close_contexts(contexts):
144 for context in contexts:
145 close = getattr(context, "close", None)
146 if close is not None:
147 close()
148 for context in contexts:
149 pool = getattr(context, "pool", None)
150 if pool is not None:
151 pool.join()
152
153
154 @pytest.fixture(
155 params=[2, 4, 8, 16, 32],
156 ids=lambda value: f"submitters={value}",
157 )
158 def ft_submitter_count(request):
159 return request.param
160
161
162 @pytest.fixture(params=[1, 3, 17, 64], ids=lambda value: f"batch={value}")
163 def ft_operations_per_submit(request):
164 return request.param
165
166
167 @pytest.fixture(params=[1, 8], ids=lambda value: f"submit-rounds={value}")
168 def ft_submit_rounds(request):
169 return request.param
170
171
172 @pytest.fixture(params=[2, 4, 8], ids=lambda value: f"claimants={value}")
173 def ft_claimant_count(request):
174 return request.param
175
176
177 @pytest.fixture(
178 params=[257, 4_096, 20_000],
179 ids=lambda value: f"claims={value}",
180 )
181 def ft_claim_operation_count(request):
182 return request.param
183
184
185 @pytest.fixture(
186 params=[63, 256, 4_096],
187 ids=lambda value: f"operations={value}",
188 )
189 def ft_operation_count(request):
190 return request.param
191
192
193 @pytest.fixture(
194 params=[2, 4, 8, 16],
195 ids=lambda value: f"drainers={value}",
196 )
197 def ft_drainer_count(request):
198 return request.param
199
200
201 @pytest.fixture(params=[1, 3, 8, 32], ids=lambda value: f"rounds={value}")
202 def ft_drain_rounds(request):
203 return request.param
204
205
206 @pytest.fixture(params=[2, 8, 16], ids=lambda value: f"readers={value}")
207 def ft_reader_count(request):
208 return request.param
209
210
211 @pytest.fixture(params=[1, 257, 2_000], ids=lambda value: f"reads={value}")
212 def ft_reads_per_thread(request):
213 return request.param
214
215
216 @pytest.fixture(params=[2, 8, 16], ids=lambda value: f"observers={value}")
217 def ft_observer_count(request):
218 return request.param
219
220
221 @pytest.fixture(
222 params=[257, 2_000],
223 ids=lambda value: f"completions={value}",
224 )
225 def ft_completion_count(request):
226 return request.param
227
228
229 @pytest.fixture(params=[2, 8, 32], ids=lambda value: f"setters={value}")
230 def ft_callback_setter_count(request):
231 return request.param
232
233
234 @pytest.fixture(params=[1, 257, 2_000], ids=lambda value: f"sets={value}")
235 def ft_callback_sets_per_thread(request):
236 return request.param
237
238
239 @pytest.fixture(params=[2, 8, 32], ids=lambda value: f"cancellers={value}")
240 def ft_canceller_count(request):
241 return request.param
242
243
244 @pytest.fixture(params=[1, 8, 64], ids=lambda value: f"cancel-rounds={value}")
245 def ft_cancel_rounds(request):
246 return request.param
247
248
249 def test_same_operation_is_claimed_once_across_contexts_all_backends(
250 tmp_path,
251 backend,
252 ft_claimant_count,
253 ft_claim_operation_count,
254 workers,
255 ):
256 """Every backend must synchronize a one-shot claim on the Operation.
257
258 This is deliberately separate from the more aggressive python_aio test
259 above: it only uses the shared public API, so future free-threading C
260 backends run exactly the same cross-Context race.
261 """
262 _require_gil_disabled()
263
264 iterations = ft_claim_operation_count
265 claim_window = min(iterations, 512)
266 path = tmp_path / "cross-context-claim.bin"
267 fd = os.open(path, os.O_RDWR | os.O_CREAT | _O_BINARY, 0o600)
268 contexts = tuple(
269 backend.Context(max_requests=claim_window)
270 for _ in range(ft_claimant_count)
271 )
272 start = workers.barrier(ft_claimant_count + 1)
273 finished = workers.barrier(ft_claimant_count + 1)
274 current = [None]
275 submitted = [0] * ft_claimant_count
276 callback_count = [0]
277 callback_lock = threading.Lock()
278
279 def on_done(_result):
280 with callback_lock:
281 callback_count[0] += 1
282
283 def submitter(index, context):
284 for _ in range(iterations):
285 start.wait()
286 submitted[index] += context.submit(current[0])
287 finished.wait()
288
289 try:
290 workers.start_many(submitter, enumerate(contexts))
291
292 for iteration in range(iterations):
293 operation = backend.Operation.write(b"x", fd, 0)
294 operation.set_callback(on_done)
295 current[0] = operation
296 start.wait()
297 finished.wait()
298 if (iteration + 1) % claim_window == 0:
299 expected_callbacks = sum(submitted)
300
301 def window_finished(expected=expected_callbacks):
302 with callback_lock:
303 return callback_count[0] >= expected
304
305 _pump_contexts(
306 contexts,
307 window_finished,
308 timeout=20,
309 )
310
311 workers.join()
312 accepted = sum(submitted)
313
314 def all_callbacks_finished():
315 with callback_lock:
316 return callback_count[0] >= accepted
317
318 _pump_contexts(
319 contexts,
320 all_callbacks_finished,
321 timeout=20,
322 )
323 assert accepted == iterations, (
324 f"{accepted - iterations} Operations were submitted twice"
325 )
326 assert callback_count[0] == iterations
327 finally:
328 workers.close()
329 _close_contexts(contexts)
330 os.close(fd)
331
332
333 def test_concurrent_submits_to_one_context_all_backends(
334 tmp_path,
335 backend,
336 ft_submitter_count,
337 ft_operations_per_submit,
338 ft_submit_rounds,
339 workers,
340 ):
341 """Distinct Operations submitted concurrently must not corrupt Context."""
342 _require_gil_disabled()
343
344 worker_count = ft_submitter_count
345 operations_per_worker = ft_operations_per_submit
346 submit_rounds = ft_submit_rounds
347 operations_per_worker_total = operations_per_worker * submit_rounds
348 total = worker_count * operations_per_worker_total
349 path = tmp_path / "one-context-submit.bin"
350 fd = os.open(path, os.O_RDWR | os.O_CREAT | _O_BINARY, 0o600)
351 context = backend.Context(max_requests=total)
352 submit_start = workers.barrier(worker_count)
353 operations = []
354 callback_results = [None] * total
355 callback_lock = threading.Lock()
356 submitted = [0] * worker_count
357
358 def make_callback(index, operation):
359 def callback(result):
360 with callback_lock:
361 callback_results[index] = (result, operation.get_value())
362 return callback
363
364 for index in range(total):
365 payload = index.to_bytes(4, "little")
366 operation = backend.Operation.write(payload, fd, index * 4)
367 operation.set_callback(make_callback(index, operation))
368 operations.append(operation)
369
370 def submitter(worker_index):
371 first = worker_index * operations_per_worker_total
372 accepted = 0
373 for round_index in range(submit_rounds):
374 batch_first = first + round_index * operations_per_worker
375 batch_last = batch_first + operations_per_worker
376 # Every round stages a batch after the same barrier. Multiple
377 # rounds vary scheduling and repeatedly collide inside the
378 # Context's SQ-tail read/write window.
379 submit_start.wait()
380 accepted += context.submit(
381 *operations[batch_first:batch_last],
382 )
383 submitted[worker_index] = accepted
384
385 try:
386 workers.start_many(
387 submitter,
388 ((index,) for index in range(worker_count)),
389 )
390 workers.join()
391
392 assert sum(submitted) == total
393
394 def all_callbacks_finished():
395 with callback_lock:
396 return all(
397 result is not None
398 for result in callback_results
399 )
400
401 _pump_contexts(
402 (context,),
403 all_callbacks_finished,
404 timeout=20,
405 )
406 assert callback_results == [(4, 4)] * total
407
408 os.lseek(fd, 0, os.SEEK_SET)
409 expected = b"".join(index.to_bytes(4, "little") for index in range(total))
410 assert os.read(fd, len(expected)) == expected
411 finally:
412 workers.close()
413 _close_contexts((context,))
414 os.close(fd)
415
416
417 def test_concurrent_process_events_delivers_each_completion_once(
418 tmp_path,
419 polling_backend,
420 ft_operation_count,
421 ft_drainer_count,
422 ft_drain_rounds,
423 workers,
424 ):
425 """Concurrent drainers must never consume or callback one event twice."""
426 _require_gil_disabled()
427
428 operation_count = ft_operation_count
429 drainer_count = ft_drainer_count
430 drain_rounds = ft_drain_rounds
431 path = tmp_path / "concurrent-process-events.bin"
432 fd = os.open(path, os.O_RDWR | os.O_CREAT | _O_BINARY, 0o600)
433 context = polling_backend.Context(max_requests=operation_count)
434 callback_counts = [0] * operation_count
435 callback_lock = threading.Lock()
436 drain_round = workers.barrier(drainer_count)
437
438 def make_callback(index):
439 def callback(_result):
440 with callback_lock:
441 callback_counts[index] += 1
442 return callback
443
444 operations = []
445 for index in range(operation_count):
446 operation = polling_backend.Operation.write(b"x", fd, index)
447 operation.set_callback(make_callback(index))
448 operations.append(operation)
449
450 assert context.submit(*operations) == operation_count
451 is_sqpoll = bool(getattr(context, "sqpoll", False))
452 if hasattr(context, "flush"):
453 context.flush()
454 if is_sqpoll:
455 with callback_lock:
456 completed_inline = sum(callback_counts)
457 if completed_inline < operation_count:
458 # flush() above wakes a sleeping SQPOLL thread and may drain
459 # already-ready CQEs. If work remains, wait until eventfd says
460 # the kernel has populated more of the CQ, but leave that CQ
461 # untouched for the synchronized drainers below.
462 readable, _, _ = select.select([context.fileno], [], [], 10)
463 assert readable, "SQPOLL produced no completion notification"
464 time.sleep(0.01)
465
466 def drain():
467 for _ in range(drain_rounds):
468 # Force all drainers to enter every round together. Without
469 # this barrier a fast first thread can consume the whole CQ
470 # before the others even start, accidentally serializing the
471 # test and hiding a duplicate cq_head read/commit.
472 drain_round.wait()
473 context.process_events(
474 max_requests=operation_count,
475 min_requests=0,
476 timeout=0,
477 )
478
479 try:
480 workers.start_many(drain, (() for _ in range(drainer_count)))
481 workers.join()
482
483 def all_callbacks_finished():
484 with callback_lock:
485 return sum(callback_counts) >= operation_count
486
487 # Fixed synchronized rounds should normally drain everything. Finish
488 # any genuinely late kernel completions serially so the assertion
489 # below diagnoses duplicate delivery, not storage latency.
490 _pump_contexts((context,), all_callbacks_finished, timeout=20)
491 assert callback_counts == [1] * operation_count
492 finally:
493 workers.close()
494 os.close(fd)
495
496
497 def test_completed_operation_supports_concurrent_readers(
498 tmp_path,
499 backend,
500 ft_reader_count,
501 ft_reads_per_thread,
502 workers,
503 ):
504 """C backends must safely return owned result references to all threads."""
505 _require_gil_disabled()
506
507 payload = bytes(range(256)) * 16
508 path = tmp_path / "concurrent-result-readers.bin"
509 path.write_bytes(payload)
510 fd = os.open(path, os.O_RDONLY | _O_BINARY)
511 context = backend.Context(max_requests=8)
512 operation = backend.Operation.read(len(payload), fd, 0)
513 completed = threading.Event()
514 operation.set_callback(lambda _result: completed.set())
515 assert context.submit(operation) == 1
516 _pump_contexts((context,), completed.is_set)
517 assert operation.get_value() == payload
518
519 reader_count = ft_reader_count
520 reads_per_thread = ft_reads_per_thread
521 start = workers.barrier(reader_count + 1)
522
523 def read_result():
524 start.wait()
525 for _ in range(reads_per_thread):
526 if operation.get_value() != payload:
527 raise AssertionError("concurrent get_value() returned wrong data")
528
529 try:
530 workers.start_many(read_result, (() for _ in range(reader_count)))
531 start.wait()
532 workers.join()
533 finally:
534 workers.close()
535 _close_contexts((context,))
536 os.close(fd)
537
538
539 def test_payload_access_is_safe_while_worker_publishes_completion(
540 tmp_path,
541 pooled_backend,
542 ft_observer_count,
543 ft_completion_count,
544 workers,
545 ):
546 """Publishing ``done`` must not expose a buffer being cleared concurrently.
547
548 In thread_aio the worker used to release-store ``done = 1`` before
549 acquiring a Python thread state and clearing a completed write's
550 ``py_buffer``. A free-running reader could therefore pass the in-flight
551 check and Py_INCREF the same pointer while the worker Py_DECREFed it.
552 """
553 _require_gil_disabled()
554
555 operation_count = ft_completion_count
556 observer_count = ft_observer_count
557 path = tmp_path / "payload-completion-race.bin"
558 fd = os.open(path, os.O_RDWR | os.O_CREAT | _O_BINARY, 0o600)
559 context = pooled_backend.Context(
560 max_requests=operation_count + 1,
561 pool_size=1,
562 )
563
564 blocker_started = threading.Event()
565 blocker_release = threading.Event()
566 blocker = pooled_backend.Operation.fsync(fd)
567 blocker.set_callback(
568 lambda _result: (
569 blocker_started.set(),
570 blocker_release.wait(30),
571 ),
572 )
573 assert context.submit(blocker) == 1
574 assert blocker_started.wait(10), "worker did not enter blocker callback"
575
576 completed_count = [0]
577 completed_lock = threading.Lock()
578 all_completed = threading.Event()
579 operations = []
580
581 def on_done(_result):
582 # thread_aio publishes done before invoking this callback and clears
583 # the write buffer immediately after it returns. Yielding here makes
584 # observers repeatedly enter payload/get_value in that exact state
585 # and then overlap the buffer's ownership transition.
586 time.sleep(0.001)
587 with completed_lock:
588 completed_count[0] += 1
589 if completed_count[0] == operation_count:
590 all_completed.set()
591
592 for index in range(operation_count):
593 operation = pooled_backend.Operation.write(b"x", fd, index)
594 operation.set_callback(on_done)
595 operations.append(operation)
596
597 assert context.submit(*operations) == operation_count
598
599 observer_start = workers.barrier(observer_count + 1)
600
601 def observe():
602 observer_start.wait()
603 while not all_completed.is_set():
604 for operation in operations:
605 try:
606 payload = operation.payload
607 if payload is not None:
608 bytes(payload)
609 except RuntimeError:
610 pass
611
612 try:
613 operation.get_value()
614 except RuntimeError:
615 pass
616
617 try:
618 workers.start_many(observe, (() for _ in range(observer_count)))
619 observer_start.wait()
620 blocker_release.set()
621 assert all_completed.wait(30), "worker did not finish queued operations"
622 workers.join(timeout=10)
623
624 assert completed_count[0] == operation_count
625 finally:
626 blocker_release.set()
627 workers.close()
628 _close_contexts((context,))
629 os.close(fd)
630
631
632 def test_concurrent_callback_replacement_releases_every_old_callback(
633 backend,
634 ft_callback_setter_count,
635 ft_callback_sets_per_thread,
636 workers,
637 ):
638 """set_callback must atomically replace and release its owned reference."""
639 _require_gil_disabled()
640
641 setter_count = ft_callback_setter_count
642 sets_per_thread = ft_callback_sets_per_thread
643 operation = backend.Operation.fsync(0)
644 start = workers.barrier(setter_count + 1)
645
646 class Callback:
647 def __call__(self, _result):
648 return None
649
650 callbacks = [
651 Callback()
652 for _ in range(setter_count * sets_per_thread)
653 ]
654 callback_refs = [weakref.ref(callback) for callback in callbacks]
655
656 def replace_callbacks(thread_index):
657 start.wait()
658 first = thread_index * sets_per_thread
659 for index in range(first, first + sets_per_thread):
660 assert operation.set_callback(callbacks[index]) is True
661
662 try:
663 workers.start_many(
664 replace_callbacks,
665 ((index,) for index in range(setter_count)),
666 )
667 start.wait()
668 workers.join()
669
670 # Move the Operation off every callback in the contested set. Each
671 # set_callback owns exactly one reference and must release the old
672 # one, even when several threads replace the same slot concurrently.
673 operation.set_callback(Callback())
674 callbacks.clear()
675 gc.collect()
676 leaked = sum(ref() is not None for ref in callback_refs)
677 assert leaked == 0, f"{leaked} replaced callbacks are still referenced"
678 finally:
679 workers.close()
680
681
682 def test_concurrent_uring_cancel_requests_do_not_corrupt_submission_ring(
683 ft_canceller_count,
684 ft_cancel_rounds,
685 workers,
686 ):
687 """cancel and submit share io_uring's SQ tail and must share its lock."""
688 _require_gil_disabled()
689 if caio.linux_uring is None:
690 pytest.skip("linux_uring backend is unavailable")
691
692 canceller_count = ft_canceller_count
693 cancel_rounds = ft_cancel_rounds
694 operation_count = canceller_count * cancel_rounds
695 context = caio.linux_uring.Context(
696 max_requests=operation_count * 2,
697 sqpoll=False,
698 )
699 read_fd, write_fd = os.pipe()
700 callback_counts = [0] * operation_count
701 callback_lock = threading.Lock()
702
703 def make_callback(index):
704 def callback(_result):
705 with callback_lock:
706 callback_counts[index] += 1
707 return callback
708
709 targets = [
710 caio.linux_uring.Operation.read(
711 1,
712 read_fd,
713 (1 << 64) - 1,
714 )
715 for _ in range(operation_count)
716 ]
717 for index, operation in enumerate(targets):
718 operation.set_callback(make_callback(index))
719 assert context.submit(*targets) == operation_count
720 context.flush()
721
722 start_round = workers.barrier(canceller_count)
723 cancelled = [0] * canceller_count
724
725 def cancel(thread_index):
726 for round_index in range(cancel_rounds):
727 start_round.wait()
728 cancelled[thread_index] += context.cancel(
729 targets[round_index * canceller_count + thread_index],
730 )
731
732 try:
733 workers.start_many(
734 cancel,
735 ((index,) for index in range(canceller_count)),
736 )
737 workers.join()
738
739 assert cancelled == [0] * canceller_count
740
741 def all_targets_completed():
742 with callback_lock:
743 return sum(callback_counts) >= operation_count
744
745 _pump_contexts((context,), all_targets_completed, timeout=10)
746 assert callback_counts == [1] * operation_count
747 finally:
748 workers.close()
749 # Release any read whose cancel SQE was lost so Context teardown
750 # cannot leave the kernel holding pointers to live Operations.
751 try:
752 os.write(write_fd, b"x" * operation_count)
753 _pump_contexts(
754 (context,),
755 lambda: sum(callback_counts) >= operation_count,
756 timeout=5,
757 )
758 except (BrokenPipeError, TimeoutError):
759 pass
760 os.close(write_fd)
761 os.close(read_fd)