Skip to content

Commit a22a43c

Browse files
committed
test(protocols): keep the #1889 spin's first raise inside its try (#1897)
- Wait in `_Spin.wait`, called from inside the `try` that drops a raise. On CPython 3.13 the backward jump closing the inline loop sat outside that `except`'s range, so a SIGALRM handled there went straight through and nothing was dropped: the `0 != 1` on CI. - Hold the deadline's own `signal.alarm` back until `wait` arms it, through `_Spin.alarm` and a new `spin_roundtrip` helper. Armed on entry, a stall of a second before the `try` delivered the raise outside it as well. - `clear` now drops the held deadline rather than cancelling the alarm. - Check the swallow outcome in one comparison that also shows the status and the seconds armed. - Add a test that raises at the spin's first backward jump through `sys.monitoring` (CPython 3.12+), and one that stalls before the spin. Closes #1897
1 parent c9b4823 commit a22a43c

1 file changed

Lines changed: 149 additions & 17 deletions

File tree

‎tests/protocols/test_option_generator_deadline_scale_1428_unit.py‎

Lines changed: 149 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,20 @@
1616
after :data:`SPIN_LIMIT` and the test fails by name, and the generator repeats
1717
the raise until :func:`roundtrip` has it.
1818
19+
The spin waits in a call made from inside the ``try`` that drops a raise, and
20+
arms the deadline there (#1897). Waiting inline, a raise handled at the jump
21+
closing the loop went past the ``except`` on CPython 3.13; armed as
22+
:func:`roundtrip` entered it, the deadline could come due in a stall before the
23+
``try``. Either way the first raise was not dropped.
24+
1925
This module is unit tier: it loads the generator by path and builds nothing, so
2026
it imports no :mod:`pcapkit` and reads no capture.
2127
2228
"""
2329

2430
from __future__ import annotations
2531

32+
import dis
2633
import importlib.util
2734
import os
2835
import signal
@@ -49,6 +56,14 @@
4956
#: repeats included, lands well inside it.
5057
SPIN_LIMIT = 10.0
5158

59+
#: Seconds a stalled :class:`_Spin` sleeps before its loop: past the one-second
60+
#: deadline, so an alarm counting down from the deadline's entry comes due in it.
61+
STALL = 1.5
62+
63+
#: :func:`signal.alarm` itself, for :class:`_Spin` to reach while its
64+
#: :meth:`_Spin.alarm` stands in for the name.
65+
_ALARM = signal.alarm
66+
5267

5368
def _load_generator() -> 'types.ModuleType':
5469
"""Load :file:`examples/generators/options.py` by path, under a name of its own.
@@ -76,40 +91,83 @@ class _SpinGaveUp(Exception):
7691
"""Raised by :class:`_Spin` once its limit passes with no deadline raised in it."""
7792

7893

79-
class _Spin: # pylint: disable=too-few-public-methods
94+
class _Spin:
8095
"""A family whose constructor spins until the deadline interrupts it.
8196
8297
It stands in for a real hang, but a bounded one: after ``limit`` seconds it
8398
sets :attr:`gave_up` and raises :exc:`_SpinGaveUp`, so a lost deadline fails
8499
the test in seconds instead of hanging the worker.
85100
101+
The first raise has to land inside the ``try`` that drops it (#1897), so the
102+
waiting is done in :meth:`wait`, called from inside that ``try``, and the
103+
deadline is armed there too: run it through
104+
:meth:`GeneratorDeadlineScaleTests.spin_roundtrip`, which puts :meth:`alarm`
105+
in place of :func:`signal.alarm` to hold the deadline back until then.
106+
86107
Args:
87108
limit: Seconds to spin before giving up.
88109
swallow: How many :exc:`TimeoutError` to drop before letting one
89110
through, standing in for a finaliser that drops the deadline's raise.
90-
clear: Cancel the pending alarm on entry, so no deadline ever fires.
111+
clear: Drop the deadline instead of arming it, so it never fires.
112+
stall: Seconds to sleep before the loop, standing in for a stalled runner.
91113
92114
"""
93115

94116
def __init__(self, limit: float = SPIN_LIMIT, swallow: int = 0,
95-
clear: bool = False) -> None:
117+
clear: bool = False, stall: float = 0.0) -> None:
96118
self.limit = limit
97119
self.swallow = swallow
98120
self.clear = clear
121+
self.stall = stall
122+
#: Seconds the deadline asked :meth:`alarm` for as it was entered, or ``0``.
123+
self.deadline = 0
124+
#: Seconds held back by :meth:`alarm` and not yet armed by :meth:`wait`.
125+
self.held = 0
99126
#: :exc:`TimeoutError` dropped so far.
100127
self.swallowed = 0
101128
#: Whether the limit passed before a deadline got through.
102129
self.gave_up = False
103130

