-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSmallOS.py
More file actions
1299 lines (1156 loc) · 49 KB
/
Copy pathSmallOS.py
File metadata and controls
1299 lines (1156 loc) · 49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Native smallOS scheduler.
This module is the core of the async runtime. Tasks yield ``TaskInstruction``
objects, the scheduler interprets them, and tasks are resumed according to
smallOS priority rules rather than ``asyncio``'s event loop behavior.
That separation is what makes the project-specific features possible:
- custom priorities
- explicit signal integration
- a runtime shape that is easier to port to MicroPython
"""
from __future__ import annotations
try:
from typing import TYPE_CHECKING
except ImportError: # pragma: no cover
TYPE_CHECKING = False
if TYPE_CHECKING:
from collections.abc import Iterable
from typing import Any
from .Kernel import Kernel
from .SmallTask import SmallTask
from ._types import (
ErrorHandler,
ExecutionAdapterLike,
RuntimeErrorEvent,
SmallOSConfigData,
)
from .awaitables import TaskInstruction
from .SmallIO import SmallIO
from .SmallConfig import SmallOSConfig
from .OSlist import OSList
from .SmallErrors import MaxProcessError, TaskCancelledError, UnsupportedAwaitableError
from .adapters.errors import (
AdapterCancelledError,
AdapterClosedError,
AdapterProtocolError,
AdapterUnavailableError,
normalize_adapter_exception,
)
_MISSING = object()
class SmallOS(SmallIO):
"""
Cooperative event loop for ``SmallTask`` coroutines.
The scheduler deliberately stays narrow in scope: pick a runnable task,
advance it once, interpret the yielded instruction, and update queues.
Keeping that control flow explicit makes the runtime easier to understand
and easier to customize.
"""
def __init__(
self,
size: int | None = None,
config: SmallOSConfig | SmallOSConfigData | None = None,
**kwargs: Any,
) -> None:
"""
Create the runtime shell plus its task and shell registries.
``config`` may be a ``SmallOSConfig`` instance or a plain dict. Older
constructor-style overrides such as ``size`` still work and take
precedence over the loaded config values when both are supplied.
"""
config_overrides = {}
if size is not None:
config_overrides["task_capacity"] = size
if "priority_levels" in kwargs:
config_overrides["priority_levels"] = kwargs.pop("priority_levels")
if "io_buffer_length" in kwargs:
config_overrides["io_buffer_length"] = kwargs.pop("io_buffer_length")
if "eternal_watchers" in kwargs:
config_overrides["eternal_watchers"] = kwargs.pop("eternal_watchers")
self.config = SmallOSConfig.from_dict(config)
if config_overrides:
self.config = self.config.copy(**config_overrides)
self.sleepTasks = []
self.waitingTasks = []
self.wakeUpdate = []
self.ioReadWaiters = {}
self.ioWriteWaiters = {}
self._io_wait_set = None
self._adapter_jobs: dict[
int,
tuple[ExecutionAdapterLike, SmallTask[Any]],
] = {}
self._next_adapter_job_id = 0
self.shells = []
self.tasks = OSList(self.config.priority_levels, self.config.task_capacity)
self.kernel = None
self.eternalWatchers = self.config.eternal_watchers
self.cursor = None
self.errorHandler = None
self.errorHandlerIncludeCancelled = False
SmallIO.__init__(self, self.config.io_buffer_length)
if kwargs:
if kwargs.get("tasks", False):
self.fork(kwargs["tasks"])
if kwargs.get("shells", False):
shells = kwargs["shells"]
if isinstance(shells, list):
[shell.setOS(self) for shell in shells]
self.shells.extend(shells)
else:
shells.setOS(self)
self.shells.append(shells)
def startOS(self) -> None:
"""Compatibility entrypoint kept from the earlier project API."""
return self.start()
def start(self) -> None:
"""
Run the scheduler until no live tasks remain.
Each pass wakes expired sleepers, selects the highest-priority runnable
task, advances it once, and then either finalizes it or handles the wait
condition it requested.
"""
self._open_io_wait_set()
try:
while len(self.tasks) != 0:
self._wake_sleeping_tasks()
if self.tasks.has_ready():
# Include newly ready I/O tasks in the priority decision.
self._wake_io_tasks(timeout_ms=0)
else:
# Go directly to the blocking wait instead of first issuing
# a redundant zero-time poll.
if not self._idle_until_next_task():
break
self._wake_sleeping_tasks()
self.cursor = self.tasks.pop()
if self.cursor is None:
continue
yielded = self.cursor.execute()
if self.cursor.done:
# Finished tasks are finalized immediately so PID lookup and join
# bookkeeping always see a consistent terminal state.
self._finalize_task(self.cursor)
else:
# Adapter failure diagnostics only describe the coroutine step
# resumed by that adapter. Once the step yields successfully,
# a later failure should not be attributed to the old job.
self._clear_adapter_resume_origin(self.cursor)
self._handle_yield(self.cursor, yielded)
if not self.eternalWatchers and len(self.tasks) != 0 and self.tasks.isOnlyWatchers():
return
return
finally:
self._close_io_wait_set()
def _open_io_wait_set(self):
"""Create and seed the kernel's optional persistent readiness set."""
self._close_io_wait_set()
if self.kernel is None:
return
factory = getattr(self.kernel, "create_io_wait_set", None)
if factory is None:
return
wait_set = factory()
if wait_set is None:
return
self._io_wait_set = wait_set
try:
self._fail_invalid_io_waiters()
for io_obj in self.ioReadWaiters:
self._refresh_io_interest(io_obj)
for io_obj in self.ioWriteWaiters:
if io_obj not in self.ioReadWaiters:
self._refresh_io_interest(io_obj)
for io_obj in self._collect_adapter_sources():
self._refresh_io_interest(io_obj)
except BaseException:
self._close_io_wait_set()
raise
def _close_io_wait_set(self):
"""Close only the backend wait set, never the registered user objects."""
wait_set = self._io_wait_set
self._io_wait_set = None
if wait_set is not None:
wait_set.close()
def next(self) -> SmallTask | None:
"""Return the next runnable task without advancing the main loop."""
self.cursor = self.tasks.pop()
return self.cursor
def fork(
self,
children: SmallTask[Any] | list[SmallTask[Any]],
) -> int | list[int]:
"""Register one task or a list of tasks with the runtime."""
if isinstance(children, list):
ids = []
for item in children:
ids.append(self._fork_one(item))
return ids
return self._fork_one(children)
def _fork_one(self, task: SmallTask[Any]) -> int:
"""Assign a PID, attach the runtime, and enqueue the task if runnable."""
pid = self.tasks.insert(task)
if pid == -1:
raise MaxProcessError("All available PIDS are in use, cannot add more tasks.")
task.setOS(self)
if task.getExeStatus():
self.tasks.enqueue(task)
return pid
def setKernel(self, kernel: Kernel) -> SmallOS:
"""Attach the platform abstraction used for time and output."""
self.kernel = kernel
return self
def setEternalWatchers(self, isEternalWatcherPresent: bool) -> SmallOS:
"""Control whether the runtime exits once only watcher tasks remain."""
self.eternalWatchers = isEternalWatcherPresent
return self
def setErrorHandler(
self, handler: ErrorHandler | None, include_cancelled: bool = False
) -> SmallOS:
"""
Install a best-effort runtime error observer for failed tasks.
``handler`` is a synchronous callable that receives one failure-event
dictionary after the task has been finalized. Returning ``None`` removes
the current handler.
"""
if handler is not None and not callable(handler):
raise TypeError("error handler must be callable or None.")
self.errorHandler = handler
self.errorHandlerIncludeCancelled = bool(include_cancelled)
return self
def _wake_sleeping_tasks(self):
"""Promote every expired sleeping task back onto the ready queues."""
if not self.kernel:
return
for task in self.tasks.wake_sleeping(self.kernel.scheduler_now_ms()):
self.resume_task(task)
def _idle_until_next_task(self):
"""
Sleep the host kernel until the next known wake-up time.
This avoids busy-looping when every live task is blocked on time rather
than CPU. If no kernel or future wake time exists, there is nothing
useful to wait for and the scheduler should stop.
"""
if not self.kernel:
return False
next_wake = self.tasks.next_wake_time()
timeout = None
if next_wake is not None:
timeout = max(0, next_wake - self.kernel.scheduler_now_ms())
has_wait_sources = bool(
self.ioReadWaiters or self.ioWriteWaiters or self._adapter_jobs
)
if next_wake is None and not has_wait_sources:
return False
if has_wait_sources and hasattr(self.kernel, "io_wait"):
self._wake_io_tasks(timeout_ms=timeout)
elif timeout is not None and timeout > 0 and hasattr(self.kernel, "sleep_ms"):
self.kernel.sleep_ms(timeout)
return True
def resume_task(
self,
task: SmallTask,
value: Any = _MISSING,
exc: BaseException | None = None,
front: bool = False,
) -> int:
"""
Requeue a blocked task with the value or exception that completed it.
Centralizing resume logic here ensures scheduler-owned wait state is
cleared before a task gets a chance to block on something else.
"""
if task is None or task == -1 or task.done:
return -1
if self.tasks.search(task.getID()) == -1:
return -1
self._clear_wait_state(task)
task.resume(value=value, exc=exc)
self.tasks.enqueue(task, front=front)
return 0
def on_signal(self, task: SmallTask, sig: int) -> None:
"""Wake a task immediately if it is actively waiting on ``sig``."""
if task._blocked_reason == "signal" and task._waiting_signal == sig:
task.signals[sig] = 0
self.resume_task(task, value=sig, front=True)
def _handle_yield(self, task: SmallTask, yielded: Any) -> None:
"""
Interpret one scheduler instruction emitted by a task.
This method is the policy hub of the runtime. Every supported ``await``
ends up in one branch here, which makes task state transitions explicit.
"""
if yielded is None:
# Treat bare ``None`` as an immediate cooperative yield so the task
# remains runnable instead of getting stranded.
self.resume_task(task)
return
if not isinstance(yielded, TaskInstruction):
task.fail(
UnsupportedAwaitableError(
"Task {!r} yielded unsupported awaitable {!r}".format(task.name, yielded)
)
)
self._finalize_task(task)
return
operation = yielded.operation
payload = yielded.payload
if operation == "yield_now":
# Voluntary CPU handoff: keep the task runnable at the same
# priority, but let other tasks get a turn first.
self.resume_task(task)
return
if operation == "sleep":
seconds = payload.get("seconds", 0)
if seconds < 0:
task.fail(ValueError("sleep duration must be non-negative"))
self._finalize_task(task)
return
delay_ms = max(0, int(seconds * 1000))
wake_time = self.kernel.scheduler_now_ms() + delay_ms if self.kernel else delay_ms
self._enter_sleep_wait(task, wake_time)
return
if operation == "wait_signal":
signal = payload["signal"]
if task.checkSignal(signal):
self.resume_task(task, value=signal, front=True)
else:
self._enter_signal_wait(task, signal)
return
if operation == "wait_readable":
self._enter_io_wait(task, payload["io_obj"], "read")
return
if operation == "wait_writable":
self._enter_io_wait(task, payload["io_obj"], "write")
return
if operation == "adapter_call":
self._handle_adapter_call(task, payload)
return
if operation == "join":
target = self._resolve_task(payload["target"])
if target is None:
task.fail(LookupError("join target does not exist"))
self._finalize_task(task)
return
if target.done:
self._resume_from_completed(task, target)
else:
self._enter_join_wait(task, target)
return
if operation == "join_all":
targets = self._normalize_targets(payload["targets"])
if targets is None:
task.fail(LookupError("join_all target does not exist"))
self._finalize_task(task)
return
if not targets:
self.resume_task(task, value=[], front=True)
return
first_exception = self._first_exception(targets)
if first_exception is not None:
self.resume_task(task, exc=first_exception, front=True)
return
pending = {child.getID() for child in targets if not child.done}
if not pending:
self.resume_task(task, value=[child.result for child in targets], front=True)
return
# Preserve the original child ordering for the eventual results
# while also tracking a fast set of outstanding child PIDs.
self._enter_join_all_wait(task, targets, pending)
return
task.fail(UnsupportedAwaitableError("Unknown instruction {!r}".format(operation)))
self._finalize_task(task)
def _adapter_name(self, adapter: object) -> str:
"""Return a stable best-effort name for adapter diagnostics."""
try:
name = getattr(adapter, "name", None)
except BaseException:
name = None
if isinstance(name, str) and name:
return name
return type(adapter).__name__
def _safe_adapter_exception(
self,
adapter: object,
exc: object,
cancelled: bool = False,
) -> Exception:
"""Normalize foreign exceptions before they enter a SmallTask."""
if not isinstance(exc, BaseException):
exc = AdapterProtocolError(
"{} produced a non-exception failure value".format(
self._adapter_name(adapter)
)
)
return normalize_adapter_exception(
exc,
self._adapter_name(adapter),
cancelled=cancelled,
)
def _validate_adapter(self, adapter: Any) -> ExecutionAdapterLike:
"""Validate and bind the structural adapter contract on submission."""
if self.kernel is None or not hasattr(self.kernel, "io_wait"):
raise AdapterUnavailableError(
"execution adapters require a kernel with io_wait()"
)
supports_external_waits = getattr(
self.kernel,
"supports_external_wait_objects",
None,
)
if callable(supports_external_waits) and not supports_external_waits():
raise AdapterUnavailableError(
"{} cannot wait on adapter completion objects".format(
type(self.kernel).__name__
)
)
for method_name in (
"_bind_runtime",
"submit",
"cancel",
"drain_completions",
):
if not callable(getattr(adapter, method_name, None)):
raise AdapterProtocolError(
"adapter is missing callable {}()".format(method_name)
)
try:
is_closed = adapter.closed
except BaseException as exc:
raise AdapterProtocolError(
"{} closed-state check failed: {}".format(
self._adapter_name(adapter),
exc,
)
) from exc
if type(is_closed) is not bool:
raise AdapterProtocolError(
"{} closed state must be boolean".format(
self._adapter_name(adapter)
)
)
if is_closed:
raise AdapterClosedError(
"{} is closed".format(self._adapter_name(adapter))
)
adapter._bind_runtime(self)
try:
wait_object = adapter.wait_object
hash(wait_object)
except BaseException as exc:
raise AdapterProtocolError(
"{} has no usable completion wait object: {}".format(
self._adapter_name(adapter),
exc,
)
) from exc
validator = getattr(self.kernel, "validate_io_wait_object", None)
if validator is not None:
try:
is_valid, exc = validator(wait_object)
except BaseException as exc:
raise AdapterUnavailableError(
"{} could not validate the completion wait object: {}".format(
type(self.kernel).__name__,
exc,
)
) from exc
if not is_valid:
raise AdapterUnavailableError(
"{} completion wait object is invalid: {}".format(
self._adapter_name(adapter),
exc,
)
)
return adapter
def _handle_adapter_call(
self,
task: SmallTask[Any],
payload: dict[str, Any],
) -> None:
"""Submit one foreign call and block ``task`` for its completion."""
adapter_candidate = payload.get("adapter")
callable_obj = payload.get("callable")
args = payload.get("args", ())
kwargs = payload.get("kwargs", {})
try:
adapter = self._validate_adapter(adapter_candidate)
if not callable(callable_obj):
raise TypeError("adapter call target must be callable")
if not isinstance(args, tuple):
raise AdapterProtocolError("adapter call args must be a tuple")
if not isinstance(kwargs, dict):
raise AdapterProtocolError("adapter call kwargs must be a dict")
except BaseException as exc:
safe_exc = self._safe_adapter_exception(adapter_candidate, exc)
self.resume_task(task, exc=safe_exc, front=True)
return
self._next_adapter_job_id += 1
job_id = self._next_adapter_job_id
self._enter_adapter_wait(task, adapter, job_id)
try:
adapter.submit(job_id, callable_obj, args, kwargs)
except BaseException as exc:
self._adapter_jobs.pop(job_id, None)
safe_exc = self._safe_adapter_exception(adapter, exc)
self._record_adapter_resume_origin(task, adapter, job_id)
self.resume_task(task, exc=safe_exc, front=True)
def _record_adapter_resume_origin(
self,
task: SmallTask[Any],
adapter: ExecutionAdapterLike,
job_id: int,
) -> None:
"""Preserve adapter identity until the resumed coroutine step finishes."""
task._adapter_resume_name = self._adapter_name(adapter)
task._adapter_resume_job_id = job_id
def _clear_adapter_resume_origin(self, task: SmallTask[Any]) -> None:
"""Clear diagnostics associated with a completed resume step."""
task._adapter_resume_name = None
task._adapter_resume_job_id = None
def _resolve_task(self, target: int | SmallTask) -> SmallTask | None:
"""Normalize either a task object or a PID to a task object."""
if not isinstance(target, int):
return target
found = self.tasks.search(target)
return None if found == -1 else found
def _normalize_targets(self, targets: Iterable[int | SmallTask]) -> list[SmallTask] | None:
"""Resolve a join target list while preserving caller-specified order."""
normalized = []
seen = set()
for target in targets:
task = self._resolve_task(target)
if task is None or task == -1:
return None
if task.getID() in seen:
continue
seen.add(task.getID())
normalized.append(task)
return normalized
def _resume_from_completed(self, waiter, target):
"""Resume a join waiter with either the child result or its exception."""
if target.exception is not None:
self.resume_task(waiter, exc=target.exception, front=True)
else:
self.resume_task(waiter, value=target.result, front=True)
def _first_exception(self, tasks):
"""Return the first terminal exception in a task list, if any."""
for task in tasks:
if task.exception is not None:
return task.exception
return None
def _clear_wait_state(self, task):
"""
Remove a task from scheduler wait bookkeeping and reset its wait metadata.
The scheduler owns the blocked-state lifecycle, so runtime transitions
clear both registration-based wait structures and the task's stored wait
markers from one place.
"""
self._clear_wait_registration(task)
self._clear_wait_metadata(task)
def _clear_wait_metadata(self, task):
"""Reset the scheduler-owned wait metadata stored on ``task``."""
task._blocked_reason = None
task._wake_at = None
task._waiting_signal = None
task._join_target = None
task._join_targets = None
task._join_pending = set()
task._io_wait_obj = None
task._io_wait_mode = None
task._adapter = None
task._adapter_job_id = None
def _begin_wait(self, task, reason):
"""Prepare a runnable task to transition into one blocked wait state."""
self._clear_wait_state(task)
task.block(reason)
def _enter_sleep_wait(self, task, wake_time):
"""Put ``task`` to sleep until ``wake_time``."""
self._begin_wait(task, "sleep")
task._wake_at = wake_time
self.tasks.add_sleeping(task, wake_time)
def _enter_signal_wait(self, task, signal):
"""Block ``task`` until ``signal`` is delivered."""
self._begin_wait(task, "signal")
task._waiting_signal = signal
def _enter_io_wait(self, task, io_obj, mode):
"""Register ``task`` for readable or writable I/O readiness."""
reason = "wait_readable" if mode == "read" else "wait_writable"
self._begin_wait(task, reason)
task._io_wait_obj = io_obj
task._io_wait_mode = mode
validator = getattr(self.kernel, "validate_io_wait_object", None)
if validator is not None:
is_valid, exc = validator(io_obj)
if not is_valid:
self.resume_task(task, exc=self._clone_wait_error(exc), front=True)
return
try:
self._register_io_wait(task, io_obj, mode)
except Exception as exc:
# Registration failures belong at the await expression; they should
# not tear down the entire scheduler loop.
self.resume_task(task, exc=exc, front=True)
def _enter_adapter_wait(
self,
task: SmallTask[Any],
adapter: ExecutionAdapterLike,
job_id: int,
) -> None:
"""Block ``task`` on one adapter-owned external operation."""
self._begin_wait(task, "adapter")
task._adapter = adapter
task._adapter_job_id = job_id
self._adapter_jobs[job_id] = (adapter, task)
def _enter_join_wait(self, task, target):
"""Block ``task`` until ``target`` finishes."""
self._begin_wait(task, "join")
task._join_target = target
target.add_join_waiter(task)
def _enter_join_all_wait(self, task, targets, pending):
"""Block ``task`` until every child in ``pending`` has completed."""
self._begin_wait(task, "join_all")
task._join_targets = list(targets)
task._join_pending = set(pending)
for child in targets:
if not child.done:
child.add_join_waiter(task)
def _register_io_wait(self, task, io_obj, mode):
"""Register a task as waiting on an I/O object's readiness event."""
waiters = self.ioReadWaiters if mode == "read" else self.ioWriteWaiters
added_interest = io_obj not in waiters
if io_obj not in waiters:
waiters[io_obj] = []
if task not in waiters[io_obj]:
waiters[io_obj].append(task)
if added_interest:
try:
self._refresh_io_interest(io_obj)
except Exception:
waiters[io_obj].remove(task)
if not waiters[io_obj]:
del waiters[io_obj]
raise
def _refresh_io_interest(self, io_obj):
"""Apply one object's combined logical interest to a persistent wait set."""
if self._io_wait_set is None:
return
adapter_readable = False
for adapter, _task in self._adapter_jobs.values():
try:
if adapter.wait_object == io_obj:
adapter_readable = True
break
except BaseException:
# Adapter validation will fail the affected jobs before the
# next wait; never hide that failure behind refresh bookkeeping.
continue
self._io_wait_set.set_interest(
io_obj,
io_obj in self.ioReadWaiters or adapter_readable,
io_obj in self.ioWriteWaiters,
)
def _wake_io_tasks(self, timeout_ms: int | None = 0):
"""
Poll user I/O and adapter completion sources in one kernel wait.
Adapter worker threads only make their completion socket readable. All
queue mutation and task resumption still happens on this scheduler
thread.
"""
if not self.kernel or not hasattr(self.kernel, "io_wait"):
return
if not self.ioReadWaiters and not self.ioWriteWaiters and not self._adapter_jobs:
return
self._fail_invalid_io_waiters()
adapter_sources = self._collect_adapter_sources()
if not self.ioReadWaiters and not self.ioWriteWaiters and not adapter_sources:
return
readables = list(self.ioReadWaiters.keys())
for wait_object in adapter_sources:
if wait_object not in self.ioReadWaiters:
readables.append(wait_object)
adapter_job_count = len(self._adapter_jobs)
io_waiter_count = len(self.ioReadWaiters) + len(self.ioWriteWaiters)
try:
if self._io_wait_set is not None:
for wait_object in adapter_sources:
self._refresh_io_interest(wait_object)
readable, writable = self._io_wait_set.wait(timeout_ms)
else:
readable, writable = self.kernel.io_wait(
readables,
list(self.ioWriteWaiters.keys()),
timeout_ms,
)
except Exception:
# A completion channel may close after validation but before poll
# registration. Revalidate once and recover if that race removed a
# broken source; otherwise preserve the kernel's original failure.
self._fail_invalid_io_waiters()
self._collect_adapter_sources()
if (
len(self._adapter_jobs) < adapter_job_count
or len(self.ioReadWaiters) + len(self.ioWriteWaiters) < io_waiter_count
):
return
raise
self._resume_ready_io(readable, writable)
for ready_object in readable:
adapter = adapter_sources.get(ready_object)
if adapter is not None:
self._drain_adapter_completions(adapter)
def _collect_adapter_sources(self) -> dict[Any, ExecutionAdapterLike]:
"""Return valid completion wait objects for adapters with live jobs."""
adapters: list[ExecutionAdapterLike] = []
for adapter, _task in list(self._adapter_jobs.values()):
if not any(existing is adapter for existing in adapters):
adapters.append(adapter)
sources: dict[Any, ExecutionAdapterLike] = {}
validator = getattr(self.kernel, "validate_io_wait_object", None)
for adapter in adapters:
try:
is_closed = adapter.closed
if type(is_closed) is not bool:
raise AdapterProtocolError(
"{} closed state must be boolean".format(
self._adapter_name(adapter)
)
)
except BaseException as exc:
self._fail_adapter_jobs(
adapter,
AdapterProtocolError(
"{} closed-state check failed: {}".format(
self._adapter_name(adapter),
exc,
)
),
)
continue
if is_closed:
self._fail_adapter_jobs(
adapter,
AdapterClosedError(
"{} closed with jobs still pending".format(
self._adapter_name(adapter)
)
),
)
continue
try:
wait_object = adapter.wait_object
hash(wait_object)
except BaseException as exc:
self._fail_adapter_jobs(
adapter,
AdapterProtocolError(
"{} completion wait object failed: {}".format(
self._adapter_name(adapter),
exc,
)
),
)
continue
if validator is not None:
try:
is_valid, exc = validator(wait_object)
except BaseException as exc:
self._fail_adapter_jobs(
adapter,
AdapterUnavailableError(
"{} could not validate its completion wait object: {}".format(
self._adapter_name(adapter),
exc,
)
),
)
continue
if not is_valid:
self._fail_adapter_jobs(
adapter,
AdapterUnavailableError(
"{} completion wait object became invalid: {}".format(
self._adapter_name(adapter),
exc,
)
),
)
continue
if wait_object in sources and sources[wait_object] is not adapter:
self._fail_adapter_jobs(
adapter,
AdapterProtocolError(
"adapter completion wait objects must be unique"
),
)
continue
sources[wait_object] = adapter
return sources
def _drain_adapter_completions(self, adapter: ExecutionAdapterLike) -> None:
"""Resume SmallTasks from every completion currently queued."""
try:
completions = adapter.drain_completions()
if completions is None:
raise AdapterProtocolError(
"{} drain_completions() returned None".format(
self._adapter_name(adapter)
)
)
completions = list(completions)
except BaseException as exc:
self._fail_adapter_jobs(
adapter,
self._safe_adapter_exception(adapter, exc),
)
return
for completion in completions:
try:
job_id = completion.job_id
if type(job_id) is not int or job_id <= 0:
raise AdapterProtocolError(
"adapter completion job_id must be a positive integer"
)
cancelled = completion.cancelled
if type(cancelled) is not bool:
raise AdapterProtocolError(
"adapter completion cancelled state must be boolean"
)
exception = completion.exception
if exception is not None and not isinstance(
exception,
BaseException,
):
raise AdapterProtocolError(
"adapter completion exception must derive from BaseException"
)
has_value = completion.has_value
if type(has_value) is not bool:
raise AdapterProtocolError(
"adapter completion has_value state must be boolean"
)
value = completion.value if has_value else _MISSING
outcome_count = int(cancelled) + int(exception is not None) + int(has_value)
if outcome_count != 1:
raise AdapterProtocolError(
"adapter completion must contain exactly one outcome"
)
except BaseException as exc:
self._fail_adapter_jobs(
adapter,
self._safe_adapter_exception(adapter, exc),
)
return
entry = self._adapter_jobs.get(job_id)
if entry is None:
# A cancelled SmallTask may leave a late foreign completion.
continue
entry_adapter, task = entry
if entry_adapter is not adapter:
self._fail_adapter_jobs(
adapter,
AdapterProtocolError(
"{} completed job {} owned by another adapter".format(
self._adapter_name(adapter),
job_id,
)
),
)
return
self._adapter_jobs.pop(job_id, None)
if task.done or self.tasks.search(task.getID()) == -1:
continue
if cancelled:
exc = AdapterCancelledError(
"{} job {} was cancelled by the foreign runtime".format(
self._adapter_name(adapter),
job_id,
)
)
self._record_adapter_resume_origin(task, adapter, job_id)
self.resume_task(task, exc=exc, front=True)
continue
if exception is not None:
safe_exc = self._safe_adapter_exception(adapter, exception)
self._record_adapter_resume_origin(task, adapter, job_id)
self.resume_task(task, exc=safe_exc, front=True)
continue
self.resume_task(task, value=value, front=True)
try:
self._refresh_io_interest(adapter.wait_object)
except BaseException:
# The next source collection turns a broken completion object into
# a task-level adapter error rather than breaking scheduler cleanup.
pass
def _fail_adapter_jobs(
self,
adapter: ExecutionAdapterLike,
exc: BaseException,
) -> None:
"""Fail every live SmallTask waiting on a broken adapter source."""
jobs = [
(job_id, task)
for job_id, (job_adapter, task) in list(self._adapter_jobs.items())
if job_adapter is adapter