flpit 0.3.4.dev1__py3-none-any.whl → 0.4.0.dev1__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
@@ -4,7 +4,7 @@ Although it's asyncio free, it can cooperate / co-exist with asyncio.
4
4
 
5
5
  Public API
6
6
  ----------
7
- Task.configure(max_workers=8, max_pending_background=128)
7
+ Task.configure(min_workers=8, max_workers=64)
8
8
  Task.run(async_function, *args, token=token)
9
9
  Task.run(blocking_function, *args, token=token, pass_token=True)
10
10
  await Task.delay(0.5, token=token)
@@ -19,6 +19,28 @@ There is no application-managed Runtime object and no asyncio dependency. The
19
19
  runtime is process-wide and starts lazily. Call Task.shutdown() for an explicit,
20
20
  observable shutdown; it can be started again by subsequent Task.run calls.
21
21
 
22
+ Execution model
23
+ ---------------
24
+ The runtime follows the .NET thread-pool model rather than an event loop:
25
+
26
+ * Coroutines and synchronous callables both execute on pool worker threads.
27
+ A coroutine may resume on a different worker after every ``await``.
28
+ * There is no scheduler thread between two steps of a coroutine. Completing a
29
+ task hands its continuations straight to the pool; awaiting an already
30
+ completed task continues inline without leaving the worker.
31
+ * A single timer thread and (only when sockets are awaited) a single selector
32
+ thread turn deadlines and socket readiness into completions. Neither of them
33
+ ever runs coroutine code.
34
+ * The pool creates workers on demand up to ``min_workers``. Beyond that it
35
+ injects further workers, up to ``max_workers``, when queued work makes no
36
+ progress or when workers are blocked in ``Task.result()``.
37
+ * ``Task.result()`` called on a worker for a task that has not started yet
38
+ runs that task inline on the calling worker instead of blocking.
39
+
40
+ With the GIL only one worker runs Python code at a time, exactly like any
41
+ other threaded program. On free-threaded builds (3.13t and later) workers run
42
+ in parallel; no state is funnelled through a single thread.
43
+
22
44
  Cancellation is cooperative for coroutines and worker functions. A worker can
23
45
  receive the same token with pass_token=True and should check it between units
24
46
  of work. Python cannot safely force-stop an arbitrary running thread.
@@ -36,11 +58,12 @@ import selectors
36
58
  import socket
37
59
  import threading
38
60
  import time
61
+ import warnings
39
62
  from collections import deque
40
- from collections.abc import Generator
41
- from concurrent.futures import Future, ThreadPoolExecutor
63
+ from collections.abc import AsyncGenerator, Generator
42
64
  from dataclasses import dataclass
43
65
  from itertools import count
66
+ from types import CoroutineType, FunctionType, MethodType
44
67
  from typing import Any, Generic, TypeVar, cast, Iterable, Final, overload
45
68
  import functools
46
69
  from functools import wraps
@@ -54,7 +77,11 @@ T = TypeVar("T")
54
77
  _LOG = logging.getLogger("task")
55
78
  _MISSING = object()
56
79
  _WAKE = object()
57
- _asyncio_bridge_init_lock: Final[threading.Lock] = threading.Lock()
80
+
81
+ _PENDING: Final = "pending"
82
+ _SUCCEEDED: Final = "succeeded"
83
+ _FAILED: Final = "failed"
84
+ _CANCELLED: Final = "cancelled"
58
85
 
59
86
 
60
87
  class OperationCanceledError(Exception):
@@ -83,7 +110,10 @@ class InvalidStateError(RuntimeError):
83
110
 
84
111
 
85
112
  class BackgroundQueueFull(RuntimeError):
86
- """Raised when the bounded background-work queue has no free capacity."""
113
+ """No longer raised: the work queue is unbounded, as in the .NET thread pool.
114
+
115
+ Kept so that existing ``except BackgroundQueueFull`` clauses keep importing.
116
+ """
87
117
 
88
118
 
89
119
  class RuntimeShutdownError(RuntimeError):
@@ -109,6 +139,7 @@ class AggregateError(Exception):
109
139
  raise TypeError("exceptions must contain Exception instances")
110
140
  super().__init__(message)
111
141
 
142
+
112
143
  class _TaskMeta(type):
113
144
 
114
145
  @property
@@ -131,6 +162,7 @@ class _TaskMeta(type):
131
162
  )
132
163
  setattr(cls, "__await__", implementation)
133
164
 
165
+
134
166
  @dataclass(frozen=True)
135
167
  class ShutdownReport:
136
168
  """Outcome of a runtime shutdown request."""
@@ -141,6 +173,158 @@ class ShutdownReport:
141
173
  timed_out: bool
142
174
 
143
175
 
176
+ class _ThreadState(threading.local):
177
+ """Per-thread scheduling state. Class attributes are the defaults."""
178
+
179
+ # The pool this thread works for, or None for foreign threads.
180
+ pool: "_WorkerPool | None" = None
181
+ # Work the worker runs next, without a round trip through the shared queue.
182
+ slot: Callable[[], None] | None = None
183
+ # True while a worker is between two work items (after user code returned).
184
+ tail: bool = False
185
+ # Consecutive slot hand-offs; bounded so queued work is not starved.
186
+ streak: int = 0
187
+ # True on the timer and selector threads, which must never block on a Task.
188
+ internal: bool = False
189
+ # Nesting depth of completions that run continuations on this thread.
190
+ depth: int = 0
191
+ # Nesting depth of tasks run inline by Task.result() on this thread.
192
+ inline: int = 0
193
+
194
+
195
+ _thread_state = _ThreadState()
196
+
197
+ # A worker may keep feeding itself continuations this many times before it
198
+ # has to go back to the shared queue.
199
+ _MAX_SLOT_STREAK: Final = 64
200
+
201
+ # Completing a task can complete an aggregate (when_all/when_any), which can
202
+ # complete another one, and so on, all on one stack. Past this depth the
203
+ # remaining continuations are handed to the pool instead (.NET guards its
204
+ # synchronous continuations against deep stacks in the same way).
205
+ _MAX_COMPLETION_DEPTH: Final = 24
206
+
207
+ # Task.result() on a worker runs a not-yet-started task inline, and that task
208
+ # may do the same with another one. Past this depth the worker blocks instead
209
+ # (.NET stops inlining when the stack is running low).
210
+ _MAX_INLINE_DEPTH: Final = 32
211
+
212
+
213
+ class _TimerHandle:
214
+ """Cancellable entry in the timer queue."""
215
+
216
+ __slots__ = ("_queue", "_callback")
217
+
218
+ def __init__(self, timer_queue: "_TimerQueue", callback: Callable[[], Any]) -> None:
219
+ self._queue = timer_queue
220
+ self._callback: Callable[[], Any] | None = callback
221
+
222
+ def cancel(self) -> None:
223
+ if self._callback is not None:
224
+ self._queue._cancel(self)
225
+
226
+
227
+ class _TimerQueue:
228
+ """One daemon thread serving every deadline in the process.
229
+
230
+ Used for ``Task.delay`` and ``CancellationTokenSource.cancel_after``, which
231
+ previously cost a scheduler round trip and one OS thread per timer
232
+ respectively. Callbacks run on the timer thread and must not block; the
233
+ runtime's own callbacks only complete a task or queue work to the pool.
234
+ """
235
+
236
+ # Condition.wait() cannot take arbitrarily large timeouts.
237
+ _MAX_WAIT: Final = 24 * 60 * 60.0
238
+
239
+ def __init__(self) -> None:
240
+ self._condition = threading.Condition(threading.Lock())
241
+ self._heap: list[tuple[float, int, _TimerHandle]] = []
242
+ self._sequence = 0
243
+ self._cancelled = 0
244
+ self._thread: threading.Thread | None = None
245
+
246
+ def schedule(self, delay: float, callback: Callable[[], Any]) -> _TimerHandle:
247
+ handle = _TimerHandle(self, callback)
248
+ deadline = time.monotonic() + delay
249
+ with self._condition:
250
+ heap = self._heap
251
+ if self._cancelled > 64 and self._cancelled * 2 > len(heap):
252
+ # Mostly dead entries (timeouts that were cancelled early):
253
+ # rebuild so they do not pin memory until their deadline.
254
+ heap = [entry for entry in heap if entry[2]._callback is not None]
255
+ heapq.heapify(heap)
256
+ self._heap = heap
257
+ self._cancelled = 0
258
+ self._sequence += 1
259
+ heapq.heappush(heap, (deadline, self._sequence, handle))
260
+ thread = self._thread
261
+ if thread is None or not thread.is_alive():
262
+ thread = threading.Thread(
263
+ target=self._run, name="Task-timer", daemon=True, **_fresh_context()
264
+ )
265
+ self._thread = thread
266
+ thread.start()
267
+ elif heap[0][2] is handle:
268
+ self._condition.notify()
269
+ return handle
270
+
271
+ def _cancel(self, handle: _TimerHandle) -> None:
272
+ with self._condition:
273
+ if handle._callback is not None:
274
+ handle._callback = None
275
+ self._cancelled += 1
276
+
277
+ def _run(self) -> None:
278
+ _thread_state.internal = True
279
+ condition = self._condition
280
+ due: list[Callable[[], Any]] = []
281
+ while True:
282
+ with condition:
283
+ while True:
284
+ heap = self._heap
285
+ now = time.monotonic()
286
+ while heap:
287
+ deadline, _, handle = heap[0]
288
+ callback = handle._callback
289
+ if callback is None:
290
+ heapq.heappop(heap)
291
+ self._cancelled -= 1
292
+ elif deadline <= now:
293
+ heapq.heappop(heap)
294
+ handle._callback = None
295
+ due.append(callback)
296
+ else:
297
+ break
298
+ if due:
299
+ break
300
+ if heap:
301
+ condition.wait(min(heap[0][0] - now, self._MAX_WAIT))
302
+ else:
303
+ condition.wait()
304
+ for callback in due:
305
+ try:
306
+ callback()
307
+ except BaseException:
308
+ _LOG.exception("Unhandled exception in Task timer callback")
309
+ due.clear()
310
+
311
+
312
+ def _fresh_context() -> dict[str, Any]:
313
+ """Thread() arguments that give a runtime thread an empty context.
314
+
315
+ From Python 3.14 a new thread may inherit the context of the thread that
316
+ happened to start it (the default on free-threaded builds). A pool thread
317
+ started from inside a task would then keep that task's AsyncLocal values
318
+ alive and observe them as its own.
319
+ """
320
+ if sys.version_info >= (3, 14):
321
+ return {"context": Context()}
322
+ return {}
323
+
324
+
325
+ _timers = _TimerQueue()
326
+
327
+
144
328
  class _CancellationState:
145
329
  """Thread-safe cancellation state shared by tokens and their source."""
146
330
 
@@ -204,24 +388,21 @@ def _invoke_cancellation_callback(callback: Callable[[], Any]) -> Exception | No
204
388
  class CancellationTokenRegistration:
205
389
  """Disposable registration returned by CancellationToken.register()."""
206
390
 
207
- __slots__ = ("_state", "_key", "_disposed", "_lock")
391
+ __slots__ = ("_state", "_key")
208
392
 
209
393
  def __init__(self, state: _CancellationState | None, key: int | None) -> None:
210
394
  self._state = state
211
395
  self._key = key
212
- self._disposed = False
213
- self._lock = threading.Lock()
214
396
 
215
397
  def dispose(self) -> None:
216
- with self._lock:
217
- if self._disposed:
218
- return
219
- self._disposed = True
220
- state, key = self._state, self._key
398
+ # Needs no lock of its own: unregistering is idempotent, so two racing
399
+ # dispose() calls are harmless.
400
+ state = self._state
401
+ if state is not None:
221
402
  self._state = None
222
- self._key = None
223
- if state is not None and key is not None:
224
- state.unregister(key)
403
+ key = self._key
404
+ if key is not None:
405
+ state.unregister(key)
225
406
 
226
407
  close = dispose
227
408
 
@@ -252,11 +433,10 @@ class CancellationToken:
252
433
 
253
434
  @property
254
435
  def is_cancellation_requested(self) -> bool:
436
+ # A single attribute read; cancellation is a one-way False -> True
437
+ # transition, so polling it in a worker loop needs no lock.
255
438
  state = self._state
256
- if state is None:
257
- return False
258
- with state.lock:
259
- return state.cancelled
439
+ return state is not None and state.cancelled
260
440
 
261
441
  def throw_if_cancellation_requested(self) -> None:
262
442
  if self.is_cancellation_requested:
@@ -289,7 +469,7 @@ class CancellationTokenSource:
289
469
  self._token = CancellationToken(self._state)
290
470
  self._lock = threading.RLock()
291
471
  self._disposed = False
292
- self._timer: threading.Timer | None = None
472
+ self._timer: _TimerHandle | None = None
293
473
  self._linked_registrations: list[CancellationTokenRegistration] = []
294
474
 
295
475
  @property
@@ -325,17 +505,14 @@ class CancellationTokenSource:
325
505
  old_timer = self._timer
326
506
  self._timer = None
327
507
  if seconds is not None and seconds != -1:
328
- if seconds < 0:
508
+ if not seconds >= 0: # also rejects NaN
329
509
  raise ValueError("seconds must be >= 0, -1, or None")
330
- timer = threading.Timer(seconds, self._cancel_from_timer)
331
- timer.daemon = True
332
- self._timer = timer
333
- else:
334
- timer = None
510
+ # Served by the shared timer thread rather than one OS thread
511
+ # per pending timeout. Registered callbacks therefore run on
512
+ # that thread and, as in .NET, are expected to return quickly.
513
+ self._timer = _timers.schedule(seconds, self._cancel_from_timer)
335
514
  if old_timer is not None:
336
515
  old_timer.cancel()
337
- if timer is not None:
338
- timer.start()
339
516
 
340
517
  def _cancel_from_timer(self) -> None:
341
518
  try:
@@ -343,6 +520,8 @@ class CancellationTokenSource:
343
520
  except RuntimeError:
344
521
  # The source was disposed concurrently with its timer firing.
345
522
  pass
523
+ except AggregateError:
524
+ _LOG.exception("Cancellation callbacks failed after cancel_after() elapsed")
346
525
 
347
526
  @classmethod
