import io import json import os import subprocess import weakref from pathlib import Path from threading import Event from threading import Timer from threading import Thread from types import SimpleNamespace from traceback import extract_tb import pytest from dx_productivity.trial_task_center import isolated_cad as runtime from dx_productivity.trial_task_center.worker_monitor import WorkerMonitorError @pytest.mark.skipif(os.name != 'nt', reason='Windows COM helper boundary') @pytest.mark.parametrize('failure', [None, 'open_project', 'quit', 'guid', 'cause', 'context']) def test_quit_helper_releases_application_before_com_uninitialization(monkeypatch, tmp_path, failure): import pythoncom import win32com.client from dx_productivity.trial_task_center import cad_identity references = [] alive_at_uninitialize = [] def nested_failure(app): raise ValueError('nested quit error') class Application: def Guid(self): return '{foreign}' if failure == 'guid' else '{owned}' def Quit(self): if failure == 'quit': raise RuntimeError('quit refused') if failure in ('cause', 'context'): try: nested_failure(self) except ValueError as error: if failure == 'cause': raise RuntimeError('quit refused') from error raise RuntimeError('quit refused') def attach(_name): app = Application() references.append(weakref.ref(app)) return app monkeypatch.setattr(pythoncom, 'CoInitialize', lambda: None) monkeypatch.setattr(pythoncom, 'CoUninitialize', lambda: alive_at_uninitialize.append(references[0]() is not None)) monkeypatch.setattr(win32com.client, 'GetActiveObject', attach) monkeypatch.setattr(runtime, 'current_desktop_name', lambda: 'dx-test') monkeypatch.setattr(cad_identity, 'current_desktop_name', lambda: 'dx-test') monkeypatch.setattr(runtime, 'project_file_path', lambda app: 'open.prj' if failure == 'open_project' else '') for key, value in dict(DXPART_DESKTOP='dx-test', DXPART_CAD_PID='123', DXPART_CAD_GUID='{owned}', DXPART_SESSION_TOKEN='a' * 32).items(): monkeypatch.setenv(key, value) if failure == 'open_project': with pytest.raises(ValueError, match='still has a project open'): runtime._native_action('quit', tmp_path / 'evidence.json', 123) elif failure == 'guid': with pytest.raises(ValueError, match='GUID does not match'): runtime._native_action('quit', tmp_path / 'evidence.json', 123) elif failure: with pytest.raises(RuntimeError, match='quit refused') as caught: runtime._native_action('quit', tmp_path / 'evidence.json', 123) assert 'Quit' in [frame.name for frame in extract_tb(caught.value.__traceback__)] if failure in ('cause', 'context'): assert str(caught.value.__context__) == 'nested quit error' assert 'nested_failure' in [frame.name for frame in extract_tb(caught.value.__context__.__traceback__)] if failure == 'cause': assert str(caught.value.__cause__) == 'nested quit error' else: assert runtime._native_action('quit', tmp_path / 'evidence.json', 123) == 0 assert alive_at_uninitialize == [False] @pytest.mark.skipif(os.name != 'nt', reason='Windows junction path handling') def test_private_evidence_uses_canonical_root_behind_a_legacy_alias(tmp_path): from dx_productivity.trial_task_center.legacy_paths import _AliasPool root = tmp_path / ('nested-' + 'x' * 90) / ('nested-' + 'y' * 90) root.mkdir(parents=True) pool = _AliasPool() try: alias = pool.alias(root.resolve()) session = runtime.IsolatedCadSession(alias) session._record(state='starting') assert session.root == root.resolve() assert (root / 'private-desktop-sessions' / (session.token + '.json')).is_file() finally: assert not pool.close() @pytest.mark.skipif(os.name != 'nt', reason='Windows state-file sharing semantics') def test_private_record_survives_a_reader_temporarily_denying_replacement(tmp_path): import win32con import win32file session = runtime.IsolatedCadSession(tmp_path) session._record(state='starting') held = win32file.CreateFile(str(tmp_path / 'private-desktop.json'), win32con.GENERIC_READ, win32con.FILE_SHARE_READ, None, win32con.OPEN_EXISTING, 0, None) reader_done = Timer(0.1, held.Close) reader_done.start() try: session._record(state='released', clean=True) finally: reader_done.join() current = json.loads((tmp_path / 'private-desktop.json').read_text()) archived = json.loads((tmp_path / 'private-desktop-sessions' / (session.token + '.json')).read_text()) assert current == archived and current['state'] == 'released' and current['clean'] @pytest.mark.skipif(os.name != 'nt', reason='Windows state-file sharing semantics') def test_private_record_reports_persistent_denial_and_keeps_previous_record(tmp_path): import win32con import win32file session = runtime.IsolatedCadSession(tmp_path) session._record(state='starting') held = win32file.CreateFile(str(tmp_path / 'private-desktop.json'), win32con.GENERIC_READ, win32con.FILE_SHARE_READ, None, win32con.OPEN_EXISTING, 0, None) try: with pytest.raises(PermissionError): session._record(state='released', clean=True) assert json.loads((tmp_path / 'private-desktop.json').read_text())['state'] == 'starting' finally: held.Close() def fake_desktop(monkeypatch, tmp_path, *, abort=None, quit_code=0, cad_exit_code=0): events = [] cad = SimpleNamespace(pid=123, returncode=None) cad.poll = lambda: cad.returncode cad.wait = lambda timeout: cad.returncode class Desktop: def __init__(self, name, **kwargs): self.name = name def __enter__(self): events.append('create') return self def start_process(self, command, **kwargs): events.append(command[0]) if command[0] == 'cad.exe': return cad action, path, pid = command if action == 'probe': Path(path).write_text(json.dumps({'desktop': self.name, 'pid': pid, 'guid': '{owned}', 'token': kwargs['env']['DXPART_SESSION_TOKEN']})) if abort is not None: abort.set() else: cad.returncode = cad_exit_code return SimpleNamespace(poll=lambda: None if abort is not None else 0, wait=lambda timeout: quit_code, close=lambda: events.append('close-helper'), stderr=io.BytesIO(b'project still open')) def close(self): events.append(('release', (tmp_path / 'uncertain.flag').exists())) cad.returncode = 1 if cad.returncode is None else cad.returncode monkeypatch.setattr(runtime, 'PrivateDesktop', Desktop) monkeypatch.setattr(runtime, '_designer_executable', lambda: 'cad.exe') monkeypatch.setattr(runtime, '_helper_command', lambda action, path, pid: (action, str(path), pid)) return events, cad def test_success_quits_owned_cad_before_releasing_desktop(monkeypatch, tmp_path): events, cad = fake_desktop(monkeypatch, tmp_path) with runtime.IsolatedCadSession(tmp_path): assert cad.poll() is None assert events.index('quit') < events.index(('release', False)) record = json.loads((tmp_path / 'private-desktop.json').read_text()) assert record['state'] == 'released' and record['clean'] def test_cleanup_preserves_orderly_exit_failure_before_desktop_failure(monkeypatch, tmp_path): fake_desktop(monkeypatch, tmp_path, quit_code=1) session = runtime.IsolatedCadSession(tmp_path) session.__enter__() def failed_release(): raise OSError('owned desktop still exists after cleanup') session.desktop.close = failed_release with pytest.raises(WorkerMonitorError) as caught: session.__exit__(None, None, None) record = json.loads((tmp_path / 'private-desktop.json').read_text()) assert 'refused orderly exit' in record['error'] assert 'desktop still exists' in record['error'] assert 'refused orderly exit' in str(caught.value) assert [item['stage'] for item in record['cleanup_errors']] == ['orderly_shutdown', 'desktop_release'] assert record['quit_helper_exit_code'] == 1 assert record['shutdown_seconds'] >= 0 assert record['state'] == 'uncertain' and (tmp_path / 'uncertain.flag').exists() def test_clean_release_records_helper_and_cad_exit_codes(monkeypatch, tmp_path): fake_desktop(monkeypatch, tmp_path) with runtime.IsolatedCadSession(tmp_path): pass record = json.loads((tmp_path / 'private-desktop.json').read_text()) assert record['quit_helper_exit_code'] == 0 and record['cad_exit_code'] == 0 assert record['cleanup_errors'] == [] @pytest.mark.parametrize('persistent', [False, True]) def test_closing_journal_failure_still_quits_and_reports_diagnostic_error(monkeypatch, tmp_path, persistent): events, cad = fake_desktop(monkeypatch, tmp_path) session = runtime.IsolatedCadSession(tmp_path) session.__enter__() record = session._record def failing_record(**values): if persistent or values.get('state') == 'closing': raise PermissionError('closing journal locked') record(**values) session._record = failing_record with pytest.raises(WorkerMonitorError, match='closing journal locked'): session.__exit__(None, None, None) assert 'quit' in events and cad.returncode == 0 assert session.record['orderly_shutdown'] is True assert session.record['clean'] is False assert session.record['diagnostic_errors'][0]['stage'] == 'closing_record' assert (tmp_path / 'uncertain.flag').exists() @pytest.mark.parametrize('helper_failure', ['refused', 'timeout']) def test_interactive_quit_failure_retains_cad_and_helper_until_explicit_force(monkeypatch, tmp_path, helper_failure): from dx_productivity.trial_task_center.stop_control import StopControl from dx_productivity.trial_task_center import worker_monitor events, cad = fake_desktop(monkeypatch, tmp_path, quit_code=1, cad_exit_code=None) control = StopControl() session = runtime.IsolatedCadSession(tmp_path, stop_control=control) session.__enter__() start = session.desktop.start_process def start_quit(command, **options): helper = start(command, **options) if command[0] == 'quit': if helper_failure == 'timeout': helper.wait = lambda timeout: (_ for _ in ()).throw(subprocess.TimeoutExpired('quit', timeout)) helper.poll = lambda: None helper.close = lambda: events.append('close-quit-helper') return helper session.desktop.start_process = start_quit waiting, finished = Event(), Event() publish = worker_monitor._publish_progress def observe_wait(path, snapshot): publish(path, snapshot) if snapshot.get('stage') == 'awaiting_reconciliation': waiting.set() monkeypatch.setattr(worker_monitor, '_publish_progress', observe_wait) failures = [] def close_session(): try: session.__exit__(None, None, None) except Exception as failure: failures.append(failure) finally: finished.set() thread = Thread(target=close_session) thread.start() try: assert waiting.wait(1), 'failed Quit must enter protected waiting before resource release' control.set() assert not finished.wait(.05) assert cad.poll() is None assert 'close-quit-helper' not in events assert not any(isinstance(event, tuple) and event[0] == 'release' for event in events) assert (tmp_path / 'uncertain.flag').exists() control.request_force() assert finished.wait(2) assert 'close-quit-helper' in events and ('release', True) in events assert cad.poll() == 1 assert isinstance(failures[0], WorkerMonitorError) assert 'forced' in str(failures[0]) assert session.record['orderly_shutdown'] is False and session.record['clean'] is False finally: control.request_force() thread.join(3) @pytest.mark.parametrize('failure', ['cad_exited', 'diagnostic']) def test_interactive_exit_does_not_hold_completed_cad_for_resolution(monkeypatch, tmp_path, failure): from dx_productivity.trial_task_center.stop_control import StopControl from dx_productivity.trial_task_center import stop_control events, _cad = fake_desktop(monkeypatch, tmp_path, quit_code=1 if failure == 'cad_exited' else 0) session = runtime.IsolatedCadSession(tmp_path, stop_control=StopControl()) session.__enter__() monkeypatch.setattr(stop_control, 'wait_for_resolution', lambda *_args: pytest.fail('exited CAD must not wait')) if failure == 'diagnostic': record = session._record def failed_journal(**values): if values.get('state') == 'closing': raise PermissionError('closing diagnostic unavailable') record(**values) session._record = failed_journal with pytest.raises(WorkerMonitorError): session.__exit__(None, None, None) assert ('release', True) in events def test_forced_descendant_cleanup_is_not_reported_as_clean_orderly_shutdown(monkeypatch, tmp_path): fake_desktop(monkeypatch, tmp_path) session = runtime.IsolatedCadSession(tmp_path) session.__enter__() release = session.desktop.close def forced_release(): release() session.desktop.cleanup_record = {'processes': [{'pid': 123, 'forced_termination': True, 'forced_root_termination': False, 'termination_reason': 'descendant_grace_expired', 'forced_descendant_pids': [456]}]} session.desktop.close = forced_release with pytest.raises(WorkerMonitorError, match='forced'): session.__exit__(None, None, None) record = json.loads((tmp_path / 'private-desktop.json').read_text()) assert record['clean'] is False and record['forced_termination'] is True assert record['orderly_shutdown'] is True assert record['forced_descendant_pids'] == [456] assert record['termination_reason'] == 'descendant_grace_expired' def test_exit_code_diagnostics_do_not_interrupt_the_normal_cad_wait(monkeypatch, tmp_path): _, cad = fake_desktop(monkeypatch, tmp_path) waited = [] cad.wait = lambda timeout: waited.append(timeout) or 0 session = runtime.IsolatedCadSession(tmp_path) record = session._record def unavailable_during_shutdown(**values): if 'quit_helper_exit_code' in values and not waited: raise PermissionError('diagnostic file temporarily locked before CAD exit') record(**values) session._record = unavailable_during_shutdown with session: pass assert waited == [15] assert session.record['clean'] @pytest.mark.parametrize('ready_after', [90, None]) def test_slow_startup_is_bounded_and_cleanup_remains_owned(monkeypatch, tmp_path, ready_after): events, _ = fake_desktop(monkeypatch, tmp_path) clock = [0.0] monkeypatch.setattr(runtime.time, 'monotonic', lambda: clock[0]) monkeypatch.setattr(runtime.time, 'sleep', lambda seconds: clock.__setitem__(0, clock[0] + seconds)) original = runtime.PrivateDesktop.start_process def start(self, command, **kwargs): process = original(self, command, **kwargs) if command[0] == 'probe': process.poll = lambda: 0 if ready_after is not None and clock[0] >= ready_after else None return process monkeypatch.setattr(runtime.PrivateDesktop, 'start_process', start) if ready_after is None: with pytest.raises(runtime.PrivateCadStartupError, match='bootstrap timed out'): with runtime.IsolatedCadSession(tmp_path): pytest.fail('unresponsive startup entered project work') assert 119 <= clock[0] <= 121 assert ('release', False) in events else: with runtime.IsolatedCadSession(tmp_path): assert clock[0] >= ready_after assert ('release', False) in events def test_owned_cad_exit_does_not_wait_for_unresponsive_startup_probe(monkeypatch, tmp_path): events, cad = fake_desktop(monkeypatch, tmp_path) clock = [0.0] monkeypatch.setattr(runtime.time, 'monotonic', lambda: clock[0]) monkeypatch.setattr(runtime.time, 'sleep', lambda seconds: clock.__setitem__(0, clock[0] + seconds)) original = runtime.PrivateDesktop.start_process def start(self, command, **kwargs): process = original(self, command, **kwargs) if command[0] == 'probe': cad.returncode = 73 process.poll = lambda: None return process monkeypatch.setattr(runtime.PrivateDesktop, 'start_process', start) with pytest.raises(runtime.PrivateCadStartupError, match='exited during startup.*73'): with runtime.IsolatedCadSession(tmp_path): pytest.fail('exited CAD must never enter project work') assert clock[0] < 1 assert events.index('close-helper') < events.index(('release', False)) def test_repeated_session_preserves_prior_release_evidence(monkeypatch, tmp_path): fake_desktop(monkeypatch, tmp_path) with runtime.IsolatedCadSession(tmp_path) as first: first_token = first.token fake_desktop(monkeypatch, tmp_path) with runtime.IsolatedCadSession(tmp_path): pass records = [json.loads(path.read_text()) for path in (tmp_path / 'private-desktop-sessions').glob('*.json')] assert len(records) == 2 and first_token in {row['token'] for row in records} assert all(row['state'] == 'released' and row['clean'] for row in records) def test_hidden_private_action_dispatches_without_opening_gui(monkeypatch, tmp_path): from dx_productivity.trial_task_center import application def forbidden(*args, **kwargs): pytest.fail('private CAD helper must not initialize the GUI') monkeypatch.setattr(application, 'QApplication', forbidden) calls = [] monkeypatch.setattr(runtime, 'native_action', lambda *args: calls.append(args) or 0) path = tmp_path / 'evidence.json' assert application.main(['--private-cad-action', 'probe', '--private-cad-evidence', str(path), '--private-cad-pid', '123']) == 0 assert calls == [('probe', path, 123)] assert application.main(['--private-cad-action', 'probe']) == 2 def test_private_helper_works_when_application_is_the_executable_entry_script(monkeypatch, tmp_path): import runpy import sys from dx_productivity.trial_task_center import application calls = [] monkeypatch.setattr(runtime, 'native_action', lambda *args: calls.append(args) or 0) evidence = tmp_path / 'binding.json' monkeypatch.setattr(sys, 'argv', [application.__file__, '--private-cad-action', 'probe', '--private-cad-evidence', str(evidence), '--private-cad-pid', '123']) with pytest.raises(SystemExit) as result: runpy.run_path(application.__file__, run_name='__main__') assert result.value.code == 0 assert calls == [('probe', evidence, 123)] def test_startup_cancellation_releases_without_waiting_for_com_timeout(monkeypatch, tmp_path): abort = Event() events, _ = fake_desktop(monkeypatch, tmp_path, abort=abort) with pytest.raises(WorkerMonitorError, match='cancelled'): with runtime.IsolatedCadSession(tmp_path, abort_event=abort): pytest.fail('cancelled startup entered replacement body') assert 'quit' not in events assert ('release', False) in events def test_startup_cleanup_failure_keeps_uncertain_lock(monkeypatch, tmp_path): abort = Event() fake_desktop(monkeypatch, tmp_path, abort=abort) session = runtime.IsolatedCadSession(tmp_path, abort_event=abort) def failure(): raise OSError('owned process did not exit') session.desktop.close = failure with pytest.raises(WorkerMonitorError, match='cleanup requires reconciliation'): session.__enter__() assert (tmp_path / 'uncertain.flag').exists() def test_released_startup_failure_returns_retryable_pre_mutation_code(monkeypatch, tmp_path): class FailedStartup: def __init__(self, *args, **kwargs): pass def __enter__(self): raise runtime.PrivateCadStartupError('startup cancelled before project launch') def __exit__(self, *args): pytest.fail('failed enter must not enter execution') monkeypatch.setattr(runtime, 'IsolatedCadSession', FailedStartup) result = runtime.run_isolated_process(('cscript.exe', '//nologo', 'helper.vbs', str(tmp_path)), 1) assert result.returncode == 2 assert 'before project launch' in result.stderr assert not (tmp_path / 'uncertain.flag').exists() def test_released_startup_identity_conflict_is_not_a_retryable_exit(monkeypatch, tmp_path): class FailedIdentity: def __init__(self, *args, **kwargs): pass def __enter__(self): raise runtime.PrivateCadIdentityError('bootstrap returned a foreign identity') def __exit__(self, *args): pytest.fail('failed identity must not enter execution') monkeypatch.setattr(runtime, 'IsolatedCadSession', FailedIdentity) with pytest.raises(runtime.CadIdentityConflict): runtime.run_isolated_process(('cscript.exe', '//nologo', 'helper.vbs', str(tmp_path)), 1) @pytest.mark.parametrize('failure', ['quit', 'cad_exit', 'unexpected_exit']) def test_uncertain_cleanup_is_durable_before_forced_owned_release(monkeypatch, tmp_path, failure): events, cad = fake_desktop(monkeypatch, tmp_path, quit_code=1 if failure == 'quit' else 0, cad_exit_code=7 if failure == 'cad_exit' else 0) with pytest.raises(WorkerMonitorError, match='reconciliation'): with runtime.IsolatedCadSession(tmp_path): if failure == 'unexpected_exit': cad.returncode = 9 assert ('release', True) in events assert not json.loads((tmp_path / 'private-desktop.json').read_text())['clean'] def test_single_step_backup_precedes_discovery_and_failure_blocks_discovery(monkeypatch, tmp_path): from dx_productivity.trial_task_center import single_step events = [] preparer = SimpleNamespace(data_root=tmp_path, progress=lambda *args, **kwargs: SimpleNamespace(queue_complete=False, next_project_path=tmp_path / 'one.prj'), ensure_batch_handoff=lambda *args, **kwargs: events.append('discover')) monkeypatch.setattr(single_step, 'create_schematic_backup', lambda *args: events.append('backup')) single_step.prepare_private_single_step(preparer, 'task', (), (), False) assert events == ['backup', 'discover'] def failed_backup(*args): raise OSError('backup failed') monkeypatch.setattr(single_step, 'create_schematic_backup', failed_backup) events.clear() with pytest.raises(OSError, match='backup failed'): single_step.prepare_private_single_step(preparer, 'task', (), (), False) assert not events