flpit 0.4.2.dev8__tar.gz → 0.4.2.dev10__tar.gz

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.
Files changed (28) hide show
  1. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/PKG-INFO +1 -1
  2. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/pyproject.toml +1 -1
  3. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/src/flpit/task.py +432 -17
  4. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/.gitignore +0 -0
  5. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/LICENSE +0 -0
  6. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/README.md +0 -0
  7. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/src/flp/__init__.py +0 -0
  8. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/src/flpit/__init__.py +0 -0
  9. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/src/flpit/asyncio_bridge.py +0 -0
  10. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/src/flpit/channels.py +0 -0
  11. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/src/flpit/concurrent.py +0 -0
  12. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/src/flpit/core/__init__.py +0 -0
  13. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/src/flpit/core/_grouping.py +0 -0
  14. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/src/flpit/core/_index.py +0 -0
  15. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/src/flpit/core/_join.py +0 -0
  16. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/src/flpit/core/_lookup.py +0 -0
  17. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/src/flpit/core/_zip.py +0 -0
  18. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/src/flpit/core/async_linq.py +0 -0
  19. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/src/flpit/core/comparers.py +0 -0
  20. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/src/flpit/core/linq.py +0 -0
  21. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/src/flpit/csv.py +0 -0
  22. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/src/flpit/flp.py +0 -0
  23. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/src/flpit/json/__init__.py +0 -0
  24. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/src/flpit/json/_core.py +0 -0
  25. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/src/flpit/json/_msgspec.py +0 -0
  26. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/src/flpit/json/_native.py +0 -0
  27. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/src/flpit/py.typed +0 -0
  28. {flpit-0.4.2.dev8 → flpit-0.4.2.dev10}/src/flpit/threading.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: flpit
3
- Version: 0.4.2.dev8
3
+ Version: 0.4.2.dev10
4
4
  Summary: Fluent LINQ for Python — flip your iterables
5
5
  Project-URL: Homepage, https://github.com/riemar/flpit
6
6
  Project-URL: Documentation, https://riemar.github.io/flpit/
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "flpit"
3
- version = "0.4.2.dev8"
3
+ version = "0.4.2.dev10"
4
4
  description = "Fluent LINQ for Python — flip your iterables"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
@@ -54,6 +54,7 @@ import inspect
54
54
  import logging
55
55
  import os
56
56
  import queue
57
+ import select
57
58
  import selectors
58
59
  import socket
59
60
  import threading
@@ -65,7 +66,7 @@ from collections.abc import AsyncGenerator, Generator
65
66
  from dataclasses import dataclass
66
67
  from itertools import count
67
68
  from types import AsyncGeneratorType, CoroutineType, FunctionType, MethodType
68
- from typing import TYPE_CHECKING, Any, Generic, Protocol, TypeVar, cast, Iterable, Final, overload
69
+ from typing import TYPE_CHECKING, Any, Generic, Protocol, TypeVar, cast, Iterable, Final, overload, override
69
70
  import functools
70
71
  from functools import wraps
71
72
  from collections.abc import Awaitable, Callable, Coroutine
@@ -300,6 +301,34 @@ class _ThreadState(threading.local):
300
301
  _thread_state = _ThreadState()
301
302
 
302
303
 
304
+ class _WorkerInfo:
305
+ """A pool worker's record, read by the gate."""
306
+
307
+ __slots__ = ("items", "cpu_clock")
308
+
309
+ def __init__(self) -> None:
310
+ # Work items started by this worker. Unchanged across the gate's ticks means the
311
+ # worker is still on the same item: it is stalled (waiting or computing).
312
+ self.items = 0
313
+ # This thread's CPU-time clock, where the platform has one (Linux, BSDs; not macOS
314
+ # or Windows): it barely moves while the thread waits, and moves while it computes.
315
+ self.cpu_clock: int | None = None
316
+ getcpuclockid = getattr(time, "pthread_getcpuclockid", None)
317
+ if getcpuclockid is not None:
318
+ try:
319
+ self.cpu_clock = getcpuclockid(threading.get_ident())
320
+ except OSError:
321
+ pass
322
+
323
+
324
+ def _cpu_capacity() -> float:
325
+ """CPU cores Python code can use at once: 1 with the GIL, all of them without."""
326
+ if getattr(sys, "_is_gil_enabled", lambda: True)():
327
+ return 1.0
328
+ counter = getattr(os, "process_cpu_count", os.cpu_count)
329
+ return float(counter() or 1)
330
+
331
+
303
332
  def _start_dedicated_thread(task: "Task[Any]") -> None:
