Debian Codegraph @

tests/test_operation_refcounting.py

raw
1 import gc
2 import sys
3 import tempfile
4 import time
5
6 import pytest
7 from conftest import wait_until
8
9
10 def test_get_value_on_fsync_does_not_corrupt_none_refcount(backend):
11 """get_value() on fsync/fdsync must return None on every backend. The 3
12 C backends used to `return Py_None` instead of Py_RETURN_NONE there - a
13 borrowed reference handed out as if it were new; run it enough times
14 that an under-refcounted None would show up as a wrong count (or, in
15 the worst case, a crash from None being freed). max_requests=256 is
16 just generous headroom for 200 in-flight ops submitted without pacing -
17 not testing capacity limits here."""
18 with tempfile.NamedTemporaryFile() as f:
19 ctx = backend.Context(max_requests=256)
20 results = []
21
22 for _ in range(200):
23 op = backend.Operation.fsync(f.fileno())
24 op.set_callback(results.append)
25 ctx.submit(op)
26
27 assert wait_until(ctx, lambda: len(results) >= 200)
28
29 op = backend.Operation.fsync(f.fileno())
30 done = []
31 op.set_callback(done.append)
32 ctx.submit(op)
33 assert wait_until(ctx, lambda: bool(done))
34 assert op.get_value() is None
35
36
37 def test_resubmitting_an_in_flight_operation_does_not_corrupt_context(backend):
38 """Resubmitting an Operation that's already in_progress must be a
39 silent no-op (not counted, not re-queued) rather than corrupting
40 anything about which Context it's tied to - previously (thread_aio.c)
41 the C struct's ctx pointer was overwritten unconditionally for every
42 argument before the in_progress check, with no matching incref, on
43 whichever Context received the resubmission attempt. python_aio's
44 plain-Python in-flight guard has nothing analogous to corrupt, but the
45 observable contract (only ctx_a's submit counts, only its callback
46 fires) must still hold identically."""
47 with tempfile.NamedTemporaryFile() as f:
48 ctx_a = backend.Context(max_requests=32)
49 ctx_b = backend.Context(max_requests=32)
50
51 results = []
52 op = backend.Operation.write(b"x", f.fileno(), 0)
53 op.set_callback(results.append)
54
55 submitted_a = ctx_a.submit(op)
56 submitted_b = ctx_b.submit(op) # op is in_progress - must be a no-op
57
58 assert submitted_a == 1
59 assert submitted_b == 0
60
61 assert wait_until(ctx_a, lambda: bool(results))
62 assert results == [1]
63
64 del ctx_a, ctx_b
65 gc.collect()
66
67
68 def test_large_batch_submit_does_not_crash(backend):
69 """A big enough batch used to overflow a caller-controlled-size stack
70 VLA in thread_aio.c/linux_aio.c/linux_uring.c. Not a C-specific concern
71 by nature (large batches should just work everywhere), so this runs
72 against all backends, including python_aio."""
73 with tempfile.NamedTemporaryFile() as f:
74 ctx = backend.Context(max_requests=8192)
75 results = []
76 ops = []
77 for _ in range(4000):
78 op = backend.Operation.fsync(f.fileno())
79 op.set_callback(results.append)
80 ops.append(op)
81
82 submitted = ctx.submit(*ops)
83 assert submitted == 4000
84 assert wait_until(ctx, lambda: len(results) >= 4000, timeout=15.0)
85
86
87 def test_context_teardown_drains_queued_operations(pooled_backend):
88 """Dropping a Context with operations still queued must not abandon
89 them (silently leaking their references) - it should drain the queue
90 (graceful threadpool shutdown) so every already in-flight callback
91 still fires. Scoped to pooled_backend (thread_aio/python_aio): only a
92 real worker-thread pool has a "queued but not yet dispatched" state
93 distinct from "accepted" - linux_aio/linux_uring have no such queue."""
94 with tempfile.NamedTemporaryFile() as f:
95 ctx = pooled_backend.Context(max_requests=256, pool_size=2)
96 results = []
97 ops = []
98 for _ in range(64):
99 op = pooled_backend.Operation.fsync(f.fileno())
100 op.set_callback(results.append)
101 ops.append(op)
102
103 ctx.submit(*ops)
104 del ctx
105 gc.collect()
106
107 deadline = time.monotonic() + 10.0
108 while len(results) < 64 and time.monotonic() < deadline:
109 time.sleep(0.01)
110 assert len(results) >= 64, (
111 f"only {len(results)}/64 callbacks fired after teardown"
112 )
113
114
115 def test_bad_args_do_not_accumulate_leaked_operations(backend):
116 """Operation.read/write/fsync/fdsync used to `return NULL` on a bad
117 argument without Py_DECREF-ing the object tp_alloc had already handed
118 them - leaking it forever (unreachable from Python, but never freed).
119 There's no live reference to take a weakref of in this scenario (the
120 object never successfully escapes the failing constructor), so the
121 only way to actually observe a per-call leak is total live-object
122 count not growing with iteration count. Covers all 4 constructors,
123 each run enough times that a real per-call leak would show up as
124 unmistakable linear growth. Runs on every backend, including
125 python_aio: its Operation.__init__ validates fd/nbytes/offset/priority
126 the same way (operator.index(), matching PyArg_ParseTupleAndKeywords'
127 own __index__-based coercion), raising the same TypeError synchronously
128 rather than storing a bad value and failing later."""
129 with tempfile.NamedTemporaryFile() as f:
130 for ctor, args in [
131 (backend.Operation.read, ("not-an-int", f.fileno(), 0)),
132 (backend.Operation.write, (b"x", "not-an-int", 0)),
133 (backend.Operation.fsync, ("not-an-int",)),
134 (backend.Operation.fdsync, ("not-an-int",)),
135 ]:
136 gc.collect()
137 before = len(gc.get_objects())
138
139 for _ in range(500):
140 try:
141 ctor(*args)
142 except TypeError:
143 pass
144
145 gc.collect()
146 after = len(gc.get_objects())
147 # Generous slack for unrelated interpreter/test-harness churn -
148 # a real per-call leak of 500 Operation objects would blow far
149 # past this.
150 assert after - before < 100, (
151 f"{ctor.__qualname__}: object count grew by {after - before} "
152 "over 500 failed constructions - looks like a per-call leak"
153 )
154
155
156 def test_write_with_non_bytes_payload_does_not_corrupt_its_refcount(backend):
157 """A non-bytes write payload must be rejected with ValueError,
158 without corrupting the caller's own reference to it, on every backend.
159 The 3 C backends used to store the "O"-parsed payload_bytes argument (a
160 borrowed reference) directly into the C struct's own buffer field
161 before validating it was actually bytes - on the ensuing type-check
162 failure, cleaning up the partially-constructed Operation decremented a
163 reference it never owned, over-decrementing the caller's own object.
164 python_aio can't have that exact bug (no manual refcounting to get
165 wrong), but validates the same way and the observable contract - raise
166 before construction completes, no lingering reference - must hold
167 identically."""
168 payload = ["not", "bytes"]
169 before = sys.getrefcount(payload)
170
171 with pytest.raises(ValueError):
172 backend.Operation.write(payload, 0, 0)
173
174 gc.collect()
175 assert sys.getrefcount(payload) == before