multiCMD 1.59__tar.gz → 1.60__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. {multicmd-1.59 → multicmd-1.60}/PKG-INFO +49 -5
  2. {multicmd-1.59 → multicmd-1.60}/README.md +48 -4
  3. {multicmd-1.59 → multicmd-1.60}/multiCMD.egg-info/PKG-INFO +49 -5
  4. {multicmd-1.59 → multicmd-1.60}/multiCMD.egg-info/SOURCES.txt +1 -0
  5. {multicmd-1.59 → multicmd-1.60}/multiCMD.py +87 -16
  6. {multicmd-1.59 → multicmd-1.60}/tests/test_async_executor.py +13 -8
  7. {multicmd-1.59 → multicmd-1.60}/tests/test_cli.py +13 -5
  8. multicmd-1.60/tests/test_embed.py +57 -0
  9. {multicmd-1.59 → multicmd-1.60}/tests/test_env.py +6 -2
  10. {multicmd-1.59 → multicmd-1.60}/tests/test_interrupts.py +222 -85
  11. {multicmd-1.59 → multicmd-1.60}/tests/test_pool.py +7 -5
  12. {multicmd-1.59 → multicmd-1.60}/tests/test_supervision.py +3 -3
  13. {multicmd-1.59 → multicmd-1.60}/LICENSE +0 -0
  14. {multicmd-1.59 → multicmd-1.60}/multiCMD.egg-info/dependency_links.txt +0 -0
  15. {multicmd-1.59 → multicmd-1.60}/multiCMD.egg-info/entry_points.txt +0 -0
  16. {multicmd-1.59 → multicmd-1.60}/multiCMD.egg-info/top_level.txt +0 -0
  17. {multicmd-1.59 → multicmd-1.60}/scripts/multiCMD +0 -0
  18. {multicmd-1.59 → multicmd-1.60}/setup.cfg +0 -0
  19. {multicmd-1.59 → multicmd-1.60}/setup.py +0 -0
  20. {multicmd-1.59 → multicmd-1.60}/tests/test_api.py +0 -0
  21. {multicmd-1.59 → multicmd-1.60}/tests/test_cli_input.py +0 -0
  22. {multicmd-1.59 → multicmd-1.60}/tests/test_cli_summary.py +0 -0
  23. {multicmd-1.59 → multicmd-1.60}/tests/test_display.py +0 -0
  24. {multicmd-1.59 → multicmd-1.60}/tests/test_expand_ranges.py +0 -0
  25. {multicmd-1.59 → multicmd-1.60}/tests/test_handover.py +0 -0
  26. {multicmd-1.59 → multicmd-1.60}/tests/test_helpers.py +0 -0
  27. {multicmd-1.59 → multicmd-1.60}/tests/test_packaging.py +0 -0
  28. {multicmd-1.59 → multicmd-1.60}/tests/test_parsing.py +0 -0
  29. {multicmd-1.59 → multicmd-1.60}/tests/test_pass_fds.py +0 -0
  30. {multicmd-1.59 → multicmd-1.60}/tests/test_ping.py +0 -0
  31. {multicmd-1.59 → multicmd-1.60}/tests/test_process_groups.py +0 -0
  32. {multicmd-1.59 → multicmd-1.60}/tests/test_pty.py +0 -0
  33. {multicmd-1.59 → multicmd-1.60}/tests/test_reader.py +0 -0
  34. {multicmd-1.59 → multicmd-1.60}/tests/test_regressions.py +0 -0
  35. {multicmd-1.59 → multicmd-1.60}/tests/test_run_command.py +0 -0
  36. {multicmd-1.59 → multicmd-1.60}/tests/test_run_commands.py +0 -0
  37. {multicmd-1.59 → multicmd-1.60}/tests/test_sudo.py +0 -0
  38. {multicmd-1.59 → multicmd-1.60}/tests/test_task.py +0 -0
  39. {multicmd-1.59 → multicmd-1.60}/tests/test_windows.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: multiCMD
3
- Version: 1.59
3
+ Version: 1.60
4
4
  Summary: Run commands simultaneously
5
5
  Home-page: https://github.com/yufei-pan/multiCMD
6
6
  Author: Yufei Pan
@@ -458,10 +458,19 @@ starts a command keeps that command from running at all; on 3.11+ such a Ctrl-C
458
458
  50-70 µs per start) can leave it running, unknown to `kill_all()`. Two Ctrl-Cs microseconds apart can leave a command running, still registered, until
459
459
  `kill_all()` or the exit stops it. On Python 3.6-3.9, which raise a Ctrl-C at nearly any instruction,
460
460
  even one at a few points between the steps of a run can leave its command registered but not signalled.
461
- On Python 3.6-3.9 and 3.14 a Ctrl-C at the wrong instruction of a `with` on a lock can leave it held: one of
462
- `threading`'s can hang the program as its threads end (CPython's own), and one of multiCMD's (an
463
- `AsyncExecutor`'s queue, the live output) hangs that executor, or the next call that is not quiet, if the
464
- program keeps going.
461
+ On Python 3.6-3.9 and 3.14 a Ctrl-C at the wrong instruction of a `with` on a C-level lock can leave it held: one of
462
+ `threading`'s, in your program's own code, can hang the program as its threads end (CPython's own; multiCMD starts
463
+ its threads where no handler runs), and one of multiCMD's (an `AsyncExecutor`'s queue, the live output) hangs that
464
+ executor, or the next call that is not quiet, if the program keeps going.
465
+ A Python-level primitive such as `threading.Semaphore` or `Condition` is reached on every Python, 3.10 to 3.13
466
+ included: if your program passes its own `Semaphore` as `sem=` to a serial `run_command()` or `run_commands()` on the
467
+ main thread, and keeps going after it catches a Ctrl-C, the Ctrl-C can lose a permit (with `Semaphore(1)` the next
468
+ call waits for ever) or leave the semaphore's internal lock held (every later `acquire()` or `release()` of it blocks,
469
+ on any thread). Measured at 0.02 to 0.42 % of the Ctrl-Cs that land during a 0.2 to 5 ms command, and the same in
470
+ 1.59. In the first milliseconds of a fire-and-forget batch (`wait_for_return=False`) a first Ctrl-C can also be
471
+ dropped, about 1 in 700 of those that land there on 3.12 and 3.14 (1.59: 1 in 1,400, and it hung on 3.14): Python
472
+ ignores an exception raised in a weakref callback and prints "Exception ignored", the program goes on, and the next
473
+ Ctrl-C works.
465
474
  These and the other known limits are in [docs/limitations.md](docs/limitations.md).
466
475
 
467
476
  ## Key functions and objects
@@ -513,6 +522,41 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
513
522
 
514
523
  `test_expand_ranges_perf.py` is a manual performance microbenchmark and is not collected by pytest.
515
524
 
