flpit 0.4.2.dev8__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/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 (("min_workers", min_workers), ("max_workers", max_workers)):
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)
@@ -3164,6 +3210,23 @@ def _spin_count() -> int:
3164
3210
  return 400 # a few tens of microseconds
3165
3211
 
3166
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
+
3167
3230
  class _WorkerPool:
3168
3231
  """Thread pool modelled on the .NET ThreadPool.
3169
3232
 
@@ -3174,6 +3237,11 @@ class _WorkerPool:
3174
3237
  (starvation), up to the hard limit ``max_workers``.
3175
3238
  * A worker blocked in ``Task.result()`` is reported to the pool, which may
3176
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.
3177
3245
  * Workers above ``min_workers`` retire after being idle for a while.
3178
3246
  * Workers are daemon threads, like .NET background threads: a worker stuck
3179
3247
  in user code never keeps the process from exiting.
@@ -3204,11 +3272,32 @@ class _WorkerPool:
3204
3272
  _IDLE_TIMEOUT: Final = 20.0 # same order as the .NET worker idle timeout
3205
3273
  _GATE_INTERVAL: Final = 0.5
3206
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
3207
3285
 
3208
- def __init__(self, runtime: "_Runtime", min_workers: int, max_workers: int) -> None:
3286
+ def __init__(
3287
+ self,
3288
+ runtime: "_Runtime",
3289
+ min_workers: int,
3290
+ max_workers: int,
3291
+ *,
3292
+ burst_workers: int = 256,
3293
+ ) -> None:
3209
3294
  self._runtime = runtime
3210
3295
  self._min = min_workers
3211
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
3212
3301
  self._items: deque[Callable[[], Any]] = deque()
3213
3302
  self._lock = threading.Lock()
3214
3303
  self._exited = threading.Condition(self._lock)
@@ -3293,6 +3382,9 @@ class _WorkerPool:
3293
3382
  def _work(self) -> None:
3294
3383
  state = _thread_state
3295
3384
  state.pool = self
3385
+ info = _WorkerInfo()
3386
+ with self._lock:
3387
+ self._workers.add(info)
3296
3388
  _install_asyncgen_hooks()
3297
3389
  items = self._items
3298
3390
  lock = self._lock
@@ -3386,6 +3478,7 @@ class _WorkerPool:
3386
3478
  searching = True # the waker counted this worker
3387
3479
 
3388
3480
  state.tail = False
3481
+ info.items += 1 # unsynchronized: only this worker writes it, the gate reads
3389
3482
  try:
3390
3483
  item()
3391
3484
  except BaseException as error:
@@ -3403,6 +3496,7 @@ class _WorkerPool:
3403
3496
  finally:
3404
3497
  state.pool = None
3405
3498
  with lock:
3499
+ self._workers.discard(info)
3406
3500
  if searching:
3407
3501
  self._searching -= 1
3408
3502
  if counted:
@@ -3435,7 +3529,7 @@ class _WorkerPool:
3435
3529
  self._gate_signal.set()
3436
3530
 
3437
3531
  def _gate(self) -> None:
3438
- """Inject a worker when queued work makes no progress (starvation)."""
3532
+ """Inject workers while queued work waits: for waiting workers, and on starvation."""
3439
3533
  _thread_state.internal = True
3440
3534
  items = self._items
3441
3535
  signal = self._gate_signal
@@ -3443,10 +3537,13 @@ class _WorkerPool:
3443
3537
  while True:
3444
3538
  signal.wait()
3445
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
3446
3545
  while True:
3447
- if closing.wait(
3448
- self._GATE_INTERVAL_BLOCKED if self._blocked else self._GATE_INTERVAL
3449
- ):
3546
+ if closing.wait(tick):
3450
3547
  return
3451
3548
  if not items:
3452
3549
  # Go dormant; re-check after clearing so that a request
@@ -3455,6 +3552,18 @@ class _WorkerPool:
3455
3552
  if not items:
3456
3553
  break
3457
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()
3458
3567
  current = self._completed
3459
3568
  if current == last:
3460
3569
  # Work is waiting and not a single item finished during
@@ -3469,6 +3578,80 @@ class _WorkerPool:
3469
3578
  self._spawn(serial)
3470
3579
  last = current
3471
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
+
3472
3655
  def close(self) -> None:
3473
3656
  """Stop accepting work, drop queued items and tell workers to exit."""
3474
3657
  with self._lock:
@@ -3497,8 +3680,14 @@ class _WorkerPool:
3497
3680
  class _Runtime:
3498
3681
  """Private singleton runtime: worker pool + socket reactor + task registry."""
3499
3682
 
3500
- def __init__(self, *, min_workers: int, max_workers: int) -> None:
3501
- self._pool = _WorkerPool(self, min_workers, max_workers)
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)
3502
3691
  self._io = _IOReactor(self)
3503
3692
  # Pending tasks, so shutdown can cancel them. The registry is weak on
3504
3693
  # purpose: a pending task that nothing references can never make
@@ -3962,12 +4151,14 @@ def _default_min_workers() -> int:
3962
4151
 
3963
4152
  _runtime_lock = threading.RLock()
3964
4153
  _runtime: _Runtime | None = None
3965
- _runtime_config: dict[str, int] = {
4154
+ _runtime_config: dict[str, Any] = {
3966
4155
  # Created on demand without delay; the same size the fixed pool used to have.
3967
4156
  "min_workers": _default_min_workers(),
3968
4157
  # Same default as the .NET thread pool: effectively unbounded, reached only
3969
4158
  # through slow injection while the pool is starved.
3970
4159
  "max_workers": 32767,
4160
+ # Workers that wait instead of compute are replaced quickly up to this pool size.
4161
+ "burst_workers": 256,
3971
4162
  }
3972
4163
 
3973
4164
 
@@ -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.dev9
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/
@@ -6,7 +6,7 @@ flpit/concurrent.py,sha256=HZueI_zSTX9ozwmxwrn7_HSrxT4VL3CKoDbKQRqAKLA,32211
6
6
  flpit/csv.py,sha256=QMG8AxYR32i4I_lD1KL284OXdScN6vjjgusvnqw2q-A,25862
7
7
  flpit/flp.py,sha256=WaZnrtYdxwEOJUEBv_hXg8Uwm81h8kcH64pjDh8oJhU,1527
8
8
  flpit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
- flpit/task.py,sha256=p1T0GVu8mxVGdPLMvfLEt7dK0Lya-MoPytD1sIirH9U,168771
9
+ flpit/task.py,sha256=PTgW6ZH9tly880zBmZEMvgZNlOBubjoiz8jMHNU_RKw,177514
10
10
  flpit/threading.py,sha256=MeWwOI2DSejmwiivSL1IVGx0US-FEsgcNRjFWdwdcSg,37236
11
11
  flpit/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
12
  flpit/core/_grouping.py,sha256=QZNdNqXx4fcRsnun4nwkGKnst63Y10Q-rYBevof7Abw,954
@@ -21,7 +21,7 @@ flpit/json/__init__.py,sha256=7U7-KaxLbQybqmNTqDf4U54Njhac2ep5gxPEaavR7hA,4625
21
21
  flpit/json/_core.py,sha256=IhLM116xW4jI4gg3-QmRGptVr5pHRY7X7aicm8TmO3Y,13445
22
22
  flpit/json/_msgspec.py,sha256=19NB98R1tftz8LYY_2QriWo9d4Syii4f7QW_s8vWL2s,20124
23
23
  flpit/json/_native.py,sha256=E_Ro3rXTCKDpb6jicBOYU9fzOJch6ZJkLqsKJNXAsTg,39974
24
- flpit-0.4.2.dev8.dist-info/METADATA,sha256=TohtpnCtXFUvu9av3-30zzkTmmuPgbz8g_yH5l7cctc,19395
25
- flpit-0.4.2.dev8.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
26
- flpit-0.4.2.dev8.dist-info/licenses/LICENSE,sha256=bi5Vg_YP3Oq3jaOMQT4b7WZu0NfBcZr-nRyOExUKJrQ,1063
27
- flpit-0.4.2.dev8.dist-info/RECORD,,
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,,