from pathlib import Path import subprocess import os import sys from uuid import uuid4 from types import SimpleNamespace import pytest from dx_productivity.trial_task_center.errors import TaskCenterError from dx_productivity.trial_task_center.isolated_desktop import PrivateDesktop, build_startup_info from dx_productivity.trial_task_center.isolated_desktop import _Win32Api, _Win32Process @pytest.mark.skipif(os.name != 'nt', reason='native Windows deferred desktop release') def test_release_waits_for_a_temporary_external_reference_without_stopping_its_owner(): desktop = PrivateDesktop('dx-test-' + uuid4().hex, enabled=True) desktop.__enter__() retained = subprocess.Popen((sys.executable, '-u', '-c', 'import win32service,sys,time; h=win32service.OpenDesktop(sys.argv[1],0,False,1); ' 'print("ready",flush=True); time.sleep(3); h.CloseDesktop(); ' 'print("released",flush=True); time.sleep(30)', desktop.name), stdout=subprocess.PIPE) try: assert retained.stdout.readline() == b'ready\r\n' desktop.close() assert desktop.cleanup_record['desktop_confirmation']['released'] assert retained.stdout.readline() == b'released\r\n' assert retained.poll() is None finally: retained.terminate() retained.wait(timeout=5) retained.stdout.close() desktop.close() @pytest.mark.skipif(os.name != 'nt', reason='native Windows desktop lifetime') @pytest.mark.parametrize('with_window', [False, True]) def test_release_does_not_report_success_while_another_handle_keeps_desktop_alive(with_window): desktop = PrivateDesktop('dx-test-' + uuid4().hex, enabled=True) desktop.__enter__() script = ('import win32service,sys,time; h=win32service.OpenDesktop(sys.argv[1],0,False,1); ' + ('import win32gui; w=win32gui.CreateWindowEx(0,"STATIC","residue",0,0,0,1,1,0,0,0,None); ' if with_window else '') + 'print("ready",flush=True); time.sleep(30)') # subprocess.STARTUPINFO ignores lpDesktop. Use the native launch boundary # so the diagnostic window really belongs to the requested desktop. retained = _Win32Api().create_process((sys.executable, '-u', '-c', script, desktop.name), build_startup_info(desktop.name).lpDesktop, None, None, stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: assert retained.stdout.readline() == b'ready\r\n' with pytest.raises(TaskCenterError, match='still exists'): desktop.close() record = desktop.cleanup_record assert record['desktop_handle_closed'] assert not record['desktop_confirmation']['released'] windows = record['desktop_confirmation']['remaining_windows'] assert {row['pid'] for row in windows} == ({retained.pid} if with_window else set()) assert retained.poll() is None # Diagnostics must not terminate a foreign owner. assert record['desktop_confirmation']['elapsed_seconds'] >= 2 finally: retained.terminate() retained.wait(timeout=5) retained.close() desktop.close() assert desktop.cleanup_record['desktop_confirmation']['released'] def test_startup_info_always_targets_private_desktop(): info = build_startup_info('dx-private-test') assert info.lpDesktop == 'winsta0\\dx-private-test' def test_desktop_records_native_handle_before_close_and_failed_retry(): class Desktop: fail = True def __int__(self): return 761 def CloseDesktop(self): if self.fail: self.fail = False raise OSError('busy') handle = Desktop() desktop = PrivateDesktop('private', enabled=True, api=SimpleNamespace(create_desktop=lambda _: handle)) desktop.__enter__() with pytest.raises(TaskCenterError): desktop.close() desktop.close() history = desktop.cleanup_record['desktop_handle_history'] assert [event['operation'] for event in history] == ['create', 'close', 'close'] assert [event['success'] for event in history] == [True, False, True] assert all(event['handle'] == 761 and event['pid'] == os.getpid() and event['thread_id'] for event in history) def test_desktop_preserves_forgotten_worker_history_and_unknown_holder_scope(): api, _, state, *_ = native_api() api.confirm_desktop_released = lambda _: None desktop = PrivateDesktop('private', enabled=True, api=api) desktop._handle = SimpleNamespace(CloseDesktop=lambda: None) process = desktop.start_process(('python.exe',)) process.close() desktop.forget_closed_process(process) desktop.close() history = desktop.cleanup_record['process_history'] assert history[0]['pid'] == 42 and history[0]['cleanup']['process_handle_closed'] assert history[0]['forgotten'] is True assert desktop.cleanup_record['diagnostic_scope']['external_handle_holders'] == 'unknown' def test_failed_release_reports_windowless_holder_unknown_and_owned_job_failure(): api, _, _, *_ = native_api() api._pending_cleanup = [] def confirm(_): api.desktop_release_check = {'released': False, 'remaining_windows': []} raise OSError('still exists') api.confirm_desktop_released = confirm desktop = PrivateDesktop('private', enabled=True, api=api) desktop._handle = SimpleNamespace(CloseDesktop=lambda: None) process = desktop.start_process(('python.exe',)) process.close = lambda: (_ for _ in ()).throw(OSError('owned handles retained')) with pytest.raises(TaskCenterError): desktop.close() report = desktop.cleanup_record['owned_resource_diagnostics'] assert report['residual_windows'] == [] assert report['external_handle_holders'] == 'unknown' assert report['thread_desktops']['complete'] is False assert report['owned_processes'][0]['pid'] == 42 assert report['owned_processes'][0]['job_accounting']['ActiveProcesses'] == 0 @pytest.mark.skipif(os.name != 'nt', reason='native Windows resource history') def test_real_helper_retains_completed_lifecycle_after_forget(): with PrivateDesktop('dx-test-' + uuid4().hex, enabled=True) as desktop: process = desktop.start_process((sys.executable, '-c', 'pass')) assert process.wait(timeout=5) == 0 process.close() desktop.forget_closed_process(process) assert desktop.cleanup_record['process_history'][0]['pid'] == process.pid assert desktop.cleanup_record['desktop_handle_history'][0]['handle'] > 0 def test_private_desktop_never_falls_back_to_input_desktop(monkeypatch): desktop = PrivateDesktop('dx-private-test', enabled=True) monkeypatch.setattr(desktop, '_create', lambda: None) monkeypatch.setattr(desktop, '_handle', None) with pytest.raises(TaskCenterError, match='private desktop'): desktop.start_process(('cad.exe',)) class Handle: def __init__(self, name, events, fail_once=False): self.name, self.events, self.fail_once = name, events, fail_once self.closed = False def Close(self): self.events.append(('close', self.name)) if self.fail_once: self.fail_once = False raise OSError('close failed') self.closed = True def native_api(*, assign_error=False): events = [] process_handle = Handle('process', events) thread = Handle('thread', events) job = Handle('job', events) state = {'running': True, 'code': 259} def create(*args): events.append(('create', args[5])) return process_handle, thread, 42, 43 def assign(*_args): events.append(('assign',)) if assign_error: raise OSError('assign failed') def terminate(*_args): events.append(('terminate',)) state['running'] = False def wait(_handle, timeout): events.append(('wait', timeout)) return 258 if state['running'] else 0 api = _Win32Api.__new__(_Win32Api) api.con = SimpleNamespace(CREATE_NO_WINDOW=0x8000000, CREATE_SUSPENDED=4) api.process = SimpleNamespace( STARTUPINFO=lambda: SimpleNamespace(), CreateProcess=create, ResumeThread=lambda _thread: events.append(('resume',)), GetExitCodeProcess=lambda _handle: state['code'], TerminateProcess=terminate, ) api.job = SimpleNamespace( CreateJobObject=lambda *_args: job, QueryInformationJobObject=lambda _job, kind: ( {'BasicLimitInformation': {'LimitFlags': 0}} if kind == 9 else {'ActiveProcesses': int(state['running'])}), SetInformationJobObject=lambda *_args: events.append(('limits',)), AssignProcessToJobObject=assign, TerminateJobObject=terminate, JobObjectExtendedLimitInformation=9, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE=0x2000, JobObjectBasicAccountingInformation=1, ) api.event = SimpleNamespace(WaitForSingleObject=wait) return api, events, state, process_handle, job def test_process_is_suspended_until_job_assignment(): api, events, *_ = native_api() process = api.create_process(('python.exe',), 'winsta0\\private', None, None) assert process.pid == 42 assert ('create', 0x8000004) in events assert events.index(('assign',)) < events.index(('resume',)) def test_failed_job_assignment_terminates_and_reaps_owned_process(): api, events, state, process_handle, job = native_api(assign_error=True) with pytest.raises(Exception, match='assign failed'): api.create_process(('python.exe',), 'winsta0\\private', None, None) assert not state['running'] assert events.index(('wait', 0)) < events.index(('close', 'process')) assert process_handle.closed and job.closed assert ('resume',) not in events def test_wait_uses_signal_and_accepts_real_exit_code_259(): api, events, state, *_ = native_api() process = api.create_process(('python.exe',), 'winsta0\\private', None, None) with pytest.raises(subprocess.TimeoutExpired): process.wait(timeout=0.025) assert ('wait', 25) in events assert process.poll() is None state['running'] = False assert process.poll() == 259 assert process.wait(timeout=0) == 259 def test_process_close_attempts_all_handles_and_retries_failed_handle(): api, events, state, process_handle, job = native_api() process = api.create_process(('python.exe',), 'winsta0\\private', None, None) process_handle.fail_once = True with pytest.raises(TaskCenterError, match='close failed'): process.close() assert job.closed assert not state['running'] process.close() assert process_handle.closed process.close() assert events.count(('close', 'job')) == 1 def test_desktop_cleanup_continues_after_process_error_and_retries(): events = [] class OwnedProcess: def __init__(self, failing=False): self.failing = failing def poll(self): return None def terminate(self): events.append('terminate') def wait(self, timeout): events.append(('wait', timeout)) def close(self): events.append('process-close') if self.failing: self.failing = False raise OSError('process close failed') class DesktopHandle: def CloseDesktop(self): events.append('desktop-close') desktop = PrivateDesktop('private', enabled=True) desktop._handle = DesktopHandle() desktop._processes = [OwnedProcess(), OwnedProcess(failing=True)] with pytest.raises(TaskCenterError, match='process close failed'): desktop.close() assert events.count('process-close') == 2 assert events[-1] == 'desktop-close' assert ('wait', 5.0) in events desktop.close() assert events.count('process-close') == 3 def test_desktop_close_reports_bounded_process_timeout_and_closes_handles(): events = [] process = SimpleNamespace( poll=lambda: None, terminate=lambda: events.append('terminate'), wait=lambda timeout: (_ for _ in ()).throw(subprocess.TimeoutExpired('owned', timeout)), close=lambda: events.append('process-close'), ) desktop = PrivateDesktop('private', enabled=True) desktop._handle = SimpleNamespace(CloseDesktop=lambda: events.append('desktop-close')) desktop._processes = [process] with pytest.raises(TaskCenterError, match='timed out'): desktop.close() assert events == ['terminate', 'process-close', 'desktop-close'] @pytest.mark.skipif(os.name != 'nt', reason='native Windows desktop/process boundary') def test_native_private_process_has_captured_output_and_real_exit_259(): with PrivateDesktop('dx-test-' + uuid4().hex, enabled=True) as desktop: process = desktop.start_process( (sys.executable, '-c', "import sys,os; print('private-out',flush=True); print('private-err',file=sys.stderr,flush=True); os._exit(259)"), stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) assert process.stdout.readline() == b'private-out\r\n' assert process.stderr.readline() == b'private-err\r\n' assert process.wait(timeout=5) == 259 assert process.poll() == 259 record = desktop.cleanup_record assert record['desktop_handle_closed'] and record['desktop_confirmation']['released'] assert record['processes'][0]['exit_code'] == 259 assert record['processes'][0]['job_active_processes'] == 0 assert record['processes'][0]['unconfirmed_descendant_handles'] == 0 def test_failed_rollback_termination_still_releases_owned_handles(): api, events, state, process_handle, job = native_api(assign_error=True) api.process.TerminateProcess = lambda *_args: (_ for _ in ()).throw(OSError('terminate failed')) with pytest.raises(Exception, match='assign failed'): api.create_process(('python.exe',), 'winsta0\\private', None, None) assert job.closed assert ('close', 'thread') in events # A process outside the job still needs its handle for a cleanup retry. assert not process_handle.closed def terminate(*_args): state['running'] = False api.process.TerminateProcess = terminate api.close_pending() assert process_handle.closed def test_poll_failure_does_not_skip_termination_or_bounded_wait(): events = [] def failed_poll(): raise OSError('poll failed') process = SimpleNamespace( poll=failed_poll, terminate=lambda: events.append('terminate'), wait=lambda timeout: events.append(('wait', timeout)), close=lambda: events.append('close'), ) desktop = PrivateDesktop('private', enabled=True) desktop._processes = [process] with pytest.raises(TaskCenterError, match='poll failed'): desktop.close() assert events == ['terminate', ('wait', 5.0), 'close'] def test_desktop_handle_close_failure_is_retried(): events = [] handle = Handle('desktop', events, fail_once=True) handle.CloseDesktop = handle.Close desktop = PrivateDesktop('private', enabled=True) desktop._handle = handle with pytest.raises(TaskCenterError, match='close failed'): desktop.close() assert desktop._handle is handle desktop.close() assert handle.closed and desktop._handle is None def test_descendant_handles_are_owned_before_terminating_the_job(): api, events, _state, *_ = native_api() api.job.JobObjectBasicProcessIdList = 3 query = api.job.QueryInformationJobObject api.job.QueryInformationJobObject = lambda job, kind: [42, 43] if kind == 3 else query(job, kind) def open_child(_access, _inherit, pid): events.append(('open-child', pid)) return Handle('child', events) api.open_process = open_child process = api.create_process(('python.exe',), 'winsta0\\private', None, None) desktop = PrivateDesktop('private', enabled=True) desktop._processes = [process] desktop.close() assert events.index(('open-child', 43)) < events.index(('terminate',)) assert ('close', 'child') in events @pytest.mark.parametrize('child_exit_after', [0.5, None]) def test_completed_root_gives_owned_descendants_bounded_natural_exit_grace(monkeypatch, child_exit_after): from dx_productivity.trial_task_center import isolated_desktop as module api, events, state, *_ = native_api() clock = [0.0] monkeypatch.setattr(module.time, 'monotonic', lambda: clock[0]) monkeypatch.setattr(module.time, 'sleep', lambda seconds: clock.__setitem__(0, clock[0] + seconds)) state['running'] = False child = Handle('child', events) child_running = lambda: not any(event[0] == 'terminate' for event in events) and ( child_exit_after is None or clock[0] < child_exit_after) api.job.JobObjectBasicProcessIdList = 3 api.job.QueryInformationJobObject = lambda job, kind: ( {'BasicLimitInformation': {'LimitFlags': 0}} if kind == 9 else ([43] if child_running() else []) if kind == 3 else {'ActiveProcesses': int(child_running())}) api.open_process = lambda *_args: child root_wait = api.event.WaitForSingleObject api.event.WaitForSingleObject = lambda handle, timeout: ( 258 if child_running() else 0) if handle is child else root_wait(handle, timeout) process = api.create_process(('python.exe',), 'winsta0\\private', None, None) process.close() assert child.closed if child_exit_after is not None: assert child_exit_after <= clock[0] < 2 assert ('terminate',) not in events assert process.cleanup_record['forced_termination'] is False assert process.cleanup_record['forced_descendant_pids'] == [] else: assert 2 <= clock[0] < 2.1 assert ('terminate',) in events assert process.cleanup_record['forced_termination'] is True assert process.cleanup_record['forced_root_termination'] is False assert process.cleanup_record['forced_descendant_pids'] == [43] assert process.cleanup_record['termination_reason'] == 'descendant_grace_expired' def test_completed_root_without_descendants_has_no_grace_delay(monkeypatch): from dx_productivity.trial_task_center import isolated_desktop as module api, events, state, *_ = native_api() state['running'] = False monkeypatch.setattr(module.time, 'sleep', lambda seconds: pytest.fail('empty job must not wait')) process = api.create_process(('python.exe',), 'winsta0\\private', None, None) process.close() assert ('terminate',) not in events assert process.cleanup_record['forced_termination'] is False def test_active_root_cleanup_is_forced_without_descendant_grace(monkeypatch): from dx_productivity.trial_task_center import isolated_desktop as module api, events, *_ = native_api() monkeypatch.setattr(module.time, 'sleep', lambda seconds: pytest.fail('active root must be bounded immediately')) process = api.create_process(('python.exe',), 'winsta0\\private', None, None) process.close() assert process.cleanup_record['forced_termination'] is True assert process.cleanup_record['forced_root_termination'] is True assert process.cleanup_record['termination_reason'] == 'root_process_active' def test_native_poll_error_still_terminates_owned_root_and_records_force(): api, events, state, *_ = native_api() wait = api.event.WaitForSingleObject def failing_poll(handle, timeout): if timeout == 0 and state['running']: raise OSError('native poll failed') return wait(handle, timeout) api.event.WaitForSingleObject = failing_poll process = api.create_process(('python.exe',), 'winsta0\\private', None, None) with pytest.raises(TaskCenterError, match='native poll failed'): process.close() assert state['running'] is False assert process.cleanup_record['forced_root_termination'] is True def test_failed_job_cleanup_retains_ownership_until_retry(monkeypatch): from dx_productivity.trial_task_center import isolated_desktop as module api, events, state, root, job = native_api() clock = [0.0] monkeypatch.setattr(module.time, 'monotonic', lambda: clock[0]) monkeypatch.setattr(module.time, 'sleep', lambda seconds: clock.__setitem__(0, clock[0] + seconds)) api.job.TerminateJobObject = lambda *_args: (_ for _ in ()).throw(OSError('job termination failed')) query = api.job.QueryInformationJobObject child_running = [True] api.job.QueryInformationJobObject = lambda handle, kind: ( {'ActiveProcesses': int(state['running']) + int(child_running[0])} if kind == 1 else query(handle, kind)) process = api.create_process(('python.exe',), 'winsta0\\private', None, None) with pytest.raises(TaskCenterError, match='descendants did not exit'): process.close() assert not job.closed and process.job is job child_running[0] = False process.close() assert job.closed @pytest.mark.parametrize('error_code', [87, 5]) def test_native_descendant_open_error_only_ignores_already_exited_process(error_code): # pywintypes.error derives directly from Exception, rather than OSError. class NativeError(Exception): pass error = NativeError(error_code, 'OpenProcess', 'native process open failed') api, events, _state, *_ = native_api() api.job.JobObjectBasicProcessIdList = 3 query = api.job.QueryInformationJobObject api.job.QueryInformationJobObject = lambda job, kind: [43] if kind == 3 else query(job, kind) def open_child(*_args): raise error api.open_process = open_child process = api.create_process(('python.exe',), 'winsta0\\private', None, None) if error_code == 87: process._remember_descendants() assert process._descendant_handles == [] else: with pytest.raises(NativeError) as caught: process._remember_descendants() assert caught.value is error def test_forced_job_preserves_partial_current_descendant_snapshot_after_open_failure(): api, events, state, *_ = native_api() api.job.JobObjectBasicProcessIdList = 3 query = api.job.QueryInformationJobObject snapshot = [45] api.job.QueryInformationJobObject = lambda job, kind: list(snapshot) if kind == 3 else query(job, kind) def open_child(_access, _inherit, pid): if pid == 44: raise OSError(5, 'child access denied') return Handle('child-' + str(pid), events) api.open_process = open_child process = api.create_process(('python.exe',), 'winsta0\\private', None, None) # PID 45 was observed earlier but is no longer part of the active Job. process._remember_descendants() snapshot[:] = [42, 43, 44] with pytest.raises(TaskCenterError, match='child access denied'): process.close() assert state['running'] is False assert process.cleanup_record['forced_termination'] is True assert process.cleanup_record['forced_descendant_pids'] == [43] assert process.cleanup_record['descendant_pids'] == [43, 45] assert process.cleanup_record['job_handle_closed'] is True def test_unconfirmed_descendant_exit_retains_handle_for_cleanup_retry(): api, events, state, *_ = native_api() process = api.create_process(('python.exe',), 'winsta0\\private', None, None) child = Handle('child', events) process._descendant_handles = [child] original_wait = api.event.WaitForSingleObject pending = {'child': True} api.event.WaitForSingleObject = lambda handle, timeout: ( 258 if handle is child and pending['child'] else original_wait(handle, timeout)) with pytest.raises(TaskCenterError, match='descendant exit'): process.close() assert not child.closed pending['child'] = False process.close() assert child.closed @pytest.mark.skipif(os.name != 'nt', reason='native Windows job descendant cleanup') @pytest.mark.parametrize('parent_exits', [True, False]) def test_native_private_job_kills_descendant_after_root_exit(parent_exits): import win32api import win32event import win32service import pywintypes name = 'dx-test-' + uuid4().hex child_handle = None try: with PrivateDesktop(name, enabled=True) as desktop: process = desktop.start_process(( sys.executable, '-c', "import subprocess,sys,time; p=subprocess.Popen([sys.executable,'-c','import time;time.sleep(60)']); print(p.pid,flush=True)" + ('' if parent_exits else '; time.sleep(60)'), ), stdout=subprocess.PIPE, stderr=subprocess.PIPE) child_pid = int(process.stdout.readline()) child_handle = win32api.OpenProcess(0x100000, False, child_pid) if parent_exits: assert process.wait(timeout=5) == 0 assert win32event.WaitForSingleObject(child_handle, 0) == 0 assert process.cleanup_record['forced_termination'] is True assert process.cleanup_record['forced_root_termination'] is (not parent_exits) assert child_pid in process.cleanup_record['forced_descendant_pids'] with pytest.raises(pywintypes.error): unexpected = win32service.OpenDesktop(name, 0, False, 1) unexpected.CloseDesktop() finally: if child_handle is not None: child_handle.Close() @pytest.mark.skipif(os.name != 'nt', reason='native Windows descendant shutdown grace') def test_native_private_job_allows_descendant_to_finish_after_root_exit(): import win32api import win32event import win32process child_handle = None try: with PrivateDesktop('dx-test-' + uuid4().hex, enabled=True) as desktop: process = desktop.start_process((sys.executable, '-c', "import subprocess,sys; p=subprocess.Popen([sys.executable,'-c','import time;time.sleep(0.5)']); print(p.pid,flush=True)"), stdout=subprocess.PIPE, stderr=subprocess.PIPE) child_pid = int(process.stdout.readline()) child_handle = win32api.OpenProcess(0x100000 | 0x1000, False, child_pid) assert process.wait(timeout=5) == 0 assert win32event.WaitForSingleObject(child_handle, 0) == 0 assert win32process.GetExitCodeProcess(child_handle) == 0 assert process.cleanup_record['forced_termination'] is False assert process.cleanup_record['forced_descendant_pids'] == [] assert desktop.cleanup_record['desktop_confirmation']['released'] is True finally: if child_handle is not None: child_handle.Close()