131+
def alarm(self, seconds: int) -> int:
132+
""":func:`signal.alarm`, but the deadline's own arm is held for :meth:`wait`.
133+
134+
The first non-zero call is the deadline being entered. It is recorded in
135+
:attr:`deadline`, and no alarm runs until :meth:`wait` arms it. Armed as
136+
the deadline is entered, it counts down through everything before the
137+
``try``, and a runner stalled there for the whole second gets the raise
138+
outside it. Every other call reaches the alarm, so the deadline's repeats
139+
and its cancel are real.
140+
"""
141+
if seconds and not self.deadline:
142+
self.deadline = self.held = seconds
143+
return _ALARM(0)
144+
return _ALARM(seconds)
145+
146+
def wait(self, end: float) -> None:
147+
"""Arm the deadline :meth:`alarm` held, then busy-wait until ``end``.
148+
149+
A call from inside :meth:`build`'s ``try``, so a raise delivered anywhere
150+
in here reaches that ``try``. Written inline there, the jump closing the
151+
loop falls outside the range its ``except`` covers, and on CPython 3.13
152+
an alarm handled at that jump raised straight past it. CPython 3.12's
153+
table has the same gap, but an alarm handled there resumes inside the
154+
``try``.
155+
"""
156+
if self.held:
157+
seconds, self.held = self.held, 0
158+
if not self.clear:
159+
_ALARM(seconds)
160+
while time.monotonic() < end:
161+
pass
162+
104163
def build(self, code: 'Any', kwargs: 'Any') -> bytes: # pylint: disable=unused-argument
105164
"""Loop until the deadline interrupts it, or until :attr:`limit` passes."""
106-
if self.clear:
107-
signal.alarm(0)
165+
if self.stall:
166+
time.sleep(self.stall)
108167
end = time.monotonic() + self.limit
109168
while time.monotonic() < end:
110169
try:
111-
while time.monotonic() < end:
112-
pass
170+
self.wait(end)
113171
except TimeoutError:
114172
if self.swallowed == self.swallow:
115173
raise
@@ -187,12 +245,32 @@ def roundtrip(self, family: 'Any') -> 'Any':
187245
with mock.patch.dict(self.options.FAMILY_MAP, {'spin': family}):
188246
return self.options.roundtrip(case, deadline=2)
189247

248+
def spin_roundtrip(self, spin: '_Spin') -> 'Any':
249+
""":meth:`roundtrip` over ``spin``, with :meth:`_Spin.alarm` as :func:`signal.alarm`."""
250+
with mock.patch.object(signal, 'alarm', spin.alarm):
251+
return self.roundtrip(spin)
252+
190253
def assert_interrupted(self, spin: '_Spin', outcome: 'Any') -> None:
191254
"""Fail by name, rather than on a status mismatch, if the deadline never got through."""
192255
if spin.gave_up:
193256
self.fail(f'the deadline never interrupted the spin; roundtrip recorded '
194257
f'{outcome.status}: {outcome.detail}')
195258

259+
def assert_dropped_once(self, spin: '_Spin', outcome: 'Any') -> None:
260+
"""One raise dropped, the next recorded as ``'TIMEOUT'``, and nothing left behind.
261+
262+
One comparison, so a failure shows the count dropped next to what
263+
:func:`roundtrip` recorded.
264+
"""
265+
self.assert_interrupted(spin, outcome)
266+
self.assertEqual(
267+
{'deadline': spin.deadline, 'swallowed': spin.swallowed,
268+
'status': outcome.status, 'detail': outcome.detail},
269+
{'deadline': 1, 'swallowed': 1,
270+
'status': 'TIMEOUT', 'detail': 'did not finish within 1s'})
271+
self.assertIs(signal.getsignal(signal.SIGALRM), self.handler)
272+
self.assertEqual(signal.alarm(0), 0)
273+
196274
def test_the_default_is_thirty_seconds_unscaled(self) -> None:
197275
"""Unset, the default applies as written -- and it is no longer 5."""
198276
self.assertEqual(self.options.DEADLINE, 30)
@@ -242,22 +320,75 @@ def test_a_zero_deadline_stays_disarmed_under_any_scale(self) -> None:
242320
def test_a_hang_is_still_recorded_as_timeout_naming_the_scaled_deadline(self) -> None:
243321
"""The ``'TIMEOUT'`` contract holds, and its detail names the seconds allowed."""
244322
spin = _Spin()
245-
outcome = self.roundtrip(spin)
323+
outcome = self.spin_roundtrip(spin)
246324
self.assert_interrupted(spin, outcome)
325+
self.assertEqual(spin.deadline, 1)
247326
self.assertEqual(outcome.status, 'TIMEOUT')
248327
self.assertEqual(outcome.detail, 'did not finish within 1s')
249328
self.assertIs(signal.getsignal(signal.SIGALRM), self.handler)
250329

