-
Notifications
You must be signed in to change notification settings - Fork 561
Expand file tree
/
Copy pathtest_process_tree.py
More file actions
3100 lines (2605 loc) · 98 KB
/
Copy pathtest_process_tree.py
File metadata and controls
3100 lines (2605 loc) · 98 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
from __future__ import annotations
import asyncio
import concurrent.futures
import contextlib
import ctypes
import ctypes.wintypes as wintypes
import errno
import io
import os
import shutil
import signal
import sqlite3
import subprocess
import sys
import textwrap
from types import SimpleNamespace
import pytest
from opensquilla import private_paths, process_tree
def _synthetic_owner_reference(
database_path,
*,
owner_id: str = "a" * 32,
session_digest: str = "b" * 64,
task_digest: str = "c" * 64,
parent_session_digest: str | None = None,
parent_task_digest: str | None = None,
platform: str = "posix",
controller_pid: int = 4242,
controller_start_identity: str = "synthetic-start-identity",
):
return process_tree._PersistedOwnerRef(
database_path=database_path,
record=process_tree._PersistedOwnerRecord(
owner_id=owner_id,
session_digest=session_digest,
task_digest=task_digest,
parent_session_digest=parent_session_digest,
parent_task_digest=parent_task_digest,
platform=platform,
controller_pid=controller_pid,
controller_start_identity=controller_start_identity,
),
)
@pytest.mark.parametrize(
("frozen", "expected_prefix"),
[
(False, ("/synthetic/python", "-m", "opensquilla.process_tree")),
(True, ("/synthetic/gateway", "--internal-child", "process-tree")),
],
)
def test_process_tree_child_argv_is_fixed_for_source_and_frozen_modes(
monkeypatch: pytest.MonkeyPatch,
frozen: bool,
expected_prefix: tuple[str, ...],
) -> None:
executable = "/synthetic/gateway" if frozen else "/synthetic/python"
monkeypatch.setattr(process_tree.sys, "executable", executable)
monkeypatch.setattr(process_tree.sys, "frozen", frozen, raising=False)
argv = process_tree._process_tree_child_argv(
"--windows-owned-launch",
"gate",
"ready",
"--",
"cmd",
)
assert argv == (
*expected_prefix,
"--windows-owned-launch",
"gate",
"ready",
"--",
"cmd",
)
def test_windows_frozen_helper_ready_wait_is_extended_and_retried_once(
monkeypatch: pytest.MonkeyPatch,
) -> None:
waits: list[float] = []
delays: list[float] = []
class Gate:
def wait_ready(self, timeout: float) -> None:
waits.append(timeout)
if len(waits) == 1:
raise TimeoutError("synthetic cold start")
monkeypatch.setattr(process_tree.sys, "frozen", True, raising=False)
monkeypatch.setattr(process_tree.time, "sleep", delays.append)
process_tree._wait_for_windows_helper_ready(Gate())
assert waits == [5.0, 5.0]
assert delays == [0.25]
def test_windows_frozen_helper_ready_wait_remains_bounded(
monkeypatch: pytest.MonkeyPatch,
) -> None:
waits: list[float] = []
delays: list[float] = []
class Gate:
def wait_ready(self, timeout: float) -> None:
waits.append(timeout)
raise TimeoutError("synthetic frozen timeout")
monkeypatch.setattr(process_tree.sys, "frozen", True, raising=False)
monkeypatch.setattr(process_tree.time, "sleep", delays.append)
with pytest.raises(TimeoutError, match="frozen timeout"):
process_tree._wait_for_windows_helper_ready(Gate())
assert waits == [5.0, 5.0]
assert delays == [0.25]
def test_windows_source_helper_ready_timeout_is_not_retried(
monkeypatch: pytest.MonkeyPatch,
) -> None:
waits: list[float] = []
class Gate:
def wait_ready(self, timeout: float) -> None:
waits.append(timeout)
raise TimeoutError("synthetic source timeout")
monkeypatch.delattr(process_tree.sys, "frozen", raising=False)
monkeypatch.setattr(
process_tree.time,
"sleep",
lambda _delay: pytest.fail("source helper readiness must not retry"),
)
with pytest.raises(TimeoutError, match="source timeout"):
process_tree._wait_for_windows_helper_ready(Gate())
assert waits == [2.0]
@pytest.mark.asyncio
async def test_posix_anchor_creation_waits_for_ready(
monkeypatch: pytest.MonkeyPatch,
) -> None:
ready = asyncio.Event()
class Stream:
async def readexactly(self, _size: int) -> bytes:
await ready.wait()
return process_tree._POSIX_ANCHOR_READY
class Process:
pid = 4141
returncode = None
stdout = Stream()
async def fake_spawn(*_argv: str, **_kwargs: object) -> Process:
return Process()
monkeypatch.setattr(process_tree.asyncio, "create_subprocess_exec", fake_spawn)
creation = asyncio.create_task(process_tree._create_posix_anchor())
await asyncio.sleep(0)
assert creation.done() is False
ready.set()
anchor = await asyncio.wait_for(creation, timeout=0.2)
assert anchor.pgid == 4141
@pytest.mark.asyncio
async def test_posix_anchor_ready_timeout_stops_unarmed_anchor(
monkeypatch: pytest.MonkeyPatch,
) -> None:
spawned: list[Process] = []
class Stream:
async def readexactly(self, _size: int) -> bytes:
await asyncio.Event().wait()
raise AssertionError("unreachable")
class Input:
def __init__(self, process: Process) -> None:
self.process = process
self.closed = False
def is_closing(self) -> bool:
return self.closed
def close(self) -> None:
self.closed = True
self.process.returncode = 125
class Process:
pid = 4242
def __init__(self) -> None:
self.returncode: int | None = None
self.stdout = Stream()
self.stdin = Input(self)
async def fake_spawn(*_argv: str, **_kwargs: object) -> Process:
process = Process()
spawned.append(process)
return process
monkeypatch.setattr(process_tree, "_CONTROL_READY_TIMEOUT_SECONDS", 0.01)
monkeypatch.setattr(process_tree.asyncio, "create_subprocess_exec", fake_spawn)
with pytest.raises(
process_tree.ProcessTreeOwnershipError,
match="did not become ready",
):
await process_tree._create_posix_anchor()
assert len(spawned) == 1
assert spawned[0].stdin.closed is True
assert spawned[0].returncode == 125
@pytest.mark.skipif(os.name != "posix", reason="process group behavior is POSIX-specific")
@pytest.mark.asyncio
async def test_immediate_stop_after_ready_cannot_kill_anchor_before_ignored_target(
tmp_path,
) -> None:
for attempt in range(20):
survived = tmp_path / f"immediate-stop-{attempt}"
def ignore_term() -> None:
signal.signal(signal.SIGTERM, signal.SIG_IGN)
process = await process_tree.create_owned_subprocess_exec(
sys.executable,
"-c",
(
"import pathlib, time; time.sleep(0.4); "
f"pathlib.Path({str(survived)!r}).write_text('leaked')"
),
preexec_fn=ignore_term,
)
owner = process_tree.capture_process_tree_owner(process, isolated=True)
assert await owner.terminate(graceful_timeout=0.01, kill_timeout=1.0)
await asyncio.wait_for(process.wait(), timeout=1.0)
await asyncio.sleep(0.01)
assert survived.exists() is False
@pytest.mark.skipif(os.name != "posix", reason="exec error pipe is POSIX-specific")
@pytest.mark.asyncio
async def test_posix_controlled_launch_preserves_missing_executable_error(tmp_path) -> None:
with process_tree.task_process_scope(
tmp_path,
session_key="synthetic-session",
task_id="synthetic-task",
):
with pytest.raises(FileNotFoundError):
await process_tree.create_owned_subprocess_exec(
"opensquilla-synthetic-command-that-does-not-exist"
)
assert process_tree._load_owner_records(tmp_path) == ()
@pytest.mark.skipif(os.name != "posix", reason="PGID lifecycle is POSIX-specific")
@pytest.mark.asyncio
async def test_posix_anchor_owns_signalling_and_closes_with_its_lifecycle(
monkeypatch: pytest.MonkeyPatch,
) -> None:
gateway_signals: list[tuple[int, int]] = []
monkeypatch.setattr(
process_tree.os,
"killpg",
lambda pgid, sig: gateway_signals.append((pgid, sig)),
)
class Input:
def __init__(self) -> None:
self.commands: list[bytes] = []
self.closed = False
def is_closing(self) -> bool:
return self.closed
def write(self, command: bytes) -> None:
self.commands.append(command)
async def drain(self) -> None:
return None
anchor_process = SimpleNamespace(returncode=None)
anchor_process.stdin = Input()
owner = process_tree.ProcessTreeOwner(
process=SimpleNamespace(returncode=0),
pid=4242,
pgid=4242,
posix_anchor=process_tree._PosixGroupAnchor(
process=anchor_process,
pgid=4242,
),
)
assert owner.is_active() is True
assert await owner.posix_anchor.request_signal(
process_tree._POSIX_ANCHOR_TERMINATE
)
assert anchor_process.stdin.commands == [process_tree._POSIX_ANCHOR_TERMINATE]
assert gateway_signals == []
# Reaping the parent-owned anchor permanently closes this owner. Even if a
# later unrelated group receives the same numeric PGID, it is never probed
# or signalled through the expired ownership token.
anchor_process.returncode = 0
assert owner.is_active() is False
assert not await owner.posix_anchor.request_signal(process_tree._POSIX_ANCHOR_KILL)
assert gateway_signals == []
@pytest.mark.asyncio
async def test_posix_incomplete_cleanup_remains_failed_after_anchor_exit() -> None:
anchor = process_tree._PosixGroupAnchor(
process=SimpleNamespace(returncode=0),
pgid=4242,
cleanup_incomplete=True,
)
owner = process_tree.ProcessTreeOwner(
process=SimpleNamespace(returncode=0),
pid=4242,
pgid=4242,
posix_anchor=anchor,
)
assert await owner.terminate(graceful_timeout=0.0, kill_timeout=0.0) is False
assert await owner.terminate(graceful_timeout=0.0, kill_timeout=0.0) is False
@pytest.mark.asyncio
async def test_posix_unacknowledged_anchor_exit_fails_closed() -> None:
class Process:
returncode: int | None = None
async def wait(self) -> int:
self.returncode = 1
return 1
class Stream:
async def read(self, _size: int) -> bytes:
return b""
anchor = process_tree._PosixGroupAnchor(process=Process(), pgid=4242)
await anchor._watch_empty(Stream())
owner = process_tree.ProcessTreeOwner(
process=SimpleNamespace(returncode=None),
pid=4242,
pgid=4242,
posix_anchor=anchor,
)
assert anchor.cleanup_incomplete is True
assert await owner.terminate(graceful_timeout=0.0, kill_timeout=0.0) is False
assert owner.process.returncode is None
@pytest.mark.asyncio
async def test_posix_anchor_transport_failure_fails_closed() -> None:
anchor_process = SimpleNamespace(returncode=None)
class Input:
def is_closing(self) -> bool:
return False
def write(self, _command: bytes) -> None:
anchor_process.returncode = 1
raise BrokenPipeError
async def drain(self) -> None:
return None
anchor_process.stdin = Input()
anchor = process_tree._PosixGroupAnchor(process=anchor_process, pgid=4242)
owner = process_tree.ProcessTreeOwner(
process=SimpleNamespace(returncode=None),
pid=4242,
pgid=4242,
posix_anchor=anchor,
)
assert await owner.terminate(graceful_timeout=0.0, kill_timeout=0.0) is False
assert anchor.cleanup_incomplete is True
assert owner.process.returncode is None
@pytest.mark.skipif(os.name != "posix", reason="PGID lifecycle is POSIX-specific")
@pytest.mark.asyncio
async def test_posix_anchor_outlives_leader_and_excludes_unrelated_group(tmp_path) -> None:
child_pid = tmp_path / "owned-child.pid"
owned_survived = tmp_path / "owned-survived"
owned_release = tmp_path / "owned-release"
sibling_survived = tmp_path / "sibling-survived"
child_script = (
"import os\n"
"import pathlib\n"
"import time\n"
f"pathlib.Path({str(child_pid)!r}).write_text(str(os.getpid()))\n"
f"release = pathlib.Path({str(owned_release)!r})\n"
"deadline = time.monotonic() + 30\n"
"while not release.exists() and time.monotonic() < deadline:\n"
" time.sleep(0.01)\n"
"if release.exists():\n"
f" pathlib.Path({str(owned_survived)!r}).write_text('survived')\n"
)
parent_script = (
"import subprocess, sys; "
f"subprocess.Popen([sys.executable, '-c', {child_script!r}])"
)
owned = await process_tree.create_owned_subprocess_exec(
sys.executable,
"-c",
parent_script,
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL,
)
owner = process_tree.capture_process_tree_owner(owned, isolated=True)
sibling = await asyncio.create_subprocess_exec(
sys.executable,
"-c",
(
"import pathlib, time; time.sleep(0.4); "
f"pathlib.Path({str(sibling_survived)!r}).write_text('survived')"
),
start_new_session=True,
)
try:
await asyncio.wait_for(owned.wait(), timeout=3.0)
for _attempt in range(200):
if child_pid.exists():
break
await asyncio.sleep(0.01)
assert child_pid.exists()
assert owner.is_active() is True
assert await owner.terminate(graceful_timeout=0.2, kill_timeout=1.0)
owned_release.write_text("release", encoding="utf-8")
await asyncio.wait_for(sibling.wait(), timeout=2.0)
await asyncio.sleep(0.9)
assert not owned_survived.exists()
assert sibling_survived.exists()
finally:
with contextlib.suppress(OSError):
owned_release.write_text("release", encoding="utf-8")
if owner.is_active():
await owner.terminate(graceful_timeout=0.1, kill_timeout=1.0)
if sibling.returncode is None:
sibling.kill()
await sibling.wait()
@pytest.mark.skipif(
not (sys.platform.startswith("linux") or sys.platform == "darwin"),
reason="process ancestry capture is Linux/macOS-specific",
)
@pytest.mark.asyncio
async def test_posix_stop_kills_new_session_descendants_and_preserves_sentinel(
tmp_path,
) -> None:
state_dir = tmp_path / "state"
pid_file = tmp_path / "owned-pids"
sleeper = "import time; time.sleep(30)"
grandchild = (
"import os,pathlib,signal,time; signal.signal(signal.SIGTERM,signal.SIG_IGN); "
f"pathlib.Path({str(pid_file)!r}).open('a').write(str(os.getpid())+'\\n'); "
"time.sleep(30)"
)
child = (
"import os,pathlib,signal,subprocess,sys,time; "
"signal.signal(signal.SIGTERM,signal.SIG_IGN); "
f"pathlib.Path({str(pid_file)!r}).open('a').write(str(os.getpid())+'\\n'); "
f"subprocess.Popen([sys.executable,'-c',{grandchild!r}],start_new_session=True); "
"time.sleep(30)"
)
background = (
"import os,pathlib,signal,subprocess,sys,time; "
"signal.signal(signal.SIGTERM,signal.SIG_IGN); "
f"pathlib.Path({str(pid_file)!r}).open('a').write(str(os.getpid())+'\\n'); "
f"subprocess.Popen([sys.executable,'-c',{child!r}],start_new_session=True); "
"time.sleep(30)"
)
foreground = (
"import os,pathlib,subprocess,sys,time; "
f"pathlib.Path({str(pid_file)!r}).open('a').write(str(os.getpid())+'\\n'); "
f"subprocess.Popen([sys.executable,'-c',{background!r}],start_new_session=True); "
"time.sleep(30)"
)
with process_tree.task_process_scope(
state_dir,
session_key="synthetic-session",
task_id="synthetic-task",
):
owned = await process_tree.create_owned_subprocess_exec(
sys.executable,
"-c",
foreground,
)
owner = process_tree.capture_process_tree_owner(owned, isolated=True)
sentinel = await asyncio.create_subprocess_exec(
sys.executable,
"-c",
sleeper,
start_new_session=True,
)
owned_pids: list[int] = []
owned_identities: dict[int, process_tree._PosixProcessInfo] = {}
try:
for _attempt in range(500):
if pid_file.exists():
owned_pids = [int(value) for value in pid_file.read_text().splitlines()]
if len(owned_pids) == 4:
break
await asyncio.sleep(0.01)
assert len(owned_pids) == 4
owned_identities = {
pid: info
for pid in owned_pids
if (info := process_tree._posix_process_info(pid)) is not None
}
owner_stopped, persisted_stopped = await asyncio.gather(
owner.terminate(graceful_timeout=0.2, kill_timeout=1.0),
process_tree.cancel_persisted_processes_for_task(
state_dir,
"synthetic-session",
"synthetic-task",
),
)
assert owner_stopped is True
assert persisted_stopped in {0, 1}
await asyncio.wait_for(owned.wait(), timeout=2.0)
for _attempt in range(300):
if all(
process_tree._strict_process_start_identity(pid) is None
for pid in owned_pids
):
break
await asyncio.sleep(0.01)
assert all(
process_tree._strict_process_start_identity(pid) is None
for pid in owned_pids
)
assert sentinel.returncode is None
finally:
if owner.is_active():
await owner.terminate(graceful_timeout=0.1, kill_timeout=1.0)
if sentinel.returncode is None:
sentinel.kill()
await sentinel.wait()
for pid, captured_info in owned_identities.items():
current_info = process_tree._posix_process_info(pid)
if (
current_info is not None
and current_info.uid == captured_info.uid
and current_info.start_identity == captured_info.start_identity
):
with contextlib.suppress(ProcessLookupError):
os.kill(pid, signal.SIGKILL)
def test_posix_captured_pid_identity_change_is_not_signalled(
monkeypatch: pytest.MonkeyPatch,
) -> None:
captured = process_tree._CapturedPosixProcess(
pid=4242,
uid=501,
start_identity="original-start",
depth=1,
)
signalled: list[tuple[int, int]] = []
monkeypatch.setattr(
process_tree,
"_posix_process_info",
lambda _pid: process_tree._PosixProcessInfo(
pid=4242,
ppid=1,
pgid=4242,
uid=501,
start_identity="replacement-start",
),
)
monkeypatch.setattr(
process_tree.os,
"kill",
lambda pid, sig: signalled.append((pid, sig)),
)
process_tree._signal_captured_posix_processes((captured,), signal.SIGTERM)
assert signalled == []
def test_linux_descendant_capture_does_not_fall_back_to_numeric_pid(
monkeypatch: pytest.MonkeyPatch,
) -> None:
uid = 501
anchor = process_tree._PosixProcessInfo(100, 1, 100, uid, "anchor")
root = process_tree._PosixProcessInfo(101, 100, 100, uid, "root")
escaped = process_tree._PosixProcessInfo(102, 101, 102, uid, "escaped")
monkeypatch.setattr(process_tree.sys, "platform", "linux")
monkeypatch.setattr(process_tree.os, "geteuid", lambda: uid, raising=False)
monkeypatch.setattr(
process_tree,
"_posix_process_snapshot",
lambda: {100: anchor, 101: root, 102: escaped},
)
monkeypatch.setattr(
process_tree,
"_posix_process_info",
lambda pid: {100: anchor, 101: root, 102: escaped}.get(pid),
)
monkeypatch.setattr(
process_tree.os,
"pidfd_open",
lambda _pid, _flags: (_ for _ in ()).throw(OSError(errno.EMFILE, "full")),
raising=False,
)
monkeypatch.setattr(
process_tree.signal,
"pidfd_send_signal",
lambda *_args: None,
raising=False,
)
capture = process_tree._capture_posix_group_descendants(100, 100)
assert capture.complete is False
assert capture.processes == ()
def test_other_posix_descendant_capture_preserves_group_only_behavior(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(process_tree.sys, "platform", "freebsd")
monkeypatch.setattr(
process_tree,
"_posix_process_snapshot",
lambda: (_ for _ in ()).throw(AssertionError("unsupported native snapshot")),
)
capture = process_tree._capture_posix_group_descendants(100, 100)
assert capture == process_tree._PosixDescendantCapture((), True)
@pytest.mark.parametrize(
("returncode", "stdout"),
[
(1, "123 123\n"),
(0, ""),
(0, "malformed\n"),
(0, "999 999\n"),
],
)
def test_posix_ps_snapshot_failures_never_report_group_empty(
monkeypatch: pytest.MonkeyPatch,
returncode: int,
stdout: str,
) -> None:
monkeypatch.setattr(process_tree.os.path, "isdir", lambda _path: False)
monkeypatch.setattr(
process_tree.subprocess,
"run",
lambda *_args, **_kwargs: SimpleNamespace(
returncode=returncode,
stdout=stdout,
),
)
assert process_tree._posix_group_members(123) is None
def test_posix_proc_skipped_read_never_reports_group_empty(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(process_tree.os.path, "isdir", lambda _path: True)
monkeypatch.setattr(process_tree.os, "listdir", lambda _path: ["123"])
def fail_open(*_args: object, **_kwargs: object) -> None:
raise FileNotFoundError
monkeypatch.setattr("builtins.open", fail_open)
assert process_tree._posix_group_members(123) is None
def test_posix_proc_ignores_unrelated_pid_disappearing_during_snapshot(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(process_tree.os.path, "isdir", lambda _path: True)
monkeypatch.setattr(process_tree.os, "listdir", lambda _path: ["123", "999"])
def selective_open(path: str, **_kwargs: object):
if path.endswith(os.path.join("123", "stat")):
return io.StringIO("123 (anchor) S 1 123")
raise FileNotFoundError
monkeypatch.setattr("builtins.open", selective_open)
assert process_tree._posix_group_members(123) == (123,)
def test_posix_empty_confirmation_requires_consecutive_complete_snapshots() -> None:
confirmations = process_tree._advance_posix_empty_confirmation(
0,
(123,),
123,
captured_alive=False,
)
assert confirmations == 1
confirmations = process_tree._advance_posix_empty_confirmation(
confirmations,
None,
123,
captured_alive=False,
)
assert confirmations == 0
confirmations = process_tree._advance_posix_empty_confirmation(
confirmations,
(123,),
123,
captured_alive=True,
)
assert confirmations == 0
confirmations = process_tree._advance_posix_empty_confirmation(
confirmations,
(123,),
123,
captured_alive=False,
)
assert confirmations == 1
confirmations = process_tree._advance_posix_empty_confirmation(
confirmations,
(123, 456),
123,
captured_alive=False,
)
assert confirmations == 0
confirmations = process_tree._advance_posix_empty_confirmation(
confirmations,
(123,),
123,
captured_alive=False,
)
assert confirmations == 1
confirmations = process_tree._advance_posix_empty_confirmation(
confirmations,
(123,),
123,
captured_alive=False,
)
assert confirmations == 2
@pytest.mark.skipif(
os.name != "posix" or os.path.isdir("/proc") or sys.platform == "darwin",
reason="requires the POSIX ps fallback",
)
@pytest.mark.asyncio
async def test_failed_ps_snapshot_keeps_real_leaderless_descendant_owned(
tmp_path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
real_ps = shutil.which("ps")
assert real_ps is not None
fake_bin = tmp_path / "bin"
fake_bin.mkdir()
failed_probe = tmp_path / "failed-probe"
fake_ps = fake_bin / "ps"
fake_ps.write_text(
"#!/bin/sh\n"
f"if [ ! -e {str(failed_probe)!r} ]; then\n"
f" : > {str(failed_probe)!r}\n"
" exit 1\n"
"fi\n"
f"exec {real_ps!r} \"$@\"\n",
encoding="utf-8",
)
fake_ps.chmod(0o755)
monkeypatch.setenv("PATH", f"{fake_bin}{os.pathsep}{os.environ.get('PATH', '')}")
child_pid = tmp_path / "child.pid"
survived = tmp_path / "child-survived"
child_script = (
"import os, pathlib, signal, time; "
"signal.signal(signal.SIGTERM, signal.SIG_IGN); "
f"pathlib.Path({str(child_pid)!r}).write_text(str(os.getpid())); "
"time.sleep(5); "
f"pathlib.Path({str(survived)!r}).write_text('leaked')"
)
leader_script = (
"import subprocess, sys, time; "
f"subprocess.Popen([sys.executable, '-c', {child_script!r}]); "
"time.sleep(0.1)"
)
leader = await process_tree.create_owned_subprocess_exec(
sys.executable,
"-c",
leader_script,
)
owner = process_tree.capture_process_tree_owner(leader, isolated=True)
try:
for _attempt in range(500):
if failed_probe.exists() and child_pid.exists():
break
await asyncio.sleep(0.01)
assert failed_probe.exists()
assert child_pid.exists()
await asyncio.wait_for(leader.wait(), timeout=2.0)
assert owner.is_active()
assert await owner.terminate(graceful_timeout=0.05, kill_timeout=1.0)
await asyncio.sleep(0.2)
assert survived.exists() is False
finally:
if owner.is_active():
await owner.terminate(graceful_timeout=0.05, kill_timeout=1.0)
await asyncio.wait_for(leader.wait(), timeout=2.0)
@pytest.mark.asyncio
async def test_non_durable_owner_never_widens_cleanup_to_a_process_group(
monkeypatch: pytest.MonkeyPatch,
) -> None:
group_signals: list[tuple[int, int]] = []
monkeypatch.setattr(
process_tree.os,
"killpg",
lambda pgid, sig: group_signals.append((pgid, sig)),
raising=False,
)
class DirectProcess:
pid = 5151
returncode: int | None = None
def terminate(self) -> None:
self.returncode = 0
def kill(self) -> None:
self.returncode = -9
proc = DirectProcess()
owner = process_tree.capture_process_tree_owner(proc, isolated=False)
assert owner.durable is False
assert await owner.terminate(graceful_timeout=0.1, kill_timeout=0.1)
assert proc.returncode == 0
assert group_signals == []
def test_windows_unowned_process_never_attempts_racy_post_spawn_job_assignment(
monkeypatch: pytest.MonkeyPatch,
) -> None:
class Process:
pid = 6262
returncode = None
proc = Process()
monkeypatch.setattr(process_tree.os, "name", "nt")
owner = process_tree.capture_process_tree_owner(proc, isolated=True)
assert not hasattr(process_tree._WindowsJob, "assign")
assert owner.durable is False
assert owner.ownership_error is not None
assert "controlled Job Object" in owner.ownership_error
@pytest.mark.asyncio
async def test_windows_controlled_launcher_assignment_failure_stops_unreleased_helper(
monkeypatch: pytest.MonkeyPatch,
) -> None:
events: list[str] = []
class Gate:
gate_name = "test-gate"
ready_name = "test-ready"
def wait_ready(self, _timeout: float) -> None:
events.append("ready")
def release(self) -> None:
events.append("released")
def close(self) -> None:
events.append("gate-closed")
class Job:
def assign_pid(self, _pid: int) -> None:
events.append("assign-failed")
raise OSError("denied")
def close(self) -> None:
events.append("job-closed")
class Process:
pid = 7373
returncode: int | None = None
def terminate(self) -> None:
events.append("terminated")
self.returncode = -15
process = Process()
async def fake_spawn(*_argv: str, **_kwargs: object) -> Process:
events.append("spawned-helper")
return process
monkeypatch.setattr(process_tree.os, "name", "nt")
monkeypatch.setattr(
process_tree._WindowsLaunchGate,
"create",
classmethod(lambda _cls: Gate()),
)
monkeypatch.setattr(
process_tree._WindowsJob,
"create",
classmethod(lambda _cls: Job()),
)
monkeypatch.setattr(process_tree.asyncio, "create_subprocess_exec", fake_spawn)
with pytest.raises(process_tree.ProcessTreeOwnershipError, match="failed closed"):
await process_tree.create_owned_subprocess_exec("command.exe")
assert events == [
"spawned-helper",
"assign-failed",
"terminated",
"job-closed",
"gate-closed",
]
@pytest.mark.asyncio
async def test_windows_controlled_launcher_waits_for_helper_ready_before_release(
monkeypatch: pytest.MonkeyPatch,
) -> None:
events: list[str] = []
class Gate:
gate_name = "test-gate"
ready_name = "test-ready"
def wait_ready(self, _timeout: float) -> None:
events.append("helper-ready")
def release(self) -> None:
events.append("released")
def close(self) -> None:
events.append("gate-closed")
class Job:
def assign_pid(self, _pid: int) -> None:
events.append("assigned")
def close(self) -> None:
events.append("job-closed")
class Process:
pid = 7474
returncode = None
spawn_kwargs: dict[str, object] = {}
async def fake_spawn(*_argv: str, **kwargs: object) -> Process:
events.append("spawned-helper")
spawn_kwargs.update(kwargs)
return Process()
monkeypatch.setattr(process_tree.os, "name", "nt")
monkeypatch.setattr(
process_tree._WindowsLaunchGate,
"create",
classmethod(lambda _cls: Gate()),
)
monkeypatch.setattr(
process_tree._WindowsJob,
"create",
classmethod(lambda _cls: Job()),
)
monkeypatch.setattr(process_tree.asyncio, "create_subprocess_exec", fake_spawn)
process = await process_tree.create_owned_subprocess_exec(