525
+ ## Upgrading to 1.60 from 1.59
526
+
527
+ - Nothing needs doing to upgrade.
528
+ - Fix: a Ctrl-C, or what your own signal handler raises, can no longer hang the program in Python's thread-start lock.
529
+ Python runs signal handlers on the main thread, and one that raised inside `threading.Thread.start()` there could
530
+ leave `threading`'s `_active_limbo_lock`, or the new thread's `_started` Event, held: every later thread start then
531
+ blocked, and on Python 3.6 the exit too. A serial run starts two output readers per command on the main thread, so a
532
+ program stopped often met it: a probe that stops a serial `run_command(['true'])` at random, 20,000 times in one
533
+ process, hung 6 of 6 runs with 1.59 on Python 3.14 (after 30 to 9,000 calls) and finished 3 of 3 with 1.60.
534
+ - Fix: what your own signal handler raises (an ordinary exception, a `TimeoutError` from SIGALRM) while a pool or a
535
+ fire-and-forget batch starts its threads is raised as an interrupt, every command stopped. Before, it was taken for a
536
+ thread that could not start, and lost. A few microseconds of each start remain (about 4 µs, before the helper that
537
+ starts the thread exists), see [docs/limitations.md](docs/limitations.md).
538
+ - A command's output readers are now threads started with `_thread.start_new_thread`: they are not in
539
+ `threading.enumerate()` or `threading.active_count()`, `threading.settrace()`, `setprofile()` and `excepthook` do not
540
+ reach them, and an error in one is reported through `sys.unraisablehook` (from Python 3.8). A serial run is no slower:
541
+ its median was 0 to 4 % below 1.59's, timed side by side on 3.6, 3.12 and 3.14.
542
+ - The threads multiCMD starts on the main thread (a pool's workers, fire-and-forget commands, an `AsyncExecutor`'s
543
+ dispatcher) start through a helper thread, so no signal handler runs inside `threading`'s start: about 20 µs more per
544
+ start on 3.12 and 3.14 and 10 µs on 3.6 with nothing else running (medians: 40 µs against 22 µs on 3.14; 61 µs
545
+ against 34 µs on a host loaded past its cores). In a batch whose first commands already run, each hand-off to the
546
+ helper waits for the GIL, and the main thread spends 0.1 to 0.35 ms more per start on 3.12 and 3.14 (0.35 to 1.1 ms
547
+ on 3.6): 2.1 ms against 1.3 ms to start 8 workers on 3.14. The batch as a whole still ends sooner, and a pool is no
548
+ slower for it: 200 `true`s on 16 workers took 35 ms against 47 ms with 1.59 on 3.14, as its readers no longer wait
549
+ for `threading`'s start. A Ctrl-C that lands while such a thread starts is raised once the start is done (1 s at
550
+ most), so multiCMD knows whether the thread runs.
551
+ - Known: in the first milliseconds of a fire-and-forget batch (`wait_for_return=False`) a first Ctrl-C is dropped about
552
+ twice as often as with 1.59 (about 1 in 700 of those that land there, against 1 in 1,400; 1.59 also hung on 3.14
553
+ there): Python prints "Exception ignored" and the program goes on, and the next Ctrl-C works. See
554
+ [docs/limitations.md](docs/limitations.md).
555
+ - The embeddable copy for programs that paste multiCMD is now `multiCMD_min_zlib_a85.py`, in place of
556
+ `multiCMD_min_lzma_a85.py`. It decodes with zlib, so it runs on a Python built without lzma, where the lzma one made
557
+ the program fail to import unless its installed multiCMD was new enough. It is about 7 % larger. Its block may be
558
+ pasted indented inside a `try`: ascii85 decoding ignores the added tabs.
559
+
516
560
  ## Upgrading to 1.59 from 1.58
517
561
 
518
562
  - Nothing needs doing to upgrade.
@@ -432,10 +432,19 @@ starts a command keeps that command from running at all; on 3.11+ such a Ctrl-C
432
432
  50-70 µs per start) can leave it running, unknown to `kill_all()`. Two Ctrl-Cs microseconds apart can leave a command running, still registered, until
433
433
  `kill_all()` or the exit stops it. On Python 3.6-3.9, which raise a Ctrl-C at nearly any instruction,
434
434
  even one at a few points between the steps of a run can leave its command registered but not signalled.
435
- On Python 3.6-3.9 and 3.14 a Ctrl-C at the wrong instruction of a `with` on a lock can leave it held: one of
436
- `threading`'s can hang the program as its threads end (CPython's own), and one of multiCMD's (an
437
- `AsyncExecutor`'s queue, the live output) hangs that executor, or the next call that is not quiet, if the
438
- program keeps going.
435
+ On Python 3.6-3.9 and 3.14 a Ctrl-C at the wrong instruction of a `with` on a C-level lock can leave it held: one of
436
+ `threading`'s, in your program's own code, can hang the program as its threads end (CPython's own; multiCMD starts
437
+ its threads where no handler runs), and one of multiCMD's (an `AsyncExecutor`'s queue, the live output) hangs that
438
+ executor, or the next call that is not quiet, if the program keeps going.
439
+ A Python-level primitive such as `threading.Semaphore` or `Condition` is reached on every Python, 3.10 to 3.13
440
+ included: if your program passes its own `Semaphore` as `sem=` to a serial `run_command()` or `run_commands()` on the
441
+ main thread, and keeps going after it catches a Ctrl-C, the Ctrl-C can lose a permit (with `Semaphore(1)` the next
442
+ call waits for ever) or leave the semaphore's internal lock held (every later `acquire()` or `release()` of it blocks,
443
+ on any thread). Measured at 0.02 to 0.42 % of the Ctrl-Cs that land during a 0.2 to 5 ms command, and the same in
444
+ 1.59. In the first milliseconds of a fire-and-forget batch (`wait_for_return=False`) a first Ctrl-C can also be
445
+ dropped, about 1 in 700 of those that land there on 3.12 and 3.14 (1.59: 1 in 1,400, and it hung on 3.14): Python
446
+ ignores an exception raised in a weakref callback and prints "Exception ignored", the program goes on, and the next
447
+ Ctrl-C works.
439
448
  These and the other known limits are in [docs/limitations.md](docs/limitations.md).
440
449
 
441
450
  ## Key functions and objects
@@ -487,6 +496,41 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
487
496
 
488
497
  `test_expand_ranges_perf.py` is a manual performance microbenchmark and is not collected by pytest.
489
498
 
499
+ ## Upgrading to 1.60 from 1.59
500
+
501
+ - Nothing needs doing to upgrade.
502
+ - Fix: a Ctrl-C, or what your own signal handler raises, can no longer hang the program in Python's thread-start lock.
503
+ Python runs signal handlers on the main thread, and one that raised inside `threading.Thread.start()` there could
504
+ leave `threading`'s `_active_limbo_lock`, or the new thread's `_started` Event, held: every later thread start then
505
+ blocked, and on Python 3.6 the exit too. A serial run starts two output readers per command on the main thread, so a
506
+ program stopped often met it: a probe that stops a serial `run_command(['true'])` at random, 20,000 times in one
507
+ process, hung 6 of 6 runs with 1.59 on Python 3.14 (after 30 to 9,000 calls) and finished 3 of 3 with 1.60.
508
+ - Fix: what your own signal handler raises (an ordinary exception, a `TimeoutError` from SIGALRM) while a pool or a
509
+ fire-and-forget batch starts its threads is raised as an interrupt, every command stopped. Before, it was taken for a
510
+ thread that could not start, and lost. A few microseconds of each start remain (about 4 µs, before the helper that
511
+ starts the thread exists), see [docs/limitations.md](docs/limitations.md).
512
+ - A command's output readers are now threads started with `_thread.start_new_thread`: they are not in
513
+ `threading.enumerate()` or `threading.active_count()`, `threading.settrace()`, `setprofile()` and `excepthook` do not
514
+ reach them, and an error in one is reported through `sys.unraisablehook` (from Python 3.8). A serial run is no slower:
515
+ its median was 0 to 4 % below 1.59's, timed side by side on 3.6, 3.12 and 3.14.
516
+ - The threads multiCMD starts on the main thread (a pool's workers, fire-and-forget commands, an `AsyncExecutor`'s
517
+ dispatcher) start through a helper thread, so no signal handler runs inside `threading`'s start: about 20 µs more per
518
+ start on 3.12 and 3.14 and 10 µs on 3.6 with nothing else running (medians: 40 µs against 22 µs on 3.14; 61 µs
519
+ against 34 µs on a host loaded past its cores). In a batch whose first commands already run, each hand-off to the
520
+ helper waits for the GIL, and the main thread spends 0.1 to 0.35 ms more per start on 3.12 and 3.14 (0.35 to 1.1 ms
521
+ on 3.6): 2.1 ms against 1.3 ms to start 8 workers on 3.14. The batch as a whole still ends sooner, and a pool is no
522
+ slower for it: 200 `true`s on 16 workers took 35 ms against 47 ms with 1.59 on 3.14, as its readers no longer wait
523
+ for `threading`'s start. A Ctrl-C that lands while such a thread starts is raised once the start is done (1 s at
524
+ most), so multiCMD knows whether the thread runs.
525
+ - Known: in the first milliseconds of a fire-and-forget batch (`wait_for_return=False`) a first Ctrl-C is dropped about
526
+ twice as often as with 1.59 (about 1 in 700 of those that land there, against 1 in 1,400; 1.59 also hung on 3.14
527
+ there): Python prints "Exception ignored" and the program goes on, and the next Ctrl-C works. See
528
+ [docs/limitations.md](docs/limitations.md).
529
+ - The embeddable copy for programs that paste multiCMD is now `multiCMD_min_zlib_a85.py`, in place of
530
+ `multiCMD_min_lzma_a85.py`. It decodes with zlib, so it runs on a Python built without lzma, where the lzma one made
531
+ the program fail to import unless its installed multiCMD was new enough. It is about 7 % larger. Its block may be
532
+ pasted indented inside a `try`: ascii85 decoding ignores the added tabs.
533
+
490
534
  ## Upgrading to 1.59 from 1.58
491
535
 
492
536
  - Nothing needs doing to upgrade.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: multiCMD
3
- Version: 1.59
3
+ Version: 1.60
4
4
  Summary: Run commands simultaneously
5
5
  Home-page: https://github.com/yufei-pan/multiCMD