251330
def test_a_raise_that_never_reaches_the_body_is_repeated(self) -> None:
252331
"""#1889: a dropped raise is followed by another, still recorded as ``'TIMEOUT'``."""
253332
spin = _Spin(swallow=1)
254-
outcome = self.roundtrip(spin)
255-
self.assert_interrupted(spin, outcome)
256-
self.assertEqual(spin.swallowed, 1)
257-
self.assertEqual(outcome.status, 'TIMEOUT')
258-
self.assertEqual(outcome.detail, 'did not finish within 1s')
259-
self.assertIs(signal.getsignal(signal.SIGALRM), self.handler)
260-
self.assertEqual(signal.alarm(0), 0)
333+
self.assert_dropped_once(spin, self.spin_roundtrip(spin))
334+
335+
def test_a_stall_before_the_spin_still_leaves_a_raise_to_drop(self) -> None:
336+
"""#1897: a runner stalled for longer than the deadline before the spin changes nothing.
337+
338+
Armed as :func:`roundtrip` entered the deadline, the alarm came due in
339+
the stall, before the ``try`` that drops a raise. That raise went
340+
straight through and none was dropped.
341+
"""
342+
spin = _Spin(swallow=1, stall=STALL)
343+
self.assert_dropped_once(spin, self.spin_roundtrip(spin))
344+
345+
@unittest.skipUnless(sys.implementation.name == 'cpython' and sys.version_info >= (3, 12),
346+
'needs sys.monitoring')
347+
@unittest.skipUnless(hasattr(signal, 'pthread_kill'), 'needs signal.pthread_kill')
348+
def test_a_raise_as_the_spin_loops_back_is_dropped_too(self) -> None:
349+
"""#1897: a raise at the jump that closes the spin's loop is dropped.
350+
351+
Written inline in the ``try``, that jump lies outside the range the
352+
``except`` covers on CPython 3.12 and 3.13. On 3.13 an alarm handled at
353+
that jump raised straight past the ``except``; on 3.12 one handled there
354+
resumes inside the ``try``. Here the signal is sent from a
355+
:mod:`sys.monitoring` callback on the first backward jump after the
356+
deadline is armed, so the raise lands on the jump itself and exercises
357+
that layout on 3.12 and 3.13. From 3.14 the range covers the jump, so
358+
there this is a guard that cannot fail.
359+
"""
360+
monitoring = sys.monitoring # pylint: disable=no-member
361+
tool = next((tool for tool in range(6) if monitoring.get_tool(tool) is None), None)
362+
if tool is None:
363+
self.skipTest('no sys.monitoring tool id is free')
364+
spin = _Spin(swallow=1)
365+
codes = [function.__code__ for function in vars(_Spin).values()
366+
if isinstance(function, types.FunctionType)]
367+
jumps = {(code, instruction.offset) for code in codes
368+
for instruction in dis.get_instructions(code)
369+
if instruction.opname == 'JUMP_BACKWARD'}
370+
sent = [] # type: list[str]
371+
372+
def instruction(code: 'types.CodeType', offset: int) -> 'Any':
373+
if sent or (code, offset) not in jumps:
374+
return monitoring.DISABLE
375+
if spin.deadline and not spin.held:
376+
sent.append(code.co_name)
377+
signal.pthread_kill(threading.get_ident(), signal.SIGALRM)
378+
return None
379+
380+
event = monitoring.events.INSTRUCTION
381+
monitoring.use_tool_id(tool, 'pcapkit #1897')
382+
self.addCleanup(monitoring.free_tool_id, tool)
383+
monitoring.register_callback(tool, event, instruction)
384+
self.addCleanup(monitoring.register_callback, tool, event, None)
385+
for code in codes:
386+
monitoring.set_local_events(tool, code, event)
387+
self.addCleanup(monitoring.set_local_events, tool, code, 0)
388+
389+
outcome = self.spin_roundtrip(spin)
390+
self.assertEqual(len(sent), 1, 'no backward jump was reached with the deadline armed')
391+
self.assert_dropped_once(spin, outcome)
261392

262393
def test_each_raise_re_arms_until_the_body_settles_it(self) -> None:
263394
"""A raise re-arms one second; once :attr:`settled` is set, a firing does nothing."""
@@ -272,9 +403,10 @@ def test_each_raise_re_arms_until_the_body_settles_it(self) -> None:
272403
self.assertIs(signal.getsignal(signal.SIGALRM), self.handler)
273404

274405
def test_a_lost_deadline_fails_in_seconds_rather_than_hanging(self) -> None:
275-
"""#1889: with the alarm cancelled under it, the spin gives up and the test says why."""
406+
"""#1889: with the deadline never armed, the spin gives up and the test says why."""
276407
spin = _Spin(limit=0.5, clear=True)
277-
outcome = self.roundtrip(spin)
408+
outcome = self.spin_roundtrip(spin)
409+
self.assertEqual(spin.deadline, 1)
278410
self.assertTrue(spin.gave_up)
279411
self.assertEqual(outcome.status, 'CONSTRUCT')
280412
self.assertEqual(outcome.detail,

0 commit comments

Comments
 (0)