from types import SimpleNamespace import pytest from test_desktop_slot import Backend, slot from dx_productivity.trial_task_center.isolated_desktop import PrivateDesktop from dx_productivity.trial_task_center.errors import TaskCenterError class Api: def __init__(self, backend): self.backend = backend; self.launches = [] def create_desktop(self, name): self.backend.exists = True return SimpleNamespace(CloseDesktop=lambda: None) def create_process(self, command, desktop, cwd, env, **options): self.launches.append(options['job_name']) return SimpleNamespace(pid=200, handle=None, poll=lambda: 0, close=lambda: None, wait=lambda **options: 0, cleanup_record={}) def test_managed_desktop_returns_external_residue_and_old_close_cannot_touch_new_owner(tmp_path): backend = Backend(); api = Api(backend) first = PrivateDesktop('ignored', enabled=True, api=api, slot=slot(tmp_path, backend)) first.__enter__(); first.close() assert first.cleanup_record['desktop_confirmation']['released'] is False assert first.cleanup_record['desktop_lease']['returned'] is True second = PrivateDesktop('another-task', enabled=True, api=api, slot=slot(tmp_path, backend)) second.__enter__() assert second.name == first.name first.close() assert backend.locked second.close() def test_managed_launch_uses_durable_named_job_and_keeps_failed_launch_unresolved(tmp_path): backend = Backend(); api = Api(backend) current = PrivateDesktop('ignored', enabled=True, api=api, slot=slot(tmp_path, backend)) current.__enter__() def failed(*args, **options): assert current._slot.record['launches'][0]['job'] == options['job_name'] raise OSError('unknown create boundary') api.create_process = failed with pytest.raises(OSError): current.start_process(('worker',)) with pytest.raises(TaskCenterError): current.close() assert backend.locked def test_managed_launch_cleanup_allows_return_only_after_job_exit(tmp_path, monkeypatch): from dx_productivity.trial_task_center import batch_resources backend = Backend(); api = Api(backend) current = PrivateDesktop('ignored', enabled=True, api=api, slot=slot(tmp_path, backend)) monkeypatch.setattr(batch_resources, 'process_identity', lambda process: {'pid': process.pid, 'creation_time': 'worker-200'}) current.__enter__() current.start_process(('worker',)) assert api.launches == [current._slot.record['launches'][0]['job']] current.close() assert not backend.locked def test_runtime_publishes_actual_managed_name_before_starting_a_worker(tmp_path): from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime backend = Backend(); api = Api(backend) def factory(requested, **options): return PrivateDesktop(requested, **options, api=api, slot=slot(tmp_path / 'slot', backend)) runtime = BatchCadRuntime(tmp_path / 'data', 'execution', desktop_factory=factory) desktop = runtime._ensure_desktop() assert runtime.record['desktop'] == desktop.name runtime.close() @pytest.mark.parametrize('confirmation', [{'released': False}, None]) def test_catalog_accepts_intact_return_without_claiming_desktop_disappearance(tmp_path, confirmation): from dx_productivity.trial_task_center.cell_catalog import _require_cleanup backend = Backend(); current = slot(tmp_path, backend).acquire() receipt = current.release(desktop_disappeared=False) cleanup = dict(desktop=current.name, desktop_handle_closed=True, owned_cleanup_complete=True, errors=[], desktop_confirmation=confirmation, desktop_lease=receipt, processes=[dict(errors=[], job_active_processes=0, process_handle_closed=True, job_handle_closed=True)]) _require_cleanup(cleanup) cleanup['desktop_lease'] = dict(receipt, lease_id='forged') with pytest.raises(TaskCenterError): _require_cleanup(cleanup) def test_mutex_release_error_preserves_the_durably_returned_lease(tmp_path): from dx_productivity.trial_task_center import batch_resources from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime class ReleaseErrorBackend(Backend): def unlock(self, handle): super().unlock(handle) raise OSError('mutex release failed') backend = ReleaseErrorBackend() api = Api(backend) def factory(name, **options): return PrivateDesktop(name, **options, api=api, slot=slot(tmp_path / 'slot', backend)) runtime = BatchCadRuntime(tmp_path / 'data', 'execution', desktop_factory=factory) with runtime: with runtime.native_scope(tmp_path / 'operation'): pass record = batch_resources.pending_resources(runtime.root)[0] assert record['state'] == 'isolated' and record['blocking'] is False assert record['cleanup']['desktop_lease']['returned'] is True assert 'mutex release failed' in record['isolation_warning'] next_owner = slot(tmp_path / 'slot', backend).acquire() with pytest.raises(OSError, match='mutex release failed'): next_owner.release(desktop_disappeared=False) assert next_owner.handle is None def test_failed_lease_return_stays_blocking_until_the_slot_can_be_returned(tmp_path, monkeypatch): from dx_productivity.trial_task_center import batch_resources from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime backend = Backend() api = Api(backend) def factory(name, **options): return PrivateDesktop(name, **options, api=api, slot=slot(tmp_path / 'slot', backend)) def fail_return(*args): raise OSError('desktop observation unavailable') runtime = BatchCadRuntime(tmp_path / 'data', 'execution', desktop_factory=factory) with pytest.raises(TaskCenterError, match='desktop observation unavailable'): with runtime: with runtime.native_scope(tmp_path / 'operation'): monkeypatch.setattr(backend, 'desktop_exists', fail_return) assert backend.locked and batch_resources.blocking_resources(runtime.root) monkeypatch.undo() batch_resources.cleanup_pending_resources(runtime.root, retry_failed=True) assert not backend.locked assert batch_resources.blocking_resources(runtime.root) == () def test_failed_owned_handle_cleanup_keeps_slot_until_cleanup_succeeds(tmp_path, monkeypatch): from dx_productivity.trial_task_center import batch_resources backend = Backend(); api = Api(backend) current = PrivateDesktop('ignored', enabled=True, api=api, slot=slot(tmp_path, backend)) monkeypatch.setattr(batch_resources, 'process_identity', lambda process: {'pid': process.pid, 'creation_time': 'worker-200'}) current.__enter__(); process = current.start_process(('worker',)) process.close = lambda: (_ for _ in ()).throw(OSError('Job handle not closed')) with pytest.raises(TaskCenterError): current.close() assert backend.locked process.close = lambda: None current.close() assert not backend.locked def test_resource_recheck_never_queries_a_reused_desktop_for_a_returned_lease(tmp_path, monkeypatch): from dx_productivity.trial_task_center import batch_resources, isolated_desktop from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime backend = Backend(); api = Api(backend) def factory(name, **options): return PrivateDesktop(name, **options, api=api, slot=slot(tmp_path / 'slot', backend)) runtime = BatchCadRuntime(tmp_path / 'data', 'execution', desktop_factory=factory) runtime._ensure_desktop(); runtime.close() assert runtime.record['state'] == 'isolated' next_owner = slot(tmp_path / 'slot', backend).acquire() from dx_productivity.trial_task_center import desktop_slot monkeypatch.setattr(desktop_slot, 'managed_desktop_disappeared', lambda receipt: False) def forbidden(*args): pytest.fail('old batch queried the currently leased desktop') monkeypatch.setattr(isolated_desktop, '_Win32Api', forbidden) warnings = batch_resources.cleanup_pending_resources(runtime.root) assert warnings and warnings[0]['blocking'] is False next_owner.release(desktop_disappeared=False) def test_failed_acquisition_cleanup_does_not_release_another_owner(tmp_path): backend = Backend(); api = Api(backend) first = PrivateDesktop('ignored', enabled=True, api=api, slot=slot(tmp_path, backend)) first.__enter__() second = PrivateDesktop('ignored', enabled=True, api=api, slot=slot(tmp_path, backend)) with pytest.raises(TaskCenterError): second.__enter__() second.close() assert backend.locked and second.cleanup_record['desktop_not_acquired'] is True first.close() def test_transient_return_proof_read_failure_can_be_rechecked_without_permanent_block(tmp_path, monkeypatch): from dx_productivity.trial_task_center import batch_resources, desktop_slot from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime backend = Backend(); api = Api(backend) def factory(name, **options): return PrivateDesktop(name, **options, api=api, slot=slot(tmp_path / 'slot', backend)) runtime = BatchCadRuntime(tmp_path / 'data', 'execution', desktop_factory=factory) runtime._ensure_desktop(); runtime.close() original = desktop_slot.returned_lease_intact monkeypatch.setattr(desktop_slot, 'managed_desktop_disappeared', lambda receipt: False) monkeypatch.setattr(desktop_slot, 'returned_lease_intact', lambda *args: False) assert batch_resources.cleanup_pending_resources(runtime.root)[0]['blocking'] is True monkeypatch.setattr(desktop_slot, 'returned_lease_intact', original) assert batch_resources.cleanup_pending_resources(runtime.root)[0]['blocking'] is False assert not batch_resources.blocking_resources(runtime.root) def test_native_job_creation_failure_is_certified_before_process_creation(): from dx_productivity.trial_task_center.isolated_desktop import _Win32Api api = _Win32Api.__new__(_Win32Api) api.process = SimpleNamespace(STARTUPINFO=SimpleNamespace) api.con = SimpleNamespace(CREATE_NO_WINDOW=1, CREATE_SUSPENDED=2) def denied(*args): raise OSError('temporary Job allocation failure') api.job = SimpleNamespace(CreateJobObject=denied) with pytest.raises(OSError) as caught: api.create_process(('worker',), 'winsta0\\probe', None, None) assert caught.value.desktop_launch_cleanup_proven is True def test_unsupported_platform_can_construct_evidence_without_win32_identity(monkeypatch): from dx_productivity.trial_task_center import desktop_slot, isolated_desktop monkeypatch.setattr(isolated_desktop, 'os', SimpleNamespace(name='posix')) def forbidden(): pytest.fail('non-Windows evidence construction queried a Windows logon') monkeypatch.setattr(desktop_slot, '_context', forbidden) desktop = PrivateDesktop('dx-evidence', enabled=True, managed=True) assert desktop.name == 'dx-evidence' and desktop._slot is None