Skip to content

Commit fc4a044

Browse files
authored
bpo-30773: Fix ag_running; prohibit running athrow/asend/aclose in parallel (#7468)
1 parent 6758e6e commit fc4a044

File tree

4 files changed

+54
-64
lines changed

4 files changed

+54
-64
lines changed

Include/genobject.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,8 @@ typedef struct {
7979
/* Flag is set to 1 when aclose() is called for the first time, or
8080
when a StopAsyncIteration exception is raised. */
8181
int ag_closed;
82+
83+
int ag_running_async;
8284
} PyAsyncGenObject;
8385

8486
PyAPI_DATA(PyTypeObject) PyAsyncGen_Type;

Lib/test/test_asyncgen.py

Lines changed: 16 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -133,24 +133,6 @@ def async_iterate(g):
133133
break
134134
return res
135135

136-
def async_iterate(g):
137-
res = []
138-
while True:
139-
try:
140-
g.__anext__().__next__()
141-
except StopAsyncIteration:
142-
res.append('STOP')
143-
break
144-
except StopIteration as ex:
145-
if ex.args:
146-
res.append(ex.args[0])
147-
else:
148-
res.append('EMPTY StopIteration')
149-
break
150-
except Exception as ex:
151-
res.append(str(type(ex)))
152-
return res
153-
154136
sync_gen_result = sync_iterate(sync_gen)
155137
async_gen_result = async_iterate(async_gen)
156138
self.assertEqual(sync_gen_result, async_gen_result)
@@ -176,19 +158,22 @@ async def gen():
176158

177159
g = gen()
178160
ai = g.__aiter__()
179-
self.assertEqual(ai.__anext__().__next__(), ('result',))
161+
162+
an = ai.__anext__()
163+
self.assertEqual(an.__next__(), ('result',))
180164

181165
try:
182-
ai.__anext__().__next__()
166+
an.__next__()
183167
except StopIteration as ex:
184168
self.assertEqual(ex.args[0], 123)
185169
else:
186170
self.fail('StopIteration was not raised')
187171

188-
self.assertEqual(ai.__anext__().__next__(), ('result',))
172+
an = ai.__anext__()
173+
self.assertEqual(an.__next__(), ('result',))
189174

190175
try:
191-
ai.__anext__().__next__()
176+
an.__next__()
192177
except StopAsyncIteration as ex:
193178
self.assertFalse(ex.args)
194179
else:
@@ -212,10 +197,11 @@ async def gen():
212197

213198
g = gen()
214199
ai = g.__aiter__()
215-
self.assertEqual(ai.__anext__().__next__(), ('result',))
200+
an = ai.__anext__()
201+
self.assertEqual(an.__next__(), ('result',))
216202

217203
try:
218-
ai.__anext__().__next__()
204+
an.__next__()
219205
except StopIteration as ex:
220206
self.assertEqual(ex.args[0], 123)
221207
else:
@@ -646,17 +632,13 @@ async def run():
646632
gen = foo()
647633
it = gen.__aiter__()
648634
self.assertEqual(await it.__anext__(), 1)
649-
t = self.loop.create_task(it.__anext__())
650-
await asyncio.sleep(0.01)
651635
await gen.aclose()
652-
return t
653636

654-
t = self.loop.run_until_complete(run())
637+
self.loop.run_until_complete(run())
655638
self.assertEqual(DONE, 1)
656639

657640
# Silence ResourceWarnings
658641
fut.cancel()
659-
t.cancel()
660642
self.loop.run_until_complete(asyncio.sleep(0.01))
661643

662644
def test_async_gen_asyncio_gc_aclose_09(self):
@@ -1053,46 +1035,18 @@ async def wait():
10531035

10541036
self.loop.run_until_complete(asyncio.sleep(0.1))
10551037

1056-
self.loop.run_until_complete(self.loop.shutdown_asyncgens())
1057-
self.assertEqual(finalized, 2)
1058-
10591038
# Silence warnings
10601039
t1.cancel()
10611040
t2.cancel()
1062-
self.loop.run_until_complete(asyncio.sleep(0.1))
10631041

1064-
def test_async_gen_asyncio_shutdown_02(self):
1065-
logged = 0
1066-
1067-
def logger(loop, context):
1068-
nonlocal logged
1069-
self.assertIn('asyncgen', context)
1070-
expected = 'an error occurred during closing of asynchronous'
1071-
if expected in context['message']:
1072-
logged += 1
1073-
1074-
async def waiter(timeout):
1075-
try:
1076-
await asyncio.sleep(timeout)
1077-
yield 1
1078-
finally:
1079-
1 / 0
1080-
1081-
async def wait():
1082-
async for _ in waiter(1):
1083-
pass
1084-
1085-
t = self.loop.create_task(wait())
1086-
self.loop.run_until_complete(asyncio.sleep(0.1))
1042+
with self.assertRaises(asyncio.CancelledError):
1043+
self.loop.run_until_complete(t1)
1044+
with self.assertRaises(asyncio.CancelledError):
1045+
self.loop.run_until_complete(t2)
10871046

1088-
self.loop.set_exception_handler(logger)
10891047
self.loop.run_until_complete(self.loop.shutdown_asyncgens())
10901048

1091-
self.assertEqual(logged, 1)
1092-
1093-
# Silence warnings
1094-
t.cancel()
1095-
self.loop.run_until_complete(asyncio.sleep(0.1))
1049+
self.assertEqual(finalized, 2)
10961050

10971051
def test_async_gen_expression_01(self):
10981052
async def arange(n):
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Prohibit parallel running of aclose() / asend() / athrow(). Fix ag_running
2+
to reflect the actual running status of the AG.

Objects/genobject.c

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1326,7 +1326,8 @@ static PyGetSetDef async_gen_getsetlist[] = {
13261326

13271327
static PyMemberDef async_gen_memberlist[] = {
13281328
{"ag_frame", T_OBJECT, offsetof(PyAsyncGenObject, ag_frame), READONLY},
1329-
{"ag_running", T_BOOL, offsetof(PyAsyncGenObject, ag_running), READONLY},
1329+
{"ag_running", T_BOOL, offsetof(PyAsyncGenObject, ag_running_async),
1330+
READONLY},
13301331
{"ag_code", T_OBJECT, offsetof(PyAsyncGenObject, ag_code), READONLY},
13311332
{NULL} /* Sentinel */
13321333
};
@@ -1420,6 +1421,7 @@ PyAsyncGen_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
14201421
o->ag_finalizer = NULL;
14211422
o->ag_closed = 0;
14221423
o->ag_hooks_inited = 0;
1424+
o->ag_running_async = 0;
14231425
return (PyObject*)o;
14241426
}
14251427

@@ -1467,13 +1469,15 @@ async_gen_unwrap_value(PyAsyncGenObject *gen, PyObject *result)
14671469
gen->ag_closed = 1;
14681470
}
14691471