6
6
  Author: Yufei Pan
@@ -458,10 +458,19 @@ starts a command keeps that command from running at all; on 3.11+ such a Ctrl-C
458
458
  50-70 µs per start) can leave it running, unknown to `kill_all()`. Two Ctrl-Cs microseconds apart can leave a command running, still registered, until
459
459
  `kill_all()` or the exit stops it. On Python 3.6-3.9, which raise a Ctrl-C at nearly any instruction,
460
460
  even one at a few points between the steps of a run can leave its command registered but not signalled.
461
- On Python 3.6-3.9 and 3.14 a Ctrl-C at the wrong instruction of a `with` on a lock can leave it held: one of
462
- `threading`'s can hang the program as its threads end (CPython's own), and one of multiCMD's (an
463
- `AsyncExecutor`'s queue, the live output) hangs that executor, or the next call that is not quiet, if the
464
- program keeps going.
461
+ On Python 3.6-3.9 and 3.14 a Ctrl-C at the wrong instruction of a `with` on a C-level lock can leave it held: one of
462
+ `threading`'s, in your program's own code, can hang the program as its threads end (CPython's own; multiCMD starts
463
+ its threads where no handler runs), and one of multiCMD's (an `AsyncExecutor`'s queue, the live output) hangs that
464
+ executor, or the next call that is not quiet, if the program keeps going.
465
+ A Python-level primitive such as `threading.Semaphore` or `Condition` is reached on every Python, 3.10 to 3.13
466
+ included: if your program passes its own `Semaphore` as `sem=` to a serial `run_command()` or `run_commands()` on the
467
+ main thread, and keeps going after it catches a Ctrl-C, the Ctrl-C can lose a permit (with `Semaphore(1)` the next
468
+ call waits for ever) or leave the semaphore's internal lock held (every later `acquire()` or `release()` of it blocks,
469
+ on any thread). Measured at 0.02 to 0.42 % of the Ctrl-Cs that land during a 0.2 to 5 ms command, and the same in
470
+ 1.59. In the first milliseconds of a fire-and-forget batch (`wait_for_return=False`) a first Ctrl-C can also be
471
+ dropped, about 1 in 700 of those that land there on 3.12 and 3.14 (1.59: 1 in 1,400, and it hung on 3.14): Python
472
+ ignores an exception raised in a weakref callback and prints "Exception ignored", the program goes on, and the next
473
+ Ctrl-C works.
465
474
  These and the other known limits are in [docs/limitations.md](docs/limitations.md).
466
475
 
467
476
  ## Key functions and objects
@@ -513,6 +522,41 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
513
522
 
514
523
  `test_expand_ranges_perf.py` is a manual performance microbenchmark and is not collected by pytest.
515
524
 
525
+ ## Upgrading to 1.60 from 1.59
526
+
527
+ - Nothing needs doing to upgrade.
528
+ - Fix: a Ctrl-C, or what your own signal handler raises, can no longer hang the program in Python's thread-start lock.
529
+ Python runs signal handlers on the main thread, and one that raised inside `threading.Thread.start()` there could
530
+ leave `threading`'s `_active_limbo_lock`, or the new thread's `_started` Event, held: every later thread start then
531
+ blocked, and on Python 3.6 the exit too. A serial run starts two output readers per command on the main thread, so a
532
+ program stopped often met it: a probe that stops a serial `run_command(['true'])` at random, 20,000 times in one
533
+ process, hung 6 of 6 runs with 1.59 on Python 3.14 (after 30 to 9,000 calls) and finished 3 of 3 with 1.60.
534
+ - Fix: what your own signal handler raises (an ordinary exception, a `TimeoutError` from SIGALRM) while a pool or a
535
+ fire-and-forget batch starts its threads is raised as an interrupt, every command stopped. Before, it was taken for a
536
+ thread that could not start, and lost. A few microseconds of each start remain (about 4 µs, before the helper that
537
+ starts the thread exists), see [docs/limitations.md](docs/limitations.md).
538
+ - A command's output readers are now threads started with `_thread.start_new_thread`: they are not in
539
+ `threading.enumerate()` or `threading.active_count()`, `threading.settrace()`, `setprofile()` and `excepthook` do not
540
+ reach them, and an error in one is reported through `sys.unraisablehook` (from Python 3.8). A serial run is no slower:
541
+ its median was 0 to 4 % below 1.59's, timed side by side on 3.6, 3.12 and 3.14.
542
+ - The threads multiCMD starts on the main thread (a pool's workers, fire-and-forget commands, an `AsyncExecutor`'s
543
+ dispatcher) start through a helper thread, so no signal handler runs inside `threading`'s start: about 20 µs more per
544
+ start on 3.12 and 3.14 and 10 µs on 3.6 with nothing else running (medians: 40 µs against 22 µs on 3.14; 61 µs
545
+ against 34 µs on a host loaded past its cores). In a batch whose first commands already run, each hand-off to the
546
+ helper waits for the GIL, and the main thread spends 0.1 to 0.35 ms more per start on 3.12 and 3.14 (0.35 to 1.1 ms
547
+ on 3.6): 2.1 ms against 1.3 ms to start 8 workers on 3.14. The batch as a whole still ends sooner, and a pool is no
548
+ slower for it: 200 `true`s on 16 workers took 35 ms against 47 ms with 1.59 on 3.14, as its readers no longer wait
549
+ for `threading`'s start. A Ctrl-C that lands while such a thread starts is raised once the start is done (1 s at
550
+ most), so multiCMD knows whether the thread runs.
551
+ - Known: in the first milliseconds of a fire-and-forget batch (`wait_for_return=False`) a first Ctrl-C is dropped about
552
+ twice as often as with 1.59 (about 1 in 700 of those that land there, against 1 in 1,400; 1.59 also hung on 3.14
553
+ there): Python prints "Exception ignored" and the program goes on, and the next Ctrl-C works. See
554
+ [docs/limitations.md](docs/limitations.md).
555
+ - The embeddable copy for programs that paste multiCMD is now `multiCMD_min_zlib_a85.py`, in place of
556
+ `multiCMD_min_lzma_a85.py`. It decodes with zlib, so it runs on a Python built without lzma, where the lzma one made
557
+ the program fail to import unless its installed multiCMD was new enough. It is about 7 % larger. Its block may be
558
+ pasted indented inside a `try`: ascii85 decoding ignores the added tabs.
559
+
516
560
  ## Upgrading to 1.59 from 1.58
517
561
 
518
562
  - Nothing needs doing to upgrade.
@@ -14,6 +14,7 @@ tests/test_cli.py
14
14
  tests/test_cli_input.py
15
15
  tests/test_cli_summary.py
16
16
  tests/test_display.py
17
+ tests/test_embed.py
17
18
  tests/test_env.py
18
19
  tests/test_expand_ranges.py
19
20
  tests/test_handover.py
@@ -4,6 +4,7 @@
4
4
  # dependencies = []
5
5
  # ///
6
6
  #%% imports
7
+ import _thread
7
8
  import argparse
8
9
  import atexit
9
10
  import collections
@@ -27,9 +28,9 @@ import traceback
27
28
  from pprint import pformat
28
29
 
29
30
  #%% global vars
30
- version = '1.59'
31
+ version = '1.60'
31
32
  __version__ = version
32
- COMMIT_DATE = '2026-11-10'
33
+ COMMIT_DATE = '2026-11-11'
33
34
  # fire-and-forget threads (run_commands with wait_for_return=False) that join_threads() waits on. multiCMD takes no
34
35
  # lock for it: each update is one set operation and each snapshot one set.copy(), as for _live_procs below
35
36
  __running_threads = set()
@@ -285,9 +286,25 @@ class _Done:
285
286
  self._wake.release()
286
287
  return True
287
288
 
289
+ # How long an interrupted _Thread.start waits for its helper to finish the start, so _started is right when the interrupt
290
+ # reaches the caller: a main-thread start through the helper took 40 us (median) and 74 us (p90) on Python 3.14, and 2 ms
291
+ # at 3.6's p90 on a host loaded past its 32 cores ( measured for 1.60 ); 1 s is the bound in which hpcp acts on a stop
292
+ # (_check_stop), so the wait never holds an interrupt longer than that.
293
+ _START_WAIT = 1
294
+
295
+ def _start_in_helper(thread, done, failed):
296
+ '''threading.Thread.start( thread ) in a thread no signal handler runs in ( internal, see _Thread.start )'''
297
+ try:
298
+ threading.Thread.start(thread)
299
+ except BaseException as e:
300
+ failed.append(e)
301
+ finally:
302
+ done.set()
303
+
288
304
  class _Thread(threading.Thread):
