flpit 0.4.2.dev7__py3-none-any.whl → 0.4.2.dev9__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- flpit/asyncio_bridge.py +705 -0
- flpit/task.py +220 -21
- {flpit-0.4.2.dev7.dist-info → flpit-0.4.2.dev9.dist-info}/METADATA +1 -1
- {flpit-0.4.2.dev7.dist-info → flpit-0.4.2.dev9.dist-info}/RECORD +6 -5
- {flpit-0.4.2.dev7.dist-info → flpit-0.4.2.dev9.dist-info}/WHEEL +0 -0
- {flpit-0.4.2.dev7.dist-info → flpit-0.4.2.dev9.dist-info}/licenses/LICENSE +0 -0
flpit/asyncio_bridge.py
ADDED
|
@@ -0,0 +1,705 @@
|
|
|
1
|
+
"""asyncio libraries on the flpit runtime: a pool of standard asyncio event loops.
|
|
2
|
+
|
|
3
|
+
Provisional: the API of this module may change in 0.5. Prefer a library's sync client where one
|
|
4
|
+
exists (``httpx.Client``, psycopg's ``ConnectionPool``): it is written for threads and can be shared.
|
|
5
|
+
|
|
6
|
+
asyncio libraries (httpx, asyncpg, redis.asyncio, aiohttp, ...) need two things: a running
|
|
7
|
+
event loop on the thread that runs their code, and loop affinity (a connection pool, lock or
|
|
8
|
+
future created on one loop is only used on that loop). This module provides both without
|
|
9
|
+
giving up flpit's threads:
|
|
10
|
+
|
|
11
|
+
* **Strand loops** (Linux, the default there): each loop is an ordinary
|
|
12
|
+
``asyncio.SelectorEventLoop`` - asyncio's own transports, sockets, timers and executor
|
|
13
|
+
hooks - but nobody calls ``run_forever()``. When a loop has work, one flpit work item runs
|
|
14
|
+
its iterations; iterations of the same loop never overlap, so each loop is a serialized
|
|
15
|
+
queue on the flpit pool (Kestrel's IOQueue model). One reactor thread waits on a master
|
|
16
|
+
epoll holding every loop's own epoll descriptor and wakes the loop that has I/O; timers go
|
|
17
|
+
to flpit's timer queue. A loop costs no thread, and loops run in parallel on the pool.
|
|
18
|
+
* **Thread loops** (other platforms, or ``configure(backend="threads")``): one dedicated
|
|
19
|
+
thread per loop running ``run_forever()``. Public asyncio API only.
|
|
20
|
+
|
|
21
|
+
Work goes to the loop already running on the calling thread when there is one (asyncio code
|
|
22
|
+
calling more asyncio code stays on its loop), otherwise to the least busy of the pool's loops
|
|
23
|
+
("power of two choices"). Loops are created on demand, up to ``configure(loops=...)``.
|
|
24
|
+
|
|
25
|
+
Loop-bound objects that should outlive one call (an ``httpx.AsyncClient``, an asyncpg pool)
|
|
26
|
+
belong in a ``LoopLocal``: one value per loop, created on first use, closed with the loop.
|
|
27
|
+
|
|
28
|
+
Strand loops drive asyncio's ``BaseEventLoop._run_once`` and replace two private hooks
|
|
29
|
+
(``_write_to_self``, the selector's wait); the thread backend needs none of that and is the
|
|
30
|
+
fallback if a Python release changes those internals.
|
|
31
|
+
"""
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
import asyncio
|
|
35
|
+
import atexit
|
|
36
|
+
import concurrent.futures
|
|
37
|
+
import contextvars
|
|
38
|
+
import os
|
|
39
|
+
import random
|
|
40
|
+
import select
|
|
41
|
+
import selectors
|
|
42
|
+
import sys
|
|
43
|
+
import threading
|
|
44
|
+
import weakref
|
|
45
|
+
from asyncio import events
|
|
46
|
+
from collections import deque
|
|
47
|
+
from collections.abc import AsyncGenerator, Awaitable, Callable, Coroutine
|
|
48
|
+
from typing import Any, Generic, TypeVar, cast, override
|
|
49
|
+
|
|
50
|
+
from . import task as _task
|
|
51
|
+
from .task import CancellationToken, OperationCanceledError, Task, TaskCompletionSource
|
|
52
|
+
from .threading import ThreadPool
|
|
53
|
+
|
|
54
|
+
__all__ = ["LoopLocal", "configure", "run_asyncio", "shutdown"]
|
|
55
|
+
|
|
56
|
+
T = TypeVar("T")
|
|
57
|
+
|
|
58
|
+
#: Iterations one drive runs before it yields its pool worker to other work.
|
|
59
|
+
_MAX_ITERATIONS_PER_DRIVE = 64
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
# ---------------------------------------------------------------------------
|
|
63
|
+
# Default executor: run_in_executor(None, ...) and getaddrinfo on the flpit pool
|
|
64
|
+
# ---------------------------------------------------------------------------
|
|
65
|
+
|
|
66
|
+
class _PoolExecutor(concurrent.futures.ThreadPoolExecutor):
|
|
67
|
+
"""``concurrent.futures`` interface over the flpit pool (asyncio's default executor here).
|
|
68
|
+
|
|
69
|
+
A ``ThreadPoolExecutor`` subclass only because ``set_default_executor`` requires one; it
|
|
70
|
+
never starts threads of its own.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
def __init__(self) -> None:
|
|
74
|
+
super().__init__(max_workers=1, thread_name_prefix="unused")
|
|
75
|
+
|
|
76
|
+
@override
|
|
77
|
+
def submit[**P, R](
|
|
78
|
+
self, fn: Callable[P, R], /, *args: P.args, **kwargs: P.kwargs
|
|
79
|
+
) -> concurrent.futures.Future[R]:
|
|
80
|
+
future: concurrent.futures.Future[R] = concurrent.futures.Future()
|
|
81
|
+
|
|
82
|
+
def run(_state: Any) -> None:
|
|
83
|
+
if not future.set_running_or_notify_cancel():
|
|
84
|
+
return
|
|
85
|
+
try:
|
|
86
|
+
result = fn(*args, **kwargs)
|
|
87
|
+
except BaseException as error: # noqa: BLE001 - delivered to the waiter
|
|
88
|
+
future.set_exception(error)
|
|
89
|
+
else:
|
|
90
|
+
future.set_result(result)
|
|
91
|
+
|
|
92
|
+
ThreadPool.queue(run, None)
|
|
93
|
+
return future
|
|
94
|
+
|
|
95
|
+
@override
|
|
96
|
+
def shutdown(self, wait: bool = True, *, cancel_futures: bool = False) -> None:
|
|
97
|
+
pass # the flpit pool outlives the loops
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
_POOL_EXECUTOR = _PoolExecutor()
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
# ---------------------------------------------------------------------------
|
|
104
|
+
# Strand loops
|
|
105
|
+
# ---------------------------------------------------------------------------
|
|
106
|
+
|
|
107
|
+
if hasattr(selectors, "EpollSelector"):
|
|
108
|
+
class _NonBlockingSelector(selectors.EpollSelector):
|
|
109
|
+
"""The loop's own selector never waits: the reactor thread does the waiting."""
|
|
110
|
+
|
|
111
|
+
@override
|
|
112
|
+
def select(self, timeout: float | None = None) -> list[tuple[selectors.SelectorKey, int]]:
|
|
113
|
+
return super().select(0)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class _Reactor:
|
|
117
|
+
"""One thread for every strand loop: waits on a master epoll of the loops' epoll descriptors.
|
|
118
|
+
|
|
119
|
+
Each loop is registered one-shot (EPOLLONESHOT) and re-armed after the loop's iterations
|
|
120
|
+
ran, so a loop with pending I/O is woken once, not on every poll.
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
def __init__(self) -> None:
|
|
124
|
+
self._epoll = select.epoll()
|
|
125
|
+
self._loops: dict[int, _StrandLoop] = {}
|
|
126
|
+
self._lock = threading.Lock()
|
|
127
|
+
self._wakeup_read, self._wakeup_write = os.pipe()
|
|
128
|
+
os.set_blocking(self._wakeup_read, False)
|
|
129
|
+
self._epoll.register(self._wakeup_read, select.EPOLLIN)
|
|
130
|
+
self._stopping = False
|
|
131
|
+
self._thread = threading.Thread(target=self._run, name="Task-asyncio-reactor", daemon=True)
|
|
132
|
+
self._thread.start()
|
|
133
|
+
|
|
134
|
+
def add(self, loop: _StrandLoop) -> None:
|
|
135
|
+
fd = loop._selector.fileno()
|
|
136
|
+
with self._lock:
|
|
137
|
+
self._loops[fd] = loop
|
|
138
|
+
self._epoll.register(fd, select.EPOLLIN | select.EPOLLONESHOT)
|
|
139
|
+
|
|
140
|
+
def rearm(self, loop: _StrandLoop) -> None:
|
|
141
|
+
try:
|
|
142
|
+
self._epoll.modify(loop._selector.fileno(), select.EPOLLIN | select.EPOLLONESHOT)
|
|
143
|
+
except (OSError, ValueError):
|
|
144
|
+
pass # closed meanwhile
|
|
145
|
+
|
|
146
|
+
def remove(self, loop: _StrandLoop) -> None:
|
|
147
|
+
fd = loop._selector.fileno()
|
|
148
|
+
with self._lock:
|
|
149
|
+
self._loops.pop(fd, None)
|
|
150
|
+
try:
|
|
151
|
+
self._epoll.unregister(fd)
|
|
152
|
+
except (OSError, ValueError):
|
|
153
|
+
pass
|
|
154
|
+
|
|
155
|
+
def stop(self) -> None:
|
|
156
|
+
self._stopping = True
|
|
157
|
+
os.write(self._wakeup_write, b"x")
|
|
158
|
+
self._thread.join(5)
|
|
159
|
+
self._epoll.close()
|
|
160
|
+
os.close(self._wakeup_read)
|
|
161
|
+
os.close(self._wakeup_write)
|
|
162
|
+
|
|
163
|
+
def _run(self) -> None:
|
|
164
|
+
poll = self._epoll.poll
|
|
165
|
+
while not self._stopping:
|
|
166
|
+
try:
|
|
167
|
+
ready = poll()
|
|
168
|
+
except InterruptedError:
|
|
169
|
+
continue
|
|
170
|
+
for fd, _events in ready:
|
|
171
|
+
if fd == self._wakeup_read:
|
|
172
|
+
try:
|
|
173
|
+
os.read(self._wakeup_read, 64)
|
|
174
|
+
except BlockingIOError:
|
|
175
|
+
pass
|
|
176
|
+
continue
|
|
177
|
+
with self._lock:
|
|
178
|
+
loop = self._loops.get(fd)
|
|
179
|
+
if loop is not None:
|
|
180
|
+
loop._wake()
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
class _StrandLoop(asyncio.SelectorEventLoop):
|
|
184
|
+
"""A standard selector event loop whose iterations run as flpit work items, never two at once."""
|
|
185
|
+
|
|
186
|
+
# asyncio internals this backend uses (CPython's BaseEventLoop / BaseSelectorEventLoop; not in
|
|
187
|
+
# typeshed). Kept to this one class; the threads backend needs none of them.
|
|
188
|
+
_selector: selectors.EpollSelector # always a _NonBlockingSelector
|
|
189
|
+
_ready: deque[asyncio.Handle]
|
|
190
|
+
_scheduled: list[asyncio.TimerHandle]
|
|
191
|
+
_thread_id: int | None
|
|
192
|
+
_run_once: Callable[[], None]
|
|
193
|
+
_asyncgen_firstiter_hook: Callable[[AsyncGenerator[Any, Any]], None]
|
|
194
|
+
_asyncgen_finalizer_hook: Callable[[AsyncGenerator[Any, Any]], None]
|
|
195
|
+
|
|
196
|
+
def __init__(self, reactor: _Reactor) -> None:
|
|
197
|
+
# Set before BaseEventLoop.__init__, which already calls overridden methods.
|
|
198
|
+
self._reactor = reactor
|
|
199
|
+
self._guard = threading.Lock()
|
|
200
|
+
self._queued = False # a drive is queued or running
|
|
201
|
+
self._again = False # woken while driving: iterate once more
|
|
202
|
+
self._timer: Any = None
|
|
203
|
+
self._timer_at: float | None = None
|
|
204
|
+
self._loop_closing = True # not running (and never driven) until fully set up
|
|
205
|
+
super().__init__(_NonBlockingSelector())
|
|
206
|
+
self.set_default_executor(_POOL_EXECUTOR)
|
|
207
|
+
reactor.add(self)
|
|
208
|
+
self._loop_closing = False
|
|
209
|
+
if self._ready:
|
|
210
|
+
self._wake()
|
|
211
|
+
|
|
212
|
+
# -- waking ----------------------------------------------------------------------------------
|
|
213
|
+
|
|
214
|
+
def _wake(self) -> None:
|
|
215
|
+
with self._guard:
|
|
216
|
+
if self._loop_closing:
|
|
217
|
+
return
|
|
218
|
+
if self._queued:
|
|
219
|
+
self._again = True
|
|
220
|
+
return
|
|
221
|
+
self._queued = True
|
|
222
|
+
ThreadPool.queue(self._drive, None)
|
|
223
|
+
|
|
224
|
+
def _write_to_self(self) -> None:
|
|
225
|
+
# call_soon_threadsafe from another thread. A strand isn't blocked in select(), so
|
|
226
|
+
# schedule it directly instead of writing to the self-pipe (and going through the reactor).
|
|
227
|
+
self._wake()
|
|
228
|
+
|
|
229
|
+
@override
|
|
230
|
+
def call_soon(self, callback: Callable[..., Any], *args: Any, context: contextvars.Context | None = None) -> Any:
|
|
231
|
+
handle = super().call_soon(callback, *args, context=context)
|
|
232
|
+
if events._get_running_loop() is not self:
|
|
233
|
+
self._wake() # scheduled outside an iteration (setup code on this loop's behalf)
|
|
234
|
+
return handle
|
|
235
|
+
|
|
236
|
+
@override
|
|
237
|
+
def is_running(self) -> bool:
|
|
238
|
+
# Logically running while it accepts work, although nobody calls run_forever().
|
|
239
|
+
return not (self._loop_closing or self.is_closed())
|
|
240
|
+
|
|
241
|
+
# -- driving ---------------------------------------------------------------------------------
|
|
242
|
+
|
|
243
|
+
def _drive(self, _state: Any) -> None:
|
|
244
|
+
hooks = sys.get_asyncgen_hooks()
|
|
245
|
+
previous = events._get_running_loop()
|
|
246
|
+
# asyncio's async-generator hooks for this loop while its code runs (pool workers carry
|
|
247
|
+
# flpit's; an abandoned asyncio generator must be closed on its loop, not by flpit).
|
|
248
|
+
sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook, finalizer=self._asyncgen_finalizer_hook)
|
|
249
|
+
events._set_running_loop(self)
|
|
250
|
+
self._thread_id = threading.get_ident()
|
|
251
|
+
requeue = False
|
|
252
|
+
next_timer: float | None = None
|
|
253
|
+
try:
|
|
254
|
+
iterations = 0
|
|
255
|
+
while not self.is_closed():
|
|
256
|
+
try:
|
|
257
|
+
self._run_once()
|
|
258
|
+
except (KeyboardInterrupt, SystemExit):
|
|
259
|
+
# asyncio re-raises these from the task that raised them, to stop run_forever().
|
|
260
|
+
# The task has already failed with it and its Task reports it to whoever waits;
|
|
261
|
+
# the loop serves its other work on.
|
|
262
|
+
pass
|
|
263
|
+
iterations += 1
|
|
264
|
+
with self._guard:
|
|
265
|
+
if not (self._ready or self._again):
|
|
266
|
+
# Read while this is still the only drive; the next may start right after.
|
|
267
|
+
scheduled = self._scheduled
|
|
268
|
+
next_timer = scheduled[0].when() if scheduled else None
|
|
269
|
+
self._queued = False
|
|
270
|
+
break
|
|
271
|
+
self._again = False
|
|
272
|
+
if iterations >= _MAX_ITERATIONS_PER_DRIVE:
|
|
273
|
+
requeue = True # yield the worker; continue in a fresh work item
|
|
274
|
+
break
|
|
275
|
+
finally:
|
|
276
|
+
self._thread_id = None
|
|
277
|
+
events._set_running_loop(previous)
|
|
278
|
+
sys.set_asyncgen_hooks(*hooks)
|
|
279
|
+
if self.is_closed():
|
|
280
|
+
return
|
|
281
|
+
if requeue:
|
|
282
|
+
ThreadPool.queue(self._drive, None)
|
|
283
|
+
return
|
|
284
|
+
self._reactor.rearm(self)
|
|
285
|
+
if next_timer is not None:
|
|
286
|
+
self._arm_timer(next_timer)
|
|
287
|
+
|
|
288
|
+
def _arm_timer(self, when: float) -> None:
|
|
289
|
+
with self._guard:
|
|
290
|
+
if self._loop_closing or (self._timer_at is not None and self._timer_at <= when):
|
|
291
|
+
return # an earlier (or the same) wake-up is already armed
|
|
292
|
+
if self._timer is not None:
|
|
293
|
+
self._timer.cancel()
|
|
294
|
+
self._timer_at = when
|
|
295
|
+
self._timer = _task._timers.schedule(max(0.0, when - self.time()), self._on_timer)
|
|
296
|
+
|
|
297
|
+
def _on_timer(self) -> None:
|
|
298
|
+
with self._guard:
|
|
299
|
+
self._timer = None
|
|
300
|
+
self._timer_at = None
|
|
301
|
+
self._wake()
|
|
302
|
+
|
|
303
|
+
@override
|
|
304
|
+
def close(self) -> None:
|
|
305
|
+
if self.is_closed():
|
|
306
|
+
return
|
|
307
|
+
with self._guard:
|
|
308
|
+
self._loop_closing = True # no more drives get queued
|
|
309
|
+
if self._timer is not None:
|
|
310
|
+
self._timer.cancel()
|
|
311
|
+
self._timer = None
|
|
312
|
+
# A drive may still be finishing on a pool worker (it completed the last task).
|
|
313
|
+
deadline = self.time() + 5.0
|
|
314
|
+
while True:
|
|
315
|
+
with self._guard:
|
|
316
|
+
if not self._queued:
|
|
317
|
+
break
|
|
318
|
+
if self.time() > deadline:
|
|
319
|
+
break
|
|
320
|
+
threading.Event().wait(0.001)
|
|
321
|
+
self._reactor.remove(self)
|
|
322
|
+
super().close()
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
# ---------------------------------------------------------------------------
|
|
326
|
+
# Thread loops (fallback backend)
|
|
327
|
+
# ---------------------------------------------------------------------------
|
|
328
|
+
|
|
329
|
+
class _ThreadLoop:
|
|
330
|
+
"""A standard event loop on a dedicated thread (public asyncio API only)."""
|
|
331
|
+
|
|
332
|
+
def __init__(self) -> None:
|
|
333
|
+
self.loop = asyncio.new_event_loop()
|
|
334
|
+
self.loop.set_default_executor(_POOL_EXECUTOR)
|
|
335
|
+
self.thread = threading.Thread(target=self._serve, name="Task-asyncio-loop", daemon=True)
|
|
336
|
+
self.thread.start()
|
|
337
|
+
|
|
338
|
+
def _serve(self) -> None:
|
|
339
|
+
while True:
|
|
340
|
+
try:
|
|
341
|
+
self.loop.run_forever()
|
|
342
|
+
return # stopped by stop()
|
|
343
|
+
except (KeyboardInterrupt, SystemExit):
|
|
344
|
+
continue # raised out of one task (which failed with it); serve on, as strands do
|
|
345
|
+
|
|
346
|
+
def stop(self) -> None:
|
|
347
|
+
self.loop.call_soon_threadsafe(self.loop.stop)
|
|
348
|
+
self.thread.join(5)
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
# ---------------------------------------------------------------------------
|
|
352
|
+
# The pool of loops
|
|
353
|
+
# ---------------------------------------------------------------------------
|
|
354
|
+
|
|
355
|
+
def _default_count() -> int:
|
|
356
|
+
counter = getattr(os, "process_cpu_count", None) or os.cpu_count
|
|
357
|
+
return max(1, counter() or 1)
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
class _LoopPool:
|
|
361
|
+
def __init__(self, count: int, backend: str) -> None:
|
|
362
|
+
self.count = count
|
|
363
|
+
self.backend = backend
|
|
364
|
+
self.loops: list[asyncio.AbstractEventLoop] = []
|
|
365
|
+
self.load: dict[asyncio.AbstractEventLoop, int] = {}
|
|
366
|
+
self.lock = threading.Lock()
|
|
367
|
+
self.reactor: _Reactor | None = None
|
|
368
|
+
self.threads: list[_ThreadLoop] = []
|
|
369
|
+
|
|
370
|
+
def acquire(self) -> asyncio.AbstractEventLoop:
|
|
371
|
+
"""The loop for a new piece of work: two random loops, the less busy one, or a new loop."""
|
|
372
|
+
with self.lock:
|
|
373
|
+
loops = self.loops
|
|
374
|
+
if loops:
|
|
375
|
+
a, b = (random.choice(loops), random.choice(loops)) if len(loops) > 1 else (loops[0], loops[0])
|
|
376
|
+
loop = a if self.load[a] <= self.load[b] else b
|
|
377
|
+
if self.load[loop] == 0 or len(loops) >= self.count:
|
|
378
|
+
self.load[loop] += 1
|
|
379
|
+
return loop
|
|
380
|
+
loop = self._new_loop()
|
|
381
|
+
loops.append(loop)
|
|
382
|
+
self.load[loop] = 1
|
|
383
|
+
return loop
|
|
384
|
+
|
|
385
|
+
def release(self, loop: asyncio.AbstractEventLoop) -> None:
|
|
386
|
+
with self.lock:
|
|
387
|
+
if loop in self.load:
|
|
388
|
+
self.load[loop] -= 1
|
|
389
|
+
|
|
390
|
+
def _new_loop(self) -> asyncio.AbstractEventLoop:
|
|
391
|
+
if self.backend == "strands":
|
|
392
|
+
if self.reactor is None:
|
|
393
|
+
self.reactor = _Reactor()
|
|
394
|
+
return _StrandLoop(self.reactor)
|
|
395
|
+
runner = _ThreadLoop()
|
|
396
|
+
self.threads.append(runner)
|
|
397
|
+
return runner.loop
|
|
398
|
+
|
|
399
|
+
def close(self, timeout: float) -> None:
|
|
400
|
+
empty: list[asyncio.AbstractEventLoop] = []
|
|
401
|
+
with self.lock:
|
|
402
|
+
loops, self.loops = self.loops, empty
|
|
403
|
+
self.load.clear()
|
|
404
|
+
for loop in loops:
|
|
405
|
+
_close_loop(loop, timeout)
|
|
406
|
+
for runner in self.threads:
|
|
407
|
+
runner.stop()
|
|
408
|
+
runner.loop.close()
|
|
409
|
+
self.threads.clear()
|
|
410
|
+
if self.reactor is not None:
|
|
411
|
+
self.reactor.stop()
|
|
412
|
+
self.reactor = None
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def _close_loop(loop: asyncio.AbstractEventLoop, timeout: float) -> None:
|
|
416
|
+
"""Cancel what still runs on ``loop``, close its LoopLocal values and async generators, close it."""
|
|
417
|
+
|
|
418
|
+
async def wind_down() -> None:
|
|
419
|
+
current = asyncio.current_task()
|
|
420
|
+
tasks = [t for t in asyncio.all_tasks(loop) if t is not current]
|
|
421
|
+
for running in tasks:
|
|
422
|
+
running.cancel()
|
|
423
|
+
if tasks:
|
|
424
|
+
await asyncio.wait(tasks, timeout=timeout)
|
|
425
|
+
await _dispose_loop_locals(loop)
|
|
426
|
+
await loop.shutdown_asyncgens()
|
|
427
|
+
|
|
428
|
+
if loop.is_closed():
|
|
429
|
+
return
|
|
430
|
+
try:
|
|
431
|
+
asyncio.run_coroutine_threadsafe(wind_down(), loop).result(timeout + 1)
|
|
432
|
+
except BaseException: # noqa: BLE001 - shutting down regardless
|
|
433
|
+
pass
|
|
434
|
+
if isinstance(loop, _StrandLoop):
|
|
435
|
+
loop.close()
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
_DEFAULT_BACKEND = "strands" if hasattr(select, "epoll") else "threads"
|
|
439
|
+
_config: dict[str, Any] = {"loops": None, "backend": _DEFAULT_BACKEND}
|
|
440
|
+
_pool: _LoopPool | None = None
|
|
441
|
+
_pool_lock = threading.Lock()
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def configure(*, loops: int | None = None, backend: str | None = None) -> None:
|
|
445
|
+
"""Set the number of loops (default: the CPU count) and the backend before first use.
|
|
446
|
+
|
|
447
|
+
``backend`` is ``"strands"`` (loops as serialized queues on the flpit pool; Linux) or
|
|
448
|
+
``"threads"`` (one thread per loop; any platform). Changing either after loops exist
|
|
449
|
+
takes effect after ``shutdown()``.
|
|
450
|
+
"""
|
|
451
|
+
if loops is not None and loops < 1:
|
|
452
|
+
raise ValueError("loops must be at least 1")
|
|
453
|
+
if backend is not None:
|
|
454
|
+
if backend not in ("strands", "threads"):
|
|
455
|
+
raise ValueError("backend must be 'strands' or 'threads'")
|
|
456
|
+
if backend == "strands" and not hasattr(select, "epoll"):
|
|
457
|
+
raise ValueError("the strands backend needs epoll (Linux); use 'threads'")
|
|
458
|
+
with _pool_lock:
|
|
459
|
+
if loops is not None:
|
|
460
|
+
_config["loops"] = loops
|
|
461
|
+
if backend is not None:
|
|
462
|
+
_config["backend"] = backend
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def _get_pool() -> _LoopPool:
|
|
466
|
+
global _pool
|
|
467
|
+
pool = _pool
|
|
468
|
+
if pool is None:
|
|
469
|
+
with _pool_lock:
|
|
470
|
+
pool = _pool
|
|
471
|
+
if pool is None:
|
|
472
|
+
pool = _pool = _LoopPool(_config["loops"] or _default_count(), _config["backend"])
|
|
473
|
+
return pool
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def shutdown(timeout: float = 5.0) -> None:
|
|
477
|
+
"""Cancel work still running on the loops, close their LoopLocal values and the loops.
|
|
478
|
+
|
|
479
|
+
Called by ``Task.shutdown`` and at interpreter exit. Later work creates new loops.
|
|
480
|
+
"""
|
|
481
|
+
global _pool
|
|
482
|
+
with _pool_lock:
|
|
483
|
+
pool, _pool = _pool, None
|
|
484
|
+
if pool is not None:
|
|
485
|
+
pool.close(timeout)
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
# ---------------------------------------------------------------------------
|
|
489
|
+
# Running asyncio code as a flpit Task
|
|
490
|
+
# ---------------------------------------------------------------------------
|
|
491
|
+
|
|
492
|
+
def run_asyncio(awaitable: Awaitable[T], *, token: CancellationToken | None = None) -> Task[T]:
|
|
493
|
+
"""Run asyncio code on an event loop and return a flpit Task for its outcome.
|
|
494
|
+
|
|
495
|
+
The loop is the one already running on this thread, if any; otherwise a loop of the pool.
|
|
496
|
+
The coroutine starts in a copy of the caller's context (``AsyncLocal`` values flow in).
|
|
497
|
+
|
|
498
|
+
``token`` cancels it: a cancelled token cancels the asyncio task (its ``finally`` blocks
|
|
499
|
+
run) and the returned Task ends cancelled; an already cancelled token starts nothing.
|
|
500
|
+
asyncio code that catches the cancellation and returns normally completes normally.
|
|
501
|
+
"""
|
|
502
|
+
source: TaskCompletionSource[T] = TaskCompletionSource()
|
|
503
|
+
if token is not None and token.is_cancellation_requested:
|
|
504
|
+
if asyncio.iscoroutine(awaitable):
|
|
505
|
+
awaitable.close()
|
|
506
|
+
source.set_canceled(token)
|
|
507
|
+
return source.task
|
|
508
|
+
coroutine = awaitable if asyncio.iscoroutine(awaitable) else _await(awaitable)
|
|
509
|
+
context = contextvars.copy_context()
|
|
510
|
+
running = events._get_running_loop()
|
|
511
|
+
if running is not None:
|
|
512
|
+
_start(running, None, coroutine, context, source, token)
|
|
513
|
+
else:
|
|
514
|
+
pool = _get_pool()
|
|
515
|
+
loop = pool.acquire()
|
|
516
|
+
loop.call_soon_threadsafe(_start, loop, pool, coroutine, context, source, token)
|
|
517
|
+
return source.task
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
async def _await(awaitable: Awaitable[T]) -> T:
|
|
521
|
+
return await awaitable
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
class _Run:
|
|
525
|
+
"""One asyncio task started for run_asyncio: its token registration and completion."""
|
|
526
|
+
|
|
527
|
+
__slots__ = ("loop", "pool", "source", "token", "registration", "task", "cancel_requested")
|
|
528
|
+
|
|
529
|
+
def __init__(self, loop: asyncio.AbstractEventLoop, pool: _LoopPool | None,
|
|
530
|
+
source: TaskCompletionSource[Any], token: CancellationToken | None) -> None:
|
|
531
|
+
self.loop = loop
|
|
532
|
+
self.pool = pool
|
|
533
|
+
self.source = source
|
|
534
|
+
self.token = token
|
|
535
|
+
self.registration: Any = None
|
|
536
|
+
self.task: asyncio.Task[Any] | None = None
|
|
537
|
+
self.cancel_requested = False
|
|
538
|
+
|
|
539
|
+
def on_cancel(self) -> None:
|
|
540
|
+
try:
|
|
541
|
+
self.loop.call_soon_threadsafe(self._cancel)
|
|
542
|
+
except RuntimeError:
|
|
543
|
+
pass # the loop is closed
|
|
544
|
+
|
|
545
|
+
def _cancel(self) -> None:
|
|
546
|
+
if self.task is None:
|
|
547
|
+
self.cancel_requested = True
|
|
548
|
+
else:
|
|
549
|
+
self.task.cancel()
|
|
550
|
+
|
|
551
|
+
def finish(self, task: asyncio.Task[Any]) -> None:
|
|
552
|
+
registration, self.registration = self.registration, None
|
|
553
|
+
if registration is not None:
|
|
554
|
+
registration.dispose()
|
|
555
|
+
if self.pool is not None:
|
|
556
|
+
self.pool.release(self.loop)
|
|
557
|
+
source, token = self.source, self.token
|
|
558
|
+
if task.cancelled():
|
|
559
|
+
source.try_set_canceled(token)
|
|
560
|
+
return
|
|
561
|
+
error = task.exception()
|
|
562
|
+
if error is None:
|
|
563
|
+
source.try_set_result(task.result())
|
|
564
|
+
elif isinstance(error, OperationCanceledError):
|
|
565
|
+
source.try_set_canceled(token if token is not None and token.is_cancellation_requested else None)
|
|
566
|
+
elif isinstance(error, Exception):
|
|
567
|
+
source.try_set_exception(error)
|
|
568
|
+
else:
|
|
569
|
+
# KeyboardInterrupt, SystemExit or another BaseException: the Task fails with it, as a
|
|
570
|
+
# flpit coroutine that raises it does (TaskCompletionSource only accepts Exceptions).
|
|
571
|
+
source._try_complete(Task.FAILED, exception=error)
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
def _start(loop: asyncio.AbstractEventLoop, pool: _LoopPool | None, coroutine: Coroutine[Any, Any, Any],
|
|
575
|
+
context: contextvars.Context, source: TaskCompletionSource[Any], token: CancellationToken | None) -> None:
|
|
576
|
+
run = _Run(loop, pool, source, token)
|
|
577
|
+
if token is not None:
|
|
578
|
+
run.registration = token.register(run.on_cancel)
|
|
579
|
+
task = loop.create_task(coroutine, context=context)
|
|
580
|
+
run.task = task
|
|
581
|
+
task.add_done_callback(run.finish)
|
|
582
|
+
if run.cancel_requested:
|
|
583
|
+
task.cancel()
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
# ---------------------------------------------------------------------------
|
|
587
|
+
# LoopLocal
|
|
588
|
+
# ---------------------------------------------------------------------------
|
|
589
|
+
|
|
590
|
+
_loop_locals: weakref.WeakSet[LoopLocal[Any]] = weakref.WeakSet()
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
class LoopLocal(Generic[T]):
|
|
594
|
+
"""One value per asyncio event loop, created on first use on that loop.
|
|
595
|
+
|
|
596
|
+
For loop-bound objects that should outlive one call: an ``httpx.AsyncClient``, an asyncpg
|
|
597
|
+
pool, an asyncio lock. ``factory`` may be a plain function or an ``async def``; read the
|
|
598
|
+
value with ``await local.get()`` (works for both) or ``local.value`` (plain factories, or
|
|
599
|
+
once created). When the bridge closes one of its loops, the loop's value is closed too:
|
|
600
|
+
``await value.aclose()`` if it has one, else ``value.close()``.
|
|
601
|
+
|
|
602
|
+
Example:
|
|
603
|
+
```python
|
|
604
|
+
clients = LoopLocal(httpx.AsyncClient)
|
|
605
|
+
|
|
606
|
+
@asyncio_task
|
|
607
|
+
async def fetch(url: str) -> dict:
|
|
608
|
+
client = await clients.get()
|
|
609
|
+
return (await client.get(url)).json()
|
|
610
|
+
```
|
|
611
|
+
"""
|
|
612
|
+
|
|
613
|
+
def __init__(self, factory: Callable[[], T | Awaitable[T]]) -> None:
|
|
614
|
+
self._factory = factory
|
|
615
|
+
self._values: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, T] = weakref.WeakKeyDictionary()
|
|
616
|
+
_loop_locals.add(self)
|
|
617
|
+
|
|
618
|
+
@staticmethod
|
|
619
|
+
def _loop() -> asyncio.AbstractEventLoop:
|
|
620
|
+
loop = events._get_running_loop()
|
|
621
|
+
if loop is None:
|
|
622
|
+
raise RuntimeError("LoopLocal is only available in code running on an asyncio event loop")
|
|
623
|
+
return loop
|
|
624
|
+
|
|
625
|
+
@property
|
|
626
|
+
def value(self) -> T:
|
|
627
|
+
loop = self._loop()
|
|
628
|
+
values = self._values
|
|
629
|
+
if loop in values:
|
|
630
|
+
return values[loop]
|
|
631
|
+
created = self._factory()
|
|
632
|
+
if asyncio.iscoroutine(created):
|
|
633
|
+
created.close()
|
|
634
|
+
raise TypeError("this LoopLocal has an async factory: use 'await local.get()'")
|
|
635
|
+
value = cast(T, created)
|
|
636
|
+
values[loop] = value
|
|
637
|
+
return value
|
|
638
|
+
|
|
639
|
+
async def get(self) -> T:
|
|
640
|
+
loop = self._loop()
|
|
641
|
+
values = self._values
|
|
642
|
+
if loop in values:
|
|
643
|
+
return values[loop]
|
|
644
|
+
created = self._factory()
|
|
645
|
+
if asyncio.iscoroutine(created) or isinstance(created, asyncio.Future):
|
|
646
|
+
value = cast(T, await created)
|
|
647
|
+
else:
|
|
648
|
+
value = cast(T, created)
|
|
649
|
+
if loop in values: # created by another task of this loop meanwhile
|
|
650
|
+
await _close_value(value)
|
|
651
|
+
return values[loop]
|
|
652
|
+
values[loop] = value
|
|
653
|
+
return value
|
|
654
|
+
|
|
655
|
+
def has_value(self) -> bool:
|
|
656
|
+
"""Whether a value exists for the loop running on this thread."""
|
|
657
|
+
loop = events._get_running_loop()
|
|
658
|
+
return loop is not None and loop in self._values
|
|
659
|
+
|
|
660
|
+
|
|
661
|
+
async def _close_value(value: object) -> None:
|
|
662
|
+
"""``await value.aclose()`` if it has one, else ``value.close()`` (awaited if it returns a coroutine)."""
|
|
663
|
+
closer = getattr(value, "aclose", None) or getattr(value, "close", None)
|
|
664
|
+
if closer is None:
|
|
665
|
+
return
|
|
666
|
+
result = closer()
|
|
667
|
+
if asyncio.iscoroutine(result):
|
|
668
|
+
await result
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
async def _dispose_loop_locals(loop: asyncio.AbstractEventLoop) -> None:
|
|
672
|
+
for local in list(_loop_locals):
|
|
673
|
+
if loop not in local._values:
|
|
674
|
+
continue
|
|
675
|
+
value = local._values.pop(loop)
|
|
676
|
+
try:
|
|
677
|
+
await _close_value(value)
|
|
678
|
+
except Exception: # noqa: BLE001 - one value's close must not keep the others open
|
|
679
|
+
_task._LOG.exception("closing a LoopLocal value failed")
|
|
680
|
+
|
|
681
|
+
|
|
682
|
+
# ---------------------------------------------------------------------------
|
|
683
|
+
# Lifecycle hooks
|
|
684
|
+
# ---------------------------------------------------------------------------
|
|
685
|
+
|
|
686
|
+
def _reset_after_fork() -> None:
|
|
687
|
+
# Only the forking thread exists in the child: the reactor and loop threads are gone.
|
|
688
|
+
global _pool
|
|
689
|
+
_pool = None
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
if hasattr(os, "register_at_fork"):
|
|
693
|
+
os.register_at_fork(after_in_child=_reset_after_fork)
|
|
694
|
+
|
|
695
|
+
|
|
696
|
+
def _shutdown_at_exit() -> None:
|
|
697
|
+
try:
|
|
698
|
+
shutdown(timeout=0.5)
|
|
699
|
+
except BaseException: # noqa: BLE001 - interpreter exit goes on
|
|
700
|
+
_task._LOG.exception("Error during asyncio bridge shutdown")
|
|
701
|
+
|
|
702
|
+
|
|
703
|
+
# Registered after flpit.task's handler (this module imports it first), so it runs before the
|
|
704
|
+
# runtime stops: the loops' remaining work still needs the pool.
|
|
705
|
+
atexit.register(_shutdown_at_exit)
|
flpit/task.py
CHANGED
|
@@ -300,6 +300,34 @@ class _ThreadState(threading.local):
|
|
|
300
300
|
_thread_state = _ThreadState()
|
|
301
301
|
|
|
302
302
|
|
|
303
|
+
class _WorkerInfo:
|
|
304
|
+
"""A pool worker's record, read by the gate."""
|
|
305
|
+
|
|
306
|
+
__slots__ = ("items", "cpu_clock")
|
|
307
|
+
|
|
308
|
+
def __init__(self) -> None:
|
|
309
|
+
# Work items started by this worker. Unchanged across the gate's ticks means the
|
|
310
|
+
# worker is still on the same item: it is stalled (waiting or computing).
|
|
311
|
+
self.items = 0
|
|
312
|
+
# This thread's CPU-time clock, where the platform has one (Linux, BSDs; not macOS
|
|
313
|
+
# or Windows): it barely moves while the thread waits, and moves while it computes.
|
|
314
|
+
self.cpu_clock: int | None = None
|
|
315
|
+
getcpuclockid = getattr(time, "pthread_getcpuclockid", None)
|
|
316
|
+
if getcpuclockid is not None:
|
|
317
|
+
try:
|
|
318
|
+
self.cpu_clock = getcpuclockid(threading.get_ident())
|
|
319
|
+
except OSError:
|
|
320
|
+
pass
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _cpu_capacity() -> float:
|
|
324
|
+
"""CPU cores Python code can use at once: 1 with the GIL, all of them without."""
|
|
325
|
+
if getattr(sys, "_is_gil_enabled", lambda: True)():
|
|
326
|
+
return 1.0
|
|
327
|
+
counter = getattr(os, "process_cpu_count", os.cpu_count)
|
|
328
|
+
return float(counter() or 1)
|
|
329
|
+
|
|
330
|
+
|
|
303
331
|
def _start_dedicated_thread(task: "Task[Any]") -> None:
|
|
304
332
|
"""Run ``task._start`` on a new background thread (.NET LongRunning)."""
|
|
305
333
|
threading.Thread(
|
|
@@ -930,6 +958,7 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
930
958
|
min_workers: int | None = None,
|
|
931
959
|
max_workers: int | None = None,
|
|
932
960
|
max_pending_background: int | None = None,
|
|
961
|
+
burst_workers: int | None = None,
|
|
933
962
|
) -> None:
|
|
934
963
|
"""Configure worker capacity before the runtime is first started.
|
|
935
964
|
|
|
@@ -945,6 +974,17 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
945
974
|
``min_workers`` is set to the same value, so that many workers start
|
|
946
975
|
on demand immediately and no more are ever added.
|
|
947
976
|
|
|
977
|
+
Workers that wait rather than compute are replaced within a few
|
|
978
|
+
milliseconds while work is queued: a worker stalled on one item while
|
|
979
|
+
the process leaves CPU unused is waiting (on a socket, a database
|
|
980
|
+
driver, a lock, a file, a sleep). A pool running sync clients thus
|
|
981
|
+
grows with the calls in flight instead of being limited to
|
|
982
|
+
``min_workers``. When the CPU is saturated (one core with the GIL,
|
|
983
|
+
every core on free-threaded builds), more threads cannot help and
|
|
984
|
+
none are added. ``burst_workers`` (default 256) caps the pool size up
|
|
985
|
+
to which this happens; beyond it only the slow starvation rule adds
|
|
986
|
+
workers. Neither ever exceeds ``max_workers``.
|
|
987
|
+
|
|
948
988
|
``max_pending_background`` is accepted for backwards compatibility and
|
|
949
989
|
ignored: like the .NET thread pool, the work queue is unbounded.
|
|
950
990
|
"""
|
|
@@ -953,7 +993,11 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
953
993
|
if _runtime is not None and not _runtime.closed:
|
|
954
994
|
raise RuntimeError("Task.configure() must be called before runtime startup")
|
|
955
995
|
config = dict(_runtime_config)
|
|
956
|
-
for label, value in (
|
|
996
|
+
for label, value in (
|
|
997
|
+
("min_workers", min_workers),
|
|
998
|
+
("max_workers", max_workers),
|
|
999
|
+
("burst_workers", burst_workers),
|
|
1000
|
+
):
|
|
957
1001
|
if value is None:
|
|
958
1002
|
continue
|
|
959
1003
|
if isinstance(value, bool) or not isinstance(value, int) or value < 1:
|
|
@@ -965,6 +1009,8 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
965
1009
|
config["min_workers"] = min_workers
|
|
966
1010
|
if config["min_workers"] > config["max_workers"]:
|
|
967
1011
|
raise ValueError("min_workers must not exceed max_workers")
|
|
1012
|
+
if burst_workers is not None:
|
|
1013
|
+
config["burst_workers"] = burst_workers
|
|
968
1014
|
if max_pending_background is not None:
|
|
969
1015
|
if (
|
|
970
1016
|
isinstance(max_pending_background, bool)
|
|
@@ -1364,6 +1410,9 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1364
1410
|
if grace_timeout < 0 or worker_timeout < 0:
|
|
1365
1411
|
raise ValueError("shutdown timeouts must be >= 0")
|
|
1366
1412
|
global _runtime
|
|
1413
|
+
bridge = sys.modules.get("flpit.asyncio_bridge")
|
|
1414
|
+
if bridge is not None:
|
|
1415
|
+
bridge.shutdown(timeout=grace_timeout) # its loops still need the pool to wind down
|
|
1367
1416
|
with _runtime_lock:
|
|
1368
1417
|
runtime = _runtime
|
|
1369
1418
|
if runtime is None:
|
|
@@ -3161,6 +3210,23 @@ def _spin_count() -> int:
|
|
|
3161
3210
|
return 400 # a few tens of microseconds
|
|
3162
3211
|
|
|
3163
3212
|
|
|
3213
|
+
class _Stall:
|
|
3214
|
+
"""The gate's view of one worker's current item: since when, and its CPU time then."""
|
|
3215
|
+
|
|
3216
|
+
__slots__ = ("items", "ticks", "since", "cpu")
|
|
3217
|
+
|
|
3218
|
+
def __init__(self, info: _WorkerInfo) -> None:
|
|
3219
|
+
self.items = info.items
|
|
3220
|
+
self.ticks = 0
|
|
3221
|
+
self.since = time.monotonic()
|
|
3222
|
+
self.cpu: float | None = None
|
|
3223
|
+
if info.cpu_clock is not None:
|
|
3224
|
+
try:
|
|
3225
|
+
self.cpu = time.clock_gettime(info.cpu_clock)
|
|
3226
|
+
except OSError:
|
|
3227
|
+
pass
|
|
3228
|
+
|
|
3229
|
+
|
|
3164
3230
|
class _WorkerPool:
|
|
3165
3231
|
"""Thread pool modelled on the .NET ThreadPool.
|
|
3166
3232
|
|
|
@@ -3171,6 +3237,11 @@ class _WorkerPool:
|
|
|
3171
3237
|
(starvation), up to the hard limit ``max_workers``.
|
|
3172
3238
|
* A worker blocked in ``Task.result()`` is reported to the pool, which may
|
|
3173
3239
|
start a replacement right away (.NET's cooperative blocking detection).
|
|
3240
|
+
* While work is queued and no worker is free, the gate looks every few
|
|
3241
|
+
milliseconds: workers stalled on one item while the process leaves CPU
|
|
3242
|
+
unused are waiting, not computing, and are replaced, up to
|
|
3243
|
+
``burst_workers``. Nothing outside flpit is patched: CPU time tells
|
|
3244
|
+
waiting from computing, whatever the wait is.
|
|
3174
3245
|
* Workers above ``min_workers`` retire after being idle for a while.
|
|
3175
3246
|
* Workers are daemon threads, like .NET background threads: a worker stuck
|
|
3176
3247
|
in user code never keeps the process from exiting.
|
|
@@ -3201,11 +3272,32 @@ class _WorkerPool:
|
|
|
3201
3272
|
_IDLE_TIMEOUT: Final = 20.0 # same order as the .NET worker idle timeout
|
|
3202
3273
|
_GATE_INTERVAL: Final = 0.5
|
|
3203
3274
|
_GATE_INTERVAL_BLOCKED: Final = 0.25
|
|
3275
|
+
# Waiting workers: how often the gate looks while work is queued and no worker is free,
|
|
3276
|
+
# how many ticks a worker must sit on one item to count as stalled, and the share of the
|
|
3277
|
+
# CPU capacity below which stalled workers are taken to be waiting rather than computing.
|
|
3278
|
+
_GATE_TICK: Final = 0.005
|
|
3279
|
+
_GATE_TICK_MAX: Final = 0.1
|
|
3280
|
+
_STALL_TICKS: Final = 2
|
|
3281
|
+
_CPU_SATURATED: Final = 0.5 # waiting workers use ~0 cores, computing ones 0.6-1 each
|
|
3282
|
+
# A stalled worker whose own CPU clock moved less than this share of the time it has been
|
|
3283
|
+
# on its item is waiting (it measures 0.000; computing ones get a share even when contended).
|
|
3284
|
+
_WAITING_CPU_SHARE: Final = 0.02
|
|
3204
3285
|
|
|
3205
|
-
def __init__(
|
|
3286
|
+
def __init__(
|
|
3287
|
+
self,
|
|
3288
|
+
runtime: "_Runtime",
|
|
3289
|
+
min_workers: int,
|
|
3290
|
+
max_workers: int,
|
|
3291
|
+
*,
|
|
3292
|
+
burst_workers: int = 256,
|
|
3293
|
+
) -> None:
|
|
3206
3294
|
self._runtime = runtime
|
|
3207
3295
|
self._min = min_workers
|
|
3208
3296
|
self._max = max_workers
|
|
3297
|
+
# Pool size up to which waiting workers are replaced without delay.
|
|
3298
|
+
self._burst = min(max_workers, max(min_workers, burst_workers))
|
|
3299
|
+
self._capacity = _cpu_capacity()
|
|
3300
|
+
self._workers: set[_WorkerInfo] = set() # one record per live worker; under _lock
|
|
3209
3301
|
self._items: deque[Callable[[], Any]] = deque()
|
|
3210
3302
|
self._lock = threading.Lock()
|
|
3211
3303
|
self._exited = threading.Condition(self._lock)
|
|
@@ -3290,6 +3382,9 @@ class _WorkerPool:
|
|
|
3290
3382
|
def _work(self) -> None:
|
|
3291
3383
|
state = _thread_state
|
|
3292
3384
|
state.pool = self
|
|
3385
|
+
info = _WorkerInfo()
|
|
3386
|
+
with self._lock:
|
|
3387
|
+
self._workers.add(info)
|
|
3293
3388
|
_install_asyncgen_hooks()
|
|
3294
3389
|
items = self._items
|
|
3295
3390
|
lock = self._lock
|
|
@@ -3383,6 +3478,7 @@ class _WorkerPool:
|
|
|
3383
3478
|
searching = True # the waker counted this worker
|
|
3384
3479
|
|
|
3385
3480
|
state.tail = False
|
|
3481
|
+
info.items += 1 # unsynchronized: only this worker writes it, the gate reads
|
|
3386
3482
|
try:
|
|
3387
3483
|
item()
|
|
3388
3484
|
except BaseException as error:
|
|
@@ -3400,6 +3496,7 @@ class _WorkerPool:
|
|
|
3400
3496
|
finally:
|
|
3401
3497
|
state.pool = None
|
|
3402
3498
|
with lock:
|
|
3499
|
+
self._workers.discard(info)
|
|
3403
3500
|
if searching:
|
|
3404
3501
|
self._searching -= 1
|
|
3405
3502
|
if counted:
|
|
@@ -3432,7 +3529,7 @@ class _WorkerPool:
|
|
|
3432
3529
|
self._gate_signal.set()
|
|
3433
3530
|
|
|
3434
3531
|
def _gate(self) -> None:
|
|
3435
|
-
"""Inject
|
|
3532
|
+
"""Inject workers while queued work waits: for waiting workers, and on starvation."""
|
|
3436
3533
|
_thread_state.internal = True
|
|
3437
3534
|
items = self._items
|
|
3438
3535
|
signal = self._gate_signal
|
|
@@ -3440,10 +3537,13 @@ class _WorkerPool:
|
|
|
3440
3537
|
while True:
|
|
3441
3538
|
signal.wait()
|
|
3442
3539
|
last = self._completed
|
|
3540
|
+
starvation_due = time.monotonic() + self._starvation_interval()
|
|
3541
|
+
stalls: dict[_WorkerInfo, _Stall] = {}
|
|
3542
|
+
cpu_then = time.process_time()
|
|
3543
|
+
wall_then = time.monotonic()
|
|
3544
|
+
tick = self._GATE_TICK
|
|
3443
3545
|
while True:
|
|
3444
|
-
if closing.wait(
|
|
3445
|
-
self._GATE_INTERVAL_BLOCKED if self._blocked else self._GATE_INTERVAL
|
|
3446
|
-
):
|
|
3546
|
+
if closing.wait(tick):
|
|
3447
3547
|
return
|
|
3448
3548
|
if not items:
|
|
3449
3549
|
# Go dormant; re-check after clearing so that a request
|
|
@@ -3452,6 +3552,18 @@ class _WorkerPool:
|
|
|
3452
3552
|
if not items:
|
|
3453
3553
|
break
|
|
3454
3554
|
signal.set()
|
|
3555
|
+
cpu_now = time.process_time()
|
|
3556
|
+
now = time.monotonic()
|
|
3557
|
+
cores_used = (cpu_now - cpu_then) / max(now - wall_then, 1e-6)
|
|
3558
|
+
cpu_then, wall_then = cpu_now, now
|
|
3559
|
+
if self._replace_waiting_workers(stalls, cores_used) is False:
|
|
3560
|
+
# The stalled workers compute: more threads cannot help; look less often.
|
|
3561
|
+
tick = min(tick * 2, self._GATE_TICK_MAX)
|
|
3562
|
+
else:
|
|
3563
|
+
tick = self._GATE_TICK
|
|
3564
|
+
if now < starvation_due:
|
|
3565
|
+
continue
|
|
3566
|
+
starvation_due = now + self._starvation_interval()
|
|
3455
3567
|
current = self._completed
|
|
3456
3568
|
if current == last:
|
|
3457
3569
|
# Work is waiting and not a single item finished during
|
|
@@ -3466,6 +3578,80 @@ class _WorkerPool:
|
|
|
3466
3578
|
self._spawn(serial)
|
|
3467
3579
|
last = current
|
|
3468
3580
|
|
|
3581
|
+
def _starvation_interval(self) -> float:
|
|
3582
|
+
return self._GATE_INTERVAL_BLOCKED if self._blocked else self._GATE_INTERVAL
|
|
3583
|
+
|
|
3584
|
+
def _replace_waiting_workers(
|
|
3585
|
+
self, stalls: dict[_WorkerInfo, _Stall], cores_used: float
|
|
3586
|
+
) -> bool | None:
|
|
3587
|
+
"""Start one worker per stalled worker that waits rather than computes.
|
|
3588
|
+
|
|
3589
|
+
True if it started any, False if the stalled workers compute (so the gate can look
|
|
3590
|
+
less often), None if there is nothing to decide yet.
|
|
3591
|
+
|
|
3592
|
+
A worker is stalled when it has been on the same item for _STALL_TICKS ticks. Whether
|
|
3593
|
+
it waits (on a socket, a driver, a lock, a file, a sleep) or computes comes from its own
|
|
3594
|
+
CPU clock where the platform has one (see _count_waiting); elsewhere from how much CPU
|
|
3595
|
+
the process used: stalled workers while most of the CPU capacity is unused are waiting.
|
|
3596
|
+
"""
|
|
3597
|
+
with self._lock:
|
|
3598
|
+
workers = list(self._workers)
|
|
3599
|
+
stalled: list[tuple[_WorkerInfo, _Stall]] = []
|
|
3600
|
+
for info in workers:
|
|
3601
|
+
record = stalls.get(info)
|
|
3602
|
+
if record is None or record.items != info.items:
|
|
3603
|
+
stalls[info] = _Stall(info) # a new item: start watching it
|
|
3604
|
+
continue
|
|
3605
|
+
record.ticks += 1
|
|
3606
|
+
if record.ticks >= self._STALL_TICKS:
|
|
3607
|
+
stalled.append((info, record))
|
|
3608
|
+
if len(stalls) > len(workers):
|
|
3609
|
+
for gone in set(stalls).difference(workers):
|
|
3610
|
+
del stalls[gone]
|
|
3611
|
+
if not stalled or self._searching or self._parked:
|
|
3612
|
+
return None # nothing stalled, or a free worker will pick the queued work up
|
|
3613
|
+
waiting = self._count_waiting(stalled, cores_used, len(workers))
|
|
3614
|
+
if not waiting:
|
|
3615
|
+
return False
|
|
3616
|
+
with self._lock:
|
|
3617
|
+
if self._closed or self._searching or self._parked:
|
|
3618
|
+
return None
|
|
3619
|
+
wanted = min(waiting, len(self._items), self._burst - self._count, self._max - self._count)
|
|
3620
|
+
if wanted <= 0:
|
|
3621
|
+
return None
|
|
3622
|
+
self._count += wanted
|
|
3623
|
+
self._searching += wanted
|
|
3624
|
+
serials = range(self._serial + 1, self._serial + wanted + 1)
|
|
3625
|
+
self._serial += wanted
|
|
3626
|
+
for serial in serials:
|
|
3627
|
+
self._spawn(serial)
|
|
3628
|
+
return True
|
|
3629
|
+
|
|
3630
|
+
def _count_waiting(self, stalled: list[tuple[_WorkerInfo, _Stall]], cores_used: float, workers: int) -> int:
|
|
3631
|
+
"""How many of the stalled workers wait rather than compute."""
|
|
3632
|
+
gil = getattr(sys, "_is_gil_enabled", lambda: True)()
|
|
3633
|
+
if gil and cores_used >= self._CPU_SATURATED:
|
|
3634
|
+
# The GIL is busy: a thread waiting for it uses no CPU and looks like a waiting
|
|
3635
|
+
# one, and more threads cannot run Python code any faster.
|
|
3636
|
+
return 0
|
|
3637
|
+
now = time.monotonic()
|
|
3638
|
+
waiting = 0
|
|
3639
|
+
for info, record in stalled:
|
|
3640
|
+
if info.cpu_clock is None or record.cpu is None:
|
|
3641
|
+
break
|
|
3642
|
+
try:
|
|
3643
|
+
cpu = time.clock_gettime(info.cpu_clock)
|
|
3644
|
+
except OSError:
|
|
3645
|
+
continue # the thread just exited
|
|
3646
|
+
if cpu - record.cpu < self._WAITING_CPU_SHARE * (now - record.since):
|
|
3647
|
+
waiting += 1
|
|
3648
|
+
else:
|
|
3649
|
+
return waiting
|
|
3650
|
+
# No per-thread CPU clocks here: decide from the CPU the process used.
|
|
3651
|
+
if cores_used >= self._CPU_SATURATED * min(self._capacity, workers):
|
|
3652
|
+
return 0
|
|
3653
|
+
return len(stalled)
|
|
3654
|
+
|
|
3469
3655
|
def close(self) -> None:
|
|
3470
3656
|
"""Stop accepting work, drop queued items and tell workers to exit."""
|
|
3471
3657
|
with self._lock:
|
|
@@ -3494,8 +3680,14 @@ class _WorkerPool:
|
|
|
3494
3680
|
class _Runtime:
|
|
3495
3681
|
"""Private singleton runtime: worker pool + socket reactor + task registry."""
|
|
3496
3682
|
|
|
3497
|
-
def __init__(
|
|
3498
|
-
|
|
3683
|
+
def __init__(
|
|
3684
|
+
self,
|
|
3685
|
+
*,
|
|
3686
|
+
min_workers: int,
|
|
3687
|
+
max_workers: int,
|
|
3688
|
+
burst_workers: int = 256,
|
|
3689
|
+
) -> None:
|
|
3690
|
+
self._pool = _WorkerPool(self, min_workers, max_workers, burst_workers=burst_workers)
|
|
3499
3691
|
self._io = _IOReactor(self)
|
|
3500
3692
|
# Pending tasks, so shutdown can cancel them. The registry is weak on
|
|
3501
3693
|
# purpose: a pending task that nothing references can never make
|
|
@@ -3959,12 +4151,14 @@ def _default_min_workers() -> int:
|
|
|
3959
4151
|
|
|
3960
4152
|
_runtime_lock = threading.RLock()
|
|
3961
4153
|
_runtime: _Runtime | None = None
|
|
3962
|
-
_runtime_config: dict[str,
|
|
4154
|
+
_runtime_config: dict[str, Any] = {
|
|
3963
4155
|
# Created on demand without delay; the same size the fixed pool used to have.
|
|
3964
4156
|
"min_workers": _default_min_workers(),
|
|
3965
4157
|
# Same default as the .NET thread pool: effectively unbounded, reached only
|
|
3966
4158
|
# through slow injection while the pool is starved.
|
|
3967
4159
|
"max_workers": 32767,
|
|
4160
|
+
# Workers that wait instead of compute are replaced quickly up to this pool size.
|
|
4161
|
+
"burst_workers": 256,
|
|
3968
4162
|
}
|
|
3969
4163
|
|
|
3970
4164
|
|
|
@@ -4112,23 +4306,28 @@ def await_using[**P, T](
|
|
|
4112
4306
|
def asyncio_task[**P, T](
|
|
4113
4307
|
async_function: Callable[P, Awaitable[T]]
|
|
4114
4308
|
) -> Callable[P, Task[T]]:
|
|
4115
|
-
"""
|
|
4116
|
-
| Wraps async functions with a dependency on asyncio to be compatible with Task.run(coro)
|
|
4309
|
+
"""Make every call of an ``async def`` that needs asyncio start a Task on an asyncio event loop.
|
|
4117
4310
|
|
|
4118
|
-
|
|
4119
|
-
|
|
4120
|
-
|
|
4311
|
+
For code that depends on asyncio, such as ``httpx.AsyncClient`` or asyncpg. Each call runs on
|
|
4312
|
+
the asyncio loop already running on the calling thread, if any, otherwise on one of the
|
|
4313
|
+
pool's shared loops (see ``flpit.asyncio_bridge``): no loop is created per call, and no pool
|
|
4314
|
+
worker is blocked while the call waits for I/O.
|
|
4315
|
+
|
|
4316
|
+
A ``CancellationToken`` passed as an argument also cancels the call, as in .NET: the asyncio
|
|
4317
|
+
task is cancelled and the returned Task ends cancelled.
|
|
4121
4318
|
|
|
4122
|
-
|
|
4123
|
-
|
|
4319
|
+
Loop-bound objects that should be reused across calls (clients, connection pools) belong in
|
|
4320
|
+
a ``LoopLocal`` (``flpit.asyncio_bridge.LoopLocal``): one per loop.
|
|
4321
|
+
"""
|
|
4124
4322
|
|
|
4125
4323
|
@functools.wraps(async_function)
|
|
4126
|
-
def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
|
|
4127
|
-
|
|
4128
|
-
|
|
4129
|
-
|
|
4324
|
+
def wrapper(*args: P.args, **kwargs: P.kwargs) -> Task[T]:
|
|
4325
|
+
from .asyncio_bridge import run_asyncio # imports asyncio on first use only
|
|
4326
|
+
|
|
4327
|
+
token = next((value for value in (*args, *kwargs.values()) if isinstance(value, CancellationToken)), None)
|
|
4328
|
+
return run_asyncio(async_function(*args, **kwargs), token=token)
|
|
4130
4329
|
|
|
4131
|
-
return
|
|
4330
|
+
return wrapper
|
|
4132
4331
|
|
|
4133
4332
|
|
|
4134
4333
|
class _SyncBridge:
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
flp/__init__.py,sha256=reAHhZtYt0f2LHeIYJbklta6Vatr6yeQCL1R-9TTyY0,688
|
|
2
2
|
flpit/__init__.py,sha256=BJh2_YMsC9G9ognk8DytyBlW4qTHAe_ql_gycf6MAhA,2608
|
|
3
|
+
flpit/asyncio_bridge.py,sha256=cZ91tGvh2l9KAy67d04KxP2LNTH0YhFblYqLIAy5BCI,27553
|
|
3
4
|
flpit/channels.py,sha256=LuJ25ReLff2eagQAoNUvOuhLCbrBDT2nwncFXafUFUc,46800
|
|
4
5
|
flpit/concurrent.py,sha256=HZueI_zSTX9ozwmxwrn7_HSrxT4VL3CKoDbKQRqAKLA,32211
|
|
5
6
|
flpit/csv.py,sha256=QMG8AxYR32i4I_lD1KL284OXdScN6vjjgusvnqw2q-A,25862
|
|
6
7
|
flpit/flp.py,sha256=WaZnrtYdxwEOJUEBv_hXg8Uwm81h8kcH64pjDh8oJhU,1527
|
|
7
8
|
flpit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
-
flpit/task.py,sha256=
|
|
9
|
+
flpit/task.py,sha256=PTgW6ZH9tly880zBmZEMvgZNlOBubjoiz8jMHNU_RKw,177514
|
|
9
10
|
flpit/threading.py,sha256=MeWwOI2DSejmwiivSL1IVGx0US-FEsgcNRjFWdwdcSg,37236
|
|
10
11
|
flpit/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
11
12
|
flpit/core/_grouping.py,sha256=QZNdNqXx4fcRsnun4nwkGKnst63Y10Q-rYBevof7Abw,954
|
|
@@ -20,7 +21,7 @@ flpit/json/__init__.py,sha256=7U7-KaxLbQybqmNTqDf4U54Njhac2ep5gxPEaavR7hA,4625
|
|
|
20
21
|
flpit/json/_core.py,sha256=IhLM116xW4jI4gg3-QmRGptVr5pHRY7X7aicm8TmO3Y,13445
|
|
21
22
|
flpit/json/_msgspec.py,sha256=19NB98R1tftz8LYY_2QriWo9d4Syii4f7QW_s8vWL2s,20124
|
|
22
23
|
flpit/json/_native.py,sha256=E_Ro3rXTCKDpb6jicBOYU9fzOJch6ZJkLqsKJNXAsTg,39974
|
|
23
|
-
flpit-0.4.2.
|
|
24
|
-
flpit-0.4.2.
|
|
25
|
-
flpit-0.4.2.
|
|
26
|
-
flpit-0.4.2.
|
|
24
|
+
flpit-0.4.2.dev9.dist-info/METADATA,sha256=0YezpATx5lp9B-HOAYMlgx1p9xGbbMSlWilbZ787Eyo,19395
|
|
25
|
+
flpit-0.4.2.dev9.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
26
|
+
flpit-0.4.2.dev9.dist-info/licenses/LICENSE,sha256=bi5Vg_YP3Oq3jaOMQT4b7WZu0NfBcZr-nRyOExUKJrQ,1063
|
|
27
|
+
flpit-0.4.2.dev9.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|