From 00db1cf5f27333cff98739028b68673e93ff6213 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E7=99=BD=E5=8F=94?= <11794527+absfan@user.noreply.gitee.com> Date: Wed, 4 Nov 2026 20:51:35 +0800 Subject: [PATCH] fix: continue released verify batches and bound automation shutdown --- docs/diagnostics/2026-11-04-batch-blockers.md | 37 +++ .../diagnostics/2026-11-04-issue4-followup.md | 2 + packaging/CbbRefreshVerify.spec | 17 +- src/cbb_refresh_verify/batch_status.py | 7 +- src/cbb_refresh_verify/desktop_worker.py | 48 +++- src/cbb_refresh_verify/mentor_adapter.py | 47 ++-- src/cbb_refresh_verify/owner_probe.py | 8 +- .../save_verified_block.vbs | 9 +- src/cbb_refresh_verify/ui/main_window.py | 4 +- src/cbb_refresh_verify/verify_runner.py | 105 ++++++-- tests/test_abnormal_shutdown.py | 2 +- tests/test_backup_recovery.py | 4 + tests/test_batch_blockers.py | 243 ++++++++++++++++++ tests/test_batch_status.py | 23 ++ tests/test_failure_lifecycle.py | 22 +- tests/test_icdb_recovery.py | 2 +- tests/test_incident_safety.py | 17 +- tests/test_independent_operations.py | 4 +- tests/test_maintenance_diagnosis.py | 9 +- tests/test_management_ui.py | 9 +- tests/test_native_repair.py | 8 +- tests/test_save_helper_runtime.py | 18 +- tests/test_verify_runner.py | 20 +- 23 files changed, 550 insertions(+), 115 deletions(-) create mode 100644 docs/diagnostics/2026-11-04-batch-blockers.md create mode 100644 tests/test_batch_blockers.py diff --git a/docs/diagnostics/2026-11-04-batch-blockers.md b/docs/diagnostics/2026-11-04-batch-blockers.md new file mode 100644 index 0000000..8067319 --- /dev/null +++ b/docs/diagnostics/2026-11-04-batch-blockers.md @@ -0,0 +1,37 @@ +# 普通校验阻塞修正 + +基准 `477a5a4`。按用户最新指示暂停 ICDB 自动修复研究,本轮只修普通校验的入口、单项失败后的继续条件、取消和退出,以及状态桥部署/重试。没有对原库运行新的校验、Repair、恢复或移除;遗留的 Project Backup 进程未被终止。 + +## 修改依据与最终行为 + +| 阻塞来源 | 修改 | +| --- | --- | +| 原生进程已退出,但单项失败仍使整批跳过 | 统一使用本轮、同库、同 CBB 的释放记录判断继续资格。FAIL/TIMEOUT/未知弹窗保持原失败状态和备注;自动化工作进程、保存/失败关闭助手及本任务原生进程全部确认退出后可继续下一项。失败不会变成 PASS。 | +| 保存或失败关闭助手漏检;工作进程已关闭句柄后再查询退出状态 | 停止和检查两类精确脚本路径、精确父 PID 的助手。退出状态在关闭句柄前读取并缓存,清理可重复调用;助手和原生 PID 合并记录。任何查询异常或客户端仍活着都不解除执行锁。 | +| 超时只写取消文件,客户端可能继续 Save/Close | 先请求协作取消,宽限到期后仅停止本任务自动化工作进程及已识别的自动化助手。保留原生 PCB/iCDB,不终止进程树。普通校验的取消事件已传入监督循环。监督程序丢失后,Verify 看门狗也限时停止已登记客户端。 | +| 启动器和迟到子进程未完整纳入清理 | 监督器清理前重读剩余事件中的目标/启动器 PID;追踪这些已确认原生进程的新后代,排除任务开始前的无关会话。 | +| 任意 PCB 已打开就禁止校验 | 精确命令参数指向同一 PCB 时才阻止启动;其他工程保留。实际 COM 文档身份和保存助手身份检查仍必须通过。保存关闭后存在其他文档时,不调用该应用的 Quit。 | +| WMI 占用查询可能无限等待 | 普通校验的进程查询统一复用已有隔离查询助手,最多等待 10 秒。超时表示无法确认,保留具体原因;不在 GUI 线程做 WMI。 | +| 端口少量抽样被当作整个原生端口区间不可用 | 默认仅发出警告并执行真实原生调用。保留内部显式严格诊断参数,不作为默认入口条件。 | +| `0 errors` 被错误关键字命中;原生工程编码误判 | 仅忽略完整的零错误计数,仍拒绝非零错误、明确错误或坏退出码;复用现有 UTF-8 BOM / UTF-16 / Windows ACP 工程读取器。 | +| 状态桥 x86 MFC 运行库缺失;加载失败对每项重复启动 | 打包时验证并携带 x86 MFC/VC 运行库到桥的独立目录,避免误用 x64 Qt DLL。识别明确的 Windows DLL 缺失/架构错误,只记录一次全局桥故障并为余项保留状态;不因此禁用维护或管理入口。 | +| 状态查询重试复用旧 TIMEOUT/ERROR | 断点读取仅复用 READY/PENDING;失败状态下次重查,不要求修改库文件才能重新查询。普通界面读取仍使用本轮权威状态。 | + +执行互斥只用于实际仍运行/释放未确认的客户端;历史诊断和 CBB 内容问题不应变成跨功能永久禁用。处于原生操作中的未知弹窗不会被盲目确认:当前项失败并留证,是否继续仍取决于该操作是否实际结束。 + +## 验证 + +新回归先复现单项已释放仍停批、取消未传递、零错误误判、编码与端口拦截等问题,再验证修改。还覆盖原生迟到子进程、保存/失败关闭助手保留,以及已关闭 Win32 句柄不再被读取。 + +使用真实 Windows 子进程验证监督程序退出后的客户端停止和原生模拟进程保留;VBS 在真正的 32 位 cscript 中使用伪 COM 对象验证 Save/Close、取消及剩余文档不被 Quit。它们没有加载现场工程,也不等于 Mentor 实机验收。 + +最终完整 Python 回归、冻结模块一致性、程序启动/正常退出、桥 JSON 编解码及实际加载 app-local x86 DLL 的结果记录在 `diagnostics/batch-blockers-20261104/`。现场日志和原始证据不随代码提交。 + +- 最终完整回归:**1,244 passed**,退出码 0,222.90 秒;1 条既有 pywinauto STA 警告。`pytest-final.log` / `pytest-final-result.json`。 +- PyInstaller 构建、编译和差异检查通过。10 个关键 Python 模块及两个 VBS 脚本与冻结程序一致,启动及正常退出冒烟返回 0。 +- 桥的 Unicode/UNC 编解码返回 0。通过真实进程模块枚举确认 `mfc140.dll`、`MSVCP140.dll`、`VCRUNTIME140.dll` 均从包内桥目录加载;不是仅检查文件名存在。系统 PATH 缩为 Windows System32,本检查没有加载 Mentor 数据库。 +- 独立审查发现并修正失败关闭助手漏检;复审无剩余必要 P1/P2。构建记录保留 `icdb_automatic_repair_acceptance=false`、`release_ready=false`。 + +## 仍待验证 + +没有把本次阻塞修正称为 ICDB 自动修复成功。Project Backup 挂起问题保持暂停;Windows 10 干净系统、其他 Mentor 环境、两个真实 PCB 同时打开的 COM 注册行为、跨机并发写库、3000 项网络库完整耗时仍需实机验证。状态桥无法读取时仍不能宣称 READY;本轮补齐了已确认的 x86 部署依赖,没有伪造状态,也未加入新的全功能禁用入口。 diff --git a/docs/diagnostics/2026-11-04-issue4-followup.md b/docs/diagnostics/2026-11-04-issue4-followup.md index fc039e8..785bf6c 100644 --- a/docs/diagnostics/2026-11-04-issue4-followup.md +++ b/docs/diagnostics/2026-11-04-issue4-followup.md @@ -2,6 +2,8 @@ 复核基准:最新工单 [#4](https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/issues/4)(更新于 2026-11-04 15:20),当前代码起点 `2587d33`,用户随后要求校验与 ICDB 维护独立执行。原工单基准为 `29959e2`,下表按当前源码重新核对,不能照搬原报告的测试数或认定全部已修复。 +后续用户要求暂停 ICDB 自动修复、先修阻塞。新的修改和最终 1,244 项完整回归见 [普通校验阻塞修正](2026-11-04-batch-blockers.md);下表保留首次复核状态,不能作为最新未修项数量使用。 + ## 本次用户失败的实际链路 最新测试程序的日志位于 `dist/issue2-tabs-release-candidate/CbbRefreshVerify-Background/data/`。北京时间 17:41:55 开始维护 `1GPHY_8212`,17:42:24 进入原生检查,17:43:17 启动 Project Backup,17:43:50 报 `TIMEOUT_UNRELEASED`。本轮没有发出 Repair,8 个后续条目被跳过。17:44:54 再运行另一工程,遗留 PID 60000 被全局进程检查拦截。 diff --git a/packaging/CbbRefreshVerify.spec b/packaging/CbbRefreshVerify.spec index 69e2bcc..3a0ef58 100644 --- a/packaging/CbbRefreshVerify.spec +++ b/packaging/CbbRefreshVerify.spec @@ -1,8 +1,23 @@ from pathlib import Path +import os +import struct project_root = Path(SPECPATH).parent assets_root = project_root / 'src' / 'cbb_refresh_verify' / 'assets' bridge_path = project_root / 'tools' / 'status_bridge' / 'bin' / 'CbbStatusBridge32.exe' verify_probe_path = project_root / 'tools' / 'status_bridge' / 'bin' / 'VerifyProbe32.exe' +# App-local x86 runtime belongs beside the x86 bridge, separate from Qt/Python. +bridge_runtime = [] +if bridge_path.is_file(): + runtime_root = Path(os.environ.get('WINDIR', r'C:\Windows')) / 'SysWOW64' + for name in ('mfc140.dll', 'msvcp140.dll', 'vcruntime140.dll', 'concrt140.dll'): + runtime = runtime_root / name + if not runtime.is_file(): + raise RuntimeError(f'Install the Microsoft VC++ 2015-2022 x86 runtime before packaging: {runtime}') + data = runtime.read_bytes() + pe_offset = struct.unpack_from(' 0) @@ -658,12 +672,23 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None, def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_runner=None, - port_check=None, dialog_supervisor_factory=None, version_prompt=None): + port_check=None, dialog_supervisor_factory=None, version_prompt=None, stop=None): timing = RunTimings() result = _run_verify(request, timing=timing, progress=progress, flag_reader=flag_reader, process_runner=process_runner, port_check=port_check, - dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt) - if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP'} and result.evidence_path: + dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt, stop=stop) + if not request.auto_repair and result.evidence_path: + try: + release = json.loads(result.evidence_path.with_name('session-release.json').read_text('utf-8')) + if (release.get('block') == request.block_name + and Path(release['library']).resolve() == Path(request.lmc_file).resolve()): + released = release.get('worker_exited') is True and release.get('safe_to_continue') is True + result = replace(result, safe_to_continue=released) + if not released and result.status == 'PASS': + result = replace(result, status='FAIL', stderr='原生会话或自动化客户端尚未退出。') + except (OSError, ValueError, KeyError): + pass + if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP', 'CANCELLED'} and result.evidence_path: job_path = result.evidence_path.with_name('request.json') if job_path.is_file(): timing.begin('failure_diagnostics') @@ -690,16 +715,6 @@ def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_ if recovery and RECOVERY_ACTION not in detail: detail = (detail + '\n' + recovery_detail(recovery)).strip() result = replace(result, stderr=detail, error_category=ERROR_CODE) - if not request.auto_repair and result.evidence_path: - try: - release = json.loads(result.evidence_path.with_name('session-release.json').read_text('utf-8')) - if (result.error_stage in {'PCB_STARTING', 'pcb_startup'} - and release.get('worker_exited') is True and release.get('safe_to_continue') is True - and release.get('block') == request.block_name - and Path(release['library']).resolve() == Path(request.lmc_file).resolve()): - result = replace(result, safe_to_continue=True) - except (OSError, ValueError, KeyError): - pass if recovery and result.evidence_path: try: record_path = result.evidence_path.parent/'diagnostics/icdb-recovery.json' @@ -737,7 +752,7 @@ def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_runner=None, port_check=None, - dialog_supervisor_factory=None, version_prompt=None): + dialog_supervisor_factory=None, version_prompt=None, stop=None): """Refresh one CBB and record its evidence. ``flag_reader`` is a read-only probe returning an authoritative ``BridgeResult``. @@ -769,6 +784,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run pass return replace(result, evidence_path=result_path) + if stop is not None and stop.is_set(): + return finish(VerifyResult('CANCELLED', stderr='已取消,未启动校验。')) timing.begin('preflight') try: project, pcb = preflight(request) @@ -809,8 +826,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run if progress: progress({'stage': 'content_check_done', 'block': request.block_name, 'status': 'PASS'}) - # The design server needs a port in 10000-10100; a system reservation there - # blocks every item, so fail fast with the fix instead of timing out. + # Sampling cannot establish that the whole native port range is unusable. from .mentor_adapter import icdb_ports_bindable check_ports = port_check or icdb_ports_bindable ports_ok, ports_detail = check_ports() @@ -898,6 +914,10 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run ) Path(job['start_gate']).touch() while process.poll() is None: + if stop is not None and stop.is_set(): + _stop_worker(process) + return finish(VerifyResult('CANCELLED', stderr='已取消当前校验。', + safe_to_continue=False, error_stage=phase.value)) if events.exists(): with events.open(encoding='utf-8') as stream: stream.seek(offset) @@ -1043,7 +1063,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run 'observation': last_post_verify_observation, }) return finish(VerifyResult(status, stderr=detail, safe_to_continue=False)) - return finish(VerifyResult('TIMEOUT', stderr='操作超时;已停止自动化并保留原生会话,停止批次,请检查恢复记录。', error_stage=phase.value, safe_to_continue=False)) + return finish(VerifyResult('TIMEOUT', stderr='操作超时,当前项未完成。', error_stage=phase.value, safe_to_continue=False)) time.sleep(.2) worker_result = root/'outcome.json' if not worker_result.exists(): @@ -1058,6 +1078,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run return finish(VerifyResult('FAIL', stderr=str(error), safe_to_continue=False)) finally: close_errors = [] + worker_exited = False + automation_release = {'safe_to_continue': False} if 'dialog_agent' in locals() and dialog_agent is not None: try: dialog_agent.close() @@ -1065,15 +1087,37 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run close_errors.append(str(error)) if 'process' in locals(): try: + worker_exited = process.poll() is not None + if not worker_exited: + worker_exited = _stop_worker(process) + if hasattr(process, 'automation_release_state'): + automation_release = process.automation_release_state() + else: + automation_release = {'safe_to_continue': worker_exited, 'remaining_pids': []} process.close() except Exception as error: close_errors.append(str(error)) if 'process' in locals(): try: + if events.is_file(): + with events.open(encoding='utf-8') as stream: + stream.seek(offset) + for line in stream: + try: + event = json.loads(line) + timing.record(event) + if event.get('pcb_pid'): target_pid = event['pcb_pid'] + if event.get('launcher_pid'): launcher_pid = event['launcher_pid'] + if event.get('lm_pid'): lm_pid = event['lm_pid'] + if event.get('stage') == 'pcb_baseline': pcb_baseline = set(event.get('pids', ())) + except (json.JSONDecodeError, ValueError): + continue + offset = stream.tell() release_result = _cleanup_session_processes( root, lm_pid=lm_pid, target_pid=target_pid, + launcher_pid=launcher_pid, pcb=pcb, pcb_baseline=pcb_baseline, progress=progress, @@ -1090,17 +1134,22 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run if close_errors: release_result = {**(release_result or {}), 'safe_to_continue': False, 'close_errors': close_errors} + if not worker_exited or not automation_release.get('safe_to_continue'): + release_result = {**(release_result or {}), 'safe_to_continue': False, + 'automation_release': automation_release, 'worker_exited': worker_exited} + release_result['remaining_pids'] = sorted(set(release_result.get('remaining_pids', [])) + | set(automation_release.get('remaining_pids', []))) try: (root/'session-release.json').write_text(json.dumps({ **(release_result or {}), 'block': request.block_name, - 'library': str(request.lmc_file), 'worker_exited': process.poll() is not None, + 'library': str(request.lmc_file), 'worker_exited': worker_exited, 'worker_pid': getattr(process, 'pid', None)}, ensure_ascii=False, default=str, indent=2), encoding='utf-8') except OSError: pass if not release_result or not release_result.get('safe_to_continue'): if 'result' in locals(): - result = replace(result, status='FAIL', safe_to_continue=False, + result = replace(result, status='FAIL' if result.status == 'PASS' else result.status, safe_to_continue=False, stderr=(result.stderr + '\nPCB_RELEASE_UNCONFIRMED: 未确认原生会话退出').strip()) recovery = {'desktop': job['desktop'], 'project': str(project), 'pcb': str(pcb), 'release': release_result, @@ -1169,7 +1218,7 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non result = VerifyResult('FAIL', stderr=str(error), safe_to_continue=False) results.append(result) # Never start another writer after an unconfirmed native shutdown. - queue_stop = queue_stop or result.status == 'QUEUE_STOP' or not result.safe_to_continue + queue_stop = queue_stop or result.status in {'QUEUE_STOP', 'CANCELLED'} or not result.safe_to_continue if queue_stop and stop is not None: stop.set() if progress: progress(request.block_name, result) diff --git a/tests/test_abnormal_shutdown.py b/tests/test_abnormal_shutdown.py index 5ee799a..9290975 100644 --- a/tests/test_abnormal_shutdown.py +++ b/tests/test_abnormal_shutdown.py @@ -69,7 +69,7 @@ def test_crashed_worker_cannot_pass_even_with_pass_file(tmp_path, monkeypatch, o pytest.fail('A crashed writer must not become PASS via a pre-existing READY flag') result = run_verify(request(tmp_path), port_check=lambda: (True, ''), flag_reader=must_not_query) assert result.status == 'FAIL' - assert result.safe_to_continue is False + assert result.safe_to_continue is True # Proven release permits another item; crash stays FAIL. def test_supervisor_crash_stops_registered_save_helper_but_not_native(tmp_path): diff --git a/tests/test_backup_recovery.py b/tests/test_backup_recovery.py index e947d9d..8ffd433 100644 --- a/tests/test_backup_recovery.py +++ b/tests/test_backup_recovery.py @@ -144,6 +144,10 @@ def test_idle_guard_queries_supported_native_process_names(recovery_files, monke queries.append(query) return [] monkeypatch.setattr(win32com.client, 'GetObject', lambda _: EmptyProcesses()) + from cbb_refresh_verify import owner_probe + import subprocess + monkeypatch.setattr(owner_probe.subprocess, 'run', lambda command, **kw: + subprocess.CompletedProcess(command, owner_probe.owner_probe_main(command[-1]))) _idle_check(request.lmc_file, original, original.parent/'PCB/A.pcb') assert any("Name='viewdraw.exe'" in query for query in queries) diff --git a/tests/test_batch_blockers.py b/tests/test_batch_blockers.py new file mode 100644 index 0000000..4fd069a --- /dev/null +++ b/tests/test_batch_blockers.py @@ -0,0 +1,243 @@ +"""Only live clients stop a batch; native writes are replaced by fixtures.""" +import json +from pathlib import Path +from threading import Event + +import pytest + +from cbb_refresh_verify import verify_runner as runner +from test_verify_runner import fixture, request, PORTS_OK + + +@pytest.mark.parametrize('status,detail', [('FAIL', 'UNKNOWN_DIALOG: native prompt'), + ('TIMEOUT', 'native operation timed out')]) +@pytest.mark.parametrize('released', [True, False]) +def test_batch_continuation_follows_actual_release(tmp_path, monkeypatch, status, detail, released): + fixture(tmp_path) + launches = [] + class Worker: + desktop = None + returncode = 1 + def __init__(self, command, *_a, **_k): + launches.append(command) + Path(command[-1]).with_name('outcome.json').write_text(json.dumps({ + 'status': status, 'stderr': detail, 'safe_to_continue': False})) + def poll(self): return 1 + def close(self): pass + monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker) + monkeypatch.setattr(runner, '_cleanup_session_processes', lambda *a, **k: + {'safe_to_continue': released, 'remaining_pids': [] if released else [123]}) + monkeypatch.setattr('cbb_refresh_verify.verify_diagnostics.capture_failure_logs_with_timeout', lambda *_: None) + req = request(tmp_path) + try: + results = runner.run_batch([req, req], verifier=lambda r: runner.run_verify(r, port_check=PORTS_OK)) + assert results[0].status == status and results[0].safe_to_continue is released + assert len(launches) == (2 if released else 1) + assert results[1].status == (status if released else 'SKIPPED') + finally: + from cbb_refresh_verify import library_lock as locks + with locks._guard: + owner = locks._owners.pop(locks.LibraryLock(req.lmc_file).key, None) + if owner: owner['handle'].Close() + + +def test_stop_worker_escalates_only_after_cooperative_deadline(): + calls = [] + class Worker: + stopped = False + def request_stop(self): calls.append('cancel') + def wait(self, timeout=5): + calls.append('wait') + if not self.stopped: raise TimeoutError() + def kill(self): calls.append('client_stop'); self.stopped = True + def poll(self): return 1 if self.stopped else None + assert runner._stop_worker(Worker(), timeout=.1) is True + assert calls == ['cancel', 'wait', 'client_stop', 'wait'] + + +def test_cancel_reaches_current_supervised_worker(tmp_path, monkeypatch): + fixture(tmp_path) + stop = Event() + cancelled = [] + class Worker: + desktop = None + returncode = None + def __init__(self, command, *_a, **_k): + self.job = json.loads(Path(command[-1]).read_text('utf-8')) + stop.set() + def bind_cancellation(self, path): self.cancel = Path(path) + def request_stop(self): + self.cancel.touch(); cancelled.append(self.cancel) + self.returncode = 1 + def wait(self, **_k): return 1 + def poll(self): return self.returncode + def close(self): pass + monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker) + monkeypatch.setattr(runner, '_cleanup_session_processes', lambda *a, **k: {'safe_to_continue': True}) + monkeypatch.setattr('cbb_refresh_verify.verify_diagnostics.capture_failure_logs_with_timeout', lambda *_: None) + result = runner.run_verify(request(tmp_path), stop=stop, port_check=PORTS_OK) + assert result.status == 'CANCELLED' and result.safe_to_continue + assert len(cancelled) == 1 and cancelled[0].is_file() + + +@pytest.mark.parametrize('text,expected', [ + ('content checking completed successfully! 0 errors, 0 warnings', 'PASS'), + ('content checking completed successfully! 10 errors', 'FAIL'), + ('content checking completed successfully! error: missing symbol', 'FAIL'), + ('content checking completed successfully! 0 errors\nERROR: cannot connect', 'FAIL'), +]) +def test_zero_error_count_does_not_block_content_check(text, expected): + assert runner.classify_output(0, text) == expected + + +@pytest.mark.parametrize('codec', ['utf-16', 'utf-8-sig', 'mbcs']) +def test_preflight_reads_native_project_encodings(tmp_path, codec): + work = fixture(tmp_path) + (work/'CBB1.prj').write_bytes(('# 中文工程\nKEY PCBDesignPath "PCB\\actual.pcb"\n').encode(codec)) + project, pcb = runner.preflight(request(tmp_path)) + assert pcb == work/'PCB/actual.pcb' + + +def test_unrelated_pcb_does_not_block_target_before_launch(tmp_path, monkeypatch): + from test_verify_worker_stability import exercise_worker + from cbb_refresh_verify import mentor_adapter as adapter + job, events, execute = exercise_worker(tmp_path, monkeypatch) + monkeypatch.setattr(adapter, 'pcb_processes', lambda: ((999, 'ExpeditionPCB.exe', '"ExpeditionPCB.exe" "C:\\other\\board.pcb"'),)) + assert execute()['status'] == 'PASS' + assert any(e['stage'] == 'pcb_launch' for e in events) + + +def test_sampling_ports_only_warn_by_default(tmp_path, monkeypatch): + fixture(tmp_path) + launches, warnings = [], [] + class Worker: + desktop = None + returncode = 0 + def __init__(self, command, *_a, **_k): + launches.append(command) + Path(command[-1]).with_name('outcome.json').write_text('{"status":"PASS"}') + def poll(self): return 0 + def close(self): pass + monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker) + monkeypatch.setattr(runner, '_cleanup_session_processes', lambda *a, **k: {'safe_to_continue': True}) + result = runner.run_verify(request(tmp_path), port_check=lambda: (False, 'sample unavailable'), + flag_reader=lambda *_: __import__('cbb_refresh_verify.status_bridge', fromlist=['BridgeResult']).BridgeResult('READY', 'IsVerifiedReuseBlock', 1), + progress=warnings.append) + assert launches and result.status == 'PASS' + assert any(e['stage'] == 'port_warning' for e in warnings) + + +def test_cleanup_includes_late_native_descendant_without_pcb_argument(monkeypatch): + from cbb_refresh_verify import mentor_adapter as adapter + rows = [(10, 'ExpeditionPCB.exe', '', 1), (11, 'ExpeditionPCB.exe', '', 10), + (99, 'ExpeditionPCB.exe', '', 77)] + monkeypatch.setattr(adapter, '_process_details', lambda name: rows if name == 'ExpeditionPCB.exe' else []) + result = adapter.cleanup_verify_processes(None, None, 10, baseline_pids={99}) + assert not result['safe_to_continue'] and result['remaining_pids'] == [10, 11] + + +def test_save_client_without_worker_still_prevents_continuation(tmp_path, monkeypatch): + fixture(tmp_path) + class Worker: + desktop = None + returncode = 1 + def __init__(self, command, *_a, **_k): + Path(command[-1]).with_name('outcome.json').write_text('{"status":"FAIL"}') + def poll(self): return 1 + def close(self): pass + def automation_release_state(self): return {'safe_to_continue': False, 'remaining_pids': [333]} + monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker) + monkeypatch.setattr(runner, '_cleanup_session_processes', lambda *a, **k: {'safe_to_continue': True}) + monkeypatch.setattr('cbb_refresh_verify.verify_diagnostics.capture_failure_logs_with_timeout', lambda *_: None) + req = request(tmp_path) + try: + result = runner.run_verify(req, port_check=PORTS_OK) + assert not result.safe_to_continue + proof = json.loads(result.evidence_path.with_name('session-release.json').read_text('utf-8')) + assert proof['worker_exited'] is True + assert proof['automation_release']['remaining_pids'] == [333] + assert proof['remaining_pids'] == [333] + finally: + from cbb_refresh_verify import library_lock as locks + with locks._guard: + owner = locks._owners.pop(locks.LibraryLock(req.lmc_file).key, None) + if owner: owner['handle'].Close() + + +def test_closed_desktop_worker_keeps_exit_status_without_using_closed_handle(monkeypatch): + from types import SimpleNamespace + from cbb_refresh_verify import desktop_worker as desktop + worker = desktop.DesktopWorker.__new__(desktop.DesktopWorker) + handle = SimpleNamespace(closed=False) + def close(): handle.closed = True + handle.Close = close + worker.handle = handle + worker.job = SimpleNamespace(Close=lambda: None) + worker.desktop = None; worker.companions = []; worker.companion_pids = [] + def code(h): + assert not h.closed, 'Read from a closed Win32 process handle' + return 1 + monkeypatch.setattr(desktop.win32process, 'GetExitCodeProcess', code) + worker.close() + assert worker.poll() == 1 + worker.close() # Idempotent cleanup. + + +def test_native_process_queries_use_bounded_shared_helper(monkeypatch): + from cbb_refresh_verify import mentor_adapter as adapter + calls = [] + def query(names): + calls.append(names) + return [{'pid': 12, 'executable': 'ExpeditionPCB.exe', 'command': 'native', 'parent': 11}] + monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', query) + assert adapter._process_details('ExpeditionPCB.exe') == [(12, 'ExpeditionPCB.exe', 'native', 11)] + assert calls == [('ExpeditionPCB.exe',)] + + +@pytest.mark.parametrize('script', ['save_verified_block.vbs', 'close_failed_block.vbs']) +def test_save_and_failure_close_clients_are_both_tracked(script, monkeypatch): + from cbb_refresh_verify import desktop_worker as desktop + worker = desktop.DesktopWorker.__new__(desktop.DesktopWorker) + worker.pid = 11; worker._closed = True; worker._exit_code = 1 + command = f'cscript.exe //nologo "{Path(desktop.__file__).with_name(script)}" "C:\\fixture\\design.prj"' + monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_a, **_k: [ + {'pid': 22, 'parent': 11, 'command': command}, + {'pid': 33, 'parent': 99, 'command': command}, + {'pid': 44, 'parent': 11, 'command': 'cscript.exe unrelated.vbs'}]) + proof = worker.automation_release_state() + assert proof['safe_to_continue'] is False and proof['remaining_pids'] == [22] + + +def test_watchdog_with_cancel_signal_stops_clients_after_supervisor_exit(tmp_path): + import subprocess, sys, time + import win32api, win32con, win32process + supervisor = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)']) + script = tmp_path/'watchdog.py'; ready = tmp_path/'ready.json'; cancel = tmp_path/'cancel.signal' + script.write_text( + 'import sys, subprocess, time, json\nfrom pathlib import Path\n' + 'from cbb_refresh_verify.desktop_worker import start_supervisor_watchdog, launch_save_helper\n' + f'start_supervisor_watchdog({supervisor.pid}, cancel_path={str(cancel)!r}, stop_clients=True)\n' + 'native = subprocess.Popen([sys.executable,"-c","import time; time.sleep(30)"])\n' + 'client = launch_save_helper([sys.executable,"-c","import time; time.sleep(30)"])\n' + f'Path({str(ready)!r}).write_text(json.dumps([native.pid,client.pid]))\n' + 'time.sleep(30)\n', encoding='utf-8') + worker = subprocess.Popen([sys.executable, str(script)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + handles = [] + try: + deadline = time.monotonic()+10 + while not ready.exists() and worker.poll() is None and time.monotonic()= .08 if save_ok: - assert completed.returncode == 0, completed.stderr + assert completed.returncode == (10 if other_document else 0), completed.stderr assert 'SAVE_OK' in parsed['markers'] assert 'CLOSE_OK' in parsed['markers'] assert parsed['timings_seconds']['post_save_check'] >= 0 assert parsed['timings_seconds']['close'] >= 0 + assert ('TEST_QUIT' in completed.stdout) is (not other_document) + assert ('APP_RETAINED_OTHER_DOCUMENT' in completed.stdout) is other_document else: assert completed.returncode == 4, completed.stderr assert 'SAVE_OK' not in parsed['markers'] diff --git a/tests/test_verify_runner.py b/tests/test_verify_runner.py index 0c2ae51..beca08d 100644 --- a/tests/test_verify_runner.py +++ b/tests/test_verify_runner.py @@ -499,7 +499,7 @@ def test_parallelism_rejected_for_shared_library(tmp_path): run_batch([], max_workers=2) -def test_timeout_stops_automation_and_blocks_next_item(tmp_path, monkeypatch): +def test_timeout_stops_automation_and_allows_retry_when_no_native_owner_remains(tmp_path, monkeypatch): """A timed-out item must not leave a Mentor process holding the library.""" fixture(tmp_path) killed = [] @@ -508,9 +508,9 @@ def test_timeout_stops_automation_and_blocks_next_item(tmp_path, monkeypatch): def __init__(self, command, name): self.name = name self.desktop = None - def poll(self): return None + def poll(self): return self.returncode returncode = None - def kill(self): killed.append(True) + def kill(self): killed.append(True); self.returncode = 1 def wait(self, timeout=5): return 0 def close(self): pass @@ -521,7 +521,7 @@ def test_timeout_stops_automation_and_blocks_next_item(tmp_path, monkeypatch): assert result.status == 'TIMEOUT' assert killed == [True] - assert not result.safe_to_continue + assert result.safe_to_continue def test_fatal_dialog_terminates_current_worker_and_cannot_become_pass(tmp_path, monkeypatch): @@ -532,8 +532,8 @@ def test_fatal_dialog_terminates_current_worker_and_cannot_become_pass(tmp_path, desktop = object() returncode = None def __init__(self, command, name): pass - def poll(self): return None - def kill(self): killed.append(True) + def poll(self): return self.returncode + def kill(self): killed.append(True); self.returncode = 1 def wait(self, timeout=5): return 1 def close(self): pass @@ -598,8 +598,8 @@ def test_unknown_dialog_writes_snapshot_before_current_item_fails(tmp_path, monk companion_pids = [701] returncode = None def __init__(self, command, name): self.name = name - def poll(self): return None - def kill(self): killed.append(True) + def poll(self): return self.returncode + def kill(self): killed.append(True); self.returncode = 1 def wait(self, timeout=5): return 1 def close(self): pass @@ -747,7 +747,7 @@ def test_reserved_design_server_ports_block_the_item_fast(tmp_path): assert result.evidence_path.is_file() -def test_reserved_design_server_ports_block_by_default_before_worker(tmp_path, monkeypatch): +def test_reserved_design_server_ports_block_only_in_explicit_strict_mode(tmp_path, monkeypatch): fixture(tmp_path) class FakeWorker: def __init__(self, command, name): @@ -757,7 +757,7 @@ def test_reserved_design_server_ports_block_by_default_before_worker(tmp_path, m def close(self): pass import cbb_refresh_verify.desktop_worker as desktop_worker monkeypatch.setattr(desktop_worker, 'DesktopWorker', FakeWorker) - result = run_verify(request(tmp_path), port_check=lambda: (False, '端口区间被系统保留'), + result = run_verify(request(tmp_path, strict_port_check=True), port_check=lambda: (False, '端口区间被系统保留'), progress=lambda event: None) assert result.status == 'BLOCKED' assert '保留' in result.stderr