Files
dxdesigner-part-replacement/tests/v1_1/test_resource_isolation.py
T
阿白叔 4a438e027b
Core regression / Python core, intervention UI and release configuration (push) Successful in 18m39s
Core regression / JavaScript syntax (push) Successful in 7s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 11m51s
Core regression / JavaScript syntax (pull_request) Successful in 7s
fix: preserve batch receipts and resource recovery after review
2026-11-19 15:24:40 +08:00

165 lines
8.6 KiB
Python

import json
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center import batch_resources, batch_runtime, isolated_desktop
def runtime_with_residual(tmp_path, monkeypatch, *, confirmation=False):
calls = []
class Desktop:
def __init__(self, name, **options):
self.name = name
self._processes = []
self.cleanup_record = None
def __enter__(self): return self
def close(self):
calls.append('close')
self.cleanup_record = {'desktop_handle_closed': True,
'owned_cleanup_complete': True,
'desktop_confirmation': None if confirmation is None else {'released': confirmation},
'errors': ['foreign reference']}
raise OSError('foreign reference')
def release_desktop(self):
calls.append('observe')
raise OSError('foreign reference')
runtime = batch_runtime.BatchCadRuntime(tmp_path, 'execute_task_queue', desktop_factory=Desktop)
runtime.__enter__()
runtime._ensure_desktop()
runtime.result = {'completed': True}
return runtime, calls
@pytest.mark.parametrize('confirmation', [False, None])
def test_residual_desktop_is_warning_admits_fresh_batch_and_never_repeats_close(tmp_path, monkeypatch, confirmation):
runtime, calls = runtime_with_residual(tmp_path, monkeypatch, confirmation=confirmation)
runtime.close()
assert runtime.record['state'] == 'isolated'
assert runtime.record['blocking'] is False
assert runtime.record['release_results']['desktop_released'] is False
assert batch_resources.blocking_resources(tmp_path) == ()
assert batch_resources.pending_resources(tmp_path)[0]['state'] == 'isolated'
with pytest.raises(batch_resources.BatchResourceCleanupError):
runtime._ensure_desktop()
runtime.close()
monkeypatch.setattr(isolated_desktop, '_Win32Api', lambda: SimpleNamespace(
confirm_desktop_released=lambda name: (_ for _ in ()).throw(OSError('foreign reference'))))
batch_resources.cleanup_pending_resources(tmp_path)
assert calls == ['close']
with batch_runtime.BatchCadRuntime(tmp_path, 'next') as admitted:
assert admitted.generation == 0
assert runtime.result == {'completed': True}
def test_isolation_proof_is_revalidated_after_restart_and_does_not_trust_label(tmp_path, monkeypatch):
runtime, _ = runtime_with_residual(tmp_path, monkeypatch)
identity = {'pid': 1234, 'creation_time': 'exact'}
runtime.record['writer_identities'] = [identity]
monkeypatch.setattr(batch_resources, '_process_gone', lambda item: True)
runtime.close()
proof = runtime.record['isolation_proof']
assert proof['processes'] == [identity]
assert proof['session_id'] == runtime.session_id and proof['generation'] == 1
assert batch_resources.blocking_resources(tmp_path) == ()
monkeypatch.setattr(batch_resources, '_process_gone', lambda item: False)
assert batch_resources.blocking_resources(tmp_path)
monkeypatch.setattr(isolated_desktop, '_Win32Api', lambda: SimpleNamespace(confirm_desktop_released=lambda _: None))
assert batch_resources.cleanup_pending_resources(tmp_path)
assert batch_resources.blocking_resources(tmp_path)
monkeypatch.setattr(batch_resources, '_process_gone', lambda item: True)
record = json.loads(runtime.path.read_text(encoding='utf-8'))
record['isolation_proof']['generation'] = 99
batch_resources.write_record(runtime.path, record)
assert batch_resources.blocking_resources(tmp_path)
def test_active_or_unknown_writer_cannot_be_isolated(tmp_path, monkeypatch):
runtime, _ = runtime_with_residual(tmp_path, monkeypatch)
runtime.record['writer_identities'] = [{'pid': 1234, 'creation_time': 'exact'}]
monkeypatch.setattr(batch_resources, '_process_gone', lambda item: False)
with pytest.raises(batch_resources.BatchResourceCleanupError): runtime.close()
assert batch_resources.blocking_resources(tmp_path)
runtime.record['writer_identities'][0]['creation_time'] = None
monkeypatch.setattr(batch_resources, '_process_gone', lambda item: True)
with pytest.raises(batch_resources.BatchResourceCleanupError): runtime.close(reason='manual_retry')
assert batch_resources.blocking_resources(tmp_path)
def test_isolation_log_never_claims_resources_released(tmp_path):
from dx_productivity.trial_task_center.batch_release_log import write_release_event
from dx_productivity.trial_task_center.logging_setup import configure_logging
context = configure_logging(tmp_path)
path = tmp_path / 'batch-resources' / ('a' * 32) / 'session.json'
record = {'session_id': 'a' * 32, 'generation': 1, 'state': 'isolated', 'kind': 'execution'}
assert write_release_event(tmp_path, path, record, 'isolated', context=context) == []
text = path.parent.joinpath('resource-release.log').read_text(encoding='utf-8')
assert 'isolated' in text
def test_passive_disappearance_confirmation_updates_both_release_state_and_result(tmp_path, monkeypatch):
runtime, calls = runtime_with_residual(tmp_path, monkeypatch)
runtime.close()
monkeypatch.setattr(isolated_desktop, '_Win32Api', lambda: SimpleNamespace(confirm_desktop_released=lambda _: None))
assert batch_resources.cleanup_pending_resources(tmp_path) == ()
final = json.loads(runtime.path.read_text(encoding='utf-8'))
assert final['release_results']['desktop_released'] is True
assert final['release_state']['desktop'] == 'released'
assert calls == ['close']
def test_supervisor_preserves_success_and_business_failure_with_nonfatal_desktop_warning(tmp_path, monkeypatch):
from dx_productivity.trial_task_center.batch_supervisor import _finish_response
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.supervisor_protocol import encode, encode_error
from dx_productivity.trial_task_center.errors import TaskCenterError
runtime, _ = runtime_with_residual(tmp_path, monkeypatch)
runtime.close()
warnings = batch_resources.pending_resources(tmp_path)
monkeypatch.setattr(batch_resources, 'cleanup_pending_resources', lambda *args, **kwargs: warnings)
journal = {'operation': 'probe', 'batch_id': runtime.session_id}
result = {'verified': True}
response = {'business_succeeded': True, 'status': 'ok', 'result': encode(result)}
assert _finish_response(tmp_path, journal, response, configure_logging(tmp_path)) == result
assert journal['state'] == 'finished'
assert journal['resource_recheck']['desktop_released'] is False
response = {'business_succeeded': False, 'status': 'error',
'error': encode_error(TaskCenterError('replacement_uncertain', 'requires verification'))}
with pytest.raises(TaskCenterError) as caught:
_finish_response(tmp_path, journal, response, configure_logging(tmp_path))
assert caught.value.code == 'replacement_uncertain'
assert caught.value.resources_released is False and caught.value.owned_writers_exited is True
def test_resource_status_displays_isolation_warning_without_blocking(qtbot):
from dx_productivity.trial_task_center.ui.resource_status import ResourceStatus
warning = {'state': 'isolated', 'blocking': False, 'desktop_released': False}
status = ResourceStatus(lambda: (warning,))
try:
status.refresh()
qtbot.waitUntil(lambda: not status.busy)
assert status.records == (warning,) and not status.blocked
status._received((warning, {'state': 'blocked'}))
assert status.blocked
finally:
status.close()
def test_failed_project_initiates_owned_cleanup_before_certifying_exit(tmp_path):
from test_batch_runtime import Desktop
from dx_productivity.trial_task_center.stop_control import StopControl
control = StopControl()
runtime = batch_runtime.BatchCadRuntime(tmp_path, 'execution', control, desktop_factory=Desktop)
runtime._ensure_desktop()
process = SimpleNamespace(returncode=None, poll=lambda: process.returncode)
def close(*args):
assert (tmp_path / 'failed' / 'uncertain.flag').exists()
assert control.cleanup_mode == 'mentor_release_required'
assert runtime.record['wait_reason'] == 'mentor_exit'
process.returncode = 0
runtime.cad = SimpleNamespace(cad=process, __exit__=close, record={})
assert runtime.release_failed_project(RuntimeError('source read failed'), tmp_path / 'failed')
assert runtime.desktop is None and runtime.cad is None
proof = json.loads((tmp_path / 'failed' / 'project-resource-release.json').read_text())
assert proof['writers_exited'] is True and proof['business_uncertainty_preserved'] is True