289
305
  '''
290
- A daemon thread that reports itself done, for every thread multiCMD starts and waits for ( internal )
306
+ A daemon thread that reports itself done, for every thread multiCMD starts and waits for but a command's output
307
+ readers ( _Reader ) ( internal )
291
308
 
292
309
  On Python 3.9.8 through 3.12 a Thread.join() that a KeyboardInterrupt interrupts leaves the thread flagged
293
310
  as stopped while it still runs ( CPython bpo-45274 ): Thread.is_alive() is then False and Thread.join()
@@ -301,7 +318,7 @@ class _Thread(threading.Thread):
301
318
  returns at once for it.
302
319
  done is a _Done, not a threading.Event, so no interrupt can leave it blocking anyone.
303
320
  @attributes:
304
- task: The Task the thread runs ( None for a dispatcher, pool worker or output reader )
321
+ task: The Task the thread runs ( None for a dispatcher or pool worker )
305
322
  done: Set once the target has returned or raised ( a _Done )
306
323
  '''
307
324
  def __init__(self, target, args=(), task=None):
@@ -312,17 +329,26 @@ class _Thread(threading.Thread):
312
329
  self._pid = os.getpid()
313
330
 
314
331
  def start(self):
315
- # what the caller is handling already: a Ctrl-C it handles is not one that landed in this start
316
- handling = sys.exc_info()[1]
332
+ '''
333
+ threading.Thread.start(), from a helper thread when called on the main thread: Python runs a signal's handler only
334
+ on the main thread, and one that raised inside start() there could leave threading's own locks held ( see
335
+ _Reader ). The helper is started by one C call, its ident stored by C ( list.extend over map ) before Python can
336
+ raise, and the caller waits on a _Done. An interrupt there waits for the helper ( _START_WAIT at most ), then is
337
+ raised: _started then says whether the thread runs. Off the main thread no handler runs, and start() is called
338
+ directly.
339
+ '''
340
+ if _thread.get_ident() != threading.main_thread().ident:
341
+ return super().start()
342
+ done, failed, helper = _Done(), [], []
317
343
  try:
318
- super().start()
319
- except RuntimeError as e:
320
- # a Ctrl-C inside start()'s wait for the thread to come up can come out as RuntimeError('release unlocked
321
- # lock') ( seen on 3.12 and free-threaded 3.13t ): the Ctrl-C is what happened
322
- context = e.__context__
323
- if context is not None and context is not handling and not isinstance(context, Exception):
324
- raise context
344
+ helper.extend(map(_thread.start_new_thread, (_start_in_helper,), ((self, done, failed),)))
345
+ done.wait()
346
+ except BaseException:
347
+ if helper:
348
+ done.wait(_START_WAIT)
325
349
  raise
350
+ if failed:
351
+ raise failed[0]
326
352
 
327
353
  def run(self):
328
354
  try:
@@ -346,6 +372,44 @@ class _Thread(threading.Thread):
346
372
  left = 1 if left is None else min(left, 1)
347
373
  super().join(left)
348
374
 
375
+ class _Reader:
376
+ '''
377
+ A command's output reader ( internal ): a thread started by one C call, _thread.start_new_thread, so its start takes no
378
+ threading lock in the calling thread and waits on nothing there. threading.Thread.start() takes _active_limbo_lock and
379
+ waits on the new thread's _started Event: a Ctrl-C that Python raised inside it on the main thread left either held, and
380
+ every later thread start blocked. A serial run starts two readers per command on the main thread. done and _started are
381
+ _Done ( no interrupt jams them ); is_alive() and join() go by them, as _Thread's do. Not in threading.enumerate(), and
382
+ threading's trace, profile and excepthook do not reach it: an exception _read_stream raises is reported by Python's
383
+ hook for a thread it started ( sys.unraisablehook from 3.8 ). Detached: its stack goes when it ends.
384
+ '''
385
+ __slots__ = ('_target', '_args', 'done', '_started', '_pid')
386
+
387
+ def __init__(self, target, args=()):
388
+ self._target, self._args = target, args
389
+ self.done = _Done()
390
+ self._started = _Done()
391
+ # ( in a child forked meanwhile only the forking thread exists )
392
+ self._pid = os.getpid()
393
+
394
+ def start(self):
395
+ _thread.start_new_thread(self._run, ())
396
+ # ( the thread sets it too, first thing: a stop that lands right here leaves it to the thread )
397
+ self._started.set()
398
+
399
+ def _run(self):
400
+ self._started.set()
401
+ try:
402
+ self._target(*self._args)
403
+ finally:
404
+ self.done.set()
405
+
406
+ def is_alive(self):
407
+ return self._started.flag and not self.done.flag and self._pid == os.getpid()
408
+
409
+ def join(self, timeout=None):
410
+ if self._pid == os.getpid() and self._started.flag:
411
+ self.done.wait(timeout)
412
+
349
413
  def _any_alive(threads):
350
414
  '''
351
415
  Whether any of the threads is alive ( internal )
@@ -1659,8 +1723,8 @@ def _join(thread, timeout=None):
1659
1723
  '''
1660
1724
  Wait for a thread to finish, in short steps ( internal )
1661
1725
  A plain join() blocks in C, where a KeyboardInterrupt only arrives if the signal happens to
1662
- land on this very thread; short steps let the waiting thread see it within 0.1s. A _Thread
1663
- waits in such steps by itself ( see _Thread ). Like Thread.join(), this raises RuntimeError for
1726
+ land on this very thread; short steps let the waiting thread see it within 0.1s. A _Thread or
1727
+ _Reader waits in such steps by itself ( see _Thread ). Like Thread.join(), this raises RuntimeError for
1664
1728
  a threading.Thread that was never started.
1665
1729
  @params:
1666
1730
  thread: The thread to wait for
@@ -1966,7 +2030,7 @@ def _execute(task, timeout, quiet, decor, use_pty=False):
1966
2030
  task._env = task._extra_env = None
1967
2031
  task.start_time = time.time()
1968
2032
  task._last_output = time.monotonic()
1969
- readers = [_Thread(_read_stream, (stream, target, task, decor, quiet)) for stream, target in streams]
2033
+ readers = [_Reader(_read_stream, (stream, target, task, decor, quiet)) for stream, target in streams]
1970
2034
  for reader in readers:
1971
2035
  reader.start()
1972
2036
  waiting = True
