diff --git a/src/cbb_refresh_verify/mentor_adapter.py b/src/cbb_refresh_verify/mentor_adapter.py index 56b0e27..8d68efc 100644 --- a/src/cbb_refresh_verify/mentor_adapter.py +++ b/src/cbb_refresh_verify/mentor_adapter.py @@ -755,9 +755,15 @@ def execute_job(job, emit): command=list(command), strategy='reusable_circuit_direct') pcb_deadline = (dispatch_deadline if job.get('native_lm_verify') else time.monotonic()+pcb_startup_timeout_seconds(job['timeout'])) + cancelled_startup = False while time.monotonic() < pcb_deadline: - if job.get('cancel_signal') and Path(job['cancel_signal']).exists(): - raise RuntimeError('VERIFY_CANCELLED: PCB 启动期间收到停止请求') + if not cancelled_startup and job.get('cancel_signal') and Path(job['cancel_signal']).exists(): + if not prewrite_eligible or launcher_process is None: + raise RuntimeError('VERIFY_CANCELLED: PCB 启动期间收到停止请求') + cancelled_startup = True + # Cancellation after CreateProcess may precede discovery of its + # child. Bind the exact client for cleanup without attaching COM. + pcb_deadline = min(pcb_deadline, time.monotonic()+5) records = _process_details('ExpeditionPCB.exe') worker = select_reusable_circuit_worker( records, @@ -786,6 +792,8 @@ def execute_job(job, emit): pass break time.sleep(.2) + if cancelled_startup or job.get('cancel_signal') and Path(job['cancel_signal']).exists(): + raise RuntimeError('VERIFY_CANCELLED: PCB 启动期间收到停止请求') if worker_pid is None: if job.get('native_lm_verify'): raise RuntimeError('VERIFY_DISPATCH_FAILED: LM 菜单返回但未观察到目标 PCB,未执行校验') @@ -1021,14 +1029,15 @@ def worker_main(request_path): def emit(**event): from .session_record import update_worker_state + stage = event.get('stage') phase = {'save_start': 'NATIVE_CALL', 'integration_action': 'NATIVE_CALL', 'integration_action_complete': 'POSTCALL', 'saved_and_closed': 'RELEASE_CHECK', - 'complete': 'FINISHED', 'failed': 'UNCONFIRMED'}.get(event.get('stage')) - if (event.get('stage') == 'pcb_worker_started' and job.get('diagnostic_only') is False + 'complete': 'FINISHED', 'failed': 'UNCONFIRMED'}.get(stage) + if (stage in ('pcb_launch', 'pcb_worker_started') and job.get('diagnostic_only') is False and not (job.get('native_lm_verify') or job.get('post_repair_consent') or job.get('interactive_input'))): - # The watchdog may retire this worker before its first native write. - phase = 'PRECALL' + # Keep the worker alive through PID registration after supervisor loss. + phase = 'UNCONFIRMED' if stage == 'pcb_launch' else 'PRECALL' identities = [(role, event.get(key)) for role, key in (('native', 'pcb_pid'), ('native', 'lm_pid')) if event.get(key)] @@ -1046,13 +1055,16 @@ def worker_main(request_path): # Save and Close run in one already admitted helper. continuing_save = event.get('helper_exited') is not True phase = 'NATIVE_CALL' if continuing_save else 'POSTCALL' - if phase or identities: + registered_startup = stage == 'pcb_worker_started' and phase == 'PRECALL' + if (phase or identities) and not registered_startup: update_worker_state(job, phase or 'UNCONFIRMED', identities=identities, write_outcome=facts, continuation=continuing_save) event.update(time=time.strftime('%Y-%m-%d %H:%M:%S'), block=job['block_name'], monotonic_seconds=time.monotonic()) with (root/'events.jsonl').open('a', encoding='utf-8') as stream: stream.write(json.dumps(event, ensure_ascii=False) + '\n') + if registered_startup: + update_worker_state(job, phase, identities=identities) try: if job.get('supervisor_pid'): diff --git a/src/cbb_refresh_verify/ui/main_window.py b/src/cbb_refresh_verify/ui/main_window.py index 6becad5..a863783 100644 --- a/src/cbb_refresh_verify/ui/main_window.py +++ b/src/cbb_refresh_verify/ui/main_window.py @@ -1004,7 +1004,8 @@ class MainWindow(QWidget): def _eligible_names(self, *, checked_only=False, require_status=False): records = self.selected_records() if checked_only else self.visible_records() return [r.name for r in records if r.status != 'READY' and r.name not in self.skipped_names - and (not require_status or self.catalog_reader is None or r.status == 'PENDING')] + and (not require_status or self.catalog_reader is None or r.status == 'PENDING' + or r.status_source == 'cancelled_verify')] def _maintenance_names(self): records = self.selected_records() or self.visible_records() @@ -2003,7 +2004,7 @@ class MainWindow(QWidget): finally: pythoncom.CoUninitialize() - def _apply_refreshed_records(self, payload): + def _apply_refreshed_records(self, payload, *, cancelled_retries=()): names, statuses, reasons, error = payload self._publish_check_statuses(self.mentor_lmc_path or self.loaded_path, {name: statuses.get(name, 'UNKNOWN') for name in names}) @@ -2015,7 +2016,10 @@ class MainWindow(QWidget): status = statuses.get(name, 'UNKNOWN') if status not in STATUS_LABELS: status = 'UNKNOWN' - self._records_by_name[name] = replace(self._records_by_name[name], status=status) + record = self._records_by_name[name] + source = ('cancelled_verify' if name in cancelled_retries else + 'unknown' if status == 'UNKNOWN' else 'authoritative') + self._records_by_name[name] = replace(record, status=status, status_source=source) self.ready_names.discard(name) if reasons is not None: self.skip_reasons.pop(name, None) @@ -2227,7 +2231,11 @@ class MainWindow(QWidget): elif affected: reason = ('状态尚未复核,请重新读取。' if all(r.safe_to_continue for r in results) else '会话或数据库安全未确认;暂缓原生状态复核,请确认释放后重新读取。') - self._defer_status_refresh(affected, reason) + cancelled = {request.block_name for request, result in zip(self._batch_requests, results) + if result.status == 'CANCELLED' and request.block_name in self._records_by_name + and (self._records_by_name[request.block_name].status == 'PENDING' + or self._records_by_name[request.block_name].status_source == 'cancelled_verify')} + self._apply_refreshed_records((tuple(affected), {}, None, reason), cancelled_retries=cancelled) from shiboken6 import isValid summary = getattr(self, 'summary', None) self.status_label.setText(summary.text().replace('\n', ' ') if summary is not None and isValid(summary) diff --git a/tests/test_issue21_session_recovery.py b/tests/test_issue21_session_recovery.py index 0758908..4b3598d 100644 --- a/tests/test_issue21_session_recovery.py +++ b/tests/test_issue21_session_recovery.py @@ -283,10 +283,42 @@ def test_verify_registers_ordinary_pcb_before_any_write_phase(tmp_path, monkeypa lambda job, phase, **options: bound_phases.append((phase, options['identities']))) def execute(job, emit): + emit(stage='pcb_launch') emit(stage='pcb_worker_started', pcb_pid=12) emit(stage='integration_action', action='UpdateNets') return {'status': 'PASS'} monkeypatch.setattr(mentor_adapter, 'execute_job', execute) assert mentor_adapter.worker_main(request) == 0 - assert bound_phases == [('PRECALL', [('native', 12)]), ('NATIVE_CALL', [])] + assert bound_phases == [('UNCONFIRMED', []), ('PRECALL', [('native', 12)]), ('NATIVE_CALL', [])] + + +def test_cancel_after_launcher_still_registers_startup_for_cleanup(tmp_path, monkeypatch): + from types import SimpleNamespace + from test_verify_worker_stability import exercise_worker + from cbb_refresh_verify import failed_session, mentor_adapter, pcb_bridge + + job, events, execute = exercise_worker(tmp_path, monkeypatch) + stop = tmp_path/'cancel.signal' + job.update(operation='verify', operation_id='ordinary', desktop='CbbVerify_test', + diagnostic_only=False, session_record_path=str(tmp_path/'session.json'), + cancel_signal=str(stop)) + + def launch(*_): + stop.touch() + return SimpleNamespace(pid=1) + + worker = iter((None, (2, 'pcb', 'command', 1))) + monkeypatch.setattr(mentor_adapter, 'launch_pcb_process', launch) + monkeypatch.setattr(mentor_adapter, 'select_reusable_circuit_worker', lambda *a, **kw: next(worker)) + monkeypatch.setattr(pcb_bridge, 'wait_for_target_document', lambda *a, **kw: + pytest.fail('cancelled startup must never attach to the PCB document')) + closed = [] + monkeypatch.setattr(failed_session, 'close_failed_startup', lambda job, pid, **kw: + closed.append(pid) or {'status': 'CLOSED'}) + + with pytest.raises(RuntimeError, match='VERIFY_CANCELLED'): + execute() + assert closed == [2] + assert any(e['stage'] == 'pcb_worker_started' and e['pcb_pid'] == 2 for e in events) + assert any(e['stage'] == 'startup_cancelled_prewrite' and e['pcb_pid'] == 2 for e in events) diff --git a/tests/test_ui.py b/tests/test_ui.py index 18e4333..e8fa463 100644 --- a/tests/test_ui.py +++ b/tests/test_ui.py @@ -364,3 +364,23 @@ def test_batch_summary_exposes_failures_only_report(qtbot, tmp_path): window._batch_done(([VerifyResult('FAIL',stderr='Mentor error')],report)) assert '仅失败日志' in window.summary.detailedText() assert str(report.with_name('failures-20260929-test.log')) in window.summary.detailedText() + + + +def test_cancelled_pending_item_can_be_submitted_for_fresh_admission(qtbot, tmp_path): + records = (CbbRecord('Pending', 'LP', status='PENDING'), CbbRecord('Unconfirmed', 'LP')) + window = MainWindow(reader=lambda _: LibraryReadResult(records), data_root=tmp_path) + qtbot.addWidget(window) + window.lmc_edit.setText('lib.lmc') + window.load_library() + qtbot.waitUntil(lambda: not window.busy) + window.catalog_reader = object() + window._batch_requests = (window._request('Pending'), window._request('Unconfirmed')) + window._batch_refreshed(([VerifyResult('CANCELLED', safe_to_continue=False), + VerifyResult('FAIL', safe_to_continue=False)], None, + ['Pending', 'Unconfirmed'], None)) + assert window._records_by_name['Pending'].status == 'UNKNOWN' + assert window._eligible_names(require_status=True) == ['Pending'] + assert window.batch_button.isEnabled() + window._apply_refreshed_records((('Pending',), {'Pending': 'READY'}, {}, '')) + assert window._eligible_names(require_status=True) == []