diff --git a/docs/releases/2026-11-09-pr11-review345.md b/docs/releases/2026-11-09-pr11-review345.md new file mode 100644 index 0000000..8eb3ddd --- /dev/null +++ b/docs/releases/2026-11-09-pr11-review345.md @@ -0,0 +1,38 @@ +# PR11 review 345 follow-up + +Repeated CBB verification and ICDB check runs replace the previous result dialog +for the same operation. Closing a result retires its Qt widgets and action +references, while the check task keeps its requests, results, invalidated targets, +and recovery context. A result for the other operation stays available. + +During application shutdown, the title and status show that background work and +path release are pending. After approximately 120 seconds a second notice says +the application is still waiting. This is a notice interval, not a deadline; +shutdown still waits for existing workers and never forces native tools to stop. + +The batch CLI accepts an optional positive `--limit`: + +```powershell +python -m cbb_refresh_verify --batch-lmc 'Z:\library\library.lmc' --limit 2 +``` + +The limit selects the first requested names in their existing order. With no +`--block`, the existing non-READY selection supplies those names; repeated +`--block` options retain their explicit order. Omitting `--limit` retains the +existing all-requested behavior. `batch_selection` logs selected, total, and +remaining counts. On batch exceptions or unconfirmed native release, +`batch_drive_retained` identifies the drive, remote share, display library and +Mentor path, and directs the operator to the confirmed-release entry. It never +disconnects a mapping while a native writer may still be active. + +Management change counts explicitly cover the compared engineering files only. + +Removed from the standalone PR11 head: all five `if False` blocks for the later +release flow, and `_reload_after_maintenance` assignments and its unused reload +branch. The hidden release control and existing method signatures remain for +the later PR12 implementation. When integrating forward, preserve PR12's live +release/resume behavior and retire its dialog-owned action references as well. +Preserve PR13's asynchronous close and lease guards when adding the wait notice. + +Validation uses the isolated offscreen review wrapper with fake native boundaries; +it does not open Mentor, kill native processes, invoke Repair, or back up a library. diff --git a/src/cbb_refresh_verify/application.py b/src/cbb_refresh_verify/application.py index 8d2fb88..8fe6dad 100644 --- a/src/cbb_refresh_verify/application.py +++ b/src/cbb_refresh_verify/application.py @@ -46,6 +46,16 @@ def resolve_data_root(cli_value: Path | None) -> Path: local = os.environ.get("LOCALAPPDATA") return (Path(local) / "CbbRefreshVerify" if local else Path.home() / "AppData" / "Local" / "CbbRefreshVerify").resolve() +def _positive_int(value): + try: + number = int(value) + except ValueError: + raise argparse.ArgumentTypeError('must be a positive integer') from None + if number <= 0: + raise argparse.ArgumentTypeError('must be a positive integer') + return number + + def main(argv: Sequence[str] | None = None) -> int: parser = argparse.ArgumentParser(prog="CbbRefreshVerify") parser.add_argument('--verify-worker', type=Path, help=argparse.SUPPRESS) @@ -57,6 +67,7 @@ def main(argv: Sequence[str] | None = None) -> int: parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS) parser.add_argument('--batch-lmc', type=Path, help=argparse.SUPPRESS) parser.add_argument('--block', action='append', default=[], help=argparse.SUPPRESS) + parser.add_argument('--limit', type=_positive_int, help='Maximum requested CBB names for --batch-lmc (default: all)') parser.add_argument('--libspec', default='', help=argparse.SUPPRESS) parser.add_argument('--dms-login-config', default='', help=argparse.SUPPRESS) parser.add_argument('--mentor-bin', default='', help=argparse.SUPPRESS) @@ -110,6 +121,11 @@ def main(argv: Sequence[str] | None = None) -> int: if library.error: raise RuntimeError(library.error) names = [record.name for record in library.records if record.status != 'READY'] if not names: raise RuntimeError('中心库未读取到需要校验的 CBB') + total = len(names) + if args.limit is not None: + names = names[:args.limit] + logger.info('batch_selection selected=%s total=%s remaining=%s limit=%s', + len(names), total, total - len(names), args.limit or 'all') requests = [VerifyRequest(mentor_path, name, context.root/'evidence', libspec=args.libspec, dms_login_config=args.dms_login_config, mentor_bin=args.mentor_bin, logging_context=context, @@ -117,13 +133,21 @@ def main(argv: Sequence[str] | None = None) -> int: mapped_remote_root=lease.remote_root, native_lm_verify=native_lm_verify_enabled()) for name in names] + def retain_mapping(reason): + lease.retain_for_recovery() + logger.warning( + 'batch_drive_retained drive=%s remote=%s display=%s mentor=%s reason=%s ' + 'guidance=请打开此中心库的“释放残留会话…”入口,确认原生会话安全释放后再释放映射;' + '原生写入仍可能运行时请保留映射。', + lease.drive or '-', lease.remote_root or '-', lease.display_path, + mentor_path, reason) try: results = run_batch(requests) except Exception: - lease.retain_for_recovery() + retain_mapping('batch_exception') raise if any(not result.safe_to_continue for result in results): - lease.retain_for_recovery() + retain_mapping('native_release_unconfirmed') report = write_batch_report(requests, results, context.root/'reports') logger.info('batch_report path=%s', report) logger.info('failure_report path=%s', failure_report_path(report)) diff --git a/src/cbb_refresh_verify/ui/main_window.py b/src/cbb_refresh_verify/ui/main_window.py index e9f3178..34e1a92 100644 --- a/src/cbb_refresh_verify/ui/main_window.py +++ b/src/cbb_refresh_verify/ui/main_window.py @@ -99,7 +99,6 @@ class MainWindow(QWidget): self._management_unsafe_libraries = set() self._management_operation_library = None self._maintenance_recovery_view = False - self._reload_after_maintenance = False self._reimport_offers = () self._batch_requests = () self._batch_records = {} @@ -133,6 +132,10 @@ class MainWindow(QWidget): self._mapping_auto_idle = False self._mapping_finish_waiters = [] self._closing = self._close_ready = False + self.close_wait_timer = QTimer(self) + self.close_wait_timer.setSingleShot(True) + self.close_wait_timer.setInterval(120_000) + self.close_wait_timer.timeout.connect(self._show_close_wait_notice) from cbb_refresh_verify.operation_queue import NativeQueue self.native_queue = NativeQueue() self.icdb_task = None @@ -575,7 +578,6 @@ class MainWindow(QWidget): mapped_drive=getattr(self.library_lease, 'drive', ''), mapped_remote_root=getattr(self.library_lease, 'remote_root', ''))) previous[record.name] = str(result.evidence_path) - self._reload_after_maintenance = False if getattr(self, 'summary', None): self.summary.close() self._open_management_dialog(requests, recovery_from=previous) @@ -630,11 +632,6 @@ class MainWindow(QWidget): result.operation, result.name, result.status, result.safe_to_continue, result.evidence_path, result.detail) if getattr(self, '_management_is_recovery', False) and result.status == 'UPLOADED_VERIFIED': self.output.append('副本恢复校验通过,版本待核对。') - if False: # Release entry arrives with the next review PR. - self._management_unsafe = True - self._management_unsafe_library = self._management_operation_library - self._management_unsafe_libraries.add(_path_key(self._management_operation_library)) - self.status_label.setText('管理操作需要人工确认恢复/释放;已停止写入,未再次读取原生目录。') self._show_unfinished_management() def _management_closed(self, *_): @@ -751,7 +748,7 @@ class MainWindow(QWidget): if hasattr(task, 'summary'): prefix = '已更新的工程:'+', '.join(sorted(task.invalidated))+'。下列为此前检查记录。\n' task.summary.setDetailedText(prefix+task.summary.detailedText()) - if names & getattr(task, 'recovery_names', set()): + if names & getattr(task, 'recovery_names', set()) and hasattr(task, 'recovery_action'): task.recovery_action.setEnabled(False) task.recovery_action.setToolTip('工程已有后续管理操作,请重新检查。') self._reimport_offers = tuple(offer for offer in self._reimport_offers if offer[0].block_name not in names @@ -851,7 +848,7 @@ class MainWindow(QWidget): self.icdb_phase.setText(text) if not self.busy: self.status_label.setText(text) self.output.append(text+'\n'+str(task.report or task.report_error)) - summary = QMessageBox(self); self.icdb_summary = summary + summary = self._new_result_summary('icdb_summary') task.summary = summary if not self.busy: self.summary = summary summary.setWindowTitle('ICDB 批量检查结果'); summary.setText(text) @@ -860,14 +857,6 @@ class MainWindow(QWidget): +(result.stderr or result.stdout or result.status) for req, result in zip(task.requests, task.results))) summary.setTextFormat(Qt.PlainText); summary.setAttribute(Qt.WA_ShowWithoutActivating) - if False: # Release entry arrives with the next review PR. - def release_task(): - if not (_library_path_keys(task.requests[0].lmc_file, task.path_lease) - & _library_path_keys(self.mentor_lmc_path or self.loaded_path, self.library_lease)): - self.status_label.setText(f'请切回 {task.requests[0].lmc_file} 后释放该检查的残留。') - return - self.check_library_release() - summary.addButton('查看残留并释放…', QMessageBox.ActionRole).clicked.connect(release_task) if offers: action = summary.addButton('选择副本恢复…', QMessageBox.ActionRole) task.recovery_action = action @@ -1389,6 +1378,28 @@ class MainWindow(QWidget): if cell is not None: cell.setBackground(QColor('#E8F5E9')) + def _new_result_summary(self, attribute): + previous = getattr(self, attribute, None) + if previous is not None: + previous.close() + summary = QMessageBox(self) + setattr(self, attribute, summary) + summary.setAttribute(Qt.WA_DeleteOnClose) + summary.finished.connect(lambda _: self._forget_result_summary(summary)) + return summary + + def _forget_result_summary(self, summary): + if getattr(self, '_batch_summary', None) is summary: + self._reimport_summary_action = None + for attribute in ('summary', '_batch_summary', 'icdb_summary'): + if getattr(self, attribute, None) is summary: + setattr(self, attribute, None) + for task in self.icdb_tasks: + if getattr(task, 'summary', None) is summary: + del task.summary + if hasattr(task, 'recovery_action'): + del task.recovery_action + def _batch_done(self, outcome): results, report = outcome[:2] failure_report = failure_report_path(report) if report is not None else '未写入' @@ -1425,8 +1436,6 @@ class MainWindow(QWidget): f'取消 {counts["cancelled"]},队列未执行 {skipped}\n' f'完整日志:{report}\n仅失败日志:{failure_report}') self.icdb_phase.setText('批量检查已结束') - if False: # Release entry arrives with the next review PR. - text += '\n未确认数据库或会话安全,已停止剩余校验。请查看恢复现场。' status_text = (f'已结束:通过 {passed},失败/受阻 {failed},' f'仅检查 {checked},未执行 {skipped + len(self.skipped_names)}。') if self._global_icdb_run: @@ -1443,14 +1452,12 @@ class MainWindow(QWidget): status_text += '\nMentor 不允许对此已验证过的 CBB 反标注,校验未通过。' else: status_text += '\n部分项目未完成,请查看详情。' - if False: # Release entry arrives with the next review PR. - status_text += '\n后续操作已暂停。' if self._reimport_offers: guidance = '\n修复未完成,可选择工程副本恢复。' text += guidance status_text += guidance self.status_label.setText(status_text.replace('\n', ' ')); self.output.append(text) - self.summary = QMessageBox(self) + self.summary = self._new_result_summary('_batch_summary') self.summary.setWindowTitle('ICDB 批量检查结果' if self._global_icdb_run else 'CBB 校验结果') self.summary.setText(status_text) self.summary.setDetailedText(text) @@ -1459,18 +1466,6 @@ class MainWindow(QWidget): self._residual_release_action = None self._resume_batch_action = None self._resume_batch = None - if False: # Release entry arrives with the next review PR. - self._residual_release_action = self.summary.addButton('查看残留并释放…', QMessageBox.ActionRole) - self._residual_release_action.clicked.connect(self.check_library_release) - self._residual_release_action.setEnabled(False) - names = [req.block_name for req, result in zip(self._batch_requests, results) - if result.status == 'SKIPPED'] - if names: - self._resume_batch = {'library': self._batch_requests[0].lmc_file, 'names': names, - 'maintenance': self._global_icdb_run, 'released': False} - self._resume_batch_action = self.summary.addButton('继续未执行项', QMessageBox.ActionRole) - self._resume_batch_action.clicked.connect(self._resume_released_batch) - self._resume_batch_action.setEnabled(False) if self._reimport_offers: self.summary.setStandardButtons(QMessageBox.Close) self._reimport_summary_action = self.summary.addButton('选择副本恢复…', QMessageBox.ActionRole) @@ -1520,10 +1515,6 @@ class MainWindow(QWidget): self.version_dialog.reject() self.version_dialog = None self.busy = False; self._update() - if self._reload_after_maintenance: - from PySide6.QtCore import QTimer - self._reload_after_maintenance = False - QTimer.singleShot(0, self.load_library) def open_logs(self): self.data_root.mkdir(parents=True, exist_ok=True); os.startfile(str(self.data_root)) @@ -1545,6 +1536,9 @@ class MainWindow(QWidget): else: self._closing = True self.busy = True; self._update() + self.setWindowTitle('CBB 刷新校验 · 等待任务安全结束') + self.status_label.setText('正在等待后台任务和路径释放完成,完成后关闭。') + self.close_wait_timer.start() retained = None if self._native_backup_session is not None: self.native_backup_timer.stop() @@ -1557,6 +1551,11 @@ class MainWindow(QWidget): self._close_when_idle() event.ignore() + def _show_close_wait_notice(self): + if self._closing and not self._close_ready: + self.setWindowTitle('CBB 刷新校验 · 仍在等待任务安全结束') + self.status_label.setText('仍在等待后台任务或路径释放完成;原生操作不会强制终止,完成后关闭。') + def _close_when_idle(self): owners = [self, *self.icdb_tasks] for name in ('management_dialog', 'backup_dialog', 'release_dialog'): @@ -1571,5 +1570,6 @@ class MainWindow(QWidget): if self._lease_pending or active: QTimer.singleShot(20, self._close_when_idle) return + self.close_wait_timer.stop() self._close_ready = True self.close() diff --git a/src/cbb_refresh_verify/ui/management_dialog.py b/src/cbb_refresh_verify/ui/management_dialog.py index f883fad..1f4249c 100644 --- a/src/cbb_refresh_verify/ui/management_dialog.py +++ b/src/cbb_refresh_verify/ui/management_dialog.py @@ -209,8 +209,8 @@ class ManagementDialog(QDialog): changes = getattr(result, 'change_report', None) if changes: if changes.get('status') == 'RECORDED': - text += (f'\n变更:新增 {len(changes["added"])}、删除 {len(changes["deleted"])}、' - f'修改 {len(changes["modified"])} 个主要文件。') + text += (f'\n已比对的工程文件:新增 {len(changes["added"])}、删除 {len(changes["deleted"])}、' + f'修改 {len(changes["modified"])};范围仅限报告列出的工程文件。') else: summary += ',变更清单待核对' text += '\n'+changes.get('detail', '变更清单未确认') diff --git a/tests/test_review345_ui_cli.py b/tests/test_review345_ui_cli.py new file mode 100644 index 0000000..d3bf41d --- /dev/null +++ b/tests/test_review345_ui_cli.py @@ -0,0 +1,166 @@ +from pathlib import Path +from threading import Event +from types import SimpleNamespace + +import pytest +from PySide6.QtCore import QCoreApplication, QEvent +from PySide6.QtWidgets import QMessageBox +from shiboken6 import isValid + +from cbb_refresh_verify.verify_runner import VerifyResult + + +def flush_deletes(): + QCoreApplication.sendPostedEvents(None, QEvent.DeferredDelete) + + +def test_repeated_batch_results_retire_previous_dialog(qtbot, tmp_path): + from cbb_refresh_verify.ui.main_window import MainWindow + window = MainWindow(data_root=tmp_path) + qtbot.addWidget(window) + window._batch_done(([VerifyResult('FAIL')], tmp_path/'report.log')) + previous = window.summary + window._batch_done(([VerifyResult('PASS')], tmp_path/'report2.log')) + flush_deletes() + assert not isValid(previous) + assert len(window.findChildren(QMessageBox)) == 1 + current = window.summary + current.close() + flush_deletes() + assert not isValid(current) + window._update() # No retained reference to deleted result actions. + + +def test_repeated_icdb_results_preserve_latest_recovery_task(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window + from test_reimport_recovery import failed_repair + window = load_window(qtbot, tmp_path, monkeypatch, + verifier=lambda _: failed_repair(tmp_path/'result.json', safe=True)) + window._run(['Beta'], maintenance=True) + qtbot.waitUntil(lambda: not window._icdb_active()) + first_task, previous = window.icdb_task, window.icdb_summary + window._run(['Gamma'], maintenance=True) + qtbot.waitUntil(lambda: not window._icdb_active()) + flush_deletes() + assert not isValid(previous) + assert not hasattr(first_task, 'summary') + assert len(window.findChildren(QMessageBox)) == 1 + assert window.icdb_task.summary is window.icdb_summary + action = next(b for b in window.icdb_summary.buttons() if '副本' in b.text()) + action.click() + assert [request.name for request in window.management_dialog.requests()] == ['Gamma'] + window.management_dialog.reject() + window._invalidate_check_targets('test.lmc', ['Beta', 'Gamma']) + window._update() + + +def test_batch_replacement_preserves_independent_icdb_result(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window + window = load_window(qtbot, tmp_path, monkeypatch, + verifier=lambda _: VerifyResult('CHECKED')) + window._run(['Beta'], maintenance=True) + qtbot.waitUntil(lambda: not window._icdb_active()) + icdb_summary = window.icdb_summary + window._batch_done(([VerifyResult('PASS')], tmp_path/'first.log')) + old_batch = window.summary + window._batch_done(([VerifyResult('PASS')], tmp_path/'second.log')) + flush_deletes() + assert not isValid(old_batch) + assert isValid(icdb_summary) and icdb_summary.isVisible() + assert window.icdb_task.summary is icdb_summary + assert len(window.findChildren(QMessageBox)) == 2 + + +def test_close_wait_notice_remains_visible_and_timer_stops_on_idle(qtbot, tmp_path): + from cbb_refresh_verify.ui.main_window import MainWindow + entered, release = Event(), Event() + def close_lease(): + entered.set() + release.wait(5) + window = MainWindow(data_root=tmp_path) + qtbot.addWidget(window) + window.library_lease = SimpleNamespace(close=close_lease) + window.show() + try: + window.close() + qtbot.waitUntil(entered.is_set) + assert window.isVisible() and '等待' in window.windowTitle() + timer = window.close_wait_timer + assert timer.isActive() and timer.interval() == 120_000 + timer.start(10) + qtbot.waitUntil(lambda: '仍在等待' in window.windowTitle()) + assert '仍在等待' in window.status_label.text() + window.close() + assert window.isVisible() + finally: + release.set() + qtbot.waitUntil(lambda: not window.isVisible()) + assert not timer.isActive() + + +@pytest.fixture +def batch_cli(tmp_path, monkeypatch): + import cbb_refresh_verify.application as application + import cbb_refresh_verify.library_reader as reader + import cbb_refresh_verify.network_path as network + import cbb_refresh_verify.verify_runner as runner + from cbb_refresh_verify.models import CbbRecord, LibraryReadResult + log, requested, retained = [], [], [] + def record(message, *args, **kwargs): + log.append(message % args if args else message) + logger = SimpleNamespace(info=record, warning=record, exception=record, handlers=()) + monkeypatch.setattr(application, 'configure', lambda *_: SimpleNamespace(root=tmp_path, logger=logger)) + class Lease: + display_path = Path(r'\\server\share\library') + mentor_path = tmp_path/'lib.lmc' + drive, remote_root, created = 'Z:', r'\\server\share', True + def __enter__(self): return self + def __exit__(self, *_): pass + def retain_for_recovery(self): retained.append(self.drive) + monkeypatch.setattr(network.LibraryPathLease, 'acquire', lambda _: Lease()) + monkeypatch.setattr(network, 'select_library_file', lambda path: path) + monkeypatch.setattr(reader, 'read_library_fast', lambda *a, **kw: LibraryReadResult(( + CbbRecord('Ready', 'LP', status='READY'), CbbRecord('One', 'LP'), + CbbRecord('Two', 'LP'), CbbRecord('Three', 'LP')))) + def run(requests): + requested.extend(request.block_name for request in requests) + return [VerifyResult('PASS') for _ in requests] + monkeypatch.setattr(runner, 'run_batch', run) + monkeypatch.setattr(runner, 'write_batch_report', lambda *a: tmp_path/'batch.log') + return application, runner, log, requested, retained + + +@pytest.mark.parametrize('extra, expected, counts', [ + ([], ['One', 'Two', 'Three'], (3, 3, 0)), + (['--limit', '2'], ['One', 'Two'], (2, 3, 1)), + (['--block', 'Three', '--block', 'One', '--limit', '1'], ['Three'], (1, 2, 1)), +]) +def test_batch_cli_limit_is_optional_and_reports_selection(batch_cli, extra, expected, counts): + app, _, log, requested, _ = batch_cli + assert app.main(['--batch-lmc', 'lib.lmc', *extra]) == 0 + assert requested == expected + assert any(all(f'{key}={value}' in line for key, value in zip( + ('selected', 'total', 'remaining'), counts)) for line in log) + + +@pytest.mark.parametrize('value', ['0', '-1', 'no']) +def test_batch_cli_rejects_nonpositive_limit(batch_cli, value): + app, _, _, requested, _ = batch_cli + with pytest.raises(SystemExit) as error: + app.main(['--batch-lmc', 'lib.lmc', '--limit', value]) + assert error.value.code == 2 and not requested + + +@pytest.mark.parametrize('raised', [False, True]) +def test_retained_mapping_logs_context_and_confirmed_release_guidance(batch_cli, monkeypatch, raised): + app, runner, log, _, retained = batch_cli + def run(_): + if raised: raise RuntimeError('native writer status unknown') + return [VerifyResult('FAIL', safe_to_continue=False)] + monkeypatch.setattr(runner, 'run_batch', run) + assert app.main(['--batch-lmc', 'lib.lmc', '--block', 'One']) == (1 if raised else 2) + assert retained == ['Z:'] + notice = next(line for line in log if 'batch_drive_retained' in line) + assert 'Z:' in notice and r'\\server\share' in notice + assert '释放残留会话' in notice and '确认' in notice + assert 'net use' not in notice.lower() diff --git a/tests/test_review_management_ui_followup.py b/tests/test_review_management_ui_followup.py index ef34087..21dd401 100644 --- a/tests/test_review_management_ui_followup.py +++ b/tests/test_review_management_ui_followup.py @@ -29,3 +29,17 @@ def test_report_failure_is_visible_without_inventing_native_failure(qtbot, setup assert '历史会话已释放' in dialog.output.toPlainText() dialog._progress({'stage':'previous_release_check','block':request.name}) assert '正在复核历史占用' in dialog.status_label.text() + + +def test_recorded_counts_identify_compared_engineering_file_scope(qtbot, setup): + from cbb_refresh_verify.management import ManagementResult + from cbb_refresh_verify.ui.management_dialog import ManagementDialog + request, _, _ = setup + dialog = ManagementDialog([request]); qtbot.addWidget(dialog) + result = ManagementResult(request.operation, request.library, request.name, request.partition, + None, False, 'complete', 'REMOVED', True, 'removed', + change_report={'status': 'RECORDED', 'added': ['a'], 'deleted': [], 'modified': ['b']}) + dialog._result([result]) + text = dialog.output.toPlainText() + assert '已比对的工程文件' in text + assert '新增 1' in text and '删除 0' in text and '修改 1' in text