1472+
gen->ag_running_async = 0;
14701473
return NULL;
14711474
}
14721475

14731476
if (_PyAsyncGenWrappedValue_CheckExact(result)) {
14741477
/* async yield */
14751478
_PyGen_SetStopIterationValue(((_PyAsyncGenWrappedValue*)result)->agw_val);
14761479
Py_DECREF(result);
1480+
gen->ag_running_async = 0;
14771481
return NULL;
14781482
}
14791483

@@ -1518,12 +1522,20 @@ async_gen_asend_send(PyAsyncGenASend *o, PyObject *arg)
15181522
}
15191523

15201524
if (o->ags_state == AWAITABLE_STATE_INIT) {
1525+
if (o->ags_gen->ag_running_async) {
1526+
PyErr_SetString(
1527+
PyExc_RuntimeError,
1528+
"anext(): asynchronous generator is already running");
1529+
return NULL;
1530+
}
1531+
15211532
if (arg == NULL || arg == Py_None) {
15221533
arg = o->ags_sendval;
15231534
}
15241535
o->ags_state = AWAITABLE_STATE_ITER;
15251536
}
15261537

1538+
o->ags_gen->ag_running_async = 1;
15271539
result = gen_send_ex((PyGenObject*)o->ags_gen, arg, 0, 0);
15281540
result = async_gen_unwrap_value(o->ags_gen, result);
15291541

@@ -1787,8 +1799,23 @@ async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg)
17871799
}
17881800

17891801
if (o->agt_state == AWAITABLE_STATE_INIT) {
1802+
if (o->agt_gen->ag_running_async) {
1803+
if (o->agt_args == NULL) {
1804+
PyErr_SetString(
1805+
PyExc_RuntimeError,
1806+
"aclose(): asynchronous generator is already running");
1807+
}
1808+
else {
1809+
PyErr_SetString(
1810+
PyExc_RuntimeError,
1811+
"athrow(): asynchronous generator is already running");
1812+
}
1813+
return NULL;
1814+
}
1815+
17901816
if (o->agt_gen->ag_closed) {
1791-
PyErr_SetNone(PyExc_StopIteration);
1817+
o->agt_state = AWAITABLE_STATE_CLOSED;
1818+
PyErr_SetNone(PyExc_StopAsyncIteration);
17921819
return NULL;
17931820
}
17941821

@@ -1798,6 +1825,7 @@ async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg)
17981825
}
17991826

18001827
o->agt_state = AWAITABLE_STATE_ITER;
1828+
o->agt_gen->ag_running_async = 1;
18011829

18021830
if (o->agt_args == NULL) {
18031831
/* aclose() mode */
@@ -1843,6 +1871,7 @@ async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg)
18431871
/* aclose() mode */
18441872
if (retval) {
18451873
if (_PyAsyncGenWrappedValue_CheckExact(retval)) {
1874+
o->agt_gen->ag_running_async = 0;
18461875
Py_DECREF(retval);
18471876
goto yield_close;
18481877
}
@@ -1856,11 +1885,13 @@ async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg)
18561885
}
18571886

18581887
yield_close:
1888+
o->agt_gen->ag_running_async = 0;
18591889
PyErr_SetString(
18601890
PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
18611891
return NULL;
18621892

18631893
check_error:
1894+
o->agt_gen->ag_running_async = 0;
18641895
if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
18651896
PyErr_ExceptionMatches(PyExc_GeneratorExit))
18661897
{
@@ -1895,6 +1926,7 @@ async_gen_athrow_throw(PyAsyncGenAThrow *o, PyObject *args)
18951926
} else {
18961927
/* aclose() mode */
18971928
if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
1929+
o->agt_gen->ag_running_async = 0;
18981930
Py_DECREF(retval);
18991931
PyErr_SetString(PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
19001932
return NULL;

0 commit comments

Comments
 (0)