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