@@ -2446,6 +2510,10 @@ def _run_pool(tasks, decors, sem, timeout, quiet, dry_run, max_threads, use_pty=
2446
2510
  try:
2447
2511
  thread.start()
2448
2512
  except Exception as e:
2513
+ if thread._started.is_set():
2514
+ # it runs: what a signal handler raised while the main thread waited for its start ( see _Thread.start )
2515
+ # is an interrupt, not a thread that cannot start
2516
+ raise
2449
2517
  # one failed start may be passing ( EAGAIN ): the next worker is tried; two in a row end the starts, as
2450
2518
  # the next would most likely fail the same way
2451
2519
  error = e
@@ -2606,6 +2674,9 @@ def run_commands(commands, timeout=0,max_threads=1,quiet=False,dry_run=False,wit
2606
2674
  try:
2607
2675
  thread.start()
2608
2676
  except Exception as e:
2677
+ if thread._started.is_set():
2678
+ # it runs: an interrupt, not a thread that cannot start ( see _run_pool )
2679
+ raise
2609
2680
  # that command fails, the others run; its task keeps the thread ( task.thread.join() returns at once )
2610
2681
  __running_threads.discard(thread)
2611
2682
  _fail_task(thread.task, f'cannot start its thread: {e}', e, quiet)
@@ -8,7 +8,7 @@ import time
8
8
  import pytest
9
9
 
10
10
  import multiCMD
11
- from conftest import sigint_main_after
11
+ from conftest import os_threads, sigint_main_after
12
12
  from multiCMD import AsyncExecutor, run_commands
13
13
 
14
14
 
@@ -78,13 +78,13 @@ def test_executor_queues_commands_instead_of_parking_threads(monkeypatch):
78
78
  run_task = multiCMD._run_executor_task
79
79
  monkeypatch.setattr(multiCMD, '_run_executor_task', lambda task, *args: (ran.append(task), run_task(task, *args)))
80
80
  gate = threading.Semaphore(0)
81
- baseline = threading.active_count()
81
+ baseline = os_threads()
82
82
  ex = AsyncExecutor(semaphore=gate, quiet=True, dry_run=True)
83
83
  start = time.monotonic()
84
84
  tasks = [ex.run_command(['true']) for _ in range(5000)]
85
85
  assert time.monotonic() - start < 5
86
86
  # no permit is free, so only the dispatcher exists and it waits for one
87
- assert threading.active_count() <= baseline + 1
87
+ assert os_threads() <= baseline + 1
88
88
  assert all(task.thread is None for task in tasks)
89
89
  for _ in range(len(tasks)):
90
90
  gate.release()
@@ -96,15 +96,16 @@ def test_executor_queues_commands_instead_of_parking_threads(monkeypatch):
96
96
 
97
97
  @pytest.mark.slow
98
98
  def test_executor_thread_count_stays_bounded():
99
- baseline = threading.active_count()
99
+ baseline = os_threads()
100
100
  ex = AsyncExecutor(semaphore=threading.Semaphore(3), quiet=True)
101
101
  ex.run_commands([['sleep', '0.05']] * 60)
102
102
  peak = 0
103
103
  while ex.runningThreads:
104
- peak = max(peak, threading.active_count())
104
+ peak = max(peak, os_threads())
105
105
  time.sleep(0.005)
106
- # the dispatcher, plus a runner and two stream readers per running command
107
- assert peak - baseline <= 1 + 3 * 3
106
+ # the dispatcher, plus a runner and two stream readers per running command, and the two readers of the command that ran
107
+ # before it, which may still be leaving ( see test_pool_keeps_threads_bounded )
108
+ assert peak - baseline <= 1 + 3 * 3 + 3 * 2
108
109
  assert ex.get_return_codes() == [0] * 60
109
110
 
110
111
 
@@ -121,7 +122,11 @@ def test_executor_releases_finished_thread_stacks():
121
122
  ex.wait(timeout=-1)
122
123
  # the executor and its tasks are still referenced: every finished thread must already be joined
123
124
  assert ex.get_return_codes() == [0] * 1200
124
- # glibc keeps a few freed stacks cached for reuse
125
+ # glibc keeps a few freed stacks cached for reuse. The last commands' output readers may still be leaving ( done,
126
+ # their last step not yet run ): a stack nobody frees stays for good, so a few seconds for theirs prove the same
127
+ deadline = time.monotonic() + 5
128
+ while _stack_mappings(stack) > 8 and time.monotonic() < deadline:
129
+ time.sleep(0.05)
125
130
  assert _stack_mappings(stack) <= 8
126
131
  finally:
127
132
  threading.stack_size(old_stack)
@@ -1,3 +1,4 @@
1
+ import os
1
2
  import re
2
3
  import shutil
3
4
  import signal
@@ -45,13 +46,20 @@ def test_max_threads_and_timeout_smoke():
45
46
  assert proc.returncode == 0
46
47
 
47
48
 
48
- def test_sudo_flag_without_sudo_binary_does_not_crash(monkeypatch):
49
- # Force child env: PATH without sudo by invoking python -c wrapper is heavy;
50
- # instead assert current host behavior: --sudo with missing sudo should not
51
- # abort with traceback. If sudo exists, command still succeeds for echo.
52
- proc = run_cli(["-q", "--sudo", "echo ok"], timeout=20)
49
+ def test_sudo_flag_without_sudo_binary_does_not_crash(tmp_path):
50
+ # a PATH that holds echo and no sudo: --sudo is ignored, with a note, and the command runs. The host's own sudo is
51
+ # never run: it may refuse this user ( exit 1, and it reports the try ), as on a Mac's standard account
52
+ env = None
53
+ echo = shutil.which('echo')
54
+ if os.name == 'posix' and echo:
55
+ (tmp_path / 'echo').symlink_to(echo)
56
+ env = dict(os.environ, PATH=str(tmp_path))
57
+ proc = run_cli(["-q", "--sudo", "echo ok"], timeout=20, env=env)
53
58
  assert proc.returncode == 0
54
59
  assert "Traceback" not in (proc.stdout + proc.stderr)
60
+ if env is not None and os.geteuid() != 0:
61
+ # ( root needs no sudo, and is not told )
62
+ assert 'sudo not found' in proc.stderr
55
63
 
56
64
 
57
65
  def test_exit_status_single_command_passes_its_code_through():
@@ -0,0 +1,57 @@
1
+ '''
2
+ The embeddable copy ( multiCMD_min_zlib_a85.py ) that hpcp, statblk and statbtrfs paste: it runs on a Python without lzma,
3
+ pasted as it is or indented inside a try, and it is the current source's
4
+ '''
5
+ import ast
6
+ import base64
7
+ import re
8
+ import subprocess
9
+ import sys
10
+ import zlib
11
+
12
+ import pytest
13
+
14
+ from conftest import PACKAGE_ROOT
15
+
16
+ EMBED = PACKAGE_ROOT / 'multiCMD_min_zlib_a85.py'
17
+
18
+
19
+ def _version(text):
20
+ return re.search(r"^version\s*=\s*['\"]([\d.]+)['\"]", text, re.M).group(1)
21
+
22
+
23
+ def _decoded(embed):
24
+ '''The source the embed's _SRC_B85 literal holds, as Python reads the literal'''
25
+ literal, = re.findall(r"_SRC_B85=(r'''.*?''')", embed, re.S)
26
+ return zlib.decompress(base64.a85decode(ast.literal_eval(literal))).decode('utf-8')
27
+
28
+
29
+ @pytest.mark.parametrize('form', ['as is', 'indented in a try'])
30
+ def test_the_embed_runs_on_a_python_without_lzma(tmp_path, form):
31
+ # ( the 1.60 plan, G1 ) up to 1.59 the embed decoded with lzma, an optional module ( a Python built without the xz
32
+ # headers lacks it ): a program that pasted it failed to import there unless its installed multiCMD was new enough.
33
+ # hpcp 9.88 pastes it indented one tab inside a try, which ascii85 decoding reads with the tabs ignored ( G2 )
34
+ block = EMBED.read_text(encoding='utf-8')
35
+ if form == 'indented in a try':
36
+ block = 'try:\n' + ''.join('\t' + line for line in block.splitlines(True)) + 'finally:\n\tpass\n'
37
+ # an installed multiCMD older than the embedded one: the embedded copy runs
38
+ (tmp_path / 'multiCMD.py').write_text("version = '1.0'\n")
39
+ probe = tmp_path / 'probe.py'
40
+ probe.write_text("import sys\nsys.modules['lzma'] = sys.modules['_lzma'] = None\n" + block +
41
+ "print(multiCMD.version, multiCMD.run_command(['true'], quiet=True, return_code_only=True))\n", encoding='utf-8')
42
+ out = subprocess.run([sys.executable, '-I', str(probe)], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
43
+ universal_newlines=True, timeout=60)
44
+ assert out.returncode == 0, out.stderr
45
+ assert out.stdout.split() == [_version((PACKAGE_ROOT / 'multiCMD.py').read_text(encoding='utf-8')), '0']
46
+
47
+
48
+ def test_the_generated_files_are_the_current_sources():
49
+ # regenerated after the last version bump ( compressedEmbeddedCodeGenerator.py, see its docstring ): the embed holds
50
+ # multiCMD_min.py, both carry multiCMD.py's version, and the embed's gate is that version
51
+ version = _version((PACKAGE_ROOT / 'multiCMD.py').read_text(encoding='utf-8'))
52
+ minified = (PACKAGE_ROOT / 'multiCMD_min.py').read_text(encoding='utf-8')
53
+ embed = EMBED.read_text(encoding='utf-8')
54
+ assert _decoded(embed) == minified
55
+ assert _version(minified) == version
56
+ assert '.version.split(\'.\')) < (%s):' % ', '.join(version.split('.')) in embed
57
+ assert '\timport sys,types,base64,zlib ' in embed
@@ -496,6 +496,8 @@ print(task.returncode)
496
496
 
497
497
 
498
498
  def test_an_inherited_variable_with_an_empty_name_is_left_out_of_an_explicit_environment(launcher):
499
+ if subprocess.run(['env', '=weird', 'true'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode:
500
+ pytest.skip("this system's env cannot set a variable with an empty name ( macOS: setenv refuses it )")
499
501
  proc = _in_fresh_python("""
500
502
  task = multiCMD.run_command(['/usr/bin/env'], quiet=True, extra_env={'A': 'x'}, return_object=True)
501
503
  print(task.returncode, sorted(task.stdout))
@@ -700,8 +702,10 @@ def test_enoexec_is_126_with_the_reason(launcher, tmp_path, kwargs):
700
702
 
701
703
  @pytest.mark.parametrize('kwargs', [{}, {'extra_env': {'A': '1'}}], ids=['plain', 'extra_env'])
702
704
  def test_e2big_is_126(launcher, kwargs):
703
- # one argument longer than the system takes in a string
704
- task = run_command(['true', 'x' * (256 * 1024)], quiet=True, return_object=True, **kwargs)
705
+ # one argument longer than the system takes: in one string on Linux ( MAX_ARG_STRLEN, 128 KiB ), elsewhere in all of
706
+ # them together ( ARG_MAX: 1 MiB on macOS, which takes 256 KiB in one )
707
+ size = 256 * 1024 if sys.platform == 'linux' else os.sysconf('SC_ARG_MAX')
708
+ task = run_command(['true', 'x' * size], quiet=True, return_object=True, **kwargs)
705
709
  assert task.returncode == 126 and not task._error
706
710
  assert 'Argument list too long' in ' '.join(task.stderr)
707
711
 
@@ -3,6 +3,7 @@ A Ctrl-C ( or what a program's signal handler raises ) while multiCMD starts, ru
3
3
  and the commands are stopped, or left registered for kill_all() and the exit hook
4
4
  '''
5
5
  import os
6
+ import re
6
7
  import signal
7
8
  import subprocess
8
9
  import sys
@@ -13,7 +14,7 @@ import _thread
13
14
  import pytest
14
15
 
15
16
  import multiCMD
16
- from conftest import pid_gone, sigint_main_after
17
+ from conftest import PACKAGE_ROOT, pid_gone, sigint_main_after
17
18
  from multiCMD import AsyncExecutor, run_commands
18
19
 
19
20
 
@@ -25,17 +26,6 @@ def _ctrl_c():
25
26
  pass
26
27
 
27
28
 
28
- @pytest.fixture
29
- def another_thread():
30
- '''A thread alive throughout: a SIGINT the main thread blocked would be taken by it'''
31
- release = threading.Event()
32
- thread = threading.Thread(target=release.wait, daemon=True)
33
- thread.start()
34
- yield thread
35
- release.set()
36
- thread.join(5)
37
-
38
-
39
29
  # ---- a command interrupted as it starts is registered while it is killed
40
30
 
41
31
  def test_a_ctrl_c_before_the_registration_still_registers_the_command_while_it_is_killed(monkeypatch):
@@ -129,13 +119,6 @@ def _left_running(before, wait=6.0):
129
119
  time.sleep(0.02)
130
120
 
131
121
 
132
- # on Python 3.6 - 3.9 and 3.14 a Ctrl-C at one instruction of a `with lock:` can leave the lock held, and
133
- # Thread.start() takes threading's own _active_limbo_lock so: every thread then hangs as it ends ( CPython's own, see
134
- # the README ). The stress test below keeps its Ctrl-Cs out of the output readers' Thread.start() there: one that would
135
- # land inside it is taken right after it
136
- _WITH_MAY_JAM = sys.version_info < (3, 10) or sys.version_info >= (3, 14)
137
-
138
-
139
122
  @pytest.mark.skipif(not sys.platform.startswith('linux'), reason='checks processes through /proc')
140
123
  def test_a_ctrl_c_while_the_command_starts_loses_it_only_inside_popen(launcher, monkeypatch, request):
141
124
  # a real SIGINT from another thread lands anywhere in the start ( 0 - 0.5 ms after the spawn begins ). A command is
@@ -159,19 +142,6 @@ def test_a_ctrl_c_while_the_command_starts_loses_it_only_inside_popen(launcher,
159
142
  if hasattr(sys, 'unraisablehook'):
160
143
  # ( CPython drops one raised in a finalizer: not pytest's to report )
161
144
  monkeypatch.setattr(sys, 'unraisablehook', lambda dropped: None)
162
- if _WITH_MAY_JAM:
163
- real_start = threading.Thread.start
164
- def start(self):
165
- if getattr(self, '_target', None) is multiCMD._read_stream:
166
- # ( unblocked whatever happens: a Ctrl-C that landed before the block is raised right after it )
167
- try:
168
- signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGINT})
169
- real_start(self)
170
- finally:
171
- signal.pthread_sigmask(signal.SIG_UNBLOCK, {signal.SIGINT})
172
- else:
173
- real_start(self)
174
- monkeypatch.setattr(threading.Thread, 'start', start)
175
145
  spawning = threading.Event()
176
146
  real_spawn = multiCMD._spawn
177
147
  def spawn(*args, **kwargs):
@@ -197,7 +167,8 @@ def test_a_ctrl_c_while_the_command_starts_loses_it_only_inside_popen(launcher,
197
167
  try:
198
168
  try:
199
169
  armed[0] = True
200
- # ( a bare thread: Thread.start() and join() take threading's own locks with `with`, see _WITH_MAY_JAM )
170
+ # ( a bare thread: Thread.start() and join() on the main thread take threading's own locks, which a Ctrl-C
171
+ # can leave held, see docs/limitations.md )
201
172
  _thread.start_new_thread(send, ())
202
173
  multiCMD.run_command(['sleep', '3'], quiet=True)
203
174
  finally:
@@ -233,7 +204,7 @@ def test_a_ctrl_c_while_the_command_starts_loses_it_only_inside_popen(launcher,
233
204
  assert described == [], len(inside_popen)
234
205
 
235
206
 
236
- # ---- a thread that cannot start: the pool tries the next worker once, and a Ctrl-C start() turns into RuntimeError is raised
207
+ # ---- a thread that cannot start: the pool tries the next worker once
237
208
 
238
209
  def _failing_worker_starts(monkeypatch, failing):
239
210
  '''Make the pool's worker starts whose 1-based number is in failing raise; returns the list of starts tried'''
@@ -275,51 +246,33 @@ def test_a_pool_that_cannot_start_two_workers_in_a_row_fails_every_task(monkeypa
275
246
  assert [task.returncode for task in tasks] == [-1] * 4 and all(task._error for task in tasks)
276
247
 
277
248
 
278
- def test_a_ctrl_c_that_thread_start_turns_into_another_error_is_still_raised(monkeypatch):
279
- # ( seen on 3.12 and free-threaded 3.13t ) a Ctrl-C inside Condition.wait()'s _acquire_restore(), as Thread.start()
280
- # waits for an output reader: the Condition's release then raises RuntimeError, and the reader runs all the same.
281
- # Taken for a reader that cannot start, the Ctrl-C was lost
282
- real_start = threading.Thread.start
249
+ @pytest.mark.skipif(not hasattr(signal, 'pthread_kill'), reason='POSIX signals')
250
+ @pytest.mark.parametrize('how', ['pool', 'fire-and-forget'])
251
+ def test_what_a_handler_raises_while_a_thread_starts_is_an_interrupt(monkeypatch, request, how):
252
+ # a program's own handler raising an ordinary exception ( TimeoutError from SIGALRM ) while the main thread waits for a
253
+ # thread it starts: the thread runs, so this is an interrupt, raised on with every command stopped. Before, it was
254
+ # taken for a thread that could not start: the pool said "started 3 of 4 threads" and ran its commands to the end, the
255
+ # batch recorded one running command as failed, and the program's timeout never fired
256
+ def handler(signum, frame):
257
+ raise TimeoutError("the program's own timeout")
258
+ previous = signal.signal(signal.SIGALRM, handler)
259
+ request.addfinalizer(lambda: signal.signal(signal.SIGALRM, previous))
260
+ main = threading.main_thread().ident
261
+ real_helper = multiCMD._start_in_helper
283
262
  armed = [True]
284
- def start(self):
285
- real_start(self)
286
- if armed[0] and getattr(self, '_target', None) is multiCMD._read_stream:
263
+ def slow_helper(*args):
264
+ # the signal lands once the helper exists, while the main thread waits for it
265
+ if armed[0]:
287
266
  armed[0] = False
288
- try:
289
- raise KeyboardInterrupt
290
- except KeyboardInterrupt:
291
- raise RuntimeError('release unlocked lock')
292
- monkeypatch.setattr(threading.Thread, 'start', start)
267
+ signal.pthread_kill(main, signal.SIGALRM)
268
+ time.sleep(0.05)
269
+ real_helper(*args)
270
+ monkeypatch.setattr(multiCMD, '_start_in_helper', slow_helper)
293
271
  started = time.monotonic()
294
- with pytest.raises(KeyboardInterrupt):
295
- multiCMD.run_command(['sleep', '2'], quiet=True)
296
- # before: the command ran to its end and the call returned
297
- assert time.monotonic() - started < 1.5 and not multiCMD._live_procs
298
-
299
-
300
- @pytest.mark.skipif(not hasattr(signal, 'pthread_sigmask'), reason='POSIX signals')
301
- def test_a_thread_start_error_while_the_caller_handles_a_ctrl_c_is_not_that_ctrl_c(monkeypatch, another_thread):
302
- # ( finding 3; probe r10probes/stale_ctx.py ) a program cleans up after a real Ctrl-C it caught, running commands
303
- # from its except block, and one pool worker cannot start ( EAGAIN ): that RuntimeError has the Ctrl-C being
304
- # handled as its context, and was taken for a Ctrl-C that landed during the start
305
- real_start = threading.Thread.start
306
- calls = []
307
- def start(self):
308
- if getattr(self, '_target', None) is not None and getattr(self._target, '__name__', '') == 'worker':
309
- calls.append(self)
310
- if len(calls) == 1:
311
- raise RuntimeError("can't start new thread")
312
- real_start(self)
313
- monkeypatch.setattr(threading.Thread, 'start', start)
314
- try:
315
- _ctrl_c()
316
- except KeyboardInterrupt:
317
- try:
318
- tasks = run_commands([['true']] * 4, max_threads=4, quiet=True, return_object=True)
319
- except KeyboardInterrupt:
320
- # before ( fdc45b9 ): the Ctrl-C being handled was raised again, and the tasks never ran
321
- pytest.fail('the Ctrl-C the caller handles was raised again')
322
- assert len(calls) == 4 and [task.returncode for task in tasks] == [0] * 4
272
+ with pytest.raises(TimeoutError):
273
+ run_commands([['sleep', '5']] * 4, max_threads=4, quiet=True, wait_for_return=how == 'pool')
274
+ multiCMD.join_threads(timeout=5)
275
+ assert time.monotonic() - started < 4 and not multiCMD._live_procs
323
276
 
324
277
 
325
278
  # ---- a normal run touches no signal state
@@ -544,20 +497,16 @@ def test_a_ctrl_c_anywhere_in_a_start_leaves_the_signal_mask_as_it_was(launcher)
544
497
  assert state['k'] > 5
545
498
 
546
499
 
547
- # ( a Ctrl-C inside Thread.start()'s wait can leave that thread's Event inconsistent, CPython's own: the thread fails
548
- # as it comes up, and CPython reports that as unraisable )
549
- @pytest.mark.filterwarnings('ignore::pytest.PytestUnraisableExceptionWarning')
550
500
  @pytest.mark.skipif(not sys.platform.startswith('linux'), reason='POSIX commands')
551
501
  @pytest.mark.parametrize('command', [['true'], ['mcmd-no-such-command-xyz']], ids=['true', 'missing'])
552
502
  def test_a_ctrl_c_at_any_point_of_a_serial_run_is_raised(command):
553
503
  # ( matrix of round 12, finding 4 ) one KeyboardInterrupt at each call, return and C-call return of a serial run in
554
- # turn, in every frame of the main thread ( subprocess's, os's ... ): run_command() raises it every time, for a
555
- # command that runs and for one that is not found. It found a Ctrl-C that Thread.start() turns into RuntimeError on
556
- # 3.12 ( see _Thread.start ). threading's own frames are left out where a Ctrl-C at one instruction of a `with lock:`
557
- # can leave the lock held ( 3.6 - 3.9, 3.14: CPython's own, see the README )
558
- skipped = {threading.__file__} if _WITH_MAY_JAM else set()
504
+ # turn, in every frame of the main thread ( subprocess's, os's, threading's ... ): run_command() raises it every time,
505
+ # for a command that runs and for one that is not found. Up to 1.59 threading's own frames were left out on 3.6 - 3.9
506
+ # and 3.14: a Ctrl-C at one instruction of the output readers' Thread.start() could leave _active_limbo_lock held, and
507
+ # every later thread start hung. From 1.60 the readers start by one C call ( see _Reader )
559
508
  def counted(frame, event):
560
- return frame.f_code.co_filename not in skipped
509
+ return True
561
510
  state = {'k': 0}
562
511
  returned = []
563
512
  while True:
@@ -622,3 +571,191 @@ def test_the_only_ctrl_c_anywhere_while_a_missing_command_is_dealt_with_is_raise
622
571
  state['k'] += 1
623
572
  assert lost == []
624
573
  assert state['k'] > 5 and not multiCMD._live_procs
574
+
575
+
576
+ # ---- a Ctrl-C as a thread starts never leaves threading's own locks held ( 1.60 )
577
+
578
+ # a serial run_command(['true']) stopped at a random moment by a SIGALRM handler that raises KeyboardInterrupt, many times
579
+ # in one process; after each stop threading._active_limbo_lock must be free, and the next call must finish
580
+ STOP_PROBE = r'''
581
+ import _thread, os, random, signal, sys, threading, time, traceback
582
+ sys.path.insert(0, sys.argv[1])
583
+ import multiCMD
584
+ n = int(sys.argv[2])
585
+ done = [0]
586
+ def watchdog():
587
+ # no call finished for 20 s is a hang: a call takes 0.2 - 5 ms, a stop at most about 3 s ( the jammed Popen lock in
588
+ # docs/limitations.md ). A bare thread, as it starts while nothing is stopped yet
589
+ last, since = -1, time.monotonic()
590
+ while True:
591
+ time.sleep(1)
592
+ if done[0] != last:
593
+ last, since = done[0], time.monotonic()
594
+ elif time.monotonic() - since > 20:
595
+ stack = sys._current_frames().get(threading.main_thread().ident)
596
+ print('HANG after %d calls; the main thread:\n%s' % (done[0], ''.join(traceback.format_stack(stack))), flush=True)
597
+ os._exit(3)
598
+ _thread.start_new_thread(watchdog, ())
599
+ armed = [False]
600
+ def handler(signum, frame):
601
+ # ( one that the kernel hands to another thread can run on the main thread after the call: only while armed )
602
+ if armed[0]:
603
+ armed[0] = False
604
+ raise KeyboardInterrupt
605
+ signal.signal(signal.SIGALRM, handler)
606
+ times = []
607
+ for _ in range(50):
608
+ start = time.perf_counter()
609
+ multiCMD.run_command(['true'], quiet=True)
610
+ times.append(time.perf_counter() - start)
611
+ window = sorted(times)[len(times) // 2] * 1.5
612
+ stops = others = 0
613
+ for i in range(n):
614
+ try:
615
+ try:
616
+ armed[0] = True
617
+ signal.setitimer(signal.ITIMER_REAL, random.uniform(1e-6, window))
618
+ multiCMD.run_command(['true'], quiet=True)
619
+ # the alarm lands here if it did not land in the call
620
+ time.sleep(window)
621
+ finally:
622
+ armed[0] = False
623
+ signal.setitimer(signal.ITIMER_REAL, 0)
624
+ except KeyboardInterrupt:
625
+ stops += 1
626
+ except Exception as e:
627
+ others += 1
628
+ print('not a KeyboardInterrupt: %r' % (e,), flush=True)
629
+ if not threading._active_limbo_lock.acquire(True, 2):
630
+ print('LEAK: threading._active_limbo_lock held after %d calls' % (i + 1), flush=True)
631
+ os._exit(2)
632
+ threading._active_limbo_lock.release()
633
+ done[0] = i + 1
634
+ assert multiCMD.run_command(['true'], quiet=True, return_code_only=True) == 0
635
+ print('%d calls, %d stopped, %d other errors' % (n, stops, others), flush=True)
636
+ '''
637
+
638
+
639
+ @pytest.mark.slow
640
+ @pytest.mark.skipif(not hasattr(signal, 'setitimer'), reason='POSIX timers')
641
+ def test_stops_in_serial_commands_never_jam_thread_starts(tmp_path):
642
+ # ( the 1.60 plan, K; seen in hpcp 9.87's re-review ) a stop inside an output reader's Thread.start() on the main thread
643
+ # left threading's _active_limbo_lock held, and every later thread start hung: up to 1.59 on 3.14 this probe hung in 6 of
644
+ # 6 runs of 20,000 calls, after 30 to 9,000 calls ( three runs by the plan, three by the build ). 3.6 never hung so in
645
+ # 60,000 calls. 5,000 calls take about 75 s on 3.6 ( a call and the sleep after it ): 600 s leaves eight times that
646
+ # under -n auto
647
+ probe = tmp_path / 'probe.py'
648
+ probe.write_text(STOP_PROBE)
649
+ run = subprocess.run([sys.executable, '-I', str(probe), str(PACKAGE_ROOT), '5000'], stdout=subprocess.PIPE,
650
+ stderr=subprocess.STDOUT, universal_newlines=True, timeout=600)
651
+ # ( Python 3.6 - 3.8 buffer stderr, where the stops that landed in a finalizer are told, until the exit )
652
+ assert run.returncode == 0 and re.search(r'^5000 calls, \d+ stopped, 0 other errors$', run.stdout, re.M), run.stdout[-4000:]
653
+
654
+
655
+ def _dummy_threads():
656
+ return {thread for thread in threading.enumerate() if isinstance(thread, threading._DummyThread)}
657
+
658
+
659
+ def test_a_main_thread_start_runs_in_a_helper(monkeypatch):
660
+ # ( 1.60 ) from the main thread, where Python runs signal handlers, threading's own start runs on a helper thread; from
661
+ # another thread it runs right there; and what it raises in the helper reaches the caller
662
+ real_start = threading.Thread.start
663
+ ran_on, fail = [], [None]
664
+ def spy(self):
665
+ ran_on.append(_thread.get_ident())
666
+ if fail[0] is not None:
667
+ raise fail[0]
668
+ real_start(self)
669
+ monkeypatch.setattr(threading.Thread, 'start', spy)
670
+ dummies = _dummy_threads()
671
+ main = threading.main_thread().ident
672
+ thread = multiCMD._Thread(time.sleep, (0,))
673
+ thread.start()
674
+ assert multiCMD._join(thread, 5)
675
+ assert ran_on[-1] != main and thread.done.flag
676
+ # from another thread ( a bare one, whose own start is not what is checked; it waits on done, as Thread.join() would
677
+ # make threading register it )
678
+ started_by, finished = [], multiCMD._Done()
679
+ def start_one():
680
+ try:
681
+ started_by.append(_thread.get_ident())
682
+ inner = multiCMD._Thread(time.sleep, (0,))
683
+ inner.start()
684
+ inner.done.wait(5)
685
+ finally:
686
+ finished.set()
687
+ _thread.start_new_thread(start_one, ())
688
+ assert finished.wait(5)
689
+ assert ran_on[-1] == started_by[0] != main
690
+ # a thread that cannot start, from the main thread: the helper's error is raised in the caller
691
+ fail[0] = RuntimeError("can't start new thread")
692
+ thread = multiCMD._Thread(time.sleep, (0,))
693
+ with pytest.raises(RuntimeError, match="can't start new thread"):
694
+ thread.start()
695
+ assert not thread._started.is_set() and not thread.is_alive()
696
+ # the helper never makes threading register a thread of its own ( a _DummyThread )
697
+ assert _dummy_threads() <= dummies
698
+
699
+
700
+ @pytest.mark.skipif(not hasattr(signal, 'pthread_kill'), reason='POSIX signals')
701
+ @pytest.mark.parametrize('what', ['a thread', 'the dispatcher'])
702
+ def test_an_interrupted_start_waits_for_its_helper(monkeypatch, request, what):
703
+ # ( the 1.60 plan, G3 ) a Ctrl-C while the main thread waits for its helper to start a thread is raised once the start
704
+ # is done ( _START_WAIT at most ), so _started says whether the thread runs. Without that wait it was still unset, and
705
+ # an AsyncExecutor took a dispatcher that came up a moment later for one that never would: the next run_commands()
706
+ # started a second one, which wait() then did not cover
707
+ previous = signal.signal(signal.SIGINT, signal.default_int_handler)
708
+ request.addfinalizer(lambda: signal.signal(signal.SIGINT, previous))
709
+ main = threading.main_thread().ident
710
+ real_helper = multiCMD._start_in_helper
711
+ armed = [True]
712
+ def slow_helper(*args):
713
+ # the Ctrl-C lands once the helper exists, while the main thread waits for it
714
+ if armed[0]:
715
+ armed[0] = False
716
+ signal.pthread_kill(main, signal.SIGINT)
717
+ time.sleep(0.05)
718
+ real_helper(*args)
719
+ monkeypatch.setattr(multiCMD, '_start_in_helper', slow_helper)
720
+ if what == 'a thread':
721
+ release = threading.Event()
722
+ thread = multiCMD._Thread(release.wait, (10,))
723
+ with pytest.raises(KeyboardInterrupt):
724
+ thread.start()
725
+ # before: unset, though the thread came up a moment later
726
+ assert thread._started.is_set() and thread.is_alive()
727
+ release.set()
728
+ assert multiCMD._join(thread, 5)
729
+ return
730
+ class Gate:
731
+ '''A semaphore with no permit that records the threads waiting on it'''
732
+ def __init__(self):
733
+ self.waiting = set()
734
+ def acquire(self, blocking=True, timeout=None):
735
+ self.waiting.add(threading.current_thread())
736
+ time.sleep(timeout or 0)
737
+ return False
738
+ def release(self):
739
+ pass
740
+ gate = Gate()
741
+ ex = AsyncExecutor(semaphore=gate, quiet=True)
742
+ dispatchers = []
743
+ real_track = ex._track
744
+ def track(thread):
745
+ if thread._target == ex._dispatch:
746
+ dispatchers.append(thread)
747
+ real_track(thread)
748
+ monkeypatch.setattr(ex, '_track', track)
749
+ try:
750
+ with pytest.raises(KeyboardInterrupt):
751
+ ex.run_commands([['true']])
752
+ # two commands: two dispatchers would each take one and wait for a permit
753
+ ex.run_commands([['true'], ['true']])
754
+ deadline = time.monotonic() + 5
755
+ while not all(d._started.is_set() and (d.done.flag or d in gate.waiting) for d in dispatchers) and time.monotonic() < deadline:
756
+ time.sleep(0.01)
757
+ # before: two
758
+ assert sum(d.is_alive() for d in dispatchers) == 1
759
+ finally:
760
+ ex.stop()
761
+ assert not any(d.is_alive() for d in dispatchers)
@@ -6,18 +6,18 @@ import time
6
6
  import pytest
7
7
 
8
8
  import multiCMD
9
- from conftest import pid_gone, sigint_main_after
9
+ from conftest import os_threads, pid_gone, sigint_main_after
10
10
  from multiCMD import run_commands
11
11
 
12
12
 
13
13
  @pytest.mark.slow
14
14
  def test_pool_keeps_threads_bounded():
15
- baseline = threading.active_count()
15
+ baseline = os_threads()
16
16
  peak = [0]
17
17
  done = threading.Event()
18
18
  def watch():
19
19
  while not done.is_set():
20
- peak[0] = max(peak[0], threading.active_count())
20
+ peak[0] = max(peak[0], os_threads())
21
21
  time.sleep(0.001)
22
22
  watcher = threading.Thread(target=watch, daemon=True)
23
23
  watcher.start()
@@ -27,8 +27,10 @@ def test_pool_keeps_threads_bounded():
27
27
  done.set()
28
28
  watcher.join()
29
29
  assert codes == [0] * 1000
30
- # 4 workers, 2 output readers per running command, and the watcher itself
31
- assert peak[0] <= baseline + 4 + 2 * 4 + 1
30
+ # 4 workers, 2 output readers per running command, the watcher itself, and the 2 readers of each worker's previous
31
+ # command, which may still be leaving: a reader is done before its thread has left ( its last step needs the CPU, and
32
+ # the GIL ), and the worker starts its next command meanwhile
33
+ assert peak[0] <= baseline + 4 + 2 * 4 + 1 + 2 * 4
32
34
 
33
35
 
34
36
  def test_empty_command_list():
@@ -236,15 +236,15 @@ def test_exit_leaves_alone_what_a_finished_fire_and_forget_command_started(tmp_p
236
236
 
237
237
  @pytest.mark.parametrize('exc', [KeyboardInterrupt, RuntimeError], ids=['ctrl-c', 'cannot-start'])
238
238
  def test_a_reader_start_that_fails_still_stops_the_command(monkeypatch, exc):
239
- real_start = multiCMD._Thread.start
239
+ real_start = multiCMD._Reader.start
240
240
  count = [0]
241
241
  def start(self):
242
- if getattr(self, '_target', None) is multiCMD._read_stream:
242
+ if self._target is multiCMD._read_stream:
243
243
  count[0] += 1
244
244
  if count[0] == 2:
245
245
  raise exc("can't start new thread")
246
246
  real_start(self)
247
- monkeypatch.setattr(multiCMD._Thread, 'start', start)
247
+ monkeypatch.setattr(multiCMD._Reader, 'start', start)
248
248
  procs = []
249
249
  real_register = multiCMD._register
250
250
  monkeypatch.setattr(multiCMD, '_register', lambda proc, pgid: (procs.append(proc), real_register(proc, pgid)))
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes