| 1 |
""" |
| 2 |
Tests against the raw Context/Operation API directly, bypassing the |
| 3 |
asyncio adapter - this is a real, documented part of the public API |
| 4 |
(see e.g. caio/linux_uring.pyi), and it's also where backend-specific |
| 5 |
low-level behavior (polling, queue capacity, cancellation) actually lives. |
| 6 |
Not every backend exposes the same surface here (only linux_aio and |
| 7 |
linux_uring have process_events/poll; only linux_uring also has flush), |
| 8 |
so most tests below are conditional on hasattr() rather than assuming a |
| 9 |
uniform API. |
| 10 |
""" |
| 11 |
import gc |
| 12 |
import os |
| 13 |
import re |
| 14 |
import subprocess |
| 15 |
import sys |
| 16 |
import threading |
| 17 |
import time |
| 18 |
import weakref |
| 19 |
|
| 20 |
import pytest |
| 21 |
from conftest import drain |
| 22 |
|
| 23 |
ABSURD_NBYTES = 2**62 |
| 24 |
|
| 25 |
|
| 26 |
def test_raw_submit_and_drain(tmp_path, polling_backend): |
| 27 |
with open(str(tmp_path / "temp.bin"), "wb+") as f: |
| 28 |
fd = f.fileno() |
| 29 |
ctx = polling_backend.Context(max_requests=8) |
| 30 |
|
| 31 |
ops = [ |
| 32 |
polling_backend.Operation.write(bytes([i]) * 4, fd, i * 4) |
| 33 |
for i in range(4) |
| 34 |
] |
| 35 |
submitted = ctx.submit(*ops) |
| 36 |
assert submitted == 4 |
| 37 |
|
| 38 |
processed = drain(ctx, 4) |
| 39 |
assert processed == 4 |
| 40 |
for op in ops: |
| 41 |
assert op.get_value() == 4 |
| 42 |
|
| 43 |
read_ops = [ |
| 44 |
polling_backend.Operation.read(4, fd, i * 4) for i in range(4) |
| 45 |
] |
| 46 |
ctx.submit(*read_ops) |
| 47 |
drain(ctx, 4) |
| 48 |
for i, op in enumerate(read_ops): |
| 49 |
assert op.get_value() == bytes([i]) * 4 |
| 50 |
|
| 51 |
|
| 52 |
def test_raw_process_events_respects_min_max(tmp_path, polling_backend): |
| 53 |
with open(str(tmp_path / "temp.bin"), "wb+") as f: |
| 54 |
fd = f.fileno() |
| 55 |
ctx = polling_backend.Context(max_requests=8) |
| 56 |
|
| 57 |
with pytest.raises(ValueError): |
| 58 |
ctx.process_events(max_requests=1, min_requests=5) |
| 59 |
|
| 60 |
op = polling_backend.Operation.write(b"x", fd, 0) |
| 61 |
ctx.submit(op) |
| 62 |
drain(ctx, 1) |
| 63 |
assert op.get_value() == 1 |
| 64 |
|
| 65 |
|
| 66 |
def test_process_events_respects_timeout_and_releases_gil(polling_backend): |
| 67 |
"""process_events(min_requests=N, timeout=T) must give up after |
| 68 |
roughly `timeout` seconds if fewer than N completions ever show up, |
| 69 |
rather than blocking indefinitely - and must release the GIL while |
| 70 |
waiting, not freeze the whole interpreter for the duration. |
| 71 |
|
| 72 |
Runs in a subprocess with its own `timeout=`, so if this regresses to |
| 73 |
an unbounded, GIL-held block, the subprocess gets killed at the OS |
| 74 |
level instead of hanging the whole test session. |
| 75 |
|
| 76 |
Submits nothing at all, so min_requests=1 can never be satisfied, and |
| 77 |
checks two things at once inside the subprocess: wall time is bounded |
| 78 |
by roughly `timeout` (whole seconds), and a second thread *inside that |
| 79 |
same subprocess* keeps making progress while the call is blocked - |
| 80 |
proving the GIL was actually released, not just that the call happened |
| 81 |
to return quickly for some other reason. |
| 82 |
""" |
| 83 |
if not polling_backend.__name__.startswith("caio."): |
| 84 |
pytest.skip("synthetic test-only variant, not importable by name in a subprocess") |
| 85 |
|
| 86 |
code = ( |
| 87 |
"import threading, time\n" |
| 88 |
f"import {polling_backend.__name__} as m\n" |
| 89 |
"ctx = m.Context(max_requests=8)\n" |
| 90 |
"progress = []\n" |
| 91 |
"stop = threading.Event()\n" |
| 92 |
"def other_thread():\n" |
| 93 |
" while not stop.is_set():\n" |
| 94 |
" progress.append(time.monotonic())\n" |
| 95 |
" time.sleep(0.01)\n" |
| 96 |
"t = threading.Thread(target=other_thread, daemon=True)\n" |
| 97 |
"t.start()\n" |
| 98 |
"start = time.monotonic()\n" |
| 99 |
"n = ctx.process_events(max_requests=8, min_requests=1, timeout=1)\n" |
| 100 |
"elapsed = time.monotonic() - start\n" |
| 101 |
"stop.set()\n" |
| 102 |
"t.join(timeout=2.0)\n" |
| 103 |
"print(f'RESULT: n={n} elapsed={elapsed} progress={len(progress)}')\n" |
| 104 |
) |
| 105 |
try: |
| 106 |
proc = subprocess.run( |
| 107 |
[sys.executable, "-c", code], |
| 108 |
capture_output=True, text=True, timeout=15, check=False, |
| 109 |
) |
| 110 |
except subprocess.TimeoutExpired: |
| 111 |
pytest.fail("process_events(timeout=1) blocked far longer than its own timeout (subprocess timed out)") |
| 112 |
|
| 113 |
match = re.search(r"RESULT: n=(\d+) elapsed=([\d.]+) progress=(\d+)", proc.stdout) |
| 114 |
assert match, f"unexpected output; stdout={proc.stdout!r} stderr={proc.stderr!r}" |
| 115 |
n, elapsed, progress = int(match[1]), float(match[2]), int(match[3]) |
| 116 |
|
| 117 |
assert n == 0 |
| 118 |
assert elapsed < 5.0, f"process_events(timeout=1) took {elapsed:.1f}s - timeout was ignored" |
| 119 |
assert progress >= 3, ( |
| 120 |
"a second thread made too little progress while process_events() was " |
| 121 |
"blocked - the GIL was probably held throughout instead of released" |
| 122 |
) |
| 123 |
|
| 124 |
|
| 125 |
def test_raw_poll_reflects_completions(tmp_path, polling_backend): |
| 126 |
with open(str(tmp_path / "temp.bin"), "wb+") as f: |
| 127 |
fd = f.fileno() |
| 128 |
ctx = polling_backend.Context(max_requests=8) |
| 129 |
op = polling_backend.Operation.write(b"hi", fd, 0) |
| 130 |
ctx.submit(op) |
| 131 |
|
| 132 |
# poll() drains the eventfd counter, so it must not be called |
| 133 |
# speculatively before we know it's signaled (it's a blocking fd) - |
| 134 |
# only call it once flush()/process_events() has confirmed there's |
| 135 |
# something to report. |
| 136 |
drain(ctx, 1) |
| 137 |
assert op.get_value() == 2 |
| 138 |
|
| 139 |
|
| 140 |
def test_poll_does_not_block_when_nothing_pending(polling_backend): |
| 141 |
"""poll() with nothing actually pending must raise BlockingIOError, as |
| 142 |
documented, rather than block the calling thread. Runs in a subprocess, |
| 143 |
killed via subprocess.run's own `timeout` (real OS-level termination) |
| 144 |
if it hangs - a background thread can't safely stand in for this check |
| 145 |
here, since poll() doesn't release the GIL, so a thread stuck inside it |
| 146 |
would hold the GIL hostage forever regardless of what the test's own |
| 147 |
main thread does. |
| 148 |
""" |
| 149 |
if not polling_backend.__name__.startswith("caio."): |
| 150 |
pytest.skip("synthetic test-only variant, not importable by name in a subprocess") |
| 151 |
|
| 152 |
code = ( |
| 153 |
f"import {polling_backend.__name__} as m\n" |
| 154 |
f"ctx = m.Context(max_requests=8)\n" |
| 155 |
f"try:\n" |
| 156 |
f" ctx.poll()\n" |
| 157 |
f" print('RESULT: unexpectedly-returned')\n" |
| 158 |
f"except BlockingIOError:\n" |
| 159 |
f" print('RESULT: raised BlockingIOError')\n" |
| 160 |
) |
| 161 |
try: |
| 162 |
proc = subprocess.run( |
| 163 |
[sys.executable, "-c", code], |
| 164 |
capture_output=True, text=True, timeout=10, check=False, |
| 165 |
) |
| 166 |
except subprocess.TimeoutExpired: |
| 167 |
pytest.fail("poll() blocked instead of raising BlockingIOError (subprocess timed out)") |
| 168 |
|
| 169 |
assert "RESULT: raised BlockingIOError" in proc.stdout, ( |
| 170 |
f"stdout={proc.stdout!r} stderr={proc.stderr!r}" |
| 171 |
) |
| 172 |
|
| 173 |
|
| 174 |
def test_payload_and_get_value_blocked_while_in_flight(tmp_path, polling_backend): |
| 175 |
"""payload/get_value() must refuse to return an operation's buffer |
| 176 |
while the kernel may still be actively writing into it - for |
| 177 |
linux_uring in particular, that buffer is the *same* Python bytes |
| 178 |
object the kernel writes into directly (zero-copy), so handing it out |
| 179 |
mid-flight would mean observing (or even, via `hash()`, corrupting the |
| 180 |
cached hash of) a nominally-immutable object while it's still being |
| 181 |
mutated. For linux_aio the read buffer is wrapped in a Mutex, but the |
| 182 |
kernel doesn't know about that lock, so reading through it mid-flight |
| 183 |
is still a data race, just a narrower one (torn reads instead of a |
| 184 |
shared identity issue). |
| 185 |
|
| 186 |
No timing race needed: `submit()` sets its own in-flight bookkeeping |
| 187 |
synchronously (for linux_uring, even before the SQE reaches the |
| 188 |
kernel via flush()), and it's only cleared once *this process* handles |
| 189 |
the completion via process_events()/flush() - regardless of how fast |
| 190 |
the kernel itself actually finishes the write. |
| 191 |
""" |
| 192 |
with open(str(tmp_path / "temp.bin"), "wb+") as f: |
| 193 |
fd = f.fileno() |
| 194 |
ctx = polling_backend.Context(max_requests=8) |
| 195 |
op = polling_backend.Operation.write(b"hello", fd, 0) |
| 196 |
ctx.submit(op) |
| 197 |
|
| 198 |
with pytest.raises(RuntimeError): |
| 199 |
_ = op.payload |
| 200 |
with pytest.raises(RuntimeError): |
| 201 |
_ = op.get_value() |
| 202 |
|
| 203 |
drain(ctx, 1) |
| 204 |
|
| 205 |
# Once actually completed, both must work normally again. |
| 206 |
assert op.get_value() == 5 |
| 207 |
assert bytes(op.payload) == b"hello" |
| 208 |
|
| 209 |
|
| 210 |
def test_thread_aio_payload_and_get_value_blocked_while_in_flight(tmp_path): |
| 211 |
"""thread_aio only: same contract as |
| 212 |
test_payload_and_get_value_blocked_while_in_flight above, but this |
| 213 |
backend has no process_events()/poll() split to hook a synchronous |
| 214 |
in-flight check onto - completion is purely callback-driven, and its |
| 215 |
worker() thread runs the actual pread()/pwrite() syscall without |
| 216 |
holding the GIL, so payload/get_value() reading result/buf_size/error |
| 217 |
concurrently from the submitting thread is a genuine, unsynchronized |
| 218 |
data race, not just a narrow window. |
| 219 |
|
| 220 |
No timing race needed here either: pool_size=1 plus a first |
| 221 |
operation whose own callback blocks (on blocker_release) makes the |
| 222 |
single worker thread provably still busy with it - so a second |
| 223 |
operation submitted right after is provably still queued, never |
| 224 |
touched by the worker, when the assertions below run. |
| 225 |
""" |
| 226 |
thread_aio = pytest.importorskip("caio.thread_aio") |
| 227 |
|
| 228 |
with open(str(tmp_path / "temp.bin"), "wb+") as f: |
| 229 |
fd = f.fileno() |
| 230 |
ctx = thread_aio.Context(max_requests=8, pool_size=1) |
| 231 |
|
| 232 |
blocker_started = threading.Event() |
| 233 |
blocker_release = threading.Event() |
| 234 |
|
| 235 |
blocker_op = thread_aio.Operation.fsync(fd) |
| 236 |
blocker_op.set_callback( |
| 237 |
lambda r: (blocker_started.set(), blocker_release.wait(5.0)), |
| 238 |
) |
| 239 |
ctx.submit(blocker_op) |
| 240 |
assert blocker_started.wait(5.0), "blocker operation's callback never ran" |
| 241 |
|
| 242 |
op = thread_aio.Operation.write(b"hello", fd, 0) |
| 243 |
op_done = threading.Event() |
| 244 |
op.set_callback(lambda r: op_done.set()) |
| 245 |
ctx.submit(op) |
| 246 |
|
| 247 |
with pytest.raises(RuntimeError): |
| 248 |
_ = op.payload |
| 249 |
with pytest.raises(RuntimeError): |
| 250 |
_ = op.get_value() |
| 251 |
|
| 252 |
blocker_release.set() |
| 253 |
assert op_done.wait(5.0), "operation never completed after unblocking the pool" |
| 254 |
|
| 255 |
# Once actually completed, both must work normally again. |
| 256 |
assert op.get_value() == 5 |
| 257 |
assert op.payload is None # thread_aio frees a write's payload on completion |
| 258 |
|
| 259 |
|
| 260 |
def test_read_with_absurd_nbytes_raises_cleanly(backend): |
| 261 |
"""Operation.read() with an unreasonably large nbytes must raise a |
| 262 |
catchable exception, never crash the process. A naive allocation |
| 263 |
strategy for a size this large doesn't just panic (which PyO3 would |
| 264 |
convert to a catchable PanicException) - it can *abort the whole |
| 265 |
process* (SIGABRT) via Rust's global alloc-error handler, which is not |
| 266 |
recoverable from Python at all. Runs in a subprocess since a real |
| 267 |
abort would otherwise take the whole test session down with it. |
| 268 |
|
| 269 |
python_aio doesn't preallocate a buffer at construction time (nbytes is |
| 270 |
just stored, the real buffer is sized lazily from whatever the actual |
| 271 |
read returns), so it was never at risk here and is skipped. |
| 272 |
""" |
| 273 |
if backend.__name__ == "caio.python_aio": |
| 274 |
pytest.skip("python_aio doesn't preallocate at construction time") |
| 275 |
if not backend.__name__.startswith("caio."): |
| 276 |
pytest.skip("synthetic test-only variant, not importable by name in a subprocess") |
| 277 |
|
| 278 |
code = ( |
| 279 |
f"import {backend.__name__} as m\n" |
| 280 |
f"try:\n" |
| 281 |
f" m.Operation.read({ABSURD_NBYTES}, 0, 0)\n" |
| 282 |
f" print('RESULT: unexpectedly-succeeded')\n" |
| 283 |
f"except (OverflowError, MemoryError, ValueError) as e:\n" |
| 284 |
f" print(f'RESULT: raised {{type(e).__name__}}')\n" |
| 285 |
) |
| 286 |
proc = subprocess.run( |
| 287 |
[sys.executable, "-c", code], |
| 288 |
capture_output=True, text=True, timeout=30, check=False, |
| 289 |
) |
| 290 |
assert proc.returncode == 0, ( |
| 291 |
f"process aborted/crashed (returncode={proc.returncode}); " |
| 292 |
f"stdout={proc.stdout!r} stderr={proc.stderr!r}" |
| 293 |
) |
| 294 |
assert "RESULT: raised" in proc.stdout, ( |
| 295 |
f"expected a catchable exception; stdout={proc.stdout!r} stderr={proc.stderr!r}" |
| 296 |
) |
| 297 |
|
| 298 |
|
| 299 |
@pytest.mark.parametrize("op_count", [1, 4]) |
| 300 |
def test_queue_full_does_not_crash(tmp_path, backend, op_count): |
| 301 |
"""Submitting far beyond a tiny max_requests must never hang or corrupt |
| 302 |
state, but backends genuinely disagree on *how* they signal it: |
| 303 |
|
| 304 |
- thread_aio, linux_uring, python_aio each track capacity themselves |
| 305 |
(a queue/ring/counter checked before any work starts) and raise |
| 306 |
immediately once it's exceeded. |
| 307 |
- linux_aio's capacity is the kernel's own io_context depth. Since |
| 308 |
writes to a regular buffered file usually complete synchronously |
| 309 |
within io_submit() itself (Linux AIO doesn't provide real asynchrony |
| 310 |
for buffered I/O on most filesystems), the "backlog" rarely builds |
| 311 |
up enough to hit that limit - and even when it does, io_submit()'s |
| 312 |
documented behavior is to return fewer than requested rather than |
| 313 |
raise (matching the original C implementation, which just returns |
| 314 |
that count as-is). So for linux_aio this only asserts the |
| 315 |
submitted-count invariant, not an exception. |
| 316 |
|
| 317 |
This test exists to make that difference explicit, not to force one |
| 318 |
"correct" answer.""" |
| 319 |
with open(str(tmp_path / "temp.bin"), "wb+") as f: |
| 320 |
fd = f.fileno() |
| 321 |
ctx = backend.Context(max_requests=op_count) |
| 322 |
|
| 323 |
ops = [ |
| 324 |
backend.Operation.write(b"x", fd, i) |
| 325 |
for i in range(op_count * 64) |
| 326 |
] |
| 327 |
|
| 328 |
if backend.__name__ == "caio.linux_aio": |
| 329 |
submitted = ctx.submit(*ops) |
| 330 |
assert 0 <= submitted <= len(ops) |
| 331 |
else: |
| 332 |
with pytest.raises((OverflowError, RuntimeError, ValueError)): |
| 333 |
ctx.submit(*ops) |
| 334 |
|
| 335 |
# The context must remain safely destructible either way. |
| 336 |
del ctx, ops |
| 337 |
|
| 338 |
|
| 339 |
def test_cancel_on_real_operation_does_not_crash(tmp_path, backend): |
| 340 |
with open(str(tmp_path / "temp.bin"), "wb+") as f: |
| 341 |
fd = f.fileno() |
| 342 |
ctx = backend.Context(max_requests=4) |
| 343 |
op = backend.Operation.read(4096, fd, 0) |
| 344 |
ctx.submit(op) |
| 345 |
|
| 346 |
try: |
| 347 |
result = ctx.cancel(op) |
| 348 |
except (SystemError, RuntimeError, ValueError, NotImplementedError) as e: |
| 349 |
# linux_aio/linux_uring may legitimately report "too late to |
| 350 |
# cancel" or similar as an exception; that's fine, it just |
| 351 |
# must not crash or hang. |
| 352 |
result = e |
| 353 |
|
| 354 |
assert result is not None |
| 355 |
|
| 356 |
# Drain whatever ends up happening to the op (cancelled or raced |
| 357 |
# to completion) so the Context can tear down cleanly. |
| 358 |
if hasattr(ctx, "process_events"): |
| 359 |
try: |
| 360 |
drain(ctx, 1, timeout=2.0) |
| 361 |
except TimeoutError: |
| 362 |
pass |
| 363 |
|
| 364 |
|
| 365 |
def test_linux_aio_operation_context_back_reference_clears_on_completion(tmp_path): |
| 366 |
"""linux_aio only: submit() makes each accepted Operation hold a |
| 367 |
strong reference to its own Context (via the `.context` property) |
| 368 |
while genuinely in flight - so it stays usable (e.g. to call |
| 369 |
`op.context.cancel(op)`) even if the caller drops their own Context |
| 370 |
reference early - but this back-reference is cleared once the |
| 371 |
Operation reaches a terminal state (drained via process_events()/ |
| 372 |
cancel()), not held forever. |
| 373 |
|
| 374 |
Holding it past completion (the original behavior) created an |
| 375 |
uncollectable reference cycle: registry -> Operation -> context -> |
| 376 |
Context -> registry. PyO3 classes don't participate in Python's |
| 377 |
cyclic GC, so once accepted, plain refcounting could never reclaim |
| 378 |
either object even after the operation finished, leaking both Python |
| 379 |
objects and - until something else eventually dropped the Context - |
| 380 |
the underlying kernel AIO context/eventfd too. |
| 381 |
""" |
| 382 |
linux_aio = pytest.importorskip("caio.linux_aio") |
| 383 |
|
| 384 |
with open(str(tmp_path / "temp.bin"), "wb+") as f: |
| 385 |
fd = f.fileno() |
| 386 |
ctx = linux_aio.Context(max_requests=8) |
| 387 |
op = linux_aio.Operation.write(b"x" * 4, fd, 0) |
| 388 |
|
| 389 |
assert ctx.submit(op) == 1 |
| 390 |
assert op.context is ctx |
| 391 |
|
| 392 |
del ctx |
| 393 |
|
| 394 |
# Still alive and fully usable through the Operation's own |
| 395 |
# back-reference while genuinely in flight - dropping the |
| 396 |
# caller's own reference alone must not have torn it down. |
| 397 |
still_alive = op.context |
| 398 |
assert still_alive.max_requests == 8 |
| 399 |
|
| 400 |
drain(still_alive, 1) |
| 401 |
assert op.get_value() == 4 |
| 402 |
|
| 403 |
# Once terminal, nothing needs the back-reference anymore - it's |
| 404 |
# cleared, breaking the cycle. |
| 405 |
assert op.context is None |
| 406 |
|
| 407 |
|
| 408 |
def test_uring_operation_context_back_reference_clears_on_completion(tmp_path): |
| 409 |
"""linux_uring only: same contract as linux_aio's `.context` property |
| 410 |
(see test_linux_aio_operation_context_back_reference_clears_on_completion |
| 411 |
above) - submit() makes each accepted Operation hold a strong |
| 412 |
reference to its own Context while genuinely in flight, cleared once |
| 413 |
the operation reaches a terminal state (drained via |
| 414 |
process_events()/flush()). Without this, a Context the caller drops |
| 415 |
while an operation is still outstanding could be garbage collected |
| 416 |
mid-flight, munmapping the SQ/CQ rings and closing uring_fd while the |
| 417 |
kernel might still be touching them. |
| 418 |
""" |
| 419 |
linux_uring = pytest.importorskip("caio.linux_uring") |
| 420 |
|
| 421 |
with open(str(tmp_path / "temp.bin"), "wb+") as f: |
| 422 |
fd = f.fileno() |
| 423 |
ctx = linux_uring.Context(max_requests=8) |
| 424 |
op = linux_uring.Operation.write(b"x" * 4, fd, 0) |
| 425 |
|
| 426 |
assert ctx.submit(op) == 1 |
| 427 |
assert op.context is ctx |
| 428 |
|
| 429 |
del ctx |
| 430 |
|
| 431 |
still_alive = op.context |
| 432 |
assert still_alive.max_requests == 8 |
| 433 |
|
| 434 |
drain(still_alive, 1) |
| 435 |
assert op.get_value() == 4 |
| 436 |
|
| 437 |
assert op.context is None |
| 438 |
|
| 439 |
|
| 440 |
def test_uring_context_stays_alive_via_operation_while_genuinely_in_flight(tmp_path): |
| 441 |
"""linux_uring only: a Context the caller drops while a submitted |
| 442 |
Operation is genuinely still in flight must not be collected out from |
| 443 |
under it - op.context (see the test above) keeps it alive via plain |
| 444 |
refcounting. Proven here with weakref, independent of the object's |
| 445 |
own repr/attributes: the outstanding write is blocked on a full pipe |
| 446 |
with no reader, so it provably cannot have completed yet when `del |
| 447 |
ctx` runs. Once the pipe is drained and the write actually completes, |
| 448 |
op.context clears and nothing else references the Context, so the |
| 449 |
weakref must clear too. |
| 450 |
""" |
| 451 |
linux_uring = pytest.importorskip("caio.linux_uring") |
| 452 |
import fcntl # Unix-only; this whole test is uring-only (Linux-only) |
| 453 |
|
| 454 |
F_SETPIPE_SZ = 1031 |
| 455 |
|
| 456 |
r_fd, w_fd = os.pipe() |
| 457 |
try: |
| 458 |
fcntl.fcntl(w_fd, F_SETPIPE_SZ, 4096) |
| 459 |
os.write(w_fd, b"f" * 4096) # fill the pipe so the next write blocks until drained |
| 460 |
|
| 461 |
ctx = linux_uring.Context(max_requests=8) |
| 462 |
ctx_ref = weakref.ref(ctx) |
| 463 |
|
| 464 |
# Offset must be -1 (io_uring's convention for non-seekable files, |
| 465 |
# same as plain write(2)) - a pipe rejects an explicit offset |
| 466 |
# outright, which would fail the write instantly instead of |
| 467 |
# leaving it pending. |
| 468 |
op = linux_uring.Operation.write(b"pending", w_fd, 0xFFFFFFFFFFFFFFFF) |
| 469 |
assert ctx.submit(op) == 1 |
| 470 |
|
| 471 |
del ctx |
| 472 |
gc.collect() |
| 473 |
|
| 474 |
assert ctx_ref() is not None, ( |
| 475 |
"Context was collected while its Operation was still genuinely " |
| 476 |
"in flight - op.context should have kept it alive" |
| 477 |
) |
| 478 |
|
| 479 |
os.read(r_fd, 8192) # unblocks the pending write |
| 480 |
drain(ctx_ref(), 1, timeout=5.0) |
| 481 |
assert op.get_value() == len(b"pending") |
| 482 |
|
| 483 |
gc.collect() |
| 484 |
assert ctx_ref() is None, ( |
| 485 |
"Context outlived its Operation's completion - op.context " |
| 486 |
"should have been cleared, leaving nothing to keep it alive" |
| 487 |
) |
| 488 |
finally: |
| 489 |
os.close(r_fd) |
| 490 |
os.close(w_fd) |
| 491 |
|
| 492 |
|
| 493 |
def test_linux_aio_context_becomes_collectible_after_operation_completes(tmp_path): |
| 494 |
"""linux_aio only: keeping a *completed* Operation alive - a common |
| 495 |
pattern, e.g. holding onto it to read `.get_value()` again later - |
| 496 |
must not also keep its Context alive, once the caller has otherwise |
| 497 |
dropped their own Context reference. Disables the cyclic garbage |
| 498 |
collector for the duration of the check so only plain refcounting |
| 499 |
can possibly free the Context: before this fix, `op.context` was |
| 500 |
never cleared on completion, so a completed Operation the caller |
| 501 |
happened to keep around would keep its Context (and the underlying |
| 502 |
kernel AIO context/eventfd) alive indefinitely too, regardless of |
| 503 |
whether the caller still wanted it. |
| 504 |
|
| 505 |
Note this is deliberately not the same scenario as an Operation |
| 506 |
abandoned *before* it ever completes (both external references |
| 507 |
dropped with nothing left to ever drain it) - see |
| 508 |
test_linux_aio_abandoned_operation_is_collectible_by_gc below for |
| 509 |
that one, which plain refcounting alone (as exercised here, with the |
| 510 |
cyclic GC disabled) genuinely cannot free - it needs `gc.collect()`. |
| 511 |
""" |
| 512 |
linux_aio = pytest.importorskip("caio.linux_aio") |
| 513 |
|
| 514 |
gc.disable() |
| 515 |
try: |
| 516 |
with open(str(tmp_path / "temp.bin"), "wb+") as f: |
| 517 |
fd = f.fileno() |
| 518 |
ctx = linux_aio.Context(max_requests=8) |
| 519 |
op = linux_aio.Operation.write(b"x" * 4, fd, 0) |
| 520 |
ctx_ref = weakref.ref(ctx) |
| 521 |
|
| 522 |
assert ctx.submit(op) == 1 |
| 523 |
drain(ctx, 1) |
| 524 |
assert op.get_value() == 4 |
| 525 |
|
| 526 |
del ctx # the caller drops Context... |
| 527 |
|
| 528 |
assert ctx_ref() is None, "Context leaked via a completed Operation's stale back-reference" |
| 529 |
# ...but the completed Operation itself is still perfectly |
| 530 |
# usable, unaffected by its Context having been freed. |
| 531 |
assert op.get_value() == 4 |
| 532 |
finally: |
| 533 |
gc.enable() |
| 534 |
|
| 535 |
|
| 536 |
def test_operation_self_referential_callback_cycle_is_collectible_by_gc(backend): |
| 537 |
"""A callback closure that captures its own Operation (a natural pattern - |
| 538 |
e.g. `op.set_callback(lambda res: op.get_value())` to stash the result |
| 539 |
somewhere) forms a genuine reference cycle: op -> callback -> cell -> op. |
| 540 |
Plain refcounting can never free this on its own - cyclic GC must find and |
| 541 |
break it, via each C backend's Operation now supporting the GC protocol |
| 542 |
(Py_TPFLAGS_HAVE_GC / tp_traverse / tp_clear), same as python_aio's plain |
| 543 |
Python class already did without any extra work. |
| 544 |
|
| 545 |
Unlike test_linux_aio_abandoned_operation_is_collectible_by_gc above, |
| 546 |
this doesn't need a Context at all - the cycle is entirely within the |
| 547 |
Operation object itself, so it's a scenario all four backends can hit, |
| 548 |
not just the two native ones with a `.context` back-reference. |
| 549 |
""" |
| 550 |
def make_cycle(): |
| 551 |
op = backend.Operation.fsync(1) |
| 552 |
op.set_callback(lambda res: op) |
| 553 |
return weakref.ref(op) |
| 554 |
|
| 555 |
gc.disable() |
| 556 |
try: |
| 557 |
op_ref = make_cycle() |
| 558 |
assert op_ref() is not None, ( |
| 559 |
"expected plain refcounting alone to NOT free this cycle - " |
| 560 |
"if it did, this test isn't exercising the scenario it claims to" |
| 561 |
) |
| 562 |
finally: |
| 563 |
gc.enable() |
| 564 |
|
| 565 |
gc.collect() |
| 566 |
assert op_ref() is None, "gc.collect() must break the self-referential callback cycle" |
| 567 |
|
| 568 |
|
| 569 |
def test_resubmission_behavior_is_backend_specific(tmp_path, backend): |
| 570 |
"""All four backends now agree that submit()-ing the same Operation |
| 571 |
object twice back to back, with no drain in between, must silently |
| 572 |
skip the second attempt - none of them will ever hand out two |
| 573 |
concurrent dispatches of the same one-shot Operation: |
| 574 |
|
| 575 |
- thread_aio marks "in_progress" sticky forever (never reset), so a |
| 576 |
second submit() always silently skips it, regardless of timing. |
| 577 |
- linux_uring/linux_aio reset "in_progress" only once the operation |
| 578 |
actually completes; since this test never calls flush() (the only |
| 579 |
thing that hands submitted SQEs to the kernel for linux_uring's |
| 580 |
default, non-SQPOLL mode), the operation cannot possibly have |
| 581 |
completed yet, so the second submit() is deterministically skipped |
| 582 |
here too - otherwise the kernel would end up with two concurrent |
| 583 |
iocbs/SQEs pointing at the same buffer, a real data race for reads. |
| 584 |
- python_aio now has the same in-flight guard as the other three |
| 585 |
(Operation.in_progress, checked/set under Context's own lock). |
| 586 |
|
| 587 |
This test exists to catch any regression in this shared guarantee.""" |
| 588 |
with open(str(tmp_path / "temp.bin"), "wb+") as f: |
| 589 |
fd = f.fileno() |
| 590 |
ctx = backend.Context(max_requests=4) |
| 591 |
op = backend.Operation.write(b"x", fd, 0) |
| 592 |
|
| 593 |
first = ctx.submit(op) |
| 594 |
assert first == 1 |
| 595 |
|
| 596 |
second = ctx.submit(op) |
| 597 |
assert second == 0, "expected sticky/not-yet-completed in-flight state to skip resubmission" |
| 598 |
|
| 599 |
if hasattr(ctx, "process_events"): |
| 600 |
try: |
| 601 |
drain(ctx, first + second, timeout=2.0) |
| 602 |
except TimeoutError: |
| 603 |
pass |
| 604 |
|
| 605 |
|
| 606 |
def test_linux_aio_rejects_concurrent_resubmit(tmp_path): |
| 607 |
"""linux_aio only, complementing test_resubmission_behavior_is_backend_specific |
| 608 |
above: submit() must atomically claim each op, so the kernel never ends |
| 609 |
up with two concurrent iocbs pointing at the very same buffer. |
| 610 |
""" |
| 611 |
linux_aio = pytest.importorskip("caio.linux_aio") |
| 612 |
|
| 613 |
with open(str(tmp_path / "temp.bin"), "wb+") as f: |
| 614 |
fd = f.fileno() |
| 615 |
ctx = linux_aio.Context(max_requests=4) |
| 616 |
op = linux_aio.Operation.write(b"x", fd, 0) |
| 617 |
|
| 618 |
first = ctx.submit(op) |
| 619 |
assert first == 1 |
| 620 |
|
| 621 |
second = ctx.submit(op) |
| 622 |
assert second == 0, "must not hand the kernel two concurrent iocbs for the same buffer" |
| 623 |
|
| 624 |
drain(ctx, first, timeout=2.0) |
| 625 |
|
| 626 |
|
| 627 |
def test_submit_same_operation_object_twice_in_one_batch_is_accepted_once(tmp_path, backend): |
| 628 |
"""All four backends: submitting the same in-flight Operation object |
| 629 |
twice within a single submit() call must only ever be accepted once - |
| 630 |
not twice with two different RequestIds/dispatches silently |
| 631 |
overwriting each other. A prior bug (thread_aio/linux_aio/linux_uring) |
| 632 |
accepted both occurrences (each one's own already-in-progress check |
| 633 |
ran before either was actually marked), causing the underlying I/O to |
| 634 |
happen twice with only one completion ever delivered. |
| 635 |
""" |
| 636 |
path = tmp_path / "data.bin" |
| 637 |
fd = os.open(str(path), os.O_WRONLY | os.O_CREAT, 0o600) |
| 638 |
try: |
| 639 |
ctx = backend.Context(max_requests=8) |
| 640 |
op = backend.Operation.write(b"x", fd, 0) |
| 641 |
|
| 642 |
done = threading.Event() |
| 643 |
op.set_callback(lambda _res: done.set()) |
| 644 |
|
| 645 |
accepted = ctx.submit(op, op) |
| 646 |
assert accepted == 1, "the same Operation object must only be accepted once per submit() call" |
| 647 |
|
| 648 |
if hasattr(ctx, "process_events"): |
| 649 |
drain(ctx, 1) |
| 650 |
else: |
| 651 |
assert done.wait(timeout=5.0), "operation never completed" |
| 652 |
|
| 653 |
assert op.get_value() == 1 |
| 654 |
finally: |
| 655 |
os.close(fd) |
| 656 |
|
| 657 |
|
| 658 |
def test_resubmit_after_short_transfer_uses_original_size(tmp_path, polling_backend): |
| 659 |
"""linux_uring, linux_aio: an operation that once got a short read must |
| 660 |
not be resubmittable at all (both are one-shot on the shared caio-core |
| 661 |
engine now - design/generalized-safe-design.md decision #4), and a |
| 662 |
fresh `Operation.read(nbytes, ...)` retrying the same read must still |
| 663 |
ask for the ORIGINAL requested size, not the smaller amount the short |
| 664 |
read actually transferred - otherwise a retried read would be silently |
| 665 |
capped forever, even once more data became available and a full-size |
| 666 |
transfer would succeed. |
| 667 |
|
| 668 |
No error involved - just a short read (fewer bytes available than |
| 669 |
requested) followed by more data actually showing up before the |
| 670 |
retry, so the only way the second read comes back short is if the |
| 671 |
request size itself got silently clamped. |
| 672 |
""" |
| 673 |
path = tmp_path / "data.bin" |
| 674 |
path.write_bytes(b"abcd") |
| 675 |
|
| 676 |
fd = os.open(str(path), os.O_RDONLY) |
| 677 |
try: |
| 678 |
ctx = polling_backend.Context(max_requests=8) |
| 679 |
op = polling_backend.Operation.read(8, fd, 0) |
| 680 |
|
| 681 |
assert ctx.submit(op) == 1 |
| 682 |
drain(ctx, 1) |
| 683 |
assert bytes(op.get_value()) == b"abcd", "expected a short read of the 4 available bytes" |
| 684 |
|
| 685 |
with open(str(path), "r+b") as f: |
| 686 |
f.seek(4) |
| 687 |
f.write(b"efgh") |
| 688 |
|
| 689 |
# One-shot: the same, already-completed Operation must not be |
| 690 |
# accepted again - silently skipped (submitted count 0). |
| 691 |
assert ctx.submit(op) == 0, "a completed one-shot Operation must not be resubmittable" |
| 692 |
retry = polling_backend.Operation.read(8, fd, 0) |
| 693 |
assert ctx.submit(retry) == 1 |
| 694 |
drain(ctx, 1) |
| 695 |
assert bytes(retry.get_value()) == b"abcdefgh", ( |
| 696 |
"a fresh Operation must request the full original size, never a shrunk one" |
| 697 |
) |
| 698 |
finally: |
| 699 |
os.close(fd) |
| 700 |
|
| 701 |
|
| 702 |
def test_uring_failed_op_not_resubmittable_and_leaves_no_stale_error(tmp_path): |
| 703 |
"""linux_uring only: an operation that failed at completion time (a |
| 704 |
real CQE with res=-EBADF, not an eager io_submit()-time raise - see |
| 705 |
below) must not be resubmittable afterward (one-shot, design decision |
| 706 |
#4), and a *fresh* Operation retried against the same, now-valid fd |
| 707 |
number must succeed with no trace of the previous attempt's error. |
| 708 |
|
| 709 |
This used to be tested by resubmitting the very same Operation object |
| 710 |
after fixing up the fd via dup2() (fd is fixed for an Operation's |
| 711 |
whole lifetime - see AbstractOperation's docstring) - that specific |
| 712 |
resubmit-after-failure path is now structurally impossible under the |
| 713 |
one-shot contract, so this instead checks the two properties that |
| 714 |
replace it: rejection of the stale object, and a clean fresh attempt. |
| 715 |
|
| 716 |
linux_uring only: a write against a closed fd fails at *completion* |
| 717 |
time here. linux_aio's io_submit() validates the fd eagerly and raises |
| 718 |
a Python exception immediately instead (confirmed by hand) rather than |
| 719 |
ever reaching its own, symmetric completion-time error handling - so |
| 720 |
the same scenario can't be driven through linux_aio's public API. |
| 721 |
""" |
| 722 |
linux_uring = pytest.importorskip("caio.linux_uring") |
| 723 |
|
| 724 |
bad_path = tmp_path / "closed.bin" |
| 725 |
good_path = tmp_path / "good.bin" |
| 726 |
|
| 727 |
ctx = linux_uring.Context(max_requests=8) # create ctx first: its own fds must not collide below |
| 728 |
|
| 729 |
closed_fd = os.open(str(bad_path), os.O_WRONLY | os.O_CREAT, 0o600) |
| 730 |
os.close(closed_fd) |
| 731 |
|
| 732 |
op = linux_uring.Operation.write(b"hello", closed_fd, 0) |
| 733 |
assert ctx.submit(op) == 1 |
| 734 |
drain(ctx, 1) |
| 735 |
|
| 736 |
assert op.error != 0, "expected the write against a closed fd to fail" |
| 737 |
with pytest.raises(SystemError): |
| 738 |
op.get_value() |
| 739 |
|
| 740 |
good_fd = os.open(str(good_path), os.O_WRONLY | os.O_CREAT, 0o600) |
| 741 |
try: |
| 742 |
# good_fd often already *is* closed_fd's number here (the OS tends |
| 743 |
# to hand out the lowest just-freed fd), making this a documented |
| 744 |
# POSIX no-op - but dup2() is what makes the aliasing deliberate |
| 745 |
# and correct regardless of which number the allocator happens to |
| 746 |
# pick. |
| 747 |
os.dup2(good_fd, closed_fd) |
| 748 |
|
| 749 |
assert ctx.submit(op) == 0, "a completed one-shot Operation must not be resubmittable, even after fd repair" |
| 750 |
|
| 751 |
retry = linux_uring.Operation.write(b"hello", closed_fd, 0) |
| 752 |
assert ctx.submit(retry) == 1 |
| 753 |
drain(ctx, 1) |
| 754 |
|
| 755 |
assert retry.error == 0, "a fresh Operation must carry no stale error from a prior, unrelated attempt" |
| 756 |
assert retry.get_value() == 5 |
| 757 |
finally: |
| 758 |
os.close(closed_fd) |
| 759 |
if good_fd != closed_fd: |
| 760 |
os.close(good_fd) |
| 761 |
|
| 762 |
|
| 763 |
def test_uring_short_read_tail_is_zeroed_not_heap_garbage(tmp_path): |
| 764 |
"""linux_uring only: bytes past a short read's actual transfer count |
| 765 |
must be deterministic zero, not whatever was previously sitting in |
| 766 |
that heap memory. `PyBytes_FromStringAndSize(NULL, n)` leaves its |
| 767 |
buffer uninitialized, so this must be zeroed explicitly. |
| 768 |
|
| 769 |
Dirties the heap with distinguishable non-zero bytes first (allocating |
| 770 |
and freeing several same-sized buffers) to raise the odds an |
| 771 |
uninitialized allocation would visibly reuse that memory and fail this |
| 772 |
check - not a fully deterministic reproduction of the bug (heap reuse |
| 773 |
isn't guaranteed), but this assertion is unconditionally the correct |
| 774 |
behavior regardless. |
| 775 |
""" |
| 776 |
linux_uring = pytest.importorskip("caio.linux_uring") |
| 777 |
|
| 778 |
nbytes = 256 |
| 779 |
for _ in range(64): |
| 780 |
bytearray(b"\xff" * nbytes) |
| 781 |
|
| 782 |
path = tmp_path / "data.bin" |
| 783 |
path.write_bytes(b"AB") # far shorter than nbytes |
| 784 |
|
| 785 |
fd = os.open(str(path), os.O_RDONLY) |
| 786 |
try: |
| 787 |
ctx = linux_uring.Context(max_requests=8) |
| 788 |
op = linux_uring.Operation.read(nbytes, fd, 0) |
| 789 |
ctx.submit(op) |
| 790 |
drain(ctx, 1) |
| 791 |
|
| 792 |
assert bytes(op.get_value()) == b"AB" |
| 793 |
assert bytes(op.payload) == b"AB" + b"\x00" * (nbytes - 2), ( |
| 794 |
"untouched tail past a short read must be zero, not leftover heap contents" |
| 795 |
) |
| 796 |
finally: |
| 797 |
os.close(fd) |
| 798 |
|
| 799 |
|
| 800 |
def test_uring_read_resubmit_rejected_and_previous_result_unmutated(tmp_path): |
| 801 |
"""linux_uring only: a completed read Operation must not be |
| 802 |
resubmittable (one-shot, design decision #4) - so the bytes object a |
| 803 |
previous completion already handed out via get_value()/.payload can |
| 804 |
never be mutated by a later kernel write into the same buffer, since |
| 805 |
there is no later kernel write into it. A fresh Operation started |
| 806 |
against the same fd afterward must get its own, independent buffer. |
| 807 |
""" |
| 808 |
linux_uring = pytest.importorskip("caio.linux_uring") |
| 809 |
|
| 810 |
path = tmp_path / "data.bin" |
| 811 |
path.write_bytes(b"AAAA") |
| 812 |
|
| 813 |
fd = os.open(str(path), os.O_RDONLY) |
| 814 |
try: |
| 815 |
ctx = linux_uring.Context(max_requests=8) |
| 816 |
op = linux_uring.Operation.read(4, fd, 0) |
| 817 |
ctx.submit(op) |
| 818 |
drain(ctx, 1) |
| 819 |
|
| 820 |
first_result = op.get_value() |
| 821 |
assert bytes(first_result) == b"AAAA" |
| 822 |
first_hash = hash(first_result) |
| 823 |
|
| 824 |
with open(str(path), "r+b") as f: |
| 825 |
f.write(b"BBBB") |
| 826 |
|
| 827 |
assert ctx.submit(op) == 0, "a completed one-shot Operation must not be resubmittable" |
| 828 |
|
| 829 |
retry = linux_uring.Operation.read(4, fd, 0) |
| 830 |
ctx.submit(retry) |
| 831 |
drain(ctx, 1) |
| 832 |
second_result = retry.get_value() |
| 833 |
assert bytes(second_result) == b"BBBB" |
| 834 |
|
| 835 |
assert bytes(first_result) == b"AAAA", ( |
| 836 |
"a rejected resubmit must not mutate a bytes object already handed out by a previous completion" |
| 837 |
) |
| 838 |
assert hash(first_result) == first_hash |
| 839 |
assert first_result is not second_result, ( |
| 840 |
"a fresh Operation must use its own buffer, not reuse a previous completion's object" |
| 841 |
) |
| 842 |
finally: |
| 843 |
os.close(fd) |
| 844 |
|
| 845 |
|
| 846 |
def test_uring_submit_overflow_does_not_strand_or_leak_prior_ops(tmp_path): |
| 847 |
"""linux_uring only: when a single submit() call overflows the SQ ring |
| 848 |
partway through a batch, every op accepted *before* the overflow point |
| 849 |
must still be genuinely visible to the kernel (sq_tail/outstanding |
| 850 |
published) and reclaimable - not permanently stuck "in flight" with an |
| 851 |
unpublished SQE and an unreachable leaked reference. |
| 852 |
|
| 853 |
max_requests=1 deliberately: with a bigger capacity, more than one op |
| 854 |
from the batch could be accepted before the overflow point, and this |
| 855 |
test's own later `drain(ctx, 1)` calls (which only wait for *some* |
| 856 |
completion, not a specific one) could then race and count one of |
| 857 |
those other, unrelated ops' completions instead of the one actually |
| 858 |
being asserted on - flaky, not a real bug. Capacity 1 makes "the op |
| 859 |
accepted before the overflow point" unambiguously just `ops[0]`. |
| 860 |
""" |
| 861 |
linux_uring = pytest.importorskip("caio.linux_uring") |
| 862 |
|
| 863 |
with open(str(tmp_path / "temp.bin"), "wb+") as f: |
| 864 |
fd = f.fileno() |
| 865 |
ctx = linux_uring.Context(max_requests=1) |
| 866 |
ops = [linux_uring.Operation.write(b"x", fd, i) for i in range(4 * 64)] |
| 867 |
|
| 868 |
with pytest.raises(OverflowError): |
| 869 |
ctx.submit(*ops) |
| 870 |
|
| 871 |
drain(ctx, 1, timeout=2.0) |
| 872 |
assert ops[0].get_value() == 1, "the first op must have been accepted, submitted, and completed" |
| 873 |
|
| 874 |
# One-shot: the completed op from the overflowed batch must not be |
| 875 |
# resubmittable itself, but a fresh Operation must submit and |
| 876 |
# complete cleanly - the overflow must not have left the context |
| 877 |
# itself in some stuck or capacity-exhausted state. |
| 878 |
assert ctx.submit(ops[0]) == 0, "a completed one-shot Operation must not be resubmittable" |
| 879 |
retry = linux_uring.Operation.write(b"x", fd, 0) |
| 880 |
assert ctx.submit(retry) == 1 |
| 881 |
drain(ctx, 1, timeout=2.0) |
| 882 |
assert retry.get_value() == 1 |
| 883 |
|
| 884 |
|
| 885 |
def test_uring_reentrant_callback_does_not_double_consume_completion(tmp_path): |
| 886 |
"""linux_uring only: drain_cq() must fully commit the completion |
| 887 |
ring's state (head + outstanding) *before* invoking any completion |
| 888 |
callback - a callback that reentrantly calls process_events()/flush() |
| 889 |
must never be able to observe (and reprocess) a CQE the outer, |
| 890 |
still-running drain has already consumed. Reprocessing it would |
| 891 |
reconstruct the same "kernel-owned" reference a second time, causing a |
| 892 |
double-decref once both reconstructions eventually drop. |
| 893 |
""" |
| 894 |
linux_uring = pytest.importorskip("caio.linux_uring") |
| 895 |
|
| 896 |
with open(str(tmp_path / "temp.bin"), "wb+") as f: |
| 897 |
fd = f.fileno() |
| 898 |
ctx = linux_uring.Context(max_requests=8) |
| 899 |
op = linux_uring.Operation.write(b"x", fd, 0) |
| 900 |
|
| 901 |
reentrant_results = [] |
| 902 |
op.set_callback(lambda _res: reentrant_results.append(ctx.process_events())) |
| 903 |
|
| 904 |
ctx.submit(op) |
| 905 |
refcount_before = sys.getrefcount(op) |
| 906 |
|
| 907 |
# flush() both publishes the SQE to the kernel and drains whatever's |
| 908 |
# already completed inline - for a plain buffered write this is |
| 909 |
# *usually* immediate, but not guaranteed synchronous on every |
| 910 |
# kernel/filesystem. If it isn't, fall back to process_events() |
| 911 |
# with a real timeout: unlike flush(), it waits/polls the CQ ring |
| 912 |
# even when there's nothing new to submit (flush() has nothing left |
| 913 |
# to publish on a second call and returns 0 without even looking at |
| 914 |
# the CQ ring). |
| 915 |
ctx.flush() |
| 916 |
if not reentrant_results: |
| 917 |
ctx.process_events(max_requests=8, min_requests=1, timeout=5) |
| 918 |
assert reentrant_results, "operation never completed within the timeout" |
| 919 |
|
| 920 |
assert reentrant_results == [0], ( |
| 921 |
"a reentrant process_events() call from inside a completion callback " |
| 922 |
"must not see (and reprocess) the CQE the outer call just consumed" |
| 923 |
) |
| 924 |
refcount_after = sys.getrefcount(op) |
| 925 |
assert refcount_after == refcount_before - 1, ( |
| 926 |
"drain must reclaim exactly one leaked reference for this completion, " |
| 927 |
"not be double-decremented by a reentrant re-consume" |
| 928 |
) |
| 929 |
assert op.get_value() == 1 |
| 930 |
|
| 931 |
|
| 932 |
def test_linux_aio_submit_type_error_does_not_strand_earlier_ops(tmp_path): |
| 933 |
"""linux_aio only: a wrong-typed argument later in the same submit() |
| 934 |
call must not leave an earlier, valid operation in that same call |
| 935 |
permanently stuck in_flight - it must never have been touched at all, |
| 936 |
since the whole call raises before anything reaches io_submit(). |
| 937 |
""" |
| 938 |
linux_aio = pytest.importorskip("caio.linux_aio") |
| 939 |
|
| 940 |
with open(str(tmp_path / "temp.bin"), "wb+") as f: |
| 941 |
fd = f.fileno() |
| 942 |
ctx = linux_aio.Context(max_requests=4) |
| 943 |
op = linux_aio.Operation.write(b"x", fd, 0) |
| 944 |
|
| 945 |
with pytest.raises(TypeError): |
| 946 |
ctx.submit(op, object()) |
| 947 |
|
| 948 |
# Must not be stuck "in flight" - a normal submit must still work. |
| 949 |
submitted = ctx.submit(op) |
| 950 |
assert submitted == 1, "op from the rejected batch must not be permanently stuck in_flight" |
| 951 |
drain(ctx, 1, timeout=2.0) |
| 952 |
assert op.get_value() == 1 |
| 953 |
|
| 954 |
|
| 955 |
def test_linux_aio_process_events_max_requests_is_bounded(backend): |
| 956 |
"""linux_aio only: process_events(max_requests=...) sizes an internal |
| 957 |
events buffer directly from this caller-controlled argument - an |
| 958 |
absurdly large value must raise cleanly instead of attempting a huge |
| 959 |
allocation (u32::MAX would be roughly 128 GiB). Runs in a subprocess: |
| 960 |
an unbounded attempt at that allocation could abort the whole process |
| 961 |
(Rust's global alloc-error handler, not a catchable panic) rather than |
| 962 |
just failing this one call, which would take the whole test session |
| 963 |
down with it. |
| 964 |
""" |
| 965 |
if backend.__name__ != "caio.linux_aio": |
| 966 |
pytest.skip("linux_aio-only") |
| 967 |
|
| 968 |
code = ( |
| 969 |
"import caio.linux_aio as m\n" |
| 970 |
"ctx = m.Context(max_requests=8)\n" |
| 971 |
"try:\n" |
| 972 |
" ctx.process_events(max_requests=2**32 - 1)\n" |
| 973 |
" print('RESULT: unexpectedly-succeeded')\n" |
| 974 |
"except OverflowError:\n" |
| 975 |
" print('RESULT: raised OverflowError')\n" |
| 976 |
) |
| 977 |
proc = subprocess.run( |
| 978 |
[sys.executable, "-c", code], |
| 979 |
capture_output=True, text=True, timeout=30, check=False, |
| 980 |
) |
| 981 |
assert proc.returncode == 0, ( |
| 982 |
f"process aborted/crashed (returncode={proc.returncode}); " |
| 983 |
f"stdout={proc.stdout!r} stderr={proc.stderr!r}" |
| 984 |
) |
| 985 |
assert "RESULT: raised OverflowError" in proc.stdout, ( |
| 986 |
f"stdout={proc.stdout!r} stderr={proc.stderr!r}" |
| 987 |
) |
| 988 |
|
| 989 |
|
| 990 |
@pytest.mark.flaky(reruns=3) |
| 991 |
def test_process_events_negative_timeout_waits_indefinitely(tmp_path, polling_backend): |
| 992 |
"""process_events(timeout<0) means "wait indefinitely" - matching the |
| 993 |
native convention each backend's own blocking primitive already uses |
| 994 |
for exactly this (linux_aio's io_getevents() takes a NULL timespec; |
| 995 |
linux_uring's new eventfd-based wait passes -1 to poll()) - rather than |
| 996 |
being rejected outright, which was the previous behavior. Verified two |
| 997 |
ways: it must still be genuinely blocked with nothing submitted yet |
| 998 |
(not return early or misinterpret negative as "don't wait"), and it |
| 999 |
must actually wake up and return once a real completion satisfies |
| 1000 |
min_requests, not stay stuck forever once given something to wait for. |
| 1001 |
""" |
| 1002 |
with open(str(tmp_path / "temp.bin"), "wb+") as f: |
| 1003 |
fd = f.fileno() |
| 1004 |
ctx = polling_backend.Context(max_requests=8) |
| 1005 |
|
| 1006 |
result = {} |
| 1007 |
|
| 1008 |
def wait(): |
| 1009 |
result["n"] = ctx.process_events(min_requests=1, timeout=-1) |
| 1010 |
|
| 1011 |
t = threading.Thread(target=wait) |
| 1012 |
t.start() |
| 1013 |
try: |
| 1014 |
t.join(timeout=0.3) |
| 1015 |
assert t.is_alive(), ( |
| 1016 |
"process_events(timeout=-1) returned before any operation " |
| 1017 |
"was even submitted - it must block, not treat a negative " |
| 1018 |
"timeout as \"don't wait\"" |
| 1019 |
) |
| 1020 |
|
| 1021 |
op = polling_backend.Operation.write(b"x" * 4, fd, 0) |
| 1022 |
ctx.submit(op) |
| 1023 |
if hasattr(ctx, "flush"): |
| 1024 |
ctx.flush() |
| 1025 |
|
| 1026 |
t.join(timeout=5.0) |
| 1027 |
assert not t.is_alive(), ( |
| 1028 |
"process_events(timeout=-1) never woke up for a real " |
| 1029 |
"completion - it must not block forever once satisfied" |
| 1030 |
) |
| 1031 |
finally: |
| 1032 |
t.join(timeout=5.0) |
| 1033 |
|
| 1034 |
assert result.get("n", 0) >= 1 |
| 1035 |
|
| 1036 |
|
| 1037 |
def test_uring_process_events_max_requests_bounds_callbacks_not_just_return_value(tmp_path): |
| 1038 |
"""linux_uring only: process_events(max_requests=N) must not run more |
| 1039 |
than N callbacks synchronously, even though poll() itself always |
| 1040 |
drains the *entire* CQ ring in one go (no peek-without-consume |
| 1041 |
support) - anything beyond N must be held back (in a bridge-side |
| 1042 |
pending queue) for a later call, not delivered anyway while only |
| 1043 |
under-reporting the count the return value claims. |
| 1044 |
|
| 1045 |
Five writes, each blocked on its own full pipe (nothing reading), are |
| 1046 |
submitted and flush()ed while still guaranteed not to have completed |
| 1047 |
- flush() itself delivers nothing yet, confirmed below, so nothing |
| 1048 |
has been delivered via any path before process_events() runs. All |
| 1049 |
five are then unblocked together (every pipe drained), so they become |
| 1050 |
real completions at roughly the same time, deterministically - |
| 1051 |
letting max_requests bound exactly how many of them get delivered per |
| 1052 |
call, not just how many get reported. |
| 1053 |
""" |
| 1054 |
linux_uring = pytest.importorskip("caio.linux_uring") |
| 1055 |
import fcntl # Unix-only; this whole test is uring-only (Linux-only) |
| 1056 |
|
| 1057 |
F_SETPIPE_SZ = 1031 |
| 1058 |
pipes = [os.pipe() for _ in range(5)] |
| 1059 |
try: |
| 1060 |
for r_fd, w_fd in pipes: |
| 1061 |
fcntl.fcntl(w_fd, F_SETPIPE_SZ, 4096) |
| 1062 |
os.write(w_fd, b"f" * 4096) # fill each pipe so the next write blocks |
| 1063 |
|
| 1064 |
ctx = linux_uring.Context(max_requests=16) |
| 1065 |
called = [] |
| 1066 |
ops = [] |
| 1067 |
for i, (_r_fd, w_fd) in enumerate(pipes): |
| 1068 |
# -1 (io_uring's convention for non-seekable files, same as |
| 1069 |
# plain write(2)) - a pipe rejects an explicit offset outright. |
| 1070 |
op = linux_uring.Operation.write(b"x", w_fd, 0xFFFFFFFFFFFFFFFF) |
| 1071 |
op.set_callback(lambda _r, i=i: called.append(i)) |
| 1072 |
ops.append(op) |
| 1073 |
ctx.submit(*ops) |
| 1074 |
|
| 1075 |
found = ctx.flush() |
| 1076 |
assert found == 0 and not called, ( |
| 1077 |
"test setup bug: all 5 writes must still be blocked (pipes full) at this point" |
| 1078 |
) |
| 1079 |
|
| 1080 |
for r_fd, _w_fd in pipes: |
| 1081 |
os.read(r_fd, 8192) |
| 1082 |
time.sleep(0.05) # let the kernel actually post the completions |
| 1083 |
|
| 1084 |
first = ctx.process_events(max_requests=1, min_requests=0, timeout=0) |
| 1085 |
assert first == 1, f"expected exactly 1 reported, got {first}" |
| 1086 |
assert len(called) == 1, ( |
| 1087 |
f"process_events(max_requests=1) must invoke exactly 1 callback, not {len(called)}" |
| 1088 |
) |
| 1089 |
|
| 1090 |
second = ctx.process_events(max_requests=10, min_requests=0, timeout=0) |
| 1091 |
assert second == 4, f"expected the remaining 4 held over from before, got {second}" |
| 1092 |
assert len(called) == 5, f"expected all 5 eventually delivered, got {len(called)}" |
| 1093 |
finally: |
| 1094 |
for r_fd, w_fd in pipes: |
| 1095 |
os.close(r_fd) |
| 1096 |
os.close(w_fd) |
| 1097 |
|
| 1098 |
|
| 1099 |
def test_uring_process_events_min_requests_ignores_cancel_sentinel(tmp_path): |
| 1100 |
"""linux_uring only: process_events(min_requests=N) must wait for N |
| 1101 |
*real* completions, not N raw CQEs - a cancel's own ASYNC_CANCEL |
| 1102 |
sentinel CQE satisfies io_uring's own notion of "something completed" |
| 1103 |
without being a real completion poll() would ever hand back. Without |
| 1104 |
this, a stray sentinel already sitting in the ring lets the wait loop |
| 1105 |
exit on its very first check (before real completions are even |
| 1106 |
checked), well before a real completion that would actually satisfy |
| 1107 |
min_requests has had a chance to arrive. |
| 1108 |
|
| 1109 |
Uses the same blocked-pipe-write + background-thread-drains-it-late |
| 1110 |
technique as the Drop-reap sentinel test above: a write genuinely |
| 1111 |
still in flight when process_events() is called, made to complete |
| 1112 |
~0.2s later. With the bug, the stray sentinel already in the ring |
| 1113 |
would satisfy min_requests=1 immediately, so the call returns 0 real |
| 1114 |
completions almost instantly, well before that 0.2s delay elapses. |
| 1115 |
""" |
| 1116 |
linux_uring = pytest.importorskip("caio.linux_uring") |
| 1117 |
import fcntl # Unix-only; this whole test is uring-only (Linux-only) |
| 1118 |
|
| 1119 |
F_SETPIPE_SZ = 1031 |
| 1120 |
|
| 1121 |
with open(str(tmp_path / "temp.bin"), "wb+") as f: |
| 1122 |
fd = f.fileno() |
| 1123 |
r_fd, w_fd = os.pipe() |
| 1124 |
try: |
| 1125 |
fcntl.fcntl(w_fd, F_SETPIPE_SZ, 4096) |
| 1126 |
os.write(w_fd, b"f" * 4096) # fill the pipe so the next write blocks |
| 1127 |
|
| 1128 |
ctx = linux_uring.Context(max_requests=16) |
| 1129 |
|
| 1130 |
# A real op, completed and drained first, purely to generate a |
| 1131 |
# cancel sentinel below - cancelling an already-finished op |
| 1132 |
# still posts an ASYNC_CANCEL completion CQE for it. |
| 1133 |
done_op = linux_uring.Operation.write(b"z", fd, 0) |
| 1134 |
ctx.submit(done_op) |
| 1135 |
drain(ctx, 1, timeout=5.0) |
| 1136 |
ctx.cancel(done_op) |
| 1137 |
time.sleep(0.05) |
| 1138 |
assert ctx.poll() > 0, "cancel's own sentinel completion never got posted" |
| 1139 |
|
| 1140 |
# Genuinely still in flight when process_events() is called |
| 1141 |
# below - the pipe is full and nothing is reading it. Offset |
| 1142 |
# must be -1 (io_uring's convention for non-seekable files) - |
| 1143 |
# a pipe rejects an explicit offset outright. |
| 1144 |
blocked_op = linux_uring.Operation.write(b"pending", w_fd, 0xFFFFFFFFFFFFFFFF) |
| 1145 |
ctx.submit(blocked_op) |
| 1146 |
ctx.flush() |
| 1147 |
|
| 1148 |
drained_before_call_returned = threading.Event() |
| 1149 |
|
| 1150 |
def drain_pipe_late(): |
| 1151 |
time.sleep(0.2) |
| 1152 |
drained_before_call_returned.set() |
| 1153 |
os.read(r_fd, 8192) |
| 1154 |
|
| 1155 |
t = threading.Thread(target=drain_pipe_late) |
| 1156 |
t.start() |
| 1157 |
try: |
| 1158 |
n = ctx.process_events(max_requests=8, min_requests=1, timeout=5) |
| 1159 |
observed_drained_flag = drained_before_call_returned.is_set() |
| 1160 |
finally: |
| 1161 |
t.join(timeout=5.0) |
| 1162 |
|
| 1163 |
assert n == 1, f"expected the one real completion, got n={n}" |
| 1164 |
assert observed_drained_flag, ( |
| 1165 |
"process_events(min_requests=1) returned before the real completion actually " |
| 1166 |
"happened - a stray cancel sentinel must have satisfied min_requests early " |
| 1167 |
"instead of being filtered out" |
| 1168 |
) |
| 1169 |
finally: |
| 1170 |
os.close(r_fd) |
| 1171 |
os.close(w_fd) |
| 1172 |
|
| 1173 |
|
| 1174 |
def test_uring_context_usable_from_a_different_thread(tmp_path): |
| 1175 |
"""linux_uring only: a Context constructed on one thread must be fully |
| 1176 |
usable (submit/flush) from a different thread - this backend's Python |
| 1177 |
API doesn't pin a Context to the thread that created it, so |
| 1178 |
io_uring_setup() must not either. IORING_SETUP_SINGLE_ISSUER, on |
| 1179 |
kernels that support it, does exactly that: it pins the ring to |
| 1180 |
whichever task's io_uring_setup()/io_uring_enter() call created it and |
| 1181 |
rejects submission from any other task with -EEXIST. |
| 1182 |
""" |
| 1183 |
linux_uring = pytest.importorskip("caio.linux_uring") |
| 1184 |
|
| 1185 |
with open(str(tmp_path / "temp.bin"), "wb+") as f: |
| 1186 |
fd = f.fileno() |
| 1187 |
ctx = linux_uring.Context(max_requests=8) # created on the main thread |
| 1188 |
op = linux_uring.Operation.write(b"hello", fd, 0) |
| 1189 |
|
| 1190 |
result = {} |
| 1191 |
errors = [] |
| 1192 |
|
| 1193 |
def worker(): |
| 1194 |
try: |
| 1195 |
ctx.submit(op) |
| 1196 |
drain(ctx, 1, timeout=5.0) |
| 1197 |
result["bytes_written"] = op.get_value() |
| 1198 |
except Exception as e: # noqa: BLE001 |
| 1199 |
errors.append(e) |
| 1200 |
|
| 1201 |
t = threading.Thread(target=worker) |
| 1202 |
t.start() |
| 1203 |
t.join(timeout=10.0) |
| 1204 |
|
| 1205 |
assert not t.is_alive(), "worker thread did not finish in time" |
| 1206 |
assert not errors, f"submit()/flush() from a different thread raised: {errors!r}" |
| 1207 |
assert result.get("bytes_written") == 5 |
| 1208 |
assert os.pread(fd, 5, 0) == b"hello" |
| 1209 |
|
| 1210 |
|
| 1211 |
def test_uring_context_drop_does_not_invoke_callbacks(tmp_path): |
| 1212 |
"""Context teardown reaps outstanding operations (see the sentinel-CQE |
| 1213 |
test above) to avoid unmapping the rings out from under still-pending |
| 1214 |
kernel I/O, but it must not invoke Python callbacks while doing so - |
| 1215 |
a destructor is a risky place to run arbitrary user code (interpreter |
| 1216 |
shutdown ordering, reentrancy into the object being destroyed), and |
| 1217 |
nothing about "waiting for the kernel to finish with this memory" |
| 1218 |
requires it. The completion should still be applied (result/error |
| 1219 |
available if some other reference to the Operation survives), just |
| 1220 |
silently, with no callback call. |
| 1221 |
""" |
| 1222 |
linux_uring = pytest.importorskip("caio.linux_uring") |
| 1223 |
|
| 1224 |
with open(str(tmp_path / "temp.bin"), "wb+") as f: |
| 1225 |
fd = f.fileno() |
| 1226 |
ctx = linux_uring.Context(max_requests=8) |
| 1227 |
op = linux_uring.Operation.write(b"hello", fd, 0) |
| 1228 |
|
| 1229 |
invoked = [] |
| 1230 |
op.set_callback(lambda res: invoked.append(res)) |
| 1231 |
ctx.submit(op) |
| 1232 |
|
| 1233 |
del ctx |
| 1234 |
gc.collect() |
| 1235 |
|
| 1236 |
assert not invoked, "Context teardown must not invoke operation callbacks" |
| 1237 |
|
| 1238 |
|
| 1239 |
def test_thread_aio_drop_waits_for_a_genuinely_blocked_worker(tmp_path): |
| 1240 |
"""thread_aio only: dropping a Context whose single worker is still |
| 1241 |
blocked in a real syscall (a `read()` on an empty pipe, not merely a |
| 1242 |
task still sitting in the queue) must wait for that worker to actually |
| 1243 |
finish, not give up the instant shutdown is signaled - the fix for |
| 1244 |
the opposite bug (an *unbounded* wait that could hang forever if a |
| 1245 |
worker never returned at all) must not have swung to the other |
| 1246 |
extreme and started abandoning genuinely in-flight work immediately. |
| 1247 |
A background thread makes the blocking read return shortly after |
| 1248 |
Drop starts (proving it's genuinely still running, not merely |
| 1249 |
queued), and teardown must not return before that write happens, but |
| 1250 |
also must return well within a few seconds - nowhere near the full |
| 1251 |
drop-reap deadline - once it does. |
| 1252 |
""" |
| 1253 |
pytest.importorskip("caio.thread_aio") |
| 1254 |
import caio.thread_aio as m |
| 1255 |
|
| 1256 |
r_fd, w_fd = os.pipe() |
| 1257 |
try: |
| 1258 |
ctx = m.Context(max_requests=4, pool_size=1) |
| 1259 |
op = m.Operation.read(1, r_fd, 0) |
| 1260 |
ctx.submit(op) |
| 1261 |
|
| 1262 |
# Give the single worker a moment to actually enter the blocking |
| 1263 |
# read() before Drop runs - otherwise it could still be sitting |
| 1264 |
# in the queue and get cancelled per the "not yet started" path |
| 1265 |
# instead of genuinely blocking. |
| 1266 |
time.sleep(0.05) |
| 1267 |
|
| 1268 |
written_before_drop_returned = threading.Event() |
| 1269 |
|
| 1270 |
def write_after_delay(): |
| 1271 |
time.sleep(0.2) |
| 1272 |
written_before_drop_returned.set() |
| 1273 |
os.write(w_fd, b"x") |
| 1274 |
|
| 1275 |
t = threading.Thread(target=write_after_delay) |
| 1276 |
t.start() |
| 1277 |
try: |
| 1278 |
start = time.monotonic() |
| 1279 |
del ctx |
| 1280 |
gc.collect() |
| 1281 |
elapsed = time.monotonic() - start |
| 1282 |
finally: |
| 1283 |
t.join(timeout=5.0) |
| 1284 |
|
| 1285 |
assert written_before_drop_returned.is_set(), ( |
| 1286 |
"Context teardown returned before the blocked read actually completed - " |
| 1287 |
"it must wait for genuinely in-flight work, not give up immediately" |
| 1288 |
) |
| 1289 |
assert elapsed < 5.0, ( |
| 1290 |
f"teardown took {elapsed:.2f}s - should return shortly after the real " |
| 1291 |
"completion, not anywhere near the full drop-reap deadline" |
| 1292 |
) |
| 1293 |
finally: |
| 1294 |
os.close(r_fd) |
| 1295 |
os.close(w_fd) |
| 1296 |
|
| 1297 |
|
| 1298 |
def test_linux_aio_cancel_from_wrong_context_is_rejected(tmp_path): |
| 1299 |
"""linux_aio only: cancelling an Operation through a Context it was |
| 1300 |
never submitted through must be rejected, not silently routed to a |
| 1301 |
same-numbered but completely unrelated request in that other Context. |
| 1302 |
|
| 1303 |
Each Context's own request-ID sequence starts at 0 independently, so |
| 1304 |
the very first operation submitted through any two Contexts both get |
| 1305 |
local RequestId(0) - a bare RequestId alone can't tell them apart. |
| 1306 |
caio-core pairs every ID with the ContextId that issued it, and checks |
| 1307 |
it in Engine::cancel() before ever touching that Context's own |
| 1308 |
registry. |
| 1309 |
""" |
| 1310 |
linux_aio = pytest.importorskip("caio.linux_aio") |
| 1311 |
|
| 1312 |
path_a = tmp_path / "a.bin" |
| 1313 |
path_b = tmp_path / "b.bin" |
| 1314 |
fd_a = os.open(str(path_a), os.O_WRONLY | os.O_CREAT, 0o600) |
| 1315 |
fd_b = os.open(str(path_b), os.O_WRONLY | os.O_CREAT, 0o600) |
| 1316 |
try: |
| 1317 |
ctx_a = linux_aio.Context(max_requests=8) |
| 1318 |
ctx_b = linux_aio.Context(max_requests=8) |
| 1319 |
|
| 1320 |
op_a = linux_aio.Operation.write(b"a" * 4096, fd_a, 0) |
| 1321 |
op_b = linux_aio.Operation.write(b"b" * 4096, fd_b, 0) |
| 1322 |
assert ctx_a.submit(op_a) == 1 |
| 1323 |
assert ctx_b.submit(op_b) == 1 |
| 1324 |
|
| 1325 |
with pytest.raises(ValueError): |
| 1326 |
ctx_b.cancel(op_a) |
| 1327 |
|
| 1328 |
# op_b, ctx_b's own unrelated request, must be completely |
| 1329 |
# unaffected by the rejected cross-context cancel attempt. |
| 1330 |
drain(ctx_b, 1) |
| 1331 |
assert op_b.get_value() == 4096 |
| 1332 |
|
| 1333 |
drain(ctx_a, 1) |
| 1334 |
assert op_a.get_value() == 4096 |
| 1335 |
finally: |
| 1336 |
os.close(fd_a) |
| 1337 |
os.close(fd_b) |
| 1338 |
|
| 1339 |
|
| 1340 |
def test_uring_cancel_from_wrong_context_does_not_disturb_other_context(tmp_path): |
| 1341 |
"""linux_uring only: same scenario as |
| 1342 |
test_linux_aio_cancel_from_wrong_context_is_rejected, but linux_uring's |
| 1343 |
cancel() is fire-and-forget (always returns 0, never raises) - so the |
| 1344 |
only observable way to confirm the fix is that the *other* Context's |
| 1345 |
own, same-numbered request completes normally and is left untouched by |
| 1346 |
a cancel() call made through a different Context. |
| 1347 |
""" |
| 1348 |
linux_uring = pytest.importorskip("caio.linux_uring") |
| 1349 |
|
| 1350 |
path_a = tmp_path / "a.bin" |
| 1351 |
path_b = tmp_path / "b.bin" |
| 1352 |
fd_a = os.open(str(path_a), os.O_WRONLY | os.O_CREAT, 0o600) |
| 1353 |
fd_b = os.open(str(path_b), os.O_WRONLY | os.O_CREAT, 0o600) |
| 1354 |
try: |
| 1355 |
ctx_a = linux_uring.Context(max_requests=8) |
| 1356 |
ctx_b = linux_uring.Context(max_requests=8) |
| 1357 |
|
| 1358 |
op_a = linux_uring.Operation.write(b"a" * 4096, fd_a, 0) |
| 1359 |
op_b = linux_uring.Operation.write(b"b" * 4096, fd_b, 0) |
| 1360 |
assert ctx_a.submit(op_a) == 1 |
| 1361 |
assert ctx_b.submit(op_b) == 1 |
| 1362 |
|
| 1363 |
# No manual flush() here - drain() below already calls it, and a |
| 1364 |
# write against a regular file can complete inline during flush() |
| 1365 |
# (see flush()'s own doc comment); flushing twice risks drain() |
| 1366 |
# waiting forever for a completion flush() already delivered. |
| 1367 |
assert ctx_b.cancel(op_a) == 0 |
| 1368 |
|
| 1369 |
drain(ctx_b, 1) |
| 1370 |
assert op_b.get_value() == 4096, "op_b must complete normally, undisturbed by a cross-context cancel" |
| 1371 |
|
| 1372 |
drain(ctx_a, 1) |
| 1373 |
assert op_a.get_value() == 4096 |
| 1374 |
finally: |
| 1375 |
os.close(fd_a) |
| 1376 |
os.close(fd_b) |