304
333
  """Run ``task._start`` on a new background thread (.NET LongRunning)."""
305
334
  threading.Thread(
@@ -728,7 +757,7 @@ class _YieldNow(_Operation):
728
757
 
729
758
 
730
759
  class _WaitIO(_Operation):
731
- __slots__ = ("sock", "mode")
760
+ __slots__ = ("sock", "mode", "fd")
732
761
 
733
762
  def __init__(
734
763
  self, runtime: "_Runtime", sock: socket.socket, mode: str,
@@ -737,6 +766,7 @@ class _WaitIO(_Operation):
737
766
  super().__init__(runtime, token)
738
767
  self.sock = sock
739
768
  self.mode = mode
769
+ self.fd = -1 # the descriptor it was armed with; the socket may be closed by then
740
770
 
741
771
  def _on_cancel(self) -> None:
742
772
  self.runtime._cancel_wait(self)
@@ -930,6 +960,7 @@ class Task(Generic[T], metaclass=_TaskMeta):
930
960
  min_workers: int | None = None,
931
961
  max_workers: int | None = None,
932
962
  max_pending_background: int | None = None,
963
+ burst_workers: int | None = None,
933
964
  ) -> None:
934
965
  """Configure worker capacity before the runtime is first started.
935
966
 
@@ -945,6 +976,17 @@ class Task(Generic[T], metaclass=_TaskMeta):
945
976
  ``min_workers`` is set to the same value, so that many workers start
946
977
  on demand immediately and no more are ever added.
947
978
 
979
+ Workers that wait rather than compute are replaced within a few
980
+ milliseconds while work is queued: a worker stalled on one item while
981
+ the process leaves CPU unused is waiting (on a socket, a database
982
+ driver, a lock, a file, a sleep). A pool running sync clients thus
983
+ grows with the calls in flight instead of being limited to
984
+ ``min_workers``. When the CPU is saturated (one core with the GIL,
985
+ every core on free-threaded builds), more threads cannot help and
986
+ none are added. ``burst_workers`` (default 256) caps the pool size up
987
+ to which this happens; beyond it only the slow starvation rule adds
988
+ workers. Neither ever exceeds ``max_workers``.
989
+
948
990
  ``max_pending_background`` is accepted for backwards compatibility and
949
991
  ignored: like the .NET thread pool, the work queue is unbounded.
950
992
  """
@@ -953,7 +995,11 @@ class Task(Generic[T], metaclass=_TaskMeta):
953
995
  if _runtime is not None and not _runtime.closed:
954
996
  raise RuntimeError("Task.configure() must be called before runtime startup")
955
997
  config = dict(_runtime_config)
956
- for label, value in (("min_workers", min_workers), ("max_workers", max_workers)):
998
+ for label, value in (
999
+ ("min_workers", min_workers),
1000
+ ("max_workers", max_workers),
1001
+ ("burst_workers", burst_workers),
1002
+ ):
957
1003
  if value is None:
958
1004
  continue
959
1005
  if isinstance(value, bool) or not isinstance(value, int) or value < 1:
@@ -965,6 +1011,8 @@ class Task(Generic[T], metaclass=_TaskMeta):
965
1011
  config["min_workers"] = min_workers
966
1012
  if config["min_workers"] > config["max_workers"]:
967
1013
  raise ValueError("min_workers must not exceed max_workers")
1014
+ if burst_workers is not None:
1015
+ config["burst_workers"] = burst_workers
968
1016
  if max_pending_background is not None:
969
1017
  if (
970
1018
  isinstance(max_pending_background, bool)
@@ -2919,6 +2967,10 @@ class _IOReactor:
2919
2967
  queue.SimpleQueue()
2920
2968
  )
2921
2969
  self._waiters: dict[socket.socket, dict[str, set[_WaitIO]]] = {}
2970
+ # Sockets registered with the selector. Tracked here, because asking the selector
2971
+ # (get_key) raises a KeyError formatted with the socket's repr for unregistered ones,
2972
+ # which costs several microseconds a wait.
2973
+ self._registered: set[socket.socket] = set()
2922
2974
  self._closing = False
2923
2975
  self._failure: BaseException | None = None
2924
2976
 
@@ -3022,19 +3074,17 @@ class _IOReactor:
3022
3074
  mask |= selectors.EVENT_READ
3023
3075
  if sides["write"]:
3024
3076
  mask |= selectors.EVENT_WRITE
3025
- try:
3026
- selector.get_key(sock)
3027
- registered = True
3028
- except (KeyError, ValueError, OSError):
3029
- registered = False
3077
+ registered = sock in self._registered
3030
3078
  try:
3031
3079
  if mask:
3032
3080
  if registered:
3033
3081
  selector.modify(sock, mask, data=None)
3034
3082
  else:
3035
3083
  selector.register(sock, mask, data=None)
3084
+ self._registered.add(sock)
3036
3085
  else:
3037
3086
  if registered:
3087
+ self._registered.discard(sock)
3038
3088
  try:
3039
3089
  selector.unregister(sock)
3040
3090
  except (KeyError, ValueError, OSError):
@@ -3046,6 +3096,7 @@ class _IOReactor:
3046
3096
  sides = self._waiters.pop(sock, None) or {"read": set(), "write": set()}
3047
3097
  for operation in sides["read"] | sides["write"]:
3048
3098
  self._wake(operation, error)
3099
+ self._registered.discard(sock)
3049
3100
  try:
3050
3101
  selector.unregister(sock)
3051
3102
  except (KeyError, ValueError, OSError):
@@ -3131,6 +3182,224 @@ class _IOReactor:
3131
3182
  return not thread.is_alive()
3132
3183
 
3133
3184
 
3185
+ class _FdWaiters:
3186
+ """The waits armed on one file descriptor of the epoll reactor."""
3187
+
3188
+ __slots__ = ("sock", "read", "write", "registered")
3189
+
3190
+ def __init__(self, sock: socket.socket) -> None:
3191
+ # Weak: a socket the program dropped must still be closed by the garbage collector.
3192
+ self.sock: weakref.ReferenceType[socket.socket] = weakref.ref(sock)
3193
+ self.read: set[_WaitIO] = set()
3194
+ self.write: set[_WaitIO] = set()
3195
+ self.registered = False
3196
+
3197
+ def events(self) -> int:
3198
+ mask = select.EPOLLONESHOT
3199
+ if self.read:
3200
+ mask |= select.EPOLLIN
3201
+ if self.write:
3202
+ mask |= select.EPOLLOUT
3203
+ return mask
3204
+
3205
+
3206
+ class _EpollIOReactor(_IOReactor):
3207
+ """Linux: waiting workers arm sockets in the reactor's epoll themselves.
3208
+
3209
+ A wait registers its socket one-shot (EPOLLONESHOT): the kernel disarms it when it
3210
+ reports readiness, and the next wait on that socket re-arms it with one epoll_ctl
3211
+ call. No command queue, no wake-up byte, no unregistering. The reactor thread only
3212
+ waits in epoll and hands woken tasks to the pool. The epoll instance is thread-safe;
3213
+ _fd_lock keeps the waiters and the armed event mask of each descriptor consistent.
3214
+ A cancelled wait leaves its descriptor armed: the readiness it may report later
3215
+ finds no waiters and is dropped.
3216
+ """
3217
+
3218
+ def __init__(self, runtime: "_Runtime") -> None:
3219
+ super().__init__(runtime)
3220
+ self._epoll: select.epoll | None = None
3221
+ self._fd_lock = threading.Lock()
3222
+ self._fds: dict[int, _FdWaiters] = {}
3223
+ self._swept = False # set by the reactor thread as it exits; under _fd_lock
3224
+
3225
+ @override
3226
+ def arm(self, operation: _WaitIO) -> None:
3227
+ error = self._started()
3228
+ if error is None:
3229
+ error = self._arm_fd(operation)
3230
+ if error is not None:
3231
+ self._wake(operation, error)
3232
+
3233
+ @override
3234
+ def disarm(self, operation: _WaitIO) -> None:
3235
+ with self._fd_lock:
3236
+ waiters = self._fds.get(operation.fd)
3237
+ if waiters is not None:
3238
+ (waiters.read if operation.mode == "read" else waiters.write).discard(operation)
3239
+
3240
+ def _started(self) -> BaseException | None:
3241
+ if self._thread is None:
3242
+ with self._lock:
3243
+ if self._thread is None and not self._closing and self._failure is None:
3244
+ try:
3245
+ self._start()
3246
+ except BaseException as error:
3247
+ # For example out of file descriptors. Not latched:
3248
+ # a later wait may well succeed.
3249
+ self._discard_resources()
3250
+ return error
3251
+ if self._closing or self._failure is not None or self._thread is None:
3252
+ return self._failure or RuntimeShutdownError("Task runtime is shutting down")
3253
+ return None
3254
+
3255
+ def _arm_fd(self, operation: _WaitIO) -> BaseException | None:
3256
+ task = operation.waiter
3257
+ if task is None or task._waiting_on is not operation:
3258
+ return None # already cancelled
3259
+ sock = operation.sock
3260
+ try:
3261
+ fd = sock.fileno()
3262
+ except OSError as error:
3263
+ return error
3264
+ if fd < 0:
3265
+ return ValueError("cannot wait on a closed socket")
3266
+ operation.fd = fd
3267
+ epoll = cast(select.epoll, self._epoll)
3268
+ stranded: list[_WaitIO] = []
3269
+ with self._fd_lock:
3270
+ if self._swept:
3271
+ return self._failure or RuntimeShutdownError("Task runtime is shutting down")
3272
+ waiters = self._fds.get(fd)
3273
+ if waiters is None or waiters.sock() is not sock:
3274
+ if waiters is not None:
3275
+ # The descriptor now belongs to another socket: the old one was closed,
3276
+ # and the kernel dropped its registration. Its waits can never complete.
3277
+ stranded = [*waiters.read, *waiters.write]
3278
+ waiters = self._fds[fd] = _FdWaiters(sock)
3279
+ (waiters.read if operation.mode == "read" else waiters.write).add(operation)
3280
+ error = self._arm_events(epoll, fd, waiters)
3281
+ if error is not None:
3282
+ (waiters.read if operation.mode == "read" else waiters.write).discard(operation)
3283
+ for old in stranded:
3284
+ self._wake(old, OSError(f"socket closed while waiting (descriptor {fd} reused)"))
3285
+ return error
3286
+
3287
+ @staticmethod
3288
+ def _arm_events(epoll: select.epoll, fd: int, waiters: _FdWaiters) -> BaseException | None:
3289
+ """(Re-)arm ``fd`` for the waits it has; under _fd_lock."""
3290
+ events = waiters.events()
3291
+ try:
3292
+ if waiters.registered:
3293
+ try:
3294
+ epoll.modify(fd, events)
3295
+ except FileNotFoundError: # closed and reopened as the same socket object? register anew
3296
+ epoll.register(fd, events)
3297
+ else:
3298
+ try:
3299
+ epoll.register(fd, events)
3300
+ except FileExistsError: # still registered from an earlier socket on this descriptor
3301
+ epoll.modify(fd, events)
3302
+ waiters.registered = True
3303
+ except OSError as error:
3304
+ return error
3305
+ return None
3306
+
3307
+ @override
3308
+ def _start(self) -> None:
3309
+ epoll = select.epoll()
3310
+ try:
3311
+ reader, writer = socket.socketpair()
3312
+ except BaseException:
3313
+ epoll.close()
3314
+ raise
3315
+ self._epoll = epoll
3316
+ self._wake_reader, self._wake_writer = reader, writer
3317
+ reader.setblocking(False)
3318
+ writer.setblocking(False)
3319
+ epoll.register(reader.fileno(), select.EPOLLIN) # used only to stop the thread
3320
+ thread = threading.Thread(
3321
+ target=self._loop, name="Task-io", daemon=True, **_fresh_context()
3322
+ )
3323
+ thread.start()
3324
+ self._thread = thread
3325
+
3326
+ @override
3327
+ def _discard_resources(self) -> None:
3328
+ epoll, self._epoll = self._epoll, None
3329
+ if epoll is not None:
3330
+ try:
3331
+ epoll.close()
3332
+ except OSError:
3333
+ pass
3334
+ super()._discard_resources()
3335
+
3336
+ def _take(self, epoll: select.epoll, fd: int, events: int) -> list[_WaitIO]:
3337
+ """The waits ``events`` on ``fd`` complete; re-arms for the ones still waiting."""
3338
+ with self._fd_lock:
3339
+ waiters = self._fds.get(fd)
3340
+ if waiters is None:
3341
+ return []
3342
+ woken: list[_WaitIO] = []
3343
+ if events & (select.EPOLLIN | select.EPOLLERR | select.EPOLLHUP):
3344
+ woken.extend(waiters.read)
3345
+ waiters.read.clear()
3346
+ if events & (select.EPOLLOUT | select.EPOLLERR | select.EPOLLHUP):
3347
+ woken.extend(waiters.write)
3348
+ waiters.write.clear()
3349
+ if waiters.read or waiters.write:
3350
+ # One-shot disarmed the descriptor; the other direction still waits.
3351
+ if self._arm_events(epoll, fd, waiters) is not None:
3352
+ woken.extend(waiters.read)
3353
+ woken.extend(waiters.write)
3354
+ waiters.read.clear()
3355
+ waiters.write.clear()
3356
+ return woken
3357
+
3358
+ @override
3359
+ def _loop(self) -> None:
3360
+ _thread_state.internal = True
3361
+ epoll = cast(select.epoll, self._epoll)
3362
+ reader = cast(socket.socket, self._wake_reader)
3363
+ wake_fd = reader.fileno()
3364
+ failure: BaseException | None = None
3365
+ try:
3366
+ park = _park_interval(None)
3367
+ timeout = -1.0 if park is None else park
3368
+ while not self._closing:
3369
+ try:
3370
+ ready = epoll.poll(timeout)
3371
+ except InterruptedError:
3372
+ continue
3373
+ for fd, events in ready:
3374
+ if fd == wake_fd:
3375
+ try:
3376
+ while reader.recv(4096):
3377
+ pass
3378
+ except OSError: # includes BlockingIOError
3379
+ pass
3380
+ continue
3381
+ for operation in self._take(epoll, fd, events):
3382
+ self._wake(operation)
3383
+ except BaseException as error:
3384
+ failure = error
3385
+ if not self._closing:
3386
+ self._runtime._report_exception(
3387
+ {"message": "Fatal error in Task IO thread; socket waits are unavailable"},
3388
+ error,
3389
+ )
3390
+ finally:
3391
+ with self._lock:
3392
+ self._failure = failure or RuntimeShutdownError("Task runtime is shutting down")
3393
+ # Nothing will ever signal the remaining waits: fail them.
3394
+ with self._fd_lock:
3395
+ self._swept = True
3396
+ stranded = [op for waiters in self._fds.values() for op in (*waiters.read, *waiters.write)]
3397
+ self._fds.clear()
3398
+ for operation in stranded:
3399
+ self._wake(operation, self._failure)
3400
+ self._discard_resources()
3401
+
3402
+
3134
3403
  def _park_interval(longest: float | None) -> float | None:
3135
3404
  """How long a runtime thread may block in one go while it has nothing to do.
3136
3405
 
@@ -3164,6 +3433,23 @@ def _spin_count() -> int:
3164
3433
  return 400 # a few tens of microseconds
3165
3434
 
3166
3435
 
3436
+ class _Stall:
3437
+ """The gate's view of one worker's current item: since when, and its CPU time then."""
3438
+
3439
+ __slots__ = ("items", "ticks", "since", "cpu")
3440
+
3441
+ def __init__(self, info: _WorkerInfo) -> None:
3442
+ self.items = info.items
3443
+ self.ticks = 0
3444
+ self.since = time.monotonic()
3445
+ self.cpu: float | None = None
3446
+ if info.cpu_clock is not None:
3447
+ try:
3448
+ self.cpu = time.clock_gettime(info.cpu_clock)
3449
+ except OSError:
3450
+ pass
3451
+
3452
+
3167
3453
  class _WorkerPool:
3168
3454
  """Thread pool modelled on the .NET ThreadPool.
3169
3455
 
@@ -3174,6 +3460,11 @@ class _WorkerPool:
3174
3460
  (starvation), up to the hard limit ``max_workers``.
3175
3461
  * A worker blocked in ``Task.result()`` is reported to the pool, which may
3176
3462
  start a replacement right away (.NET's cooperative blocking detection).
3463
+ * While work is queued and no worker is free, the gate looks every few
3464
+ milliseconds: workers stalled on one item while the process leaves CPU
3465
+ unused are waiting, not computing, and are replaced, up to
3466
+ ``burst_workers``. Nothing outside flpit is patched: CPU time tells
3467
+ waiting from computing, whatever the wait is.
3177
3468
  * Workers above ``min_workers`` retire after being idle for a while.
3178
3469
  * Workers are daemon threads, like .NET background threads: a worker stuck
3179
3470
  in user code never keeps the process from exiting.
@@ -3204,11 +3495,32 @@ class _WorkerPool:
3204
3495
  _IDLE_TIMEOUT: Final = 20.0 # same order as the .NET worker idle timeout
3205
3496
  _GATE_INTERVAL: Final = 0.5
3206
3497
  _GATE_INTERVAL_BLOCKED: Final = 0.25
3498
+ # Waiting workers: how often the gate looks while work is queued and no worker is free,
3499
+ # how many ticks a worker must sit on one item to count as stalled, and the share of the
3500
+ # CPU capacity below which stalled workers are taken to be waiting rather than computing.
3501
+ _GATE_TICK: Final = 0.005
3502
+ _GATE_TICK_MAX: Final = 0.1
3503
+ _STALL_TICKS: Final = 2
3504
+ _CPU_SATURATED: Final = 0.5 # waiting workers use ~0 cores, computing ones 0.6-1 each
3505
+ # A stalled worker whose own CPU clock moved less than this share of the time it has been
3506
+ # on its item is waiting (it measures 0.000; computing ones get a share even when contended).
3507
+ _WAITING_CPU_SHARE: Final = 0.02
3207
3508
 
3208
- def __init__(self, runtime: "_Runtime", min_workers: int, max_workers: int) -> None:
3509
+ def __init__(
3510
+ self,
3511
+ runtime: "_Runtime",
3512
+ min_workers: int,
3513
+ max_workers: int,
3514
+ *,
3515
+ burst_workers: int = 256,
3516
+ ) -> None:
3209
3517
  self._runtime = runtime
3210
3518
  self._min = min_workers
3211
3519
  self._max = max_workers
3520
+ # Pool size up to which waiting workers are replaced without delay.
3521
+ self._burst = min(max_workers, max(min_workers, burst_workers))
3522
+ self._capacity = _cpu_capacity()
3523
+ self._workers: set[_WorkerInfo] = set() # one record per live worker; under _lock
3212
3524
  self._items: deque[Callable[[], Any]] = deque()
3213
3525
  self._lock = threading.Lock()
3214
3526
  self._exited = threading.Condition(self._lock)
@@ -3293,6 +3605,9 @@ class _WorkerPool:
3293
3605
  def _work(self) -> None:
3294
3606
  state = _thread_state
3295
3607
  state.pool = self
3608
+ info = _WorkerInfo()
3609
+ with self._lock:
3610
+ self._workers.add(info)
3296
3611
  _install_asyncgen_hooks()
3297
3612
  items = self._items
3298
3613
  lock = self._lock
@@ -3386,6 +3701,7 @@ class _WorkerPool:
3386
3701
  searching = True # the waker counted this worker
3387
3702
 
3388
3703
  state.tail = False
3704
+ info.items += 1 # unsynchronized: only this worker writes it, the gate reads
3389
3705
  try:
3390
3706
  item()
3391
3707
  except BaseException as error:
@@ -3403,6 +3719,7 @@ class _WorkerPool:
3403
3719
  finally:
3404
3720
  state.pool = None
3405
3721
  with lock:
3722
+ self._workers.discard(info)
3406
3723
  if searching:
3407
3724
  self._searching -= 1
3408
3725
  if counted:
@@ -3435,7 +3752,7 @@ class _WorkerPool:
3435
3752
  self._gate_signal.set()
3436
3753
 
3437
3754
  def _gate(self) -> None:
3438
- """Inject a worker when queued work makes no progress (starvation)."""
3755
+ """Inject workers while queued work waits: for waiting workers, and on starvation."""
3439
3756
  _thread_state.internal = True
3440
3757
  items = self._items
3441
3758
  signal = self._gate_signal
@@ -3443,10 +3760,13 @@ class _WorkerPool:
3443
3760
  while True:
3444
3761
  signal.wait()
3445
3762
  last = self._completed
3763
+ starvation_due = time.monotonic() + self._starvation_interval()
3764
+ stalls: dict[_WorkerInfo, _Stall] = {}
3765
+ cpu_then = time.process_time()
3766
+ wall_then = time.monotonic()
3767
+ tick = self._GATE_TICK
3446
3768
  while True:
3447
- if closing.wait(
3448
- self._GATE_INTERVAL_BLOCKED if self._blocked else self._GATE_INTERVAL
3449
- ):
3769
+ if closing.wait(tick):
3450
3770
  return
3451
3771
  if not items:
3452
3772
  # Go dormant; re-check after clearing so that a request
@@ -3455,6 +3775,18 @@ class _WorkerPool:
3455
3775
  if not items:
3456
3776
  break
3457
3777
  signal.set()
3778
+ cpu_now = time.process_time()
3779
+ now = time.monotonic()
3780
+ cores_used = (cpu_now - cpu_then) / max(now - wall_then, 1e-6)
3781
+ cpu_then, wall_then = cpu_now, now
3782
+ if self._replace_waiting_workers(stalls, cores_used) is False:
3783
+ # The stalled workers compute: more threads cannot help; look less often.
3784
+ tick = min(tick * 2, self._GATE_TICK_MAX)
3785
+ else:
3786
+ tick = self._GATE_TICK
3787
+ if now < starvation_due:
3788
+ continue
3789
+ starvation_due = now + self._starvation_interval()
3458
3790
  current = self._completed
3459
3791
  if current == last:
3460
3792
  # Work is waiting and not a single item finished during
@@ -3469,6 +3801,80 @@ class _WorkerPool:
3469
3801
  self._spawn(serial)
3470
3802
  last = current
3471
3803
 
3804
+ def _starvation_interval(self) -> float:
3805
+ return self._GATE_INTERVAL_BLOCKED if self._blocked else self._GATE_INTERVAL
3806
+
3807
+ def _replace_waiting_workers(
3808
+ self, stalls: dict[_WorkerInfo, _Stall], cores_used: float
3809
+ ) -> bool | None:
3810
+ """Start one worker per stalled worker that waits rather than computes.
3811
+
3812
+ True if it started any, False if the stalled workers compute (so the gate can look
3813
+ less often), None if there is nothing to decide yet.
3814
+
3815
+ A worker is stalled when it has been on the same item for _STALL_TICKS ticks. Whether
3816
+ it waits (on a socket, a driver, a lock, a file, a sleep) or computes comes from its own
3817
+ CPU clock where the platform has one (see _count_waiting); elsewhere from how much CPU
3818
+ the process used: stalled workers while most of the CPU capacity is unused are waiting.
3819
+ """
3820
+ with self._lock:
3821
+ workers = list(self._workers)
3822
+ stalled: list[tuple[_WorkerInfo, _Stall]] = []
3823
+ for info in workers:
3824
+ record = stalls.get(info)
3825
+ if record is None or record.items != info.items:
3826
+ stalls[info] = _Stall(info) # a new item: start watching it
3827
+ continue
3828
+ record.ticks += 1
3829
+ if record.ticks >= self._STALL_TICKS:
3830
+ stalled.append((info, record))
3831
+ if len(stalls) > len(workers):
3832
+ for gone in set(stalls).difference(workers):
3833
+ del stalls[gone]
3834
+ if not stalled or self._searching or self._parked:
3835
+ return None # nothing stalled, or a free worker will pick the queued work up
3836
+ waiting = self._count_waiting(stalled, cores_used, len(workers))
3837
+ if not waiting:
3838
+ return False
3839
+ with self._lock:
3840
+ if self._closed or self._searching or self._parked:
3841
+ return None
3842
+ wanted = min(waiting, len(self._items), self._burst - self._count, self._max - self._count)
3843
+ if wanted <= 0:
3844
+ return None
3845
+ self._count += wanted
3846
+ self._searching += wanted
3847
+ serials = range(self._serial + 1, self._serial + wanted + 1)
3848
+ self._serial += wanted
3849
+ for serial in serials:
3850
+ self._spawn(serial)
3851
+ return True
3852
+
3853
+ def _count_waiting(self, stalled: list[tuple[_WorkerInfo, _Stall]], cores_used: float, workers: int) -> int:
3854
+ """How many of the stalled workers wait rather than compute."""
3855
+ gil = getattr(sys, "_is_gil_enabled", lambda: True)()
3856
+ if gil and cores_used >= self._CPU_SATURATED:
3857
+ # The GIL is busy: a thread waiting for it uses no CPU and looks like a waiting
3858
+ # one, and more threads cannot run Python code any faster.
3859
+ return 0
3860
+ now = time.monotonic()
3861
+ waiting = 0
3862
+ for info, record in stalled:
3863
+ if info.cpu_clock is None or record.cpu is None:
3864
+ break
3865
+ try:
3866
+ cpu = time.clock_gettime(info.cpu_clock)
3867
+ except OSError:
3868
+ continue # the thread just exited
3869
+ if cpu - record.cpu < self._WAITING_CPU_SHARE * (now - record.since):
3870
+ waiting += 1
3871
+ else:
3872
+ return waiting
3873
+ # No per-thread CPU clocks here: decide from the CPU the process used.
3874
+ if cores_used >= self._CPU_SATURATED * min(self._capacity, workers):
3875
+ return 0
3876
+ return len(stalled)
3877
+
3472
3878
  def close(self) -> None:
3473
3879
  """Stop accepting work, drop queued items and tell workers to exit."""
3474
3880
  with self._lock:
@@ -3497,9 +3903,16 @@ class _WorkerPool:
3497
3903
  class _Runtime:
3498
3904
  """Private singleton runtime: worker pool + socket reactor + task registry."""
3499
3905
 
3500
- def __init__(self, *, min_workers: int, max_workers: int) -> None:
3501
- self._pool = _WorkerPool(self, min_workers, max_workers)
3502
- self._io = _IOReactor(self)
3906
+ def __init__(
3907
+ self,
3908
+ *,
3909
+ min_workers: int,
3910
+ max_workers: int,
3911
+ burst_workers: int = 256,
3912
+ ) -> None:
3913
+ self._pool = _WorkerPool(self, min_workers, max_workers, burst_workers=burst_workers)
3914
+ # Linux: workers arm sockets in epoll themselves; elsewhere, a selector thread.
3915
+ self._io: _IOReactor = _EpollIOReactor(self) if hasattr(select, "epoll") else _IOReactor(self)
3503
3916
  # Pending tasks, so shutdown can cancel them. The registry is weak on
3504
3917
  # purpose: a pending task that nothing references can never make
3505
3918
  # progress (anything that can resume it -- the pool queue, a running
@@ -3962,12 +4375,14 @@ def _default_min_workers() -> int:
3962
4375
 
3963
4376
  _runtime_lock = threading.RLock()
3964
4377
  _runtime: _Runtime | None = None
3965
- _runtime_config: dict[str, int] = {
4378
+ _runtime_config: dict[str, Any] = {
3966
4379
  # Created on demand without delay; the same size the fixed pool used to have.
3967
4380
  "min_workers": _default_min_workers(),
3968
4381
  # Same default as the .NET thread pool: effectively unbounded, reached only
3969
4382
  # through slow injection while the pool is starved.
3970
4383
  "max_workers": 32767,
4384
+ # Workers that wait instead of compute are replaced quickly up to this pool size.
4385
+ "burst_workers": 256,
3971
4386
  }
3972
4387
 
3973
4388
 
File without changes
File without changes
File without changes
File without changes
File without changes