348
527
  def create_linked_token_source(
@@ -404,35 +583,29 @@ class CancellationTokenSource:
404
583
 
405
584
 
406
585
  class _Operation:
407
- """Instruction yielded by an awaitable and consumed by the scheduler."""
586
+ """Instruction yielded by an awaitable and consumed by the worker driving it."""
587
+
588
+ __slots__ = ("runtime", "token", "waiter", "_token_registration")
408
589
 
409
590
  def __init__(self, runtime: "_Runtime", token: CancellationToken | None = None) -> None:
410
591
  self.runtime = runtime
411
- self.token = token or CancellationToken.none()
592
+ self.token = token if token is not None else _NONE_TOKEN
593
+ # The task suspended on this operation; set when it parks.
594
+ self.waiter: Task[Any] | None = None
412
595
  self._token_registration: CancellationTokenRegistration | None = None
413
596
 
414
- def __await__(self):
597
+ def __await__(self) -> Generator[Any, Any, Any]:
415
598
  result = yield self
416
599
  return result
417
600
 
418
601
 
419
- class _Sleep(_Operation):
420
- def __init__(
421
- self,
422
- runtime: "_Runtime",
423
- delay: float,
424
- token: CancellationToken | None = None,
425
- ) -> None:
426
- super().__init__(runtime, token)
427
- self.delay = delay
428
- self.deadline = time.monotonic() + delay
429
-
430
-
431
602
  class _YieldNow(_Operation):
432
- pass
603
+ __slots__ = ()
433
604
 
434
605
 
435
606
  class _WaitIO(_Operation):
607
+ __slots__ = ("sock", "mode")
608
+
436
609
  def __init__(
437
610
  self, runtime: "_Runtime", sock: socket.socket, mode: str,
438
611
  token: CancellationToken | None = None,
@@ -441,12 +614,25 @@ class _WaitIO(_Operation):
441
614
  self.sock = sock
442
615
  self.mode = mode
443
616
 
617
+ def _on_cancel(self) -> None:
618
+ self.runtime._cancel_wait(self)
619
+
444
620
 
445
- class _WaitTask[T](_Operation):
446
- def __init__(self, runtime: "_Runtime", ttw: "Task[T]") -> None:
621
+ class _WaitTask(_Operation):
622
+ """A coroutine awaiting another task. Doubles as that task's continuation."""
623
+
624
+ __slots__ = ("task",)
625
+
626
+ def __init__(self, runtime: "_Runtime", ttw: "Task[Any]") -> None:
447
627
  super().__init__(runtime)
448
628
  self.task = ttw
449
629
 
630
+ def __call__(self, completed: "Task[Any]") -> None:
631
+ waiter = self.waiter
632
+ if waiter is not None and waiter._claim(self):
633
+ _resume_from(waiter, completed)
634
+ waiter._runtime._enqueue_task(waiter)
635
+
450
636
  def __repr__(self) -> str:
451
637
  return (
452
638
  "<flpit _WaitTask: this await operation requires the "
@@ -455,154 +641,90 @@ class _WaitTask[T](_Operation):
455
641
  )
456
642
 
457
643
 
458
- class _WaitMany[T](_Operation):
459
- """Wait for all or any of a set of tasks to complete."""
644
+ def _resume_from(waiter: "Task[Any]", completed: "Task[Any]") -> None:
645
+ """Store the outcome of ``completed`` as the next value sent into ``waiter``.
460
646
 
461
- def __init__(
462
- self, runtime: "_Runtime", tasks: tuple["Task[T]", ...], mode: str
463
- ) -> None:
464
- super().__init__(runtime)
465
- if mode not in ("all", "any"):
466
- raise ValueError("mode must be 'all' or 'any'")
467
- self.tasks = tasks
468
- self.mode = mode
647
+ Only called by the thread that currently owns ``waiter`` (see Task._claim).
648
+ """
649
+ state = completed._state
650
+ if state is _SUCCEEDED:
651
+ waiter._next_value = completed._result
652
+ elif state is _CANCELLED:
653
+ waiter._next_exception = completed._cancellation_exception()
654
+ else:
655
+ waiter._next_exception = completed._exception
469
656
 
470
657
 
471
- class _BackgroundCall(_Operation):
472
- def __init__(
473
- self,
474
- runtime: "_Runtime",
475
- function: Callable[..., Any],
476
- args: tuple[Any, ...],
477
- kwargs: dict[str, Any],
478
- ) -> None:
479
- super().__init__(runtime)
480
- self.function = function
481
- self.args = args
482
- self.kwargs = kwargs
483
- self.future: Future[Any] | None = None
484
- self._counted_active = False
658
+ def _close_if_coroutine(value: Any) -> None:
659
+ if type(value) is CoroutineType:
660
+ value.close()
485
661
 
486
662
 
487
663
  async def _await_any(awaitable: Any) -> Any:
488
664
  return await awaitable
489
665
 
490
666
 
491
- async def _invoke_async(
492
- function: Callable[..., Any], args: tuple[Any, ...], kwargs: dict[str, Any]
493
- ) -> Any:
494
- return await function(*args, **kwargs)
495
-
496
-
497
- async def _invoke_background(
498
- runtime: "_Runtime",
499
- function: Callable[..., Any],
500
- args: tuple[Any, ...],
501
- kwargs: dict[str, Any],
502
- ) -> Any:
503
- result = await _BackgroundCall(runtime, function, args, kwargs)
504
- # Support sync wrappers that return an awaitable.
505
- if inspect.isawaitable(result):
506
- return await result
507
- return result
508
-
509
- @dataclass(frozen=True)
510
- class _CoroutineStep:
511
- yielded: Any = None
512
- result: Any = None
513
- error: BaseException | None = None
514
- completed: bool = False
515
-
516
- def _advance_coroutine(
517
- coroutine: Coroutine[Any, Any, Any],
518
- value: Any,
519
- exception: BaseException | None,
520
- ) -> _CoroutineStep:
521
- try:
522
- if exception is not None:
523
- yielded = coroutine.throw(exception)
524
- else:
525
- yielded = coroutine.send(value)
526
- except StopIteration as stop:
527
- return _CoroutineStep(result=stop.value, completed=True)
528
- except BaseException as error:
529
- return _CoroutineStep(error=error, completed=True)
530
-
531
- return _CoroutineStep(yielded=yielded)
532
-
533
- async def _delay_coroutine(
534
- runtime: "_Runtime",
535
- delay: float,
536
- token: CancellationToken | None = None,
537
- ) -> None:
538
- await _Sleep(runtime, delay, token=token)
539
-
540
- class _AsyncioBridge:
541
- """Manages completion notifications for asyncio awaiters of a Task."""
542
-
543
- def __init__(self) -> None:
544
- self._callbacks: list[Callable[[], None]] = []
545
- self._lock = threading.Lock()
546
- self._completed = False
547
-
548
- def add(self, callback: Callable[[], None]) -> None:
549
- with self._lock:
550
- if not self._completed:
551
- self._callbacks.append(callback)
552
- return
553
-
554
- callback()
555
-
556
- def complete(self) -> None:
557
- with self._lock:
558
- if self._completed:
559
- return
560
-
561
- self._completed = True
562
- callbacks: list[Callable[[], None]] = self._callbacks.copy()
563
- self._callbacks.clear()
564
-
565
- for callback in callbacks:
566
- callback()
567
-
568
-
569
667
  class Task(Generic[T], metaclass=_TaskMeta):
570
- """Result-bearing task managed by FlpIt's process-wide scheduler."""
668
+ """Result-bearing task executed by FlpIt's process-wide thread pool.
669
+
670
+ Ownership rule used throughout: at any moment a pending coroutine task is
671
+ owned by exactly one party -- the worker running its current step, the
672
+ pool queue, or the single operation it is parked on. A parked task is
673
+ resumed by whoever wins ``_claim()`` for that operation; everyone else
674
+ backs off. That is what makes completion, cancellation, timers and
675
+ shutdown safe to race against each other without a scheduler thread.
676
+ """
571
677
 
572
- PENDING = "pending"
573
- SUCCEEDED = "succeeded"
574
- FAILED = "failed"
575
- CANCELLED = "cancelled"
678
+ PENDING = _PENDING
679
+ SUCCEEDED = _SUCCEEDED
680
+ FAILED = _FAILED
681
+ CANCELLED = _CANCELLED
576
682
 
577
683
  def __init__(
578
684
  self,
579
685
  runtime: "_Runtime",
580
686
  *,
581
687
  token: CancellationToken | None = None,
688
+ capture_context: bool = True,
582
689
  ) -> None:
583
690
  self._runtime = runtime
584
- self._execution_context: Context = copy_context()
585
- self.name = f"Task-{id(self):x}"
586
- self._state = self.PENDING
691
+ # Guards the state transition, the continuation list and parking.
692
+ self._lock = threading.Lock()
693
+ self._state: str = _PENDING
587
694
  self._result: Any = None
588
695
  self._exception: BaseException | None = None
696
+ self._continuations: list[Callable[[Task[Any]], Any]] | None = None
697
+ self._done_event: threading.Event | None = None
698
+ # Promise-style tasks never run code and need no execution context.
699
+ self._execution_context: Context | None = (
700
+ copy_context() if capture_context else None
701
+ )
702
+ self._work: tuple[Any, tuple[Any, ...], dict[str, Any]] | None = None
589
703
  self._coroutine: Coroutine[Any, Any, Any] | None = None
590
- self._awaiters: set[Task[Any]] = set()
591
704
  self._waiting_on: _Operation | None = None
592
- self._queued = False
593
705
  self._running = False
594
- self._step_future: Future[_CoroutineStep] | None = None
595
- self._coroutine_lock = threading.Lock()
706
+ self._sync_running = False
596
707
  self._next_value: Any = None
597
708
  self._next_exception: BaseException | None = None
598
709
  self._cancel_requested = False
599
- self._completed = threading.Event()
600
- self._token = token or CancellationToken.none()
710
+ self._token = token if token is not None else _NONE_TOKEN
601
711
  self._token_registration: CancellationTokenRegistration | None = None
712
+ self._timer: _TimerHandle | None = None
602
713
  self._pass_token = False
603
714
  self._is_promise_task = False
715
+ self._name: str | None = None
604
716
  self.async_state: Any = None
605
- self._asyncio_bridge: _AsyncioBridge | None = None
717
+
718
+ @property
719
+ def name(self) -> str:
720
+ name = self._name
721
+ if name is None:
722
+ name = self._name = f"Task-{id(self):x}"
723
+ return name
724
+
725
+ @name.setter
726
+ def name(self, value: str) -> None:
727
+ self._name = value
606
728
 
607
729
  @property
608
730
  def status(self) -> str:
@@ -613,24 +735,44 @@ class Task(Generic[T], metaclass=_TaskMeta):
613
735
  def configure(
614
736
  cls,
615
737
  *,
738
+ min_workers: int | None = None,
616
739
  max_workers: int | None = None,
617
740
  max_pending_background: int | None = None,
618
741
  ) -> None:
619
742
  """Configure worker capacity before the runtime is first started.
620
743
 
621
- Background overload policy is intentionally explicit and currently fixed
622
- to rejection: excess work fails with BackgroundQueueFull rather than
623
- growing an unbounded queue or blocking the scheduler thread.
744
+ ``min_workers`` is the number of worker threads the pool creates on
745
+ demand without delay (.NET ``ThreadPool.SetMinThreads``).
746
+ ``max_workers`` is the hard upper bound (``SetMaxThreads``). Between
747
+ the two, a worker is added only when queued work makes no progress
748
+ for a while or when workers are blocked in ``Task.result()``.
749
+ (A worker calling ``Task.result()`` on a task that has not started
750
+ runs it inline and does not count as blocked.)
751
+
752
+ Passing ``max_workers`` on its own configures a fixed-size pool:
753
+ ``min_workers`` is set to the same value, so that many workers start
754
+ on demand immediately and no more are ever added.
755
+
756
+ ``max_pending_background`` is accepted for backwards compatibility and
757
+ ignored: like the .NET thread pool, the work queue is unbounded.
624
758
  """
625
759
  global _runtime_config
626
760
  with _runtime_lock:
627
761
  if _runtime is not None and not _runtime.closed:
628
762
  raise RuntimeError("Task.configure() must be called before runtime startup")
629
763
  config = dict(_runtime_config)
764
+ for label, value in (("min_workers", min_workers), ("max_workers", max_workers)):
765
+ if value is None:
766
+ continue
767
+ if isinstance(value, bool) or not isinstance(value, int) or value < 1:
768
+ raise ValueError(f"{label} must be an integer >= 1")
630
769
  if max_workers is not None:
631
- if isinstance(max_workers, bool) or not isinstance(max_workers, int) or max_workers < 1:
632
- raise ValueError("max_workers must be an integer >= 1")
633
770
  config["max_workers"] = max_workers
771
+ config["min_workers"] = max_workers if min_workers is None else min_workers
772
+ elif min_workers is not None:
773
+ config["min_workers"] = min_workers
774
+ if config["min_workers"] > config["max_workers"]:
775
+ raise ValueError("min_workers must not exceed max_workers")
634
776
  if max_pending_background is not None:
635
777
  if (
636
778
  isinstance(max_pending_background, bool)
@@ -638,7 +780,11 @@ class Task(Generic[T], metaclass=_TaskMeta):
638
780
  or max_pending_background < 0
639
781
  ):
640
782
  raise ValueError("max_pending_background must be an integer >= 0")
641
- config["max_pending_background"] = max_pending_background
783
+ warnings.warn(
784
+ "max_pending_background is ignored: the Task work queue is unbounded",
785
+ DeprecationWarning,
786
+ stacklevel=2,
787
+ )
642
788
  _runtime_config = config
643
789
 
644
790
  @classmethod
@@ -688,29 +834,31 @@ class Task(Generic[T], metaclass=_TaskMeta):
688
834
  pass_token: bool = False,
689
835
  **kwargs: Any,
690
836
  ) -> Task[Any]:
691
- # Keep your existing implementation here.
692
- ...
693
- """Schedule a coroutine/awaitable or ordinary callable.
837
+ """Schedule a coroutine/awaitable or ordinary callable on the pool.
694
838
 
695
- Ordinary functions run in the bounded worker pool. ``token`` controls
696
- the Task's cancellation. With ``pass_token=True``, that same token is
839
+ ``token`` controls the Task's cancellation: as in .NET it is checked
840
+ before the work starts. With ``pass_token=True``, that same token is
697
841
  also supplied to the target callable as the keyword argument ``token``
698
842
  (useful for cooperative worker functions).
699
843
  """
700
- if inspect.isawaitable(work):
844
+ kind = type(work)
845
+ is_coroutine = kind is CoroutineType
846
+ if kind is FunctionType or kind is MethodType:
847
+ pass # the common case: skip the comparatively slow awaitable check
848
+ elif is_coroutine or inspect.isawaitable(work):
701
849
  if args or kwargs or pass_token:
702
- if inspect.iscoroutine(work):
703
- work.close()
850
+ if is_coroutine:
851
+ cast(Any, work).close()
704
852
  raise TypeError("args/kwargs/pass_token cannot be supplied with an awaitable instance")
705
853
  elif not callable(work):
706
854
  raise TypeError("Task.run() expects an awaitable or a callable")
707
855
  if token is not None and not isinstance(token, CancellationToken):
708
- if inspect.iscoroutine(work):
709
- work.close()
856
+ if is_coroutine:
857
+ cast(Any, work).close()
710
858
  raise TypeError("token must be a CancellationToken")
711
859
  if pass_token and token is None:
712
- if inspect.iscoroutine(work):
713
- work.close()
860
+ if is_coroutine:
861
+ cast(Any, work).close()
714
862
  raise ValueError("pass_token=True requires an explicit token")
715
863
  runtime = _get_runtime()
716
864
  task = cls(runtime, token=token)
@@ -733,10 +881,9 @@ class Task(Generic[T], metaclass=_TaskMeta):
733
881
  If there are no tasks, the result is an empty list.
734
882
  """
735
883
  normalized = _normalize_tasks(tasks, allow_empty=True)
736
- return cast(
737
- "Task[list[Any]]",
738
- cls.run(_when_all_coroutine, normalized),
739
- )
884
+ promise: Task[list[Any]] = cls._promise(_get_runtime())
885
+ _WhenAll(promise, normalized).start()
886
+ return promise
740
887
 
741
888
  @classmethod
742
889
  def when_any(
@@ -754,26 +901,48 @@ class Task(Generic[T], metaclass=_TaskMeta):
754
901
  breaks the tie deterministically.
755
902
  """
756
903
  normalized = _normalize_tasks(tasks, allow_empty=False)
757
- return cast(
758
- "Task[Task[Any]]",
759
- cls.run(_when_any_coroutine, normalized),
760
- )
904
+ promise: Task[Task[Any]] = cls._promise(_get_runtime())
905
+ _WhenAny(promise, normalized).start()
906
+ return promise
761
907
 
762
908
  @staticmethod
763
- async def collect(*tasks: Task[Any] | list[Task[Any]]):
909
+ async def collect(*tasks: Task[Any] | list[Task[Any]]) -> AsyncGenerator[Task[Any], None]:
764
910
  """
765
911
  Yields tasks as they complete. Accepts either a list or loose positional tasks.
766
912
  """
767
- # FIX: If it's a list or tuple, extract and cast the FIRST element to a mutable list
768
- if len(tasks) == 1 and isinstance(tasks[0], (list, tuple)):
769
- pending = list(tasks[0]) # Converts the inner container into a fresh list
770
- else:
771
- pending = list(tasks) # Converts the *tasks tuple into a fresh list
913
+ pending = _normalize_tasks(tasks, allow_empty=True)
914
+ if not pending:
915
+ return
772
916
 
773
- while pending:
774
- finished_task = await Task.when_any(pending)
775
- pending.remove(finished_task) # Safe to call, because pending is ALWAYS a list!
776
- yield finished_task
917
+ # Every task reports its own completion exactly once, so the whole
918
+ # stream costs O(n) instead of one when_any over the rest per item.
919
+ runtime = _get_runtime()
920
+ lock = threading.Lock()
921
+ completed: deque[Task[Any]] = deque()
922
+ signal: list[Task[None] | None] = [None]
923
+
924
+ def on_completed(finished: Task[Any]) -> None:
925
+ with lock:
926
+ completed.append(finished)
927
+ waiter = signal[0]
928
+ signal[0] = None
929
+ if waiter is not None:
930
+ waiter._finish(_SUCCEEDED)
931
+
932
+ for item in pending:
933
+ if not item._add_continuation(on_completed):
934
+ on_completed(item)
935
+
936
+ for _ in range(len(pending)):
937
+ while True:
938
+ with lock:
939
+ if completed:
940
+ finished = completed.popleft()
941
+ break
942
+ waiter = signal[0] = Task(runtime, capture_context=False)
943
+ waiter._is_promise_task = True
944
+ await waiter
945
+ yield finished
777
946
 
778
947
  @classmethod
779
948
  def delay(
@@ -783,23 +952,71 @@ class Task(Generic[T], metaclass=_TaskMeta):
783
952
  token: CancellationToken | None = None,
784
953
  ) -> "Task[None]":
785
954
  """Return a task completed after seconds without blocking a worker."""
786
- if seconds < 0:
955
+ if not seconds >= 0: # also rejects NaN
787
956
  raise ValueError("delay must be >= 0")
788
957
  if token is not None and not isinstance(token, CancellationToken):
789
958
  raise TypeError("token must be a CancellationToken")
790
- runtime = _get_runtime()
791
- task: Task[None] = cls(runtime, token=token)
792
959
  # During graceful cancellation, allow an already-running coroutine to
793
960
  # create a delay for async cleanup. External callers are still rejected.
794
- runtime._submit_coroutine(
795
- task,
796
- _delay_coroutine(runtime, seconds, token),
797
- allow_during_shutdown=(
798
- runtime.is_runtime_thread() or _current_task.value is not None
799
- ),
961
+ task: Task[None] = cls._promise(
962
+ _get_runtime(),
963
+ token=token,
964
+ internal=_current_task.value is not None,
800
965
  )
966
+ if token is not None and token.is_cancellation_requested:
967
+ task._delay_cancelled()
968
+ elif seconds == 0:
969
+ task._finish(_SUCCEEDED)
970
+ else:
971
+ # The timer thread completes the task directly; no coroutine and
972
+ # no worker are involved until something awaits the result.
973
+ try:
974
+ task._timer = _timers.schedule(seconds, task._delay_elapsed)
975
+ if token is not None and token.can_be_cancelled:
976
+ task._token_registration = token.register(task._delay_cancelled)
977
+ except BaseException:
978
+ task._runtime._tasks.discard(task)
979
+ task._release_handles()
980
+ raise
981
+ if task._state is not _PENDING:
982
+ # Completed while the handles were being attached.
983
+ task._release_handles()
984
+ return task
985
+
986
+ @classmethod
987
+ def _promise(
988
+ cls,
989
+ runtime: "_Runtime",
990
+ *,
991
+ token: CancellationToken | None = None,
992
+ internal: bool = False,
993
+ ) -> "Task[Any]":
994
+ """Create a tracked task that is completed externally, not executed."""
995
+ task: Task[Any] = cls(runtime, token=token, capture_context=False)
996
+ task._is_promise_task = True
997
+ runtime._track(task, internal=internal)
801
998
  return task
802
999
 
1000
+ def _delay_elapsed(self) -> None:
1001
+ self._finish(_SUCCEEDED)
1002
+
1003
+ def _delay_cancelled(self) -> None:
1004
+ self._finish(
1005
+ _CANCELLED,
1006
+ exception=OperationCanceledError("Operation token was cancelled", token=self._token),
1007
+ )
1008
+
1009
+ def _release_handles(self) -> None:
1010
+ with self._lock:
1011
+ registration = self._token_registration
1012
+ self._token_registration = None
1013
+ timer = self._timer
1014
+ self._timer = None
1015
+ if registration is not None:
1016
+ registration.dispose()
1017
+ if timer is not None:
1018
+ timer.cancel()
1019
+
803
1020
  @classmethod
804
1021
  def yield_now(cls) -> _YieldNow:
805
1022
  """Awaitable that lets other ready tasks run."""
@@ -837,56 +1054,116 @@ class Task(Generic[T], metaclass=_TaskMeta):
837
1054
  return self._token
838
1055
 
839
1056
  def done(self) -> bool:
840
- return self._completed.is_set()
1057
+ return self._state is not _PENDING
841
1058
 
842
1059
  def cancelled(self) -> bool:
843
- return self._completed.is_set() and self._state == self.CANCELLED
1060
+ return self._state is _CANCELLED
844
1061
 
845
1062
  def result(self) -> T:
846
- """Block an external thread until completion and return/raise the result."""
847
- if not self.done() and (
848
- self._runtime.is_runtime_thread()
849
- or _current_task.value is not None
850
- ):
851
- raise RuntimeError(
852
- "Task.result() would block the runtime or a Task worker; "
853
- "use 'await task'"
854
- )
855
- self._completed.wait()
1063
+ """Block the calling thread until completion and return/raise the result.
1064
+
1065
+ As with .NET's ``Task.Result`` this also blocks when called from inside
1066
+ a task. Two things keep that from starving the pool:
1067
+
1068
+ * A task that has not started yet is run inline on the calling worker
1069
+ instead of being waited for (.NET does the same). A coroutine runs
1070
+ inline up to its first pending ``await``.
1071
+ * Otherwise the pool is told that the worker is blocked, so it can add
1072
+ a replacement.
1073
+
1074
+ With ``max_workers`` reached, tasks that have already started and block
1075
+ on each other can still starve the pool: prefer ``await task`` inside
1076
+ tasks.
1077
+ """
1078
+ if self._state is _PENDING:
1079
+ self._wait()
856
1080
  return self._raise_or_return()
857
1081
 
858
1082
  def exception(self) -> BaseException | None:
859
- if not self.done() and self._runtime.is_runtime_thread():
860
- raise RuntimeError("Task.exception() would block the runtime thread")
861
- self._completed.wait()
862
- if self._state == self.CANCELLED:
1083
+ if self._state is _PENDING:
1084
+ self._wait()
1085
+ if self._state is _CANCELLED:
863
1086
  raise self._cancellation_exception()
864
1087
  return self._exception
865
1088
 
866
- def _get_asyncio_bridge(self) -> _AsyncioBridge:
867
- bridge = self._asyncio_bridge
868
-
869
- if bridge is None:
870
- with _asyncio_bridge_init_lock:
871
- bridge = self._asyncio_bridge
872
-
873
- if bridge is None:
874
- bridge = _AsyncioBridge()
875
- self._asyncio_bridge = bridge
1089
+ def _wait(self) -> None:
1090
+ state = _thread_state
1091
+ if state.internal:
1092
+ raise RuntimeError(
1093
+ "Task.result() would block the runtime's timer/IO thread; "
1094
+ "use 'await task'"
1095
+ )
1096
+ pool = state.pool
1097
+ if (
1098
+ pool is not None
1099
+ and self._work is not None
1100
+ and pool is self._runtime._pool
1101
+ and state.inline < _MAX_INLINE_DEPTH
1102
+ ):
1103
+ self._run_inline(state, pool)
1104
+ with self._lock:
1105
+ if self._state is not _PENDING:
1106
+ return
1107
+ event = self._done_event
1108
+ if event is None:
1109
+ event = self._done_event = threading.Event()
1110
+ if pool is None:
1111
+ event.wait()
1112
+ return
1113
+ pool._worker_blocked()
1114
+ try:
1115
+ event.wait()
1116
+ finally:
1117
+ pool._worker_unblocked()
876
1118
 
877
- if self.done():
878
- bridge.complete()
1119
+ def _run_inline(self, state: _ThreadState, pool: "_WorkerPool") -> None:
1120
+ """Start this task on the calling worker instead of waiting for it.
879
1121
 
880
- assert bridge is not None
881
- return bridge
1122
+ ``_start()`` takes the work under the task's lock, so either this
1123
+ thread or the worker that pops the queued item runs it, never both;
1124
+ the loser finds nothing to do.
1125
+ """
1126
+ tail = state.tail
1127
+ state.inline += 1
1128
+ try:
1129
+ self._start()
1130
+ finally:
1131
+ state.inline -= 1
1132
+ # The caller is still inside its own work item. Anything the
1133
+ # inlined task left for "this worker's next item" must not wait
1134
+ # until the caller returns -- the caller may be about to block on
1135
+ # exactly that.
1136
+ state.tail = tail
1137
+ item = state.slot
1138
+ if item is not None:
1139
+ state.slot = None
1140
+ # False only if the pool closed, and then shutdown has
1141
+ # already cancelled the task behind the item.
1142
+ pool.queue(item)
1143
+
1144
+ def _add_continuation(self, continuation: Callable[[Task[Any]], Any]) -> bool:
1145
+ """Call ``continuation(self)`` on completion; False if already complete.
1146
+
1147
+ Continuations run on the completing thread and must not block.
1148
+ """
1149
+ with self._lock:
1150
+ if self._state is not _PENDING:
1151
+ return False
1152
+ continuations = self._continuations
1153
+ if continuations is None:
1154
+ self._continuations = [continuation]
1155
+ else:
1156
+ continuations.append(continuation)
1157
+ return True
882
1158
 
883
- def _close_coroutine(self) -> None:
884
- with self._coroutine_lock:
885
- coroutine = self._coroutine
886
- if coroutine is None:
887
- return
888
- self._coroutine = None
889
- coroutine.close()
1159
+ def _remove_continuation(self, continuation: Callable[[Task[Any]], Any]) -> None:
1160
+ with self._lock:
1161
+ continuations = self._continuations
1162
+ if continuations:
1163
+ try:
1164
+ continuations.remove(continuation)
1165
+ except ValueError:
1166
+ pass
890
1167
 
891
1168
  def _cancellation_exception(self) -> OperationCanceledError:
892
1169
  if isinstance(self._exception, OperationCanceledError):
@@ -894,15 +1171,15 @@ class Task(Generic[T], metaclass=_TaskMeta):
894
1171
  return OperationCanceledError(f"{self.name} was cancelled")
895
1172
 
896
1173
  def _await_pure_flpit_task(self) -> Generator[Any, T, T]:
897
- if self.done():
1174
+ if self._state is not _PENDING:
898
1175
  return self._raise_or_return()
899
- result = yield _WaitTask[T](self._runtime, self)
1176
+ result = yield _WaitTask(self._runtime, self)
900
1177
  return result
901
1178
 
902
1179
  __await__ = _await_pure_flpit_task
903
1180
 
904
1181
  def _await_asyncio_interop(self) -> Generator[Any, T, T]:
905
- if self.done():
1182
+ if self._state is not _PENDING:
906
1183
  return self._raise_or_return()
907
1184
 
908
1185
  if "asyncio" in sys.modules:
@@ -926,84 +1203,318 @@ class Task(Generic[T], metaclass=_TaskMeta):
926
1203
  else:
927
1204
  future.set_result(result)
928
1205
 
929
- def notify() -> None:
1206
+ def notify(_: Task[Any]) -> None:
930
1207
  try:
931
1208
  loop.call_soon_threadsafe(complete_future)
932
1209
  except RuntimeError:
933
1210
  pass
934
1211
 
935
- self._get_asyncio_bridge().add(notify)
1212
+ if not self._add_continuation(notify):
1213
+ notify(self)
936
1214
 
937
1215
  return (
938
1216
  yield from cast(Generator[Any, T, T], future.__await__())
939
1217
  )
940
1218
 
941
- result = yield _WaitTask[T](self._runtime, self)
1219
+ result = yield _WaitTask(self._runtime, self)
942
1220
  return result
943
1221
 
944
1222
  def _raise_or_return(self) -> T:
945
- if self._state == self.CANCELLED:
1223
+ state = self._state
1224
+ if state is _SUCCEEDED:
1225
+ return cast(T, self._result)
1226
+ if state is _CANCELLED:
946
1227
  raise self._cancellation_exception()
947
- if self._state == self.FAILED:
1228
+ if state is _FAILED:
948
1229
  assert self._exception is not None
949
1230
  raise self._exception
950
- if self._state != self.SUCCEEDED:
951
- raise InvalidStateError(f"{self.name} has not completed")
952
- return cast(T, self._result)
1231
+ raise InvalidStateError(f"{self.name} has not completed")
953
1232
 
954
- def _cancel_on_runtime(self) -> None:
955
- if self.done():
956
- return
957
- self._cancel_requested = True
958
- self._runtime._detach_wait(self)
959
- if self._is_promise_task:
960
- self._finish(
961
- self.CANCELLED,
962
- exception=OperationCanceledError(f"{self.name} cancelled"),
963
- )
964
- elif not self._running:
965
- self._runtime._schedule(self, exc=OperationCanceledError(f"{self.name} cancelled"))
1233
+ # ------------------------------------------------------------------
1234
+ # State transitions
1235
+ # ------------------------------------------------------------------
966
1236
 
967
1237
  def _finish(
968
1238
  self,
969
1239
  state: str,
970
1240
  result: Any = None,
971
1241
  exception: BaseException | None = None,
972
- ) -> None:
973
- if self.done():
974
- return
975
- self._state = state
976
- self._result = result
977
- self._exception = exception
978
- registration = self._token_registration
979
- self._token_registration = None
1242
+ ) -> bool:
1243
+ """Complete the task. Exactly one caller wins; the others get False."""
1244
+ with self._lock:
1245
+ if self._state is not _PENDING:
1246
+ return False
1247
+ self._result = result
1248
+ self._exception = exception
1249
+ # Published last: lock-free readers check the state first.
1250
+ self._state = state
1251
+ continuations = self._continuations
1252
+ self._continuations = None
1253
+ event = self._done_event
1254
+ registration = self._token_registration
1255
+ self._token_registration = None
1256
+ timer = self._timer
1257
+ self._timer = None
980
1258
  if registration is not None:
981
1259
  registration.dispose()
982
- self._completed.set()
983
- self._runtime._task_completed(self)
1260
+ if timer is not None:
1261
+ timer.cancel()
1262
+ runtime = self._runtime
1263
+ runtime._task_completed(self, state)
1264
+ if event is not None:
1265
+ event.set()
1266
+ if continuations is not None:
1267
+ thread = _thread_state
1268
+ if thread.depth >= _MAX_COMPLETION_DEPTH and runtime._pool.queue(
1269
+ functools.partial(self._run_continuations, continuations)
1270
+ ):
1271
+ return True
1272
+ thread.depth += 1
1273
+ try:
1274
+ self._run_continuations(continuations)
1275
+ finally:
1276
+ thread.depth -= 1
1277
+ return True
1278
+
1279
+ def _run_continuations(self, continuations: list[Callable[[Task[Any]], Any]]) -> None:
1280
+ for continuation in continuations:
1281
+ try:
1282
+ continuation(self)
1283
+ except BaseException as error:
1284
+ self._runtime._report_exception(
1285
+ {"message": f"Unhandled exception in continuation of {self.name}"},
1286
+ error,
1287
+ )
1288
+
1289
+ def _claim(self, operation: _Operation) -> bool:
1290
+ """Take ownership of a task parked on ``operation``; one caller wins."""
1291
+ with self._lock:
1292
+ if self._waiting_on is operation:
1293
+ self._waiting_on = None
1294
+ return True
1295
+ return False
1296
+
1297
+ def _park(self, operation: _Operation) -> bool:
1298
+ """Give up ownership to ``operation``. False if the task must not wait."""
1299
+ with self._lock:
1300
+ if self._state is not _PENDING or self._cancel_requested:
1301
+ return False
1302
+ self._waiting_on = operation
1303
+ self._running = False
1304
+ return True
984
1305
 
985
- bridge = self._asyncio_bridge
1306
+ # ------------------------------------------------------------------
1307
+ # Execution (pool worker threads only)
1308
+ # ------------------------------------------------------------------
986
1309
 
987
- if bridge is not None:
988
- bridge.complete()
1310
+ def _start(self) -> None:
1311
+ """First work item of a task created by Task.run()."""
1312
+ with self._lock:
1313
+ work = self._work
1314
+ self._work = None
1315
+ if work is None:
1316
+ return # taken by shutdown, or run inline by Task.result()
1317
+ alive = self._state is _PENDING
1318
+ if alive:
1319
+ self._running = True
1320
+ target, args, kwargs = work
1321
+ if not alive:
1322
+ _close_if_coroutine(target)
1323
+ return
1324
+ token = self._token
1325
+ if token.is_cancellation_requested or self._cancel_requested:
1326
+ _close_if_coroutine(target)
1327
+ self._finish(
1328
+ _CANCELLED,
1329
+ exception=OperationCanceledError(
1330
+ f"{self.name} cancelled before start", token=token
1331
+ ),
1332
+ )
1333
+ return
989
1334
 
990
- def _step(self) -> None:
991
- if self.done():
1335
+ state = _thread_state
1336
+ context = cast(Context, self._execution_context)
1337
+ value: Any
1338
+ coroutine: Coroutine[Any, Any, Any]
1339
+ try:
1340
+ # The context belongs to this task alone, so the current task is
1341
+ # set once instead of being set and restored around every step.
1342
+ context.run(_current_task._value.set, self)
1343
+ if type(target) is CoroutineType:
1344
+ value = target
1345
+ elif inspect.isawaitable(target):
1346
+ value = _await_any(target)
1347
+ else:
1348
+ if self._pass_token:
1349
+ kwargs = {**kwargs, "token": token}
1350
+ if _is_async_callable(target):
1351
+ # Only creates the coroutine object; no user code runs yet.
1352
+ value = context.run(target, *args, **kwargs)
1353
+ else:
1354
+ self._sync_running = True
1355
+ try:
1356
+ value = _run_with_context(context, target, *args, **kwargs)
1357
+ finally:
1358
+ self._sync_running = False
1359
+ state.tail = True
1360
+ if type(value) is CoroutineType:
1361
+ coroutine = value
1362
+ elif inspect.isawaitable(value):
1363
+ # Support sync wrappers that return an awaitable.
1364
+ coroutine = _await_any(value)
1365
+ else:
1366
+ self._finish(_SUCCEEDED, result=value)
1367
+ return
1368
+ except OperationCanceledError as error:
1369
+ state.tail = True
1370
+ self._finish(_CANCELLED, exception=error)
992
1371
  return
993
- coroutine = self._coroutine
994
- if coroutine is None:
995
- self._finish(self.FAILED, exception=RuntimeError("task has no coroutine"))
1372
+ except BaseException as error:
1373
+ state.tail = True
1374
+ self._finish(_FAILED, exception=error)
996
1375
  return
997
- value = self._next_value
998
- exc = self._next_exception
999
- self._next_value = None
1000
- self._next_exception = None
1001
1376
 
1002
- if isinstance(exc, OperationCanceledError):
1003
- self._cancel_requested = False
1377
+ self._coroutine = coroutine
1378
+ if self._runtime._shutdown_requested:
1379
+ # A synchronous function that returned an awaitable after the
1380
+ # shutdown sweep: it missed the cancellation request.
1381
+ self._cancel_requested = True
1382
+ self._drive()
1383
+
1384
+ def _drive(self) -> None:
1385
+ """Run coroutine steps until the task parks, yields or completes."""
1386
+ runtime = self._runtime
1387
+ lock = self._lock
1388
+ context = cast(Context, self._execution_context)
1389
+ state = _thread_state
1390
+ while True:
1391
+ value: Any = None
1392
+ error: BaseException | None = None
1393
+ with lock:
1394
+ coroutine = self._coroutine
1395
+ alive = self._state is _PENDING
1396
+ if alive:
1397
+ self._running = True
1398
+ value = self._next_value
1399
+ error = self._next_exception
1400
+ self._next_value = None
1401
+ self._next_exception = None
1402
+ if self._cancel_requested:
1403
+ self._cancel_requested = False
1404
+ if not isinstance(error, OperationCanceledError):
1405
+ error = OperationCanceledError(f"{self.name} cancelled")
1406
+ else:
1407
+ # Finished from outside (shutdown) while it was not ours.
1408
+ self._coroutine = None
1409
+ self._running = False
1410
+ if coroutine is None:
1411
+ return
1412
+ if not alive:
1413
+ runtime._close_coroutine(self, coroutine)
1414
+ return
1415
+
1416
+ state.tail = False
1417
+ try:
1418
+ if error is None:
1419
+ yielded = _run_with_context(context, coroutine.send, value)
1420
+ else:
1421
+ yielded = _run_with_context(context, coroutine.throw, error)
1422
+ except StopIteration as stop:
1423
+ state.tail = True
1424
+ self._coroutine = None
1425
+ self._finish(_SUCCEEDED, result=stop.value)
1426
+ return
1427
+ except OperationCanceledError as cancellation:
1428
+ state.tail = True
1429
+ self._coroutine = None
1430
+ self._finish(_CANCELLED, exception=cancellation)
1431
+ return
1432
+ except BaseException as failure:
1433
+ state.tail = True
1434
+ self._coroutine = None
1435
+ self._finish(_FAILED, exception=failure)
1436
+ return
1437
+
1438
+ state.tail = True
1439
+ try:
1440
+ resume = runtime._suspend(self, yielded)
1441
+ except BaseException as failure:
1442
+ # Not expected. Rather than leave the task pending forever,
1443
+ # raise in the coroutine -- provided the task is still ours.
1444
+ with lock:
1445
+ resume = self._running or self._waiting_on is yielded
1446
+ if resume:
1447
+ self._waiting_on = None
1448
+ self._next_exception = failure
1449
+ if not resume:
1450
+ # Parked or re-queued: the task now belongs to someone else
1451
+ # and must not be touched from here.
1452
+ return
1453
+
1454
+ # ------------------------------------------------------------------
1455
+ # Shutdown (called by the thread running Task.shutdown())
1456
+ # ------------------------------------------------------------------
1457
+
1458
+ def _cancel_for_shutdown(self) -> bool:
1459
+ """Request cancellation. True if a synchronous function is executing."""
1460
+ work = None
1461
+ finish = False
1462
+ with self._lock:
1463
+ if self._state is not _PENDING:
1464
+ return False
1465
+ operation = self._waiting_on
1466
+ if operation is not None:
1467
+ self._waiting_on = None # claimed
1468
+ elif self._is_promise_task:
1469
+ finish = True
1470
+ elif self._work is not None:
1471
+ # Still queued: it never starts.
1472
+ work = self._work
1473
+ self._work = None
1474
+ finish = True
1475
+ elif self._sync_running:
1476
+ return True
1477
+ else:
1478
+ # Running or queued for its next step; delivered at the next
1479
+ # step boundary by _drive()/_park().
1480
+ self._cancel_requested = True
1481
+ if operation is not None:
1482
+ runtime = self._runtime
1483
+ runtime._release_wait(operation)
1484
+ self._next_exception = OperationCanceledError(f"{self.name} cancelled")
1485
+ runtime._enqueue_task(self)
1486
+ elif finish:
1487
+ if work is not None:
1488
+ _close_if_coroutine(work[0])
1489
+ self._finish(
1490
+ _CANCELLED,
1491
+ exception=OperationCanceledError(f"{self.name} cancelled"),
1492
+ )
1493
+ return False
1004
1494
 
1005
- self._running = True
1006
- self._runtime._dispatch_coroutine_step(self, coroutine, value, exc)
1495
+ def _force_cancel(self) -> None:
1496
+ """Complete as cancelled no matter what the task is doing."""
1497
+ with self._lock:
1498
+ if self._state is not _PENDING:
1499
+ return
1500
+ operation = self._waiting_on
1501
+ self._waiting_on = None
1502
+ runtime = self._runtime
1503
+ if operation is not None:
1504
+ runtime._release_wait(operation)
1505
+ self._finish(_CANCELLED, exception=OperationCanceledError("runtime shutting down"))
1506
+ with self._lock:
1507
+ if self._running:
1508
+ # A worker is inside a step; it cleans up when the step returns.
1509
+ return
1510
+ coroutine = self._coroutine
1511
+ self._coroutine = None
1512
+ work = self._work
1513
+ self._work = None
1514
+ if work is not None:
1515
+ _close_if_coroutine(work[0])
1516
+ if coroutine is not None:
1517
+ runtime._close_coroutine(self, coroutine)
1007
1518
 
1008
1519
  def __repr__(self) -> str:
1009
1520
  return f"<{self.name} state={self._state}>"
@@ -1025,14 +1536,10 @@ class TaskCompletionSource(Generic[T]):
1025
1536
  """
1026
1537
 
1027
1538
  def __init__(self, state: Any = None) -> None:
1028
- runtime = _get_runtime()
1029
- self._runtime = runtime
1030
- self._task: Task[T] = Task(runtime)
1031
- self._task._is_promise_task = True
1032
- self._task.async_state = state
1033
1539
  # Promise tasks are tracked so runtime shutdown can cancel unresolved
1034
1540
  # externally-completed tasks and wake any awaiters.
1035
- runtime._call_sync(lambda: runtime._tasks.add(self._task), internal=False)
1541
+ self._task: Task[T] = Task._promise(_get_runtime())
1542
+ self._task.async_state = state
1036
1543
 
1037
1544
  @property
1038
1545
  def task(self) -> Task[T]:
@@ -1152,23 +1659,10 @@ class TaskCompletionSource(Generic[T]):
1152
1659
  result: Any = None,
1153
1660
  exception: Exception | BaseException | None = None,
1154
1661
  ) -> bool:
1155
- if self._task.done():
1156
- return False
1157
-
1158
- def complete_on_runtime() -> bool:
1159
- if self._task.done():
1160
- return False
1161
- self._task._finish(state, result=result, exception=exception)
1162
- return True
1163
-
1164
- try:
1165
- return bool(self._runtime._call_sync(complete_on_runtime, internal=True))
1166
- except RuntimeShutdownError:
1167
- # Shutdown may have won the race and completed this promise task as
1168
- # cancelled. In that case TrySet* follows the standard lost-race path.
1169
- if self._task.done():
1170
- return False
1171
- raise
1662
+ # Safe from any thread and never blocks: the task's own lock decides
1663
+ # the winner and its continuations are handed to the pool, so the
1664
+ # caller of set_result() does not end up running awaiting coroutines.
1665
+ return self._task._finish(state, result=result, exception=exception)
1172
1666
 
1173
1667
 
1174
1668
  def _normalize_tasks(items: tuple[Any, ...], *, allow_empty: bool) -> tuple[Task[Any], ...]:
@@ -1243,27 +1737,92 @@ def _normalize_tasks(items: tuple[Any, ...], *, allow_empty: bool) -> tuple[Task
1243
1737
  return tuple(normalized)
1244
1738
 
1245
1739
 
1246
- async def _when_all_coroutine(tasks: tuple[Task[T], ...]) -> list[T]:
1247
- await _WaitMany(_get_runtime(), tasks, "all")
1248
- failures = tuple(task._exception for task in tasks if task._state == Task.FAILED)
1740
+ class _WhenAll:
1741
+ """Completes a promise once every child has completed.
1249
1742
 
1250
- if len(failures) == 1:
1251
- assert failures[0] is not None
1252
- raise failures[0]
1253
- if len(failures) > 1:
1254
- raise AggregateError(cast(tuple[Exception, ...], failures))
1255
- if any(task._state == Task.CANCELLED for task in tasks):
1256
- raise OperationCanceledError("One or more tasks passed to Task.when_all() were cancelled")
1257
- return [task._result for task in tasks]
1743
+ Registered as a continuation on each pending child, so no coroutine and no
1744
+ worker round trip is needed, and each completion is O(1).
1745
+ """
1258
1746
 
1747
+ __slots__ = ("_promise", "_tasks", "_remaining", "_lock")
1259
1748
 
1260
- async def _when_any_coroutine(tasks: tuple[Task[T], ...]) -> Task[T]:
1261
- winner = await _WaitMany(_get_runtime(), tasks, "any")
1262
- return cast(Task[Any], winner)
1749
+ def __init__(self, promise: Task[list[Any]], tasks: tuple[Task[Any], ...]) -> None:
1750
+ self._promise = promise
1751
+ self._tasks = tasks
1752
+ # One extra count is held by start() until every child is registered.
1753
+ self._remaining = len(tasks) + 1
1754
+ self._lock = threading.Lock()
1263
1755
 
1756
+ def start(self) -> None:
1757
+ for child in self._tasks:
1758
+ if not child._add_continuation(self):
1759
+ self(child)
1760
+ self(None)
1264
1761
 
1265
- class IO:
1266
- """Selector-backed awaitables for nonblocking sockets."""
1762
+ def __call__(self, _completed: Task[Any] | None) -> None:
1763
+ with self._lock:
1764
+ self._remaining -= 1
1765
+ if self._remaining:
1766
+ return
1767
+ tasks = self._tasks
1768
+ failures = tuple(child._exception for child in tasks if child._state is _FAILED)
1769
+ if len(failures) == 1:
1770
+ self._promise._finish(_FAILED, exception=failures[0])
1771
+ elif failures:
1772
+ self._promise._finish(
1773
+ _FAILED,
1774
+ exception=AggregateError(cast(tuple[Exception, ...], failures)),
1775
+ )
1776
+ elif any(child._state is _CANCELLED for child in tasks):
1777
+ self._promise._finish(
1778
+ _CANCELLED,
1779
+ exception=OperationCanceledError(
1780
+ "One or more tasks passed to Task.when_all() were cancelled"
1781
+ ),
1782
+ )
1783
+ else:
1784
+ self._promise._finish(_SUCCEEDED, result=[child._result for child in tasks])
1785
+
1786
+
1787
+ class _WhenAny:
1788
+ """Completes a promise with the first child to complete."""
1789
+
1790
+ __slots__ = ("_promise", "_tasks")
1791
+
1792
+ def __init__(self, promise: Task[Task[Any]], tasks: tuple[Task[Any], ...]) -> None:
1793
+ self._promise = promise
1794
+ self._tasks = tasks
1795
+
1796
+ def start(self) -> None:
1797
+ promise = self._promise
1798
+ # Deterministic tie-breaking for tasks already completed when the
1799
+ # operation is first observed: first completed in input order.
1800
+ for child in self._tasks:
1801
+ if child._state is not _PENDING:
1802
+ promise._finish(_SUCCEEDED, result=child)
1803
+ return
1804
+ for child in self._tasks:
1805
+ if not child._add_continuation(self):
1806
+ self(child)
1807
+ if promise._state is not _PENDING:
1808
+ break
1809
+ if promise._state is not _PENDING:
1810
+ # A winner arrived while registration was still in progress.
1811
+ self._detach(None)
1812
+
1813
+ def __call__(self, completed: Task[Any]) -> None:
1814
+ if self._promise._finish(_SUCCEEDED, result=completed):
1815
+ self._detach(completed)
1816
+
1817
+ def _detach(self, winner: Task[Any] | None) -> None:
1818
+ # Losers keep running; do not let them keep this aggregate alive.
1819
+ for child in self._tasks:
1820
+ if child is not winner:
1821
+ child._remove_continuation(self)
1822
+
1823
+
1824
+ class IO:
1825
+ """Selector-backed awaitables for nonblocking sockets."""
1267
1826
 
1268
1827
  @staticmethod
1269
1828
  def wait_readable(
@@ -1282,462 +1841,122 @@ class IO:
1282
1841
  return _WaitIO(_get_runtime(), sock, "write", token)
1283
1842
 
1284
1843
 
1285
- class _Runtime:
1286
- """Private singleton scheduler: ready queue + timers + selector + workers."""
1844
+ class _IOReactor:
1845
+ """Selector thread turning socket readiness into task wake-ups.
1846
+
1847
+ Started on the first socket wait, so programs that never await a socket
1848
+ pay nothing for it. All selector state is owned by the reactor thread;
1849
+ other threads only post commands and wake it. It never runs task code.
1850
+ """
1287
1851
 
1288
- def __init__(self, *, max_workers: int, max_pending_background: int) -> None:
1852
+ def __init__(self, runtime: "_Runtime") -> None:
1853
+ self._runtime = runtime
1854
+ self._lock = threading.Lock()
1855
+ self._thread: threading.Thread | None = None
1856
+ self._selector: selectors.BaseSelector | None = None
1857
+ self._wake_reader: socket.socket | None = None
1858
+ self._wake_writer: socket.socket | None = None
1859
+ self._commands: queue.SimpleQueue[tuple[Callable[[_WaitIO], None], _WaitIO]] = (
1860
+ queue.SimpleQueue()
1861
+ )
1862
+ self._waiters: dict[socket.socket, dict[str, set[_WaitIO]]] = {}
1863
+ self._closing = False
1864
+ self._failure: BaseException | None = None
1865
+
1866
+ def arm(self, operation: _WaitIO) -> None:
1867
+ error = self._post(self._arm, operation)
1868
+ if error is not None:
1869
+ # The wait can never be signalled: fail it rather than strand it.
1870
+ self._wake(operation, error)
1871
+
1872
+ def disarm(self, operation: _WaitIO) -> None:
1873
+ if self._thread is not None:
1874
+ self._post(self._disarm, operation)
1875
+
1876
+ def _post(
1877
+ self, command: Callable[[_WaitIO], None], operation: _WaitIO
1878
+ ) -> BaseException | None:
1879
+ """Hand a command to the reactor thread; returns why it could not."""
1880
+ if self._thread is None:
1881
+ with self._lock:
1882
+ if self._thread is None and not self._closing and self._failure is None:
1883
+ try:
1884
+ self._start()
1885
+ except BaseException as error:
1886
+ # For example out of file descriptors. Not latched:
1887
+ # a later wait may well succeed.
1888
+ self._discard_resources()
1889
+ return error
1890
+ if self._closing or self._failure is not None or self._thread is None:
1891
+ return self._failure or RuntimeShutdownError("Task runtime is shutting down")
1892
+ self._commands.put((command, operation))
1893
+ self._notify()
1894
+ return None
1895
+
1896
+ def _start(self) -> None:
1289
1897
  self._selector = selectors.DefaultSelector()
1290
1898
  self._wake_reader, self._wake_writer = socket.socketpair()
1291
1899
  self._wake_reader.setblocking(False)
1292
1900
  self._wake_writer.setblocking(False)
1293
1901
  self._selector.register(self._wake_reader, selectors.EVENT_READ, data=_WAKE)
1294
- self._ready: deque[Task[Any]] = deque()
1295
- self._tasks: set[Task[Any]] = set()
1296
- self._timers: list[tuple[float, int, Task[Any], _Sleep]] = []
1297
- self._timer_sequence = count()
1298
- self._io_waiters: dict[socket.socket, dict[str, set[Task[Any]]]] = {}
1299
- self._commands: queue.SimpleQueue[Callable[[], None]] = queue.SimpleQueue()
1300
- self._max_workers = max_workers
1301
- self._max_pending_background = max_pending_background
1302
- self._pending_background: deque[tuple[Task[Any], _BackgroundCall]] = deque()
1303
- self._background_active = 0 # scheduler-thread-owned submitted call count
1304
- self._executor = ThreadPoolExecutor(max_workers=max_workers, thread_name_prefix="Thread")
1305
- self._inflight_lock = threading.Condition()
1306
- self._inflight_futures: set[Future[Any]] = set()
1307
- self._worker_context = threading.local()
1308
- self._thread_id: int | None = None
1309
- self._start_lock = threading.Lock()
1310
- self._started = threading.Event()
1311
- self._state_lock = threading.RLock()
1312
- self._shutdown_requested = False
1313
- self._shutdown_deadline: float | None = None
1314
- self._stopping = False
1315
- self._closed = False
1316
- self._shutdown_tasks_cancelled = 0
1317
- self._thread: threading.Thread | None = None
1318
- self._exception_handler: Callable[[dict[str, Any]], Any] | None = None
1319
-
1320
- @property
1321
- def closed(self) -> bool:
1322
- with self._state_lock:
1323
- return self._closed
1324
-
1325
- def _ensure_started(self) -> None:
1326
- if self._started.is_set():
1327
- return
1328
- with self._start_lock:
1329
- if self._started.is_set():
1330
- return
1331
- with self._state_lock:
1332
- if self._closed or self._shutdown_requested:
1333
- raise RuntimeShutdownError("Task runtime is shutting down")
1334
- self._thread = threading.Thread(target=self._loop, name="Task-runtime", daemon=True)
1335
- self._thread.start()
1336
- self._started.wait()
1337
-
1338
- def is_runtime_thread(self) -> bool:
1339
- return self._thread_id == threading.get_ident()
1340
-
1341
- def set_exception_handler(self, handler: Callable[[dict[str, Any]], Any] | None) -> None:
1342
- self._exception_handler = handler
1343
-
1344
- def _report_exception(self, context: dict[str, Any], error: BaseException) -> None:
1345
- handler = self._exception_handler
1346
- if handler is not None:
1347
- try:
1348
- handler({**context, "exception": error})
1349
- return
1350
- except Exception:
1351
- _LOG.exception("Task exception handler itself failed")
1352
- message = str(context.get("message", "Unexpected Task runtime error"))
1353
- _LOG.error("%s", message, exc_info=(type(error), error, error.__traceback__))
1354
-
1355
- def _call_sync(self, callback: Callable[[], T], *, internal: bool = False) -> T:
1356
- """Run a small state mutation on the scheduler thread and return its value.
1357
-
1358
- External completion APIs use this so callbacks/awaiters are manipulated
1359
- only by the scheduler thread while callers retain synchronous Set/TrySet
1360
- semantics. The operation fails rather than hanging if the runtime stops.
1361
- """
1362
- self._ensure_started()
1363
- if self.is_runtime_thread():
1364
- return callback()
1365
-
1366
- completed = threading.Event()
1367
- outcome: dict[str, Any] = {}
1368
-
1369
- def invoke() -> None:
1370
- try:
1371
- outcome["value"] = callback()
1372
- except BaseException as error:
1373
- outcome["error"] = error
1374
- finally:
1375
- completed.set()
1376
-
1377
- self._post(invoke, internal=internal)
1378
- while not completed.wait(0.05):
1379
- thread = self._thread
1380
- if thread is None or not thread.is_alive():
1381
- raise RuntimeShutdownError(
1382
- "Task runtime stopped before the scheduled operation ran"
1383
- )
1384
- if "error" in outcome:
1385
- raise outcome["error"]
1386
- return cast(T, outcome.get("value"))
1387
-
1388
- def _post(self, callback: Callable[[], None], *, internal: bool = False) -> None:
1389
- self._ensure_started()
1390
- execute_inline = False
1391
- with self._state_lock:
1392
- if self._closed or self._stopping or (self._shutdown_requested and not internal):
1393
- raise RuntimeShutdownError("Task runtime is shutting down")
1394
- if self.is_runtime_thread():
1395
- execute_inline = True
1396
- else:
1397
- self._commands.put(callback)
1398
- if execute_inline:
1399
- callback()
1400
- return
1401
- try:
1402
- self._wake_writer.send(b"\x00")
1403
- except (BlockingIOError, OSError):
1404
- # A full wake-up socket already guarantees selector readability.
1405
- pass
1406
-
1407
- def _submit(self, task: Task[Any], work: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> None:
1408
- try:
1409
- self._post(lambda: self._start_target(task, work, args, kwargs))
1410
- except BaseException:
1411
- if inspect.iscoroutine(work):
1412
- work.close()
1413
- raise
1414
-
1415
- def _submit_coroutine(
1416
- self,
1417
- task: Task[Any],
1418
- coroutine: Coroutine[Any, Any, Any],
1419
- *,
1420
- allow_during_shutdown: bool = False,
1421
- ) -> None:
1422
- try:
1423
- self._post(
1424
- lambda: self._start_coroutine(task, coroutine),
1425
- internal=allow_during_shutdown,
1426
- )
1427
- except BaseException:
1428
- coroutine.close()
1429
- raise
1902
+ thread = threading.Thread(
1903
+ target=self._loop, name="Task-io", daemon=True, **_fresh_context()
1904
+ )
1905
+ thread.start()
1906
+ self._thread = thread
1430
1907
 
1431
- def _start_target(
1432
- self, task: Task[Any], work: Any, args: tuple[Any, ...], kwargs: dict[str, Any]
1433
- ) -> None:
1434
- if task.done():
1435
- if inspect.iscoroutine(work):
1436
- work.close()
1437
- return
1438
- if task._token.is_cancellation_requested:
1439
- if inspect.iscoroutine(work):
1440
- work.close()
1441
- task._finish(Task.CANCELLED, exception=OperationCanceledError(f"{task.name} cancelled before start"))
1442
- return
1908
+ def _discard_resources(self) -> None:
1909
+ selector, self._selector = self._selector, None
1910
+ reader, self._wake_reader = self._wake_reader, None
1911
+ writer, self._wake_writer = self._wake_writer, None
1443
1912
  try:
1444
- call_kwargs = dict(kwargs)
1445
- if task._pass_token:
1446
- call_kwargs["token"] = task._token
1447
- if inspect.isawaitable(work):
1448
- coroutine = work if inspect.iscoroutine(work) else _await_any(work)
1449
- elif _is_async_callable(work):
1450
- coroutine = _invoke_async(work, args, call_kwargs)
1451
- else:
1452
- self._tasks.add(task)
1453
- self._queue_background(
1454
- task,
1455
- _BackgroundCall(self, work, args, call_kwargs),
1456
- )
1457
- return
1458
- self._start_coroutine(task, coroutine)
1913
+ if selector is not None:
1914
+ selector.close()
1459
1915
  except BaseException as error:
1460
- self._tasks.add(task)
1461
- task._finish(Task.FAILED, exception=error)
1462
-
1463
- def _start_coroutine(self, task: Task[Any], coroutine: Coroutine[Any, Any, Any]) -> None:
1464
- if task.done():
1465
- coroutine.close()
1466
- return
1467
- task._coroutine = coroutine
1468
- self._tasks.add(task)
1469
- self._schedule(task)
1470
-
1471
- def _schedule(
1472
- self, task: Task[Any], value: Any = None, exc: BaseException | None = None
1473
- ) -> None:
1474
- if task.done():
1475
- return
1476
- if task._queued:
1477
- if exc is not None:
1478
- task._next_exception = exc
1479
- task._next_value = None
1480
- elif task._next_exception is None:
1481
- task._next_value = value
1482
- return
1483
- task._queued = True
1484
- task._next_value = value
1485
- task._next_exception = exc
1486
- self._ready.append(task)
1487
-
1488
- def _task_completed(self, task: Task[Any]) -> None:
1489
- self._tasks.discard(task)
1490
- if self._shutdown_requested and task._state == Task.CANCELLED:
1491
- self._shutdown_tasks_cancelled += 1
1492
- self._detach_wait(task)
1493
- for waiter in list(task._awaiters):
1494
- operation = waiter._waiting_on
1495
- if isinstance(operation, _WaitTask) and operation.task is task:
1496
- self._detach_wait(waiter)
1497
- if task._state == Task.SUCCEEDED:
1498
- self._schedule(waiter, value=task._result)
1499
- elif task._state == Task.CANCELLED:
1500
- self._schedule(waiter, exc=OperationCanceledError(f"{task.name} was cancelled"))
1501
- else:
1502
- assert task._exception is not None
1503
- self._schedule(waiter, exc=task._exception)
1504
- elif isinstance(operation, _WaitMany) and task in operation.tasks:
1505
- if operation.mode == "any":
1506
- self._detach_wait(waiter)
1507
- self._schedule(waiter, value=task)
1508
- elif all(child.done() for child in operation.tasks):
1509
- self._detach_wait(waiter)
1510
- self._schedule(waiter, value=operation.tasks)
1511
- task._awaiters.clear()
1512
-
1513
- def _handle_yielded(self, task: Task[Any], yielded: Any) -> None:
1514
- if not isinstance(yielded, _Operation):
1515
- raise RuntimeError(
1516
- f"{task.name} yielded unsupported object {yielded!r}; "
1517
- "this runtime only supports Task awaitables"
1518
- )
1519
- if yielded.runtime is not self:
1520
- raise RuntimeError("awaitable belongs to a different runtime")
1521
- if yielded.token.is_cancellation_requested:
1522
- self._schedule(task, exc=OperationCanceledError("Operation token was cancelled"))
1523
- return
1524
-
1525
- if isinstance(yielded, _YieldNow):
1526
- self._schedule(task)
1527
- elif isinstance(yielded, _Sleep):
1528
- if yielded.delay == 0:
1529
- self._schedule(task)
1530
- else:
1531
- task._waiting_on = yielded
1532
- heapq.heappush(self._timers, (yielded.deadline, next(self._timer_sequence), task, yielded))
1533
- self._register_operation_token(task, yielded)
1534
- elif isinstance(yielded, _WaitIO):
1535
- self._arm_io(task, yielded)
1536
- self._register_operation_token(task, yielded)
1537
- elif isinstance(yielded, _WaitMany):
1538
- if yielded.mode == "any":
1539
- # Deterministic tie-breaking for tasks already completed when
1540
- # the operation is first observed: first completed in input order.
1541
- winner = next((child for child in yielded.tasks if child.done()), None)
1542
- if winner is not None:
1543
- self._schedule(task, value=winner)
1544
- return
1545
- elif all(child.done() for child in yielded.tasks):
1546
- self._schedule(task, value=yielded.tasks)
1547
- return
1548
-
1549
- pending = [child for child in yielded.tasks if not child.done()]
1550
- if any(child._runtime is not self for child in pending):
1551
- raise RuntimeError("cannot combine pending tasks from different runtimes")
1552
- task._waiting_on = yielded
1553
- for child in pending:
1554
- child._awaiters.add(task)
1555
- elif isinstance(yielded, _WaitTask):
1556
- target = yielded.task
1557
- if target is task:
1558
- raise RuntimeError("a task cannot await itself")
1559
- if target.done():
1560
- if target._state == Task.SUCCEEDED:
1561
- self._schedule(task, value=target._result)
1562
- elif target._state == Task.CANCELLED:
1563
- self._schedule(task, exc=OperationCanceledError(f"{target.name} was cancelled"))
1564
- else:
1565
- assert target._exception is not None
1566
- self._schedule(task, exc=target._exception)
1567
- else:
1568
- task._waiting_on = yielded
1569
- target._awaiters.add(task)
1570
- self._register_operation_token(task, yielded)
1571
- elif isinstance(yielded, _BackgroundCall):
1572
- self._queue_background(task, yielded)
1573
- else:
1574
- raise RuntimeError(f"unsupported operation type: {type(yielded).__name__}")
1575
-
1576
- def _register_operation_token(self, task: Task[Any], operation: _Operation) -> None:
1577
- token = operation.token
1578
- if not token.can_be_cancelled:
1579
- return
1916
+ self._runtime._report_exception({"message": "Error closing selector"}, error)
1917
+ for wake_socket in (reader, writer):
1918
+ if wake_socket is not None:
1919
+ try:
1920
+ wake_socket.close()
1921
+ except OSError:
1922
+ pass
1580
1923
 
1581
- def on_cancel() -> None:
1924
+ def _notify(self) -> None:
1925
+ writer = self._wake_writer
1926
+ if writer is not None:
1582
1927
  try:
1583
- self._post(lambda: self._cancel_operation_wait(task, operation), internal=True)
1584
- except RuntimeShutdownError:
1928
+ writer.send(b"\x00")
1929
+ except (BlockingIOError, OSError):
1930
+ # A full wake-up socket already guarantees selector readability.
1585
1931
  pass
1586
1932
 
1587
- operation._token_registration = token.register(on_cancel)
1588
-
1589
- def _dispose_operation_token(self, operation: _Operation) -> None:
1590
- registration = operation._token_registration
1591
- operation._token_registration = None
1592
- if registration is not None:
1593
- registration.dispose()
1594
-
1595
- def _cancel_operation_wait(self, task: Task[Any], operation: _Operation) -> None:
1596
- if task.done() or task._waiting_on is not operation:
1597
- return
1598
- self._detach_wait(task)
1599
- self._schedule(task, exc=OperationCanceledError("Operation token was cancelled"))
1600
-
1601
- def _start_background(self, task: Task[Any], operation: _BackgroundCall) -> None:
1602
- if task.done() or task._waiting_on is not operation or self._shutdown_requested:
1603
- return
1604
- self._background_active += 1
1605
- operation._counted_active = True
1606
- try:
1607
- future = self._executor.submit(
1608
- self._run_background_call,
1609
- task,
1610
- operation,
1611
- )
1612
- except BaseException as error:
1613
- self._background_active -= 1
1614
- operation._counted_active = False
1615
- task._waiting_on = None
1616
- self._dispose_operation_token(operation)
1617
- self._schedule(task, exc=error)
1618
- self._pump_background_queue()
1619
- return
1620
- operation.future = future
1621
- with self._inflight_lock:
1622
- self._inflight_futures.add(future)
1623
- future.add_done_callback(
1624
- lambda completed, task=task, op=operation: self._background_worker_done(task, op, completed)
1625
- )
1626
-
1627
- def _run_background_call(
1628
- self,
1629
- task: Task[Any],
1630
- operation: _BackgroundCall,
1631
- ) -> Any:
1632
- def execute() -> Any:
1633
- previous_task = _current_task.value
1634
- _current_task.value = task
1635
-
1636
- try:
1637
- return operation.function(
1638
- *operation.args,
1639
- **operation.kwargs,
1640
- )
1641
- finally:
1642
- _current_task.value = previous_task
1643
-
1644
- return task._execution_context.run(execute)
1645
-
1646
- def _background_worker_done(
1647
- self, task: Task[Any], operation: _BackgroundCall, future: Future[Any]
1648
- ) -> None:
1649
- with self._inflight_lock:
1650
- self._inflight_futures.discard(future)
1651
- self._inflight_lock.notify_all()
1652
- try:
1653
- self._post(lambda: self._background_finished(task, operation, future), internal=True)
1654
- except RuntimeShutdownError:
1655
- # The future's terminal state is still recorded in _inflight_futures;
1656
- # after shutdown there is no scheduler left to resume a task.
1657
- pass
1658
-
1659
- def _background_finished(
1660
- self,
1661
- task: Task[Any],
1662
- operation: _BackgroundCall,
1663
- future: Future[Any],
1664
- ) -> None:
1665
- if operation._counted_active:
1666
- operation._counted_active = False
1667
- self._background_active = max(0, self._background_active - 1)
1668
-
1669
- if not task.done() and task._waiting_on is operation:
1670
- task._waiting_on = None
1671
- self._dispose_operation_token(operation)
1672
-
1673
- try:
1674
- value = future.result()
1675
- except BaseException as error:
1676
- if task._coroutine is None:
1677
- state = (
1678
- Task.CANCELLED
1679
- if isinstance(error, OperationCanceledError)
1680
- else Task.FAILED
1681
- )
1682
- task._finish(state, exception=error)
1683
- else:
1684
- self._schedule(task, exc=error)
1685
- else:
1686
- if task._coroutine is None:
1687
- if inspect.isawaitable(value):
1688
- coroutine = (
1689
- value if inspect.iscoroutine(value)
1690
- else _await_any(value)
1691
- )
1692
- self._start_coroutine(task, coroutine)
1693
- else:
1694
- task._finish(Task.SUCCEEDED, result=value)
1695
- else:
1696
- self._schedule(task, value=value)
1697
-
1698
- self._pump_background_queue()
1699
-
1700
- def _queue_background(
1701
- self,
1702
- task: Task[Any],
1703
- operation: _BackgroundCall,
1704
- ) -> None:
1705
- task._waiting_on = operation
1706
-
1707
- if self._background_active < self._max_workers and not self._pending_background:
1708
- self._start_background(task, operation)
1709
-
1710
- elif len(self._pending_background) < self._max_pending_background:
1711
- self._pending_background.append((task, operation))
1712
- self._register_operation_token(task, operation)
1713
-
1714
- else:
1715
- task._waiting_on = None
1716
- raise BackgroundQueueFull(
1717
- f"background queue is full (max_workers={self._max_workers}, "
1718
- f"max_pending_background={self._max_pending_background})"
1719
- )
1720
-
1721
- def _pump_background_queue(self) -> None:
1722
- if self._shutdown_requested:
1723
- return
1724
- while self._background_active < self._max_workers and self._pending_background:
1725
- task, operation = self._pending_background.popleft()
1726
- if task.done() or task._waiting_on is not operation:
1727
- continue
1728
- self._dispose_operation_token(operation)
1729
- self._start_background(task, operation)
1730
-
1731
- def _arm_io(self, task: Task[Any], operation: _WaitIO) -> None:
1732
- if operation.sock.fileno() < 0:
1733
- raise ValueError("cannot wait on a closed socket")
1734
- task._waiting_on = operation
1735
- sides = self._io_waiters.setdefault(operation.sock, {"read": set(), "write": set()})
1736
- sides[operation.mode].add(task)
1737
- self._refresh_socket(operation.sock)
1738
-
1739
- def _refresh_socket(self, sock: socket.socket) -> None:
1740
- sides = self._io_waiters.get(sock)
1933
+ def _wake(self, operation: _WaitIO, error: BaseException | None = None) -> None:
1934
+ task = operation.waiter
1935
+ if task is not None and task._claim(operation):
1936
+ runtime = self._runtime
1937
+ runtime._dispose_operation_token(operation)
1938
+ if error is not None:
1939
+ task._next_exception = error
1940
+ runtime._enqueue_task(task)
1941
+
1942
+ def _arm(self, operation: _WaitIO) -> None:
1943
+ task = operation.waiter
1944
+ if task is None or task._waiting_on is not operation:
1945
+ return # cancelled before the reactor got to it
1946
+ sock = operation.sock
1947
+ sides = self._waiters.setdefault(sock, {"read": set(), "write": set()})
1948
+ sides[operation.mode].add(operation)
1949
+ self._refresh(sock)
1950
+
1951
+ def _disarm(self, operation: _WaitIO) -> None:
1952
+ sides = self._waiters.get(operation.sock)
1953
+ if sides is not None:
1954
+ sides[operation.mode].discard(operation)
1955
+ self._refresh(operation.sock)
1956
+
1957
+ def _refresh(self, sock: socket.socket) -> None:
1958
+ selector = cast(selectors.BaseSelector, self._selector)
1959
+ sides = self._waiters.get(sock)
1741
1960
  mask = 0
1742
1961
  if sides:
1743
1962
  if sides["read"]:
@@ -1745,414 +1964,767 @@ class _Runtime:
1745
1964
  if sides["write"]:
1746
1965
  mask |= selectors.EVENT_WRITE
1747
1966
  try:
1748
- self._selector.get_key(sock)
1967
+ selector.get_key(sock)
1749
1968
  registered = True
1750
1969
  except (KeyError, ValueError, OSError):
1751
1970
  registered = False
1752
1971
  try:
1753
1972
  if mask:
1754
1973
  if registered:
1755
- self._selector.modify(sock, mask, data=None)
1974
+ selector.modify(sock, mask, data=None)
1756
1975
  else:
1757
- self._selector.register(sock, mask, data=None)
1976
+ selector.register(sock, mask, data=None)
1758
1977
  else:
1759
1978
  if registered:
1760
1979
  try:
1761
- self._selector.unregister(sock)
1980
+ selector.unregister(sock)
1762
1981
  except (KeyError, ValueError, OSError):
1763
1982
  pass
1764
- self._io_waiters.pop(sock, None)
1983
+ self._waiters.pop(sock, None)
1765
1984
  except (KeyError, ValueError, OSError) as error:
1766
1985
  # A socket may be closed while tasks are waiting on it. Fail those
1767
- # waits instead of allowing a selector error to kill the scheduler.
1768
- sides = self._io_waiters.pop(sock, None) or {"read": set(), "write": set()}
1769
- affected = set(sides["read"]) | set(sides["write"])
1770
- for task in affected:
1771
- operation = task._waiting_on
1772
- if isinstance(operation, _WaitIO) and operation.sock is sock:
1773
- task._waiting_on = None
1774
- self._dispose_operation_token(operation)
1775
- self._schedule(task, exc=error)
1986
+ # waits instead of allowing a selector error to kill the reactor.
1987
+ sides = self._waiters.pop(sock, None) or {"read": set(), "write": set()}
1988
+ for operation in sides["read"] | sides["write"]:
1989
+ self._wake(operation, error)
1776
1990
  try:
1777
- self._selector.unregister(sock)
1991
+ selector.unregister(sock)
1778
1992
  except (KeyError, ValueError, OSError):
1779
1993
  pass
1780
1994
 
1781
- def _detach_wait(self, task: Task[Any]) -> None:
1782
- operation = task._waiting_on
1783
- if operation is None:
1995
+ def _ready(self, sock: Any, mask: int) -> None:
1996
+ sides = self._waiters.get(sock)
1997
+ if sides is None:
1784
1998
  return
1785
- task._waiting_on = None
1786
- self._dispose_operation_token(operation)
1787
- if isinstance(operation, _WaitIO):
1788
- sides = self._io_waiters.get(operation.sock)
1789
- if sides is not None:
1790
- sides[operation.mode].discard(task)
1791
- self._refresh_socket(operation.sock)
1792
- elif isinstance(operation, _WaitTask):
1793
- operation.task._awaiters.discard(task)
1794
- elif isinstance(operation, _WaitMany):
1795
- for target in operation.tasks:
1796
- target._awaiters.discard(task)
1797
- elif isinstance(operation, _BackgroundCall):
1798
- if operation.future is None:
1799
- try:
1800
- self._pending_background.remove((task, operation))
1801
- except ValueError:
1802
- pass
1803
- else:
1804
- # This cancels queued executor work where possible. If already
1805
- # running, the worker continues and remains tracked until it exits.
1806
- operation.future.cancel()
1807
- # Timer entries are lazily discarded when they reach the heap's top.
1999
+ to_wake: set[_WaitIO] = set()
2000
+ if mask & selectors.EVENT_READ:
2001
+ to_wake.update(sides["read"])
2002
+ sides["read"].clear()
2003
+ if mask & selectors.EVENT_WRITE:
2004
+ to_wake.update(sides["write"])
2005
+ sides["write"].clear()
2006
+ for operation in to_wake:
2007
+ self._wake(operation)
2008
+ self._refresh(sock)
1808
2009
 
1809
- def _drain_wakeup(self) -> None:
1810
- while True:
1811
- try:
1812
- if not self._wake_reader.recv(4096):
1813
- break
1814
- except BlockingIOError:
1815
- break
1816
- except OSError:
1817
- break
1818
- while True:
1819
- try:
1820
- callback = self._commands.get_nowait()
1821
- except queue.Empty:
1822
- break
1823
- try:
1824
- callback()
1825
- except BaseException as error:
1826
- self._report_exception(
1827
- {"message": "Unhandled exception in Task scheduler callback", "callback": callback},
2010
+ def _loop(self) -> None:
2011
+ _thread_state.internal = True
2012
+ selector = cast(selectors.BaseSelector, self._selector)
2013
+ reader = cast(socket.socket, self._wake_reader)
2014
+ commands = self._commands
2015
+ failure: BaseException | None = None
2016
+ try:
2017
+ while not self._closing:
2018
+ for key, mask in selector.select(None):
2019
+ if key.data is _WAKE:
2020
+ try:
2021
+ while reader.recv(4096):
2022
+ pass
2023
+ except OSError: # includes BlockingIOError
2024
+ pass
2025
+ else:
2026
+ self._ready(key.fileobj, mask)
2027
+ while True:
2028
+ try:
2029
+ command, operation = commands.get_nowait()
2030
+ except queue.Empty:
2031
+ break
2032
+ command(operation)
2033
+ except BaseException as error:
2034
+ failure = error
2035
+ if not self._closing:
2036
+ self._runtime._report_exception(
2037
+ {"message": "Fatal error in Task IO thread; socket waits are unavailable"},
1828
2038
  error,
1829
2039
  )
2040
+ finally:
2041
+ with self._lock:
2042
+ self._failure = failure or RuntimeShutdownError("Task runtime is shutting down")
2043
+ # Nothing will ever signal the remaining waits: fail them, both
2044
+ # the armed ones and those still sitting in the command queue.
2045
+ stranded = [
2046
+ operation
2047
+ for sides in self._waiters.values()
2048
+ for operation in sides["read"] | sides["write"]
2049
+ ]
2050
+ self._waiters.clear()
2051
+ while True:
2052
+ try:
2053
+ command, operation = commands.get_nowait()
2054
+ except queue.Empty:
2055
+ break
2056
+ if command == self._arm:
2057
+ stranded.append(operation)
2058
+ for operation in stranded:
2059
+ self._wake(operation, self._failure)
2060
+ self._discard_resources()
2061
+
2062
+ def close(self) -> bool:
2063
+ """Stop the reactor thread. False if it did not stop in time."""
2064
+ with self._lock:
2065
+ self._closing = True
2066
+ thread = self._thread
2067
+ if thread is None:
2068
+ return True
2069
+ self._notify()
2070
+ thread.join(1.0)
2071
+ return not thread.is_alive()
1830
2072
 
1831
- def _process_events(self, events: list[tuple[selectors.SelectorKey, int]]) -> None:
1832
- for key, mask in events:
1833
- if key.data is _WAKE:
1834
- self._drain_wakeup()
1835
- continue
1836
- sock: Any = key.fileobj
1837
- sides = self._io_waiters.get(sock)
1838
- if sides is None:
1839
- continue
1840
- to_wake: set[Task[Any]] = set()
1841
- if mask & selectors.EVENT_READ:
1842
- to_wake.update(sides["read"])
1843
- sides["read"].clear()
1844
- if mask & selectors.EVENT_WRITE:
1845
- to_wake.update(sides["write"])
1846
- sides["write"].clear()
1847
- for task in to_wake:
1848
- operation = task._waiting_on
1849
- if isinstance(operation, _WaitIO) and operation.sock is sock:
1850
- task._waiting_on = None
1851
- self._dispose_operation_token(operation)
1852
- self._schedule(task)
1853
- self._refresh_socket(sock)
1854
-
1855
- def _expire_timers(self) -> None:
1856
- now = time.monotonic()
1857
- while self._timers and self._timers[0][0] <= now:
1858
- _, _, task, operation = heapq.heappop(self._timers)
1859
- if task.done() or task._waiting_on is not operation:
1860
- continue
1861
- task._waiting_on = None
1862
- self._dispose_operation_token(operation)
1863
- self._schedule(task)
1864
-
1865
- def _next_timeout(self) -> float | None:
1866
- max_selector_wait = 24 * 60 * 60 # 24 hours, in seconds
1867
-
1868
- shutdown_timeout = None
1869
- if self._shutdown_requested and self._shutdown_deadline is not None:
1870
- shutdown_timeout = max(
1871
- 0.0,
1872
- self._shutdown_deadline - time.monotonic(),
1873
- )
1874
2073
 
1875
- while self._timers:
1876
- deadline, _, task, operation = self._timers[0]
2074
+ def _spin_count() -> int:
2075
+ """How long an idle worker polls for work before it parks.
1877
2076
 
1878
- if task.done() or task._waiting_on is not operation:
1879
- heapq.heappop(self._timers)
1880
- else:
1881
- remaining = max(0.0, deadline - time.monotonic())
1882
- timer_timeout = min(remaining, max_selector_wait)
2077
+ Spinning only pays off when another thread can produce work at the same
2078
+ time. With the GIL it would merely keep that thread from running.
2079
+ """
2080
+ gil_enabled = getattr(sys, "_is_gil_enabled", None)
2081
+ if gil_enabled is None or gil_enabled():
2082
+ return 0
2083
+ return 400 # a few tens of microseconds
2084
+
2085
+
2086
+ class _WorkerPool:
2087
+ """Thread pool modelled on the .NET ThreadPool.
2088
+
2089
+ * One shared FIFO queue (a ``collections.deque``, whose append/popleft are
2090
+ atomic with the GIL and on free-threaded builds).
2091
+ * Workers are created on demand: immediately up to ``min_workers``, and
2092
+ beyond that by the gate thread when queued work stops making progress
2093
+ (starvation), up to the hard limit ``max_workers``.
2094
+ * A worker blocked in ``Task.result()`` is reported to the pool, which may
2095
+ start a replacement right away (.NET's cooperative blocking detection).
2096
+ * Workers above ``min_workers`` retire after being idle for a while.
2097
+ * Workers are daemon threads, like .NET background threads: a worker stuck
2098
+ in user code never keeps the process from exiting.
2099
+
2100
+ Waking a sleeping thread is by far the most expensive step of handing work
2101
+ over, so it is avoided wherever the work would get picked up anyway:
2102
+
2103
+ * A worker that makes exactly one task runnable while finishing its
2104
+ current item runs that task next itself (``_ThreadState.slot``).
2105
+ * Queuing work wakes a parked worker only if no worker is already
2106
+ *searching* (awake and looking for work). A woken worker that finds
2107
+ work wakes the next one if more is waiting, so a burst still fans out
2108
+ over all workers, while a chain of sequential hand-offs stays on the
2109
+ threads that are already running instead of bouncing between sleepers.
2110
+ * On free-threaded builds a worker that runs dry keeps looking for a few
2111
+ tens of microseconds before it parks, which covers the usual gap until
2112
+ the next continuation arrives.
2113
+
2114
+ There is deliberately no per-worker queue and no work stealing: with the
2115
+ GIL it cannot help, and one shared queue is enough for Python-level work
2116
+ on free-threaded builds.
2117
+
2118
+ ``_count``, ``_searching``, ``_blocked`` and ``_parked`` are only written
2119
+ under ``_lock``; the unlocked reads are hints, and every path that could
2120
+ lose a wake-up re-checks after publishing its own state.
2121
+ """
1883
2122
 
1884
- if shutdown_timeout is None:
1885
- return timer_timeout
2123
+ _IDLE_TIMEOUT: Final = 20.0 # same order as the .NET worker idle timeout
2124
+ _GATE_INTERVAL: Final = 0.5
2125
+ _GATE_INTERVAL_BLOCKED: Final = 0.25
1886
2126
 
1887
- return min(timer_timeout, shutdown_timeout)
2127
+ def __init__(self, runtime: "_Runtime", min_workers: int, max_workers: int) -> None:
2128
+ self._runtime = runtime
2129
+ self._min = min_workers
2130
+ self._max = max_workers
2131
+ self._items: deque[Callable[[], Any]] = deque()
2132
+ self._lock = threading.Lock()
2133
+ self._exited = threading.Condition(self._lock)
2134
+ self._count = 0 # live workers
2135
+ self._searching = 0 # workers awake without work, looking for some
2136
+ self._blocked = 0 # workers blocked in Task.result()
2137
+ self._parked: list[threading.Lock] = [] # wake handles of sleeping workers
2138
+ self._serial = 0
2139
+ self._completed = 0 # progress indicator for the gate; approximate
2140
+ self._spin = _spin_count()
2141
+ self._closed = False
2142
+ self._closing = threading.Event()
2143
+ self._gate_signal = threading.Event()
2144
+ self._gate_thread: threading.Thread | None = None
1888
2145
 
1889
- return shutdown_timeout
2146
+ def queue(self, item: Callable[[], Any]) -> bool:
2147
+ """Queue a work item. False if the pool no longer accepts work."""
2148
+ if self._closed:
2149
+ return False
2150
+ self._items.append(item)
2151
+ # Read *after* the append. A searching worker re-checks the queue
2152
+ # after it stops searching, so one of the two sides sees the other.
2153
+ if self._searching == 0:
2154
+ self._wake_one()
2155
+ return True
1890
2156
 
1891
- def _begin_shutdown(self) -> None:
1892
- self._shutdown_deadline = time.monotonic() + self._shutdown_grace
1893
- for task in list(self._tasks):
1894
- task._cancel_on_runtime()
1895
- # Anything waiting in our bounded background queue is removed as its
1896
- # task receives cancellation. Do not admit more background work at shutdown.
2157
+ def _wake_one(self) -> None:
2158
+ """Get one more worker to look at the queue, if that is possible."""
2159
+ if not self._parked:
2160
+ # Unlocked early outs for a busy pool, where this runs per item.
2161
+ count = self._count
2162
+ if count >= self._max:
2163
+ return
2164
+ if count >= self._min + min(self._blocked, self._min):
2165
+ # Past the on-demand allowance: only starvation adds workers.
2166
+ if not self._gate_signal.is_set():
2167
+ self._wake_gate()
2168
+ return
2169
+ parker = None
2170
+ serial = 0
2171
+ with self._lock:
2172
+ if self._closed or self._searching:
2173
+ return
2174
+ if self._parked:
2175
+ parker = self._parked.pop() # most recently parked: still warm
2176
+ self._searching += 1
2177
+ elif (
2178
+ self._count < self._max
2179
+ # Blocked workers do not count against the on-demand
2180
+ # allowance, up to one extra set.
2181
+ and self._count < self._min + min(self._blocked, self._min)
2182
+ ):
2183
+ self._count += 1
2184
+ self._searching += 1
2185
+ self._serial += 1
2186
+ serial = self._serial
2187
+ if parker is not None:
2188
+ parker.release()
2189
+ elif serial:
2190
+ self._spawn(serial)
2191
+
2192
+ def _spawn(self, serial: int) -> None:
2193
+ """Start a worker that was already counted as live and searching."""
2194
+ try:
2195
+ threading.Thread(
2196
+ target=self._work,
2197
+ name=f"Task-worker-{serial}",
2198
+ daemon=True,
2199
+ **_fresh_context(),
2200
+ ).start()
2201
+ except BaseException as error:
2202
+ # Out of threads/memory, or the interpreter is finalizing. Queued
2203
+ # work stays queued for the workers that do exist.
2204
+ with self._lock:
2205
+ self._count -= 1
2206
+ self._searching -= 1
2207
+ self._exited.notify_all()
2208
+ self._runtime._report_exception(
2209
+ {"message": "Failed to start a Task worker thread"}, error
2210
+ )
1897
2211
 
1898
- def is_task_worker_thread(self) -> bool:
1899
- return getattr(self._worker_context, "current_task", None) is not None
2212
+ def _work(self) -> None:
2213
+ state = _thread_state
2214
+ state.pool = self
2215
+ items = self._items
2216
+ lock = self._lock
2217
+ report = self._runtime._report_exception
2218
+ # Held while awake; released by whoever wakes this worker.
2219
+ parker = threading.Lock()
2220
+ parker.acquire()
2221
+ searching = True # whoever started this thread counted it as such
2222
+ counted = True
2223
+ try:
2224
+ while True:
2225
+ item = state.slot
2226
+ if item is not None:
2227
+ state.slot = None
2228
+ state.streak += 1
2229
+ else:
2230
+ state.streak = 0
2231
+ while True:
2232
+ if self._closed:
2233
+ return
2234
+ try:
2235
+ item = items.popleft()
2236
+ except IndexError:
2237
+ pass
2238
+ else:
2239
+ if searching:
2240
+ searching = False
2241
+ with lock:
2242
+ self._searching -= 1
2243
+ if items and self._searching == 0:
2244
+ # More is waiting and nobody is looking.
2245
+ self._wake_one()
2246
+ break
2247
+
2248
+ if self._spin:
2249
+ if not searching:
2250
+ searching = True
2251
+ with lock:
2252
+ self._searching += 1
2253
+ for _ in range(self._spin):
2254
+ if items:
2255
+ break
2256
+ if items:
2257
+ continue
2258
+
2259
+ # Nothing to do: park. Publish that first, then look
2260
+ # at the queue once more, so that a concurrent queue()
2261
+ # either sees this worker parked or is seen here.
2262
+ with lock:
2263
+ if searching:
2264
+ searching = False
2265
+ self._searching -= 1
2266
+ self._parked.append(parker)
2267
+ if items or self._closed:
2268
+ with lock:
2269
+ try:
2270
+ self._parked.remove(parker)
2271
+ continue
2272
+ except ValueError:
2273
+ pass # already picked by a waker
2274
+ parker.acquire()
2275
+ searching = True
2276
+ continue
2277
+
2278
+ while not parker.acquire(timeout=self._IDLE_TIMEOUT):
2279
+ with lock:
2280
+ if parker not in self._parked:
2281
+ # A waker picked this worker just now.
2282
+ parker_pending = True
2283
+ elif self._count > self._min and not self._closed:
2284
+ # Surplus worker: retire. Decided and
2285
+ # counted atomically, so the pool cannot
2286
+ # drop below min_workers.
2287
+ self._parked.remove(parker)
2288
+ self._count -= 1
2289
+ self._exited.notify_all()
2290
+ counted = False
2291
+ return
2292
+ else:
2293
+ parker_pending = False
2294
+ if parker_pending:
2295
+ parker.acquire()
2296
+ break
2297
+ searching = True # the waker counted this worker
2298
+
2299
+ state.tail = False
2300
+ try:
2301
+ item()
2302
+ except BaseException as error:
2303
+ report(
2304
+ {
2305
+ "message": "Unhandled exception in Task scheduler callback",
2306
+ "callback": item,
2307
+ },
2308
+ error,
2309
+ )
2310
+ item = None
2311
+ # Unsynchronized on purpose: the gate only needs to see that
2312
+ # the number moved, a lost increment is harmless.
2313
+ self._completed += 1
2314
+ finally:
2315
+ state.pool = None
2316
+ with lock:
2317
+ if searching:
2318
+ self._searching -= 1
2319
+ if counted:
2320
+ self._count -= 1
2321
+ self._exited.notify_all()
2322
+
2323
+ def _worker_blocked(self) -> None:
2324
+ with self._lock:
2325
+ self._blocked += 1
2326
+ if self._items and self._searching == 0:
2327
+ self._wake_one()
1900
2328
 
1901
- def _run_coroutine_step(
1902
- self,
1903
- task: Task[Any],
1904
- coroutine: Coroutine[Any, Any, Any],
1905
- value: Any,
1906
- exception: BaseException | None,
1907
- ) -> _CoroutineStep:
1908
- def execute_step() -> _CoroutineStep:
1909
- previous_task = _current_task.value
1910
- _current_task.value = task
2329
+ def _worker_unblocked(self) -> None:
2330
+ with self._lock:
2331
+ self._blocked -= 1
1911
2332
 
1912
- try:
1913
- return _advance_coroutine(coroutine, value, exception)
1914
- finally:
1915
- _current_task.value = previous_task
2333
+ def _wake_gate(self) -> None:
2334
+ with self._lock:
2335
+ if self._closed:
2336
+ return
2337
+ if self._gate_thread is None:
2338
+ thread = threading.Thread(
2339
+ target=self._gate, name="Task-gate", daemon=True, **_fresh_context()
2340
+ )
2341
+ try:
2342
+ thread.start()
2343
+ except BaseException:
2344
+ return
2345
+ self._gate_thread = thread
2346
+ self._gate_signal.set()
2347
+
2348
+ def _gate(self) -> None:
2349
+ """Inject a worker when queued work makes no progress (starvation)."""
2350
+ _thread_state.internal = True
2351
+ items = self._items
2352
+ signal = self._gate_signal
2353
+ closing = self._closing
2354
+ while True:
2355
+ signal.wait()
2356
+ last = self._completed
2357
+ while True:
2358
+ if closing.wait(
2359
+ self._GATE_INTERVAL_BLOCKED if self._blocked else self._GATE_INTERVAL
2360
+ ):
2361
+ return
2362
+ if not items:
2363
+ # Go dormant; re-check after clearing so that a request
2364
+ # arriving in between is not lost.
2365
+ signal.clear()
2366
+ if not items:
2367
+ break
2368
+ signal.set()
2369
+ current = self._completed
2370
+ if current == last:
2371
+ # Work is waiting and not a single item finished during
2372
+ # the whole interval: every worker is tied up.
2373
+ with self._lock:
2374
+ if self._closed or self._count >= self._max:
2375
+ continue
2376
+ self._count += 1
2377
+ self._searching += 1
2378
+ self._serial += 1
2379
+ serial = self._serial
2380
+ self._spawn(serial)
2381
+ last = current
2382
+
2383
+ def close(self) -> None:
2384
+ """Stop accepting work, drop queued items and tell workers to exit."""
2385
+ with self._lock:
2386
+ self._closed = True
2387
+ parked = self._parked[:]
2388
+ self._parked.clear()
2389
+ self._searching += len(parked) # each one wakes up as a searcher
2390
+ self._closing.set()
2391
+ self._gate_signal.set()
2392
+ self._items.clear()
2393
+ for parker in parked:
2394
+ parker.release()
2395
+
2396
+ def wait(self, timeout: float) -> int:
2397
+ """Wait for workers to exit; returns how many are still running."""
2398
+ deadline = time.monotonic() + timeout
2399
+ with self._exited:
2400
+ while self._count > 0:
2401
+ remaining = deadline - time.monotonic()
2402
+ if remaining <= 0:
2403
+ break
2404
+ self._exited.wait(remaining)
2405
+ return self._count
1916
2406
 
1917
- return _run_with_context(task._execution_context, execute_step)
1918
2407
 
1919
- def _dispatch_coroutine_step(
1920
- self,
1921
- task: Task[Any],
1922
- coroutine: Coroutine[Any, Any, Any],
1923
- value: Any,
1924
- exception: BaseException | None,
1925
- ) -> None:
1926
- try:
1927
- future = self._executor.submit(
1928
- self._run_coroutine_step,
1929
- task,
1930
- coroutine,
1931
- value,
1932
- exception,
1933
- )
1934
- except BaseException as error:
1935
- task._running = False
1936
- task._finish(Task.FAILED, exception=error)
1937
- return
2408
+ class _Runtime:
2409
+ """Private singleton runtime: worker pool + socket reactor + task registry."""
1938
2410
 
1939
- task._step_future = future
1940
- with self._inflight_lock:
1941
- self._inflight_futures.add(future)
2411
+ def __init__(self, *, min_workers: int, max_workers: int) -> None:
2412
+ self._pool = _WorkerPool(self, min_workers, max_workers)
2413
+ self._io = _IOReactor(self)
2414
+ # Pending tasks, so shutdown can cancel them. add()/discard() are
2415
+ # single atomic operations with the GIL and on free-threaded builds.
2416
+ self._tasks: set[Task[Any]] = set()
2417
+ self._state_lock = threading.Lock()
2418
+ self._shutdown_lock = threading.Lock()
2419
+ self._shutdown_requested = False
2420
+ self._stopping = False
2421
+ self._closed = False
2422
+ self._drained = threading.Event()
2423
+ self._shutdown_tasks_cancelled = 0
2424
+ self._report: ShutdownReport | None = None
2425
+ self._exception_handler: Callable[[dict[str, Any]], Any] | None = None
1942
2426
 
1943
- future.add_done_callback(
1944
- lambda completed: self._coroutine_step_worker_done(task, completed)
1945
- )
2427
+ @property
2428
+ def closed(self) -> bool:
2429
+ return self._closed
1946
2430
 
1947
- def _coroutine_step_worker_done(
1948
- self,
1949
- task: Task[Any],
1950
- future: Future[_CoroutineStep],
1951
- ) -> None:
1952
- with self._inflight_lock:
1953
- self._inflight_futures.discard(future)
1954
- self._inflight_lock.notify_all()
2431
+ def set_exception_handler(self, handler: Callable[[dict[str, Any]], Any] | None) -> None:
2432
+ self._exception_handler = handler
1955
2433
 
1956
- try:
1957
- self._post(
1958
- lambda: self._coroutine_step_finished(task, future),
1959
- internal=True,
1960
- )
1961
- except RuntimeShutdownError:
2434
+ def _report_exception(self, context: dict[str, Any], error: BaseException) -> None:
2435
+ handler = self._exception_handler
2436
+ if handler is not None:
1962
2437
  try:
1963
- task._close_coroutine()
1964
- except BaseException as error:
1965
- self._report_exception(
1966
- {"message": f"Error closing coroutine for {task.name}"},
1967
- error,
1968
- )
2438
+ handler({**context, "exception": error})
2439
+ return
2440
+ except Exception:
2441
+ _LOG.exception("Task exception handler itself failed")
2442
+ message = str(context.get("message", "Unexpected Task runtime error"))
2443
+ _LOG.error("%s", message, exc_info=(type(error), error, error.__traceback__))
1969
2444
 
1970
- def _coroutine_step_finished(
1971
- self,
1972
- task: Task[Any],
1973
- future: Future[_CoroutineStep],
1974
- ) -> None:
1975
- task._step_future = None
1976
- task._running = False
2445
+ # ------------------------------------------------------------------
2446
+ # Submission
2447
+ # ------------------------------------------------------------------
1977
2448
 
1978
- if task.done():
1979
- return
2449
+ def _track(self, task: Task[Any], *, internal: bool = False) -> None:
2450
+ """Register a pending task, or reject it if the runtime is stopping.
1980
2451
 
1981
- try:
1982
- outcome = future.result()
1983
- except BaseException as error:
1984
- task._finish(Task.FAILED, exception=error)
1985
- return
2452
+ Lock-free on purpose (this runs for every task). The order matters:
2453
+ the task is added *before* the flags are read, and shutdown sets the
2454
+ flags *before* it snapshots the registry. Either this thread sees the
2455
+ flag and backs out, or the snapshot sees the task.
2456
+ """
2457
+ self._tasks.add(task)
2458
+ if self._shutdown_requested and (self._stopping or not internal):
2459
+ self._tasks.discard(task)
2460
+ raise RuntimeShutdownError("Task runtime is shutting down")
1986
2461
 
1987
- if outcome.completed:
1988
- if isinstance(outcome.error, OperationCanceledError):
1989
- task._finish(Task.CANCELLED, exception=outcome.error)
1990
- elif outcome.error is not None:
1991
- task._finish(Task.FAILED, exception=outcome.error)
1992
- else:
1993
- task._finish(Task.SUCCEEDED, result=outcome.result)
2462
+ def _post(self, callback: Callable[[], Any], *, internal: bool = False) -> None:
2463
+ """Run ``callback`` on a pool worker; failures go to the exception handler."""
2464
+ if self._stopping or (self._shutdown_requested and not internal):
2465
+ raise RuntimeShutdownError("Task runtime is shutting down")
2466
+ if not self._pool.queue(callback):
2467
+ raise RuntimeShutdownError("Task runtime is shutting down")
2468
+
2469
+ def _submit(self, task: Task[Any], work: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> None:
2470
+ task._work = (work, args, kwargs)
2471
+ try:
2472
+ self._track(task)
2473
+ except BaseException:
2474
+ task._work = None
2475
+ _close_if_coroutine(work)
2476
+ raise
2477
+ # If the pool closes in between, shutdown's final sweep cancels the task.
2478
+ self._pool.queue(task._start)
2479
+
2480
+ def _enqueue_task(self, task: Task[Any]) -> None:
2481
+ """Make a claimed task runnable."""
2482
+ state = _thread_state
2483
+ if (
2484
+ state.tail
2485
+ and state.slot is None
2486
+ and state.pool is self._pool
2487
+ and state.streak < _MAX_SLOT_STREAK
2488
+ ):
2489
+ # The calling worker is about to look for work anyway: let it run
2490
+ # this task next instead of waking another thread for it.
2491
+ state.slot = task._drive
1994
2492
  return
2493
+ self._pool.queue(task._drive)
1995
2494
 
1996
- if task._cancel_requested:
1997
- self._schedule(
1998
- task,
1999
- exc=OperationCanceledError(f"{task.name} cancelled"),
2495
+ def _task_completed(self, task: Task[Any], state: str) -> None:
2496
+ self._tasks.discard(task)
2497
+ if self._shutdown_requested:
2498
+ if state is _CANCELLED:
2499
+ with self._state_lock:
2500
+ self._shutdown_tasks_cancelled += 1
2501
+ if not self._tasks:
2502
+ self._drained.set()
2503
+
2504
+ # ------------------------------------------------------------------
2505
+ # Suspension (called by the worker that just ran a coroutine step)
2506
+ # ------------------------------------------------------------------
2507
+
2508
+ def _suspend(self, task: Task[Any], operation: Any) -> bool:
2509
+ """Act on what a coroutine yielded.
2510
+
2511
+ Returns True if the worker should run the next step right away (the
2512
+ value or exception to deliver is already stored on the task), False
2513
+ if the task was handed to someone else.
2514
+ """
2515
+ kind = type(operation)
2516
+ if kind is _WaitTask:
2517
+ target = operation.task
2518
+ if target._state is not _PENDING:
2519
+ # Awaiting an already completed task continues synchronously.
2520
+ _resume_from(task, target)
2521
+ return True
2522
+ if operation.runtime is self and target is not task:
2523
+ operation.waiter = task
2524
+ if not task._park(operation):
2525
+ return True
2526
+ if target._add_continuation(operation):
2527
+ return False
2528
+ # The target completed between the check and the registration.
2529
+ if task._claim(operation):
2530
+ _resume_from(task, target)
2531
+ return True
2532
+ return False
2533
+ if target is task:
2534
+ task._next_exception = RuntimeError("a task cannot await itself")
2535
+ return True
2536
+ elif kind is _YieldNow:
2537
+ if operation.runtime is self:
2538
+ with task._lock:
2539
+ task._running = False
2540
+ alive = task._state is _PENDING
2541
+ # Always through the shared queue: the point of yielding is to
2542
+ # let work that is already queued go first.
2543
+ return not (alive and self._pool.queue(task._drive))
2544
+ elif kind is _WaitIO:
2545
+ if operation.runtime is self:
2546
+ return self._suspend_io(task, operation)
2547
+
2548
+ if not isinstance(operation, _Operation):
2549
+ task._next_exception = RuntimeError(
2550
+ f"{task.name} yielded unsupported object {operation!r}; "
2551
+ "this runtime only supports Task awaitables"
2000
2552
  )
2001
- return
2553
+ elif operation.runtime is not self:
2554
+ task._next_exception = RuntimeError("awaitable belongs to a different runtime")
2555
+ else:
2556
+ task._next_exception = RuntimeError(f"unsupported operation type: {kind.__name__}")
2557
+ return True
2002
2558
 
2559
+ def _suspend_io(self, task: Task[Any], operation: _WaitIO) -> bool:
2560
+ token = operation.token
2561
+ if token.is_cancellation_requested:
2562
+ task._next_exception = OperationCanceledError(
2563
+ "Operation token was cancelled", token=token
2564
+ )
2565
+ return True
2003
2566
  try:
2004
- self._handle_yielded(task, outcome.yielded)
2005
- except BaseException as error:
2006
- self._detach_wait(task)
2007
- self._schedule(task, exc=error)
2567
+ if operation.sock.fileno() < 0:
2568
+ raise ValueError("cannot wait on a closed socket")
2569
+ except Exception as error:
2570
+ task._next_exception = error
2571
+ return True
2572
+ operation.waiter = task
2573
+ if not task._park(operation):
2574
+ return True
2575
+ self._io.arm(operation)
2576
+ if token.can_be_cancelled:
2577
+ # May run the callback inline if the token was cancelled meanwhile.
2578
+ registration = token.register(operation._on_cancel)
2579
+ operation._token_registration = registration
2580
+ if task._waiting_on is not operation:
2581
+ # Already resumed: nobody else will dispose the registration.
2582
+ operation._token_registration = None
2583
+ registration.dispose()
2584
+ return False
2585
+
2586
+ def _cancel_wait(self, operation: _Operation) -> None:
2587
+ """Token callback: abort the wait and raise in the waiting coroutine."""
2588
+ task = operation.waiter
2589
+ if task is not None and task._claim(operation):
2590
+ self._release_wait(operation)
2591
+ task._next_exception = OperationCanceledError(
2592
+ "Operation token was cancelled", token=operation.token
2593
+ )
2594
+ self._enqueue_task(task)
2008
2595
 
2009
- def _loop(self) -> None:
2010
- self._thread_id = threading.get_ident()
2011
- self._started.set()
2596
+ def _dispose_operation_token(self, operation: _Operation) -> None:
2597
+ registration = operation._token_registration
2598
+ if registration is not None:
2599
+ operation._token_registration = None
2600
+ registration.dispose()
2601
+
2602
+ def _release_wait(self, operation: _Operation) -> None:
2603
+ """Undo the registrations of a wait that was claimed by cancellation."""
2604
+ self._dispose_operation_token(operation)
2605
+ if isinstance(operation, _WaitTask):
2606
+ operation.task._remove_continuation(operation)
2607
+ elif isinstance(operation, _WaitIO):
2608
+ self._io.disarm(operation)
2609
+
2610
+ def _close_coroutine(self, task: Task[Any], coroutine: Coroutine[Any, Any, Any]) -> None:
2012
2611
  try:
2013
- while not self._stopping:
2014
- self._drain_wakeup()
2015
- if self._shutdown_requested:
2016
- if not self._tasks:
2017
- self._stopping = True
2018
- elif self._shutdown_deadline is not None and time.monotonic() >= self._shutdown_deadline:
2019
- self._stopping = True
2020
- while self._ready and not self._stopping:
2021
- task = self._ready.popleft()
2022
- task._queued = False
2023
- task._step()
2024
- self._drain_wakeup()
2025
- if self._shutdown_requested:
2026
- if not self._tasks:
2027
- self._stopping = True
2028
- elif self._shutdown_deadline is not None and time.monotonic() >= self._shutdown_deadline:
2029
- self._stopping = True
2030
- self._expire_timers()
2031
- if self._stopping:
2032
- break
2033
- if self._ready:
2034
- continue
2035
- try:
2036
- events = self._selector.select(self._next_timeout())
2037
- except (OSError, ValueError) as error:
2038
- if self._stopping or self.closed:
2039
- break
2040
- self._report_exception(
2041
- {"message": "Selector failed; stopping Task runtime"}, error
2042
- )
2043
- self._stopping = True
2044
- break
2045
- try:
2046
- self._process_events(events)
2047
- except BaseException as error:
2048
- self._report_exception(
2049
- {"message": "Unhandled error while processing selector events"}, error
2050
- )
2051
- self._stopping = True
2612
+ _run_with_context(cast(Context, task._execution_context), coroutine.close)
2052
2613
  except BaseException as error:
2053
- self._report_exception({"message": "Fatal error in Task scheduler loop"}, error)
2054
- self._stopping = True
2055
- finally:
2056
- # Stop accepting work before releasing scheduler resources. The
2057
- # closed flag is published after cleanup, so new runtimes do not
2058
- # overlap this runtime's resource finalization.
2059
- tasks = list(self._tasks)
2060
- for task in tasks:
2061
- self._detach_wait(task)
2062
- for task in tasks:
2063
- future = task._step_future
2064
- if future is None or future.done():
2065
- try:
2066
- task._close_coroutine()
2067
- except BaseException as error:
2068
- self._report_exception(
2069
- {"message": f"Error closing coroutine for {task.name}"}, error
2070
- )
2071
- task._finish(Task.CANCELLED, exception=OperationCanceledError("runtime shutting down"))
2072
- # Remove scheduler-owned pending calls; they have never entered a worker.
2073
- self._pending_background.clear()
2614
+ self._report_exception(
2615
+ {"message": f"Error closing coroutine for {task.name}"}, error
2616
+ )
2617
+
2618
+ # ------------------------------------------------------------------
2619
+ # Shutdown
2620
+ # ------------------------------------------------------------------
2621
+
2622
+ def _snapshot_tasks(self) -> list[Task[Any]]:
2623
+ while True:
2074
2624
  try:
2075
- self._selector.close()
2076
- except BaseException as error:
2077
- self._report_exception({"message": "Error closing selector"}, error)
2078
- for wake_socket in (self._wake_reader, self._wake_writer):
2079
- try:
2080
- wake_socket.close()
2081
- except OSError:
2082
- pass
2083
- with self._state_lock:
2084
- self._closed = True
2625
+ return list(self._tasks)
2626
+ except RuntimeError:
2627
+ # Resized by another thread while being copied.
2628
+ continue
2085
2629
 
2086
2630
  def shutdown(self, *, grace_timeout: float, worker_timeout: float) -> ShutdownReport:
2087
- if self.is_runtime_thread():
2088
- raise RuntimeError("Task.shutdown() cannot block from the runtime thread")
2089
- with self._state_lock:
2631
+ with self._shutdown_lock:
2090
2632
  if self._closed:
2091
- thread = self._thread
2092
- else:
2093
- self._shutdown_requested = True
2094
- self._shutdown_grace = grace_timeout
2095
- self._commands.put(self._begin_shutdown)
2096
- thread = self._thread
2097
- try:
2098
- self._wake_writer.send(b"\x00")
2099
- except (BlockingIOError, OSError):
2100
- pass
2101
- if thread is not None and thread.is_alive():
2102
- # Grace timeout is enforced by the loop; the small allowance lets the
2103
- # loop execute its finalizer after the deadline.
2104
- thread.join(timeout=grace_timeout + 1.0)
2105
- runtime_stopped = thread is None or not thread.is_alive()
2106
- if not runtime_stopped:
2107
- self._report_exception(
2108
- {"message": "Task scheduler thread did not stop before timeout"},
2109
- TimeoutError("scheduler shutdown timed out"),
2110
- )
2111
-
2112
- # Cancel executor-queued calls. Already-running functions are not killable.
2113
- self._executor.shutdown(wait=False, cancel_futures=True)
2114
- worker_deadline = time.monotonic() + worker_timeout
2115
- with self._inflight_lock:
2116
- while self._inflight_futures:
2117
- remaining = worker_deadline - time.monotonic()
2633
+ return cast(ShutdownReport, self._report)
2634
+
2635
+ # 1. Reject new external work and ask every pending task to cancel.
2636
+ self._shutdown_requested = True
2637
+ deadline = time.monotonic() + grace_timeout
2638
+ # Synchronous functions cannot be cancelled and get worker_timeout
2639
+ # rather than the coroutine grace period.
2640
+ synchronous = [
2641
+ task for task in self._snapshot_tasks() if task._cancel_for_shutdown()
2642
+ ]
2643
+ self._tasks.difference_update(synchronous)
2644
+
2645
+ # 2. Give coroutines the grace period to unwind (they may still
2646
+ # await delays for cleanup).
2647
+ while self._tasks:
2648
+ remaining = deadline - time.monotonic()
2118
2649
  if remaining <= 0:
2119
2650
  break
2120
- self._inflight_lock.wait(remaining)
2121
- workers_still_running = len(self._inflight_futures)
2122
- if workers_still_running == 0:
2123
- # It is now safe to join worker threads without an unbounded wait.
2124
- self._executor.shutdown(wait=True, cancel_futures=True)
2125
- return ShutdownReport(
2126
- runtime_stopped=runtime_stopped,
2127
- tasks_cancelled=self._shutdown_tasks_cancelled,
2128
- workers_still_running=workers_still_running,
2129
- timed_out=(not runtime_stopped or workers_still_running > 0),
2130
- )
2651
+ self._drained.wait(min(remaining, 0.05))
2652
+ self._drained.clear()
2653
+
2654
+ # 3. Stop for good: nothing is accepted any more, whatever is
2655
+ # still pending is completed as cancelled.
2656
+ self._stopping = True
2657
+ while True:
2658
+ leftover = self._snapshot_tasks()
2659
+ if not leftover:
2660
+ break
2661
+ for task in leftover:
2662
+ task._force_cancel()
2663
+ self._tasks.discard(task)
2664
+ self._pool.close()
2665
+ io_stopped = self._io.close()
2666
+
2667
+ # 4. Running synchronous functions cannot be stopped; wait a bit.
2668
+ workers_still_running = self._pool.wait(worker_timeout)
2669
+ for task in synchronous:
2670
+ task._force_cancel()
2671
+
2672
+ if not io_stopped:
2673
+ self._report_exception(
2674
+ {"message": "Task IO thread did not stop before timeout"},
2675
+ TimeoutError("IO thread shutdown timed out"),
2676
+ )
2677
+ report = ShutdownReport(
2678
+ runtime_stopped=io_stopped,
2679
+ tasks_cancelled=self._shutdown_tasks_cancelled,
2680
+ workers_still_running=workers_still_running,
2681
+ timed_out=(not io_stopped or workers_still_running > 0),
2682
+ )
2683
+ self._report = report
2684
+ self._closed = True
2685
+ return report
2131
2686
 
2132
2687
 
2133
2688
  def _is_async_callable(value: Any) -> bool:
2689
+ function = value.__func__ if type(value) is MethodType else value
2690
+ if type(function) is FunctionType:
2691
+ if function.__code__.co_flags & inspect.CO_COROUTINE:
2692
+ return True
2693
+ if not function.__dict__:
2694
+ # A plain function: nothing (functools.wraps,
2695
+ # inspect.markcoroutinefunction, ...) could make it async.
2696
+ return False
2134
2697
  if inspect.iscoroutinefunction(value):
2135
2698
  return True
2136
2699
  call = getattr(value, "__call__", None)
2137
2700
  return inspect.iscoroutinefunction(call)
2138
2701
 
2139
2702
 
2703
+ def _default_min_workers() -> int:
2704
+ cpus = getattr(os, "process_cpu_count", os.cpu_count)() or 1
2705
+ return min(32, cpus + 4)
2706
+
2707
+
2140
2708
  _runtime_lock = threading.RLock()
2141
2709
  _runtime: _Runtime | None = None
2142
2710
  _runtime_config: dict[str, int] = {
2143
- "max_workers": min(32, (os.cpu_count() or 1) + 4),
2144
- "max_pending_background": 128,
2711
+ # Created on demand without delay; the same size the fixed pool used to have.
2712
+ "min_workers": _default_min_workers(),
2713
+ # Same default as the .NET thread pool: effectively unbounded, reached only
2714
+ # through slow injection while the pool is starved.
2715
+ "max_workers": 32767,
2145
2716
  }
2146
2717
 
2147
2718
 
2148
2719
  def _get_runtime() -> _Runtime:
2149
2720
  global _runtime
2721
+ runtime = _runtime
2722
+ if runtime is not None and not runtime._closed:
2723
+ return runtime
2150
2724
  with _runtime_lock:
2151
2725
  if _runtime is None or _runtime.closed:
2152
2726
  _runtime = _Runtime(**_runtime_config)
2153
- runtime = _runtime
2154
- runtime._ensure_started()
2155
- return runtime
2727
+ return _runtime
2156
2728
 
2157
2729
 
2158
2730
  def _shutdown_at_exit() -> None:
@@ -2165,6 +2737,24 @@ def _shutdown_at_exit() -> None:
2165
2737
  atexit.register(_shutdown_at_exit)
2166
2738
 
2167
2739
 
2740
+ def _reset_after_fork() -> None:
2741
+ # Only the forking thread exists in the child: the pool, timer and IO
2742
+ # threads are gone and any lock may be held by a thread that no longer
2743
+ # exists. Start from scratch; the runtime is recreated lazily.
2744
+ global _runtime, _runtime_lock, _timers
2745
+ _runtime_lock = threading.RLock()
2746
+ _runtime = None
2747
+ _timers = _TimerQueue()
2748
+ _thread_state.pool = None
2749
+ _thread_state.slot = None
2750
+ _thread_state.tail = False
2751
+ _thread_state.internal = False
2752
+
2753
+
2754
+ if hasattr(os, "register_at_fork"):
2755
+ os.register_at_fork(after_in_child=_reset_after_fork)
2756
+
2757
+
2168
2758
  @overload
2169
2759
  def task[**P, T](
2170
2760
  function: Callable[P, Awaitable[T]]