fix: continue released verify batches and bound automation shutdown

This commit is contained in:
阿白叔 committed 2026-11-04 20:51:35 +08:00
1 parent 477a5a46e3
commit 00db1cf5f2
23 files changed
+550 -115

No files matched your search

@@ -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 部署依赖,没有伪造状态,也未加入新的全功能禁用入口。
@@ -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`,下表按当前源码重新核对,不能照搬原报告的测试数或认定全部已修复。 复核基准:最新工单 [#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 被全局进程检查拦截。 最新测试程序的日志位于 `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 被全局进程检查拦截。
+16 -1
View File
@@ -1,8 +1,23 @@
from pathlib import Path from pathlib import Path
import os
import struct
project_root = Path(SPECPATH).parent project_root = Path(SPECPATH).parent
assets_root = project_root / 'src' / 'cbb_refresh_verify' / 'assets' assets_root = project_root / 'src' / 'cbb_refresh_verify' / 'assets'
bridge_path = project_root / 'tools' / 'status_bridge' / 'bin' / 'CbbStatusBridge32.exe' bridge_path = project_root / 'tools' / 'status_bridge' / 'bin' / 'CbbStatusBridge32.exe'
verify_probe_path = project_root / 'tools' / 'status_bridge' / 'bin' / 'VerifyProbe32.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('<I', data, 0x3c)[0]
if data[pe_offset:pe_offset+4] != b'PE\x00\x00' or struct.unpack_from('<H', data, pe_offset+4)[0] != 0x14c:
raise RuntimeError(f'Expected an x86 bridge runtime: {runtime}')
bridge_runtime.append((str(runtime), 'tools/status_bridge/bin'))
a = Analysis( a = Analysis(
[str(project_root / 'src' / 'cbb_refresh_verify' / '__main__.py')], [str(project_root / 'src' / 'cbb_refresh_verify' / '__main__.py')],
pathex=[str(project_root / 'src'), r'F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src'], pathex=[str(project_root / 'src'), r'F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src'],
@@ -12,7 +27,7 @@ a = Analysis(
[(str(verify_probe_path), 'tools/status_bridge/bin')] [(str(verify_probe_path), 'tools/status_bridge/bin')]
if verify_probe_path.is_file() else [] if verify_probe_path.is_file() else []
), ),
datas=[(str(project_root / 'src' / 'cbb_refresh_verify' / 'save_verified_block.vbs'), 'cbb_refresh_verify'), datas=bridge_runtime + [(str(project_root / 'src' / 'cbb_refresh_verify' / 'save_verified_block.vbs'), 'cbb_refresh_verify'),
(str(project_root / 'src' / 'cbb_refresh_verify' / 'close_failed_block.vbs'), 'cbb_refresh_verify'), (str(project_root / 'src' / 'cbb_refresh_verify' / 'close_failed_block.vbs'), 'cbb_refresh_verify'),
(str(assets_root / 'cbb_refresh_verify.ico'), 'cbb_refresh_verify/assets'), (str(assets_root / 'cbb_refresh_verify.ico'), 'cbb_refresh_verify/assets'),
(str(assets_root / 'cbb_refresh_verify.png'), 'cbb_refresh_verify/assets'), (str(assets_root / 'cbb_refresh_verify.png'), 'cbb_refresh_verify/assets'),
+5 -2
View File
@@ -211,7 +211,8 @@ class BatchStatusSession:
queried = 0 queried = 0
for index, name in enumerate(names): for index, name in enumerate(names):
previous = checkpoint.get(name) previous = checkpoint.get(name)
if previous and previous.fingerprint == fingerprint.sha256: if (previous and previous.status in {'READY', 'PENDING'}
and previous.fingerprint == fingerprint.sha256):
results.append(previous) results.append(previous)
continue continue
try: try:
@@ -231,7 +232,9 @@ class BatchStatusSession:
except BridgeResponseError as error: except BridgeResponseError as error:
message = str(error) message = str(error)
lower_message = message.casefold() lower_message = message.casefold()
unavailable = any(marker in message for marker in ("LMCDLL70", "私有 MFC", "未找到可用")) unavailable = any(marker in message for marker in ("LMCDLL70", "私有 MFC", "未找到可用")) or any(
code in lower_message for code in ('0xc0000135', '-1073741515', '3221225781',
'0xc000007b', '-1073741701', '3221225595'))
malformed = (any(marker in message for marker in ( malformed = (any(marker in message for marker in (
"路径不匹配", "请求标识不匹配", "CBB 标识不匹配", "路径不匹配", "请求标识不匹配", "CBB 标识不匹配",
)) or "mismatch" in lower_message) )) or "mismatch" in lower_message)
+40 -8
View File
@@ -22,7 +22,7 @@ def launch_save_helper(command, **kwargs):
return helper return helper
def start_supervisor_watchdog(supervisor_pid, *, cancel_path=None): def start_supervisor_watchdog(supervisor_pid, *, cancel_path=None, stop_clients=False):
"""A crashed supervisor must not leave unsupervised automation writing. """A crashed supervisor must not leave unsupervised automation writing.
Stop only this Python worker and its registered automation clients. Native Stop only this Python worker and its registered automation clients. Native
@@ -38,7 +38,9 @@ def start_supervisor_watchdog(supervisor_pid, *, cancel_path=None):
# Let native calls finish before the worker closes its exact # Let native calls finish before the worker closes its exact
# document. Killing a pending automation client can abandon it. # document. Killing a pending automation client can abandon it.
Path(cancel_path).touch() Path(cancel_path).touch()
return if not stop_clients:
return
threading.Event().wait(5)
with _automation_clients_lock: with _automation_clients_lock:
for helper in _automation_clients: for helper in _automation_clients:
try: try:
@@ -48,7 +50,7 @@ def start_supervisor_watchdog(supervisor_pid, *, cancel_path=None):
pass pass
finally: finally:
parent.Close() parent.Close()
if cancel_path is None: if cancel_path is None or stop_clients:
os._exit(75) os._exit(75)
thread = threading.Thread(target=watch, name='supervisor-watchdog', daemon=True) thread = threading.Thread(target=watch, name='supervisor-watchdog', daemon=True)
@@ -118,9 +120,38 @@ class DesktopWorker:
return int(pid) return int(pid)
def poll(self): def poll(self):
if getattr(self, '_closed', False):
return self._exit_code
code = win32process.GetExitCodeProcess(self.handle) code = win32process.GetExitCodeProcess(self.handle)
return None if code == 259 else code return None if code == 259 else code
def _save_clients(self):
from .owner_probe import query_owners
from .failed_session import _command_args
expected = {Path(__file__).with_name(name).resolve()
for name in ('save_verified_block.vbs', 'close_failed_block.vbs')}
clients = []
for row in query_owners(('cscript.exe',), timeout_seconds=3):
if row.get('parent') != self.pid:
continue
args = _command_args(row['command'])
if any(Path(arg).resolve() in expected for arg in args[1:] if arg.casefold().endswith('.vbs')):
clients.append(row['pid'])
return clients
def automation_release_state(self):
try:
remaining = self._save_clients()
return {'safe_to_continue': self.poll() is not None and not remaining,
'remaining_pids': remaining}
except Exception as error:
return {'safe_to_continue': False, 'remaining_pids': [], 'error': str(error)}
def stop_automation_clients(self):
from .mentor_adapter import _terminate_pid
for pid in self._save_clients():
_terminate_pid(pid)
@property @property
def returncode(self): def returncode(self):
return self.poll() return self.poll()
@@ -132,12 +163,9 @@ class DesktopWorker:
except Exception: except Exception:
pass pass
# The worker is now stopped and cannot spawn another save helper. # The worker is now stopped and cannot spawn another save helper.
from .mentor_adapter import _process_details, _terminate_pid
try: try:
for pid, _exe, command, parent in _process_details('cscript.exe'): self.wait(timeout=5)
if (int(parent or 0) == self.pid self.stop_automation_clients()
and 'save_verified_block.vbs' in str(command).casefold()):
_terminate_pid(pid) # single automation process, no /T
except Exception: except Exception:
pass pass
for companion in self.companions: for companion in self.companions:
@@ -162,6 +190,8 @@ class DesktopWorker:
return self.poll() return self.poll()
def close(self): def close(self):
if getattr(self, '_closed', False):
return
# Releasing Python resources must not kill native database owners. # Releasing Python resources must not kill native database owners.
try: try:
if self.poll() is None: if self.poll() is None:
@@ -177,7 +207,9 @@ class DesktopWorker:
pass pass
self.companions.clear() self.companions.clear()
self.companion_pids.clear() self.companion_pids.clear()
self._exit_code = self.poll()
self.handle.Close() self.handle.Close()
self._closed = True
# Native processes keep their desktop alive if manual recovery is needed. # Native processes keep their desktop alive if manual recovery is needed.
self.job.Close() self.job.Close()
if self.desktop is not None: if self.desktop is not None:
+25 -22
View File
@@ -217,23 +217,12 @@ def launch_pcb_process(command, cwd):
def _process_details(name): def _process_details(name):
queries = { if name not in {'ExpeditionPCB.exe', 'LibraryManager.exe', 'iCDBProjectBackup.exe',
'ExpeditionPCB.exe': "SELECT ProcessId, ParentProcessId, ExecutablePath, CommandLine FROM Win32_Process WHERE Name='ExpeditionPCB.exe'", 'ReuseBlockImporter.exe', 'cscript.exe', 'viewdraw.exe'}:
'LibraryManager.exe': "SELECT ProcessId, ParentProcessId, ExecutablePath, CommandLine FROM Win32_Process WHERE Name='LibraryManager.exe'",
'iCDBProjectBackup.exe': "SELECT ProcessId, ParentProcessId, ExecutablePath, CommandLine FROM Win32_Process WHERE Name='iCDBProjectBackup.exe'",
'ReuseBlockImporter.exe': "SELECT ProcessId, ParentProcessId, ExecutablePath, CommandLine FROM Win32_Process WHERE Name='ReuseBlockImporter.exe'",
'cscript.exe': "SELECT ProcessId, ParentProcessId, ExecutablePath, CommandLine FROM Win32_Process WHERE Name='cscript.exe'",
'viewdraw.exe': "SELECT ProcessId, ParentProcessId, ExecutablePath, CommandLine FROM Win32_Process WHERE Name='viewdraw.exe'",
}
if name not in queries:
raise ValueError(f'Unsupported process query: {name}') raise ValueError(f'Unsupported process query: {name}')
import win32com.client from .owner_probe import query_owners
service = win32com.client.GetObject('winmgmts:') return [(row['pid'], row['executable'], row['command'], row['parent'])
return [ for row in query_owners((name,))]
(int(p.ProcessId), str(p.ExecutablePath or ''), str(p.CommandLine or ''),
int(p.ParentProcessId or 0))
for p in service.ExecQuery(queries[name])
]
def _processes(name): def _processes(name):
@@ -616,11 +605,15 @@ def execute_job(job, emit):
root = Path(job['root']) root = Path(job['root'])
block_root = Path(job['project']).parent.parent block_root = Path(job['project']).parent.parent
# COM publishes a shared active application. Never attach while another # Unrelated designs stay open; COM and save helpers still require the exact
# native PCB session (including a retained failure) is still running. # project identity before any integration or save call.
pcb_before = {pid for pid, _, _ in pcb_processes()} from .failed_session import _command_args
if pcb_before: existing = tuple(pcb_processes())
raise RuntimeError(f'PCB_SESSION_ACTIVE: 已有 PCB 会话,请正常关闭后再校验: {sorted(pcb_before)}') pcb_before = {pid for pid, _, _ in existing}
expected = os.path.normcase(os.path.abspath(job['pcb']))
for pid, _, command in existing:
if command and expected in [os.path.normcase(os.path.abspath(a)) for a in _command_args(command)[1:]]:
raise RuntimeError(f'PCB_SESSION_ACTIVE: 目标工程已经打开:{pid}')
# Backups are user-managed on local and network libraries alike. # Backups are user-managed on local and network libraries alike.
mapped_drive = str(job.get('mapped_drive') or '') mapped_drive = str(job.get('mapped_drive') or '')
mapped_remote_root = str(job.get('mapped_remote_root') or '') mapped_remote_root = str(job.get('mapped_remote_root') or '')
@@ -820,6 +813,8 @@ def execute_job(job, emit):
emit(stage='save_helper', helper_pid=helper.pid) emit(stage='save_helper', helper_pid=helper.pid)
last_markers = () last_markers = ()
while helper.poll() is None: while helper.poll() is None:
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
raise RuntimeError('VERIFY_CANCELLED: 已停止等待保存客户端')
try: try:
current = tuple(line.strip() for line in (root/'save.log').read_text(encoding='utf-8', errors='replace').splitlines() if line.strip()) current = tuple(line.strip() for line in (root/'save.log').read_text(encoding='utf-8', errors='replace').splitlines() if line.strip())
except OSError: except OSError:
@@ -939,6 +934,14 @@ def cleanup_verify_processes(lm_pid, worker_pid, worker_parent_pid=None, *,
if (expected_pcb and int(pid) not in baseline if (expected_pcb and int(pid) not in baseline
and is_reusable_circuit_pcb(executable, command, expected_pcb)): and is_reusable_circuit_pcb(executable, command, expected_pcb)):
tracked.add(int(pid)) tracked.add(int(pid))
# Native launcher children can omit the PCB argument. Track only new
# descendants of this task's already identified native processes.
while True:
children = {int(pid) for pid, _, _, parent in pcb_records
if int(pid) not in baseline and int(parent) in tracked}
if children.issubset(tracked):
break
tracked.update(children)
alive = {int(record[0]) for record in (*pcb_records, *lm_records)} alive = {int(record[0]) for record in (*pcb_records, *lm_records)}
remaining = sorted(tracked & alive) remaining = sorted(tracked & alive)
result = {'safe_to_continue': not remaining, 'remaining_pids': remaining} result = {'safe_to_continue': not remaining, 'remaining_pids': remaining}
@@ -984,7 +987,7 @@ def worker_main(request_path):
try: try:
if job.get('supervisor_pid'): if job.get('supervisor_pid'):
from .desktop_worker import start_supervisor_watchdog from .desktop_worker import start_supervisor_watchdog
start_supervisor_watchdog(job['supervisor_pid'], cancel_path=job.get('cancel_signal')) start_supervisor_watchdog(job['supervisor_pid'], cancel_path=job.get('cancel_signal'), stop_clients=True)
start_gate = Path(job.get('start_gate', '')) if job.get('start_gate') else None start_gate = Path(job.get('start_gate', '')) if job.get('start_gate') else None
if start_gate is not None: if start_gate is not None:
gate_deadline = time.monotonic() + 15 gate_deadline = time.monotonic() + 15
+5 -3
View File
@@ -31,7 +31,8 @@ def query_owners(names, *, timeout_seconds=10):
raise ValueError('invalid result') raise ValueError('invalid result')
for row in rows: for row in rows:
if (type(row['pid']) is not int or row['pid'] <= 0 or row['name'].casefold() not in {n.casefold() for n in names} if (type(row['pid']) is not int or row['pid'] <= 0 or row['name'].casefold() not in {n.casefold() for n in names}
or not isinstance(row['command'], str)): or not isinstance(row['command'], str) or not isinstance(row['executable'], str)
or type(row['parent']) is not int or row['parent'] < 0):
raise ValueError('invalid owner') raise ValueError('invalid owner')
return rows return rows
except (OSError, ValueError, KeyError, TypeError, AttributeError) as error: except (OSError, ValueError, KeyError, TypeError, AttributeError) as error:
@@ -48,10 +49,11 @@ def owner_probe_main(job):
pythoncom.CoInitialize() pythoncom.CoInitialize()
try: try:
service = win32com.client.GetObject('winmgmts:') service = win32com.client.GetObject('winmgmts:')
query = 'SELECT ProcessId,Name,CommandLine FROM Win32_Process WHERE ' + ' OR '.join( query = 'SELECT ProcessId,Name,CommandLine,ExecutablePath,ParentProcessId FROM Win32_Process WHERE ' + ' OR '.join(
f"Name='{name}'" for name in names) f"Name='{name}'" for name in names)
rows = [{'pid': int(item.ProcessId), 'name': str(item.Name), rows = [{'pid': int(item.ProcessId), 'name': str(item.Name),
'command': str(item.CommandLine or '')} for item in service.ExecQuery(query)] 'command': str(item.CommandLine or ''), 'executable': str(item.ExecutablePath or ''),
'parent': int(item.ParentProcessId or 0)} for item in service.ExecQuery(query)]
service = None service = None
job.with_name('result.json').write_text(json.dumps({'names': names, 'owners': rows}), encoding='utf-8') job.with_name('result.json').write_text(json.dumps({'names': names, 'owners': rows}), encoding='utf-8')
return 0 return 0
@@ -1,5 +1,5 @@
Option Explicit Option Explicit
Dim app, doc, pi, licensing, token, expected, attempt, stable, measuredStart, operationOK Dim app, doc, pi, licensing, token, expected, attempt, stable, measuredStart, operationOK, remaining
expected = WScript.Arguments(0) expected = WScript.Arguments(0)
Set app = GetObject(, "MGCPCB.Application") Set app = GetObject(, "MGCPCB.Application")
Set doc = app.ActiveDocument Set doc = app.ActiveDocument
@@ -55,6 +55,13 @@ WScript.Echo "CLOSE_OK"
Set pi = Nothing Set pi = Nothing
Set doc = Nothing Set doc = Nothing
Set licensing = Nothing Set licensing = Nothing
Set remaining = app.ActiveDocument
If Not remaining Is Nothing Then
Set remaining = Nothing
WScript.Echo "APP_RETAINED_OTHER_DOCUMENT"
WScript.Quit 10
End If
Set remaining = Nothing
measuredStart = Timer measuredStart = Timer
app.Quit app.Quit
LogElapsed "quit", measuredStart LogElapsed "quit", measuredStart
+2 -2
View File
@@ -315,7 +315,7 @@ class MainWindow(QWidget):
self.counts_label.setText(f'可见 {counts["visible"]} / {len(self._records_by_name)} · ' self.counts_label.setText(f'可见 {counts["visible"]} / {len(self._records_by_name)} · '
f'READY {counts["ready"]} · 异常/待确认 {counts["error"]}') f'READY {counts["ready"]} · 异常/待确认 {counts["error"]}')
self.stop_button.setEnabled(self.busy and self.loaded_path is not None and not self.stop.is_set()) self.stop_button.setEnabled(self.busy and self.loaded_path is not None and not self.stop.is_set())
self.stop_button.setText('取消当前检查并停止队列' if self._global_icdb_run else '当前项完成后停止') self.stop_button.setText('取消当前任务并停止队列')
available = bool(self._reimport_offers) and not self.busy and self.management_capabilities['update'].supported available = bool(self._reimport_offers) and not self.busy and self.management_capabilities['update'].supported
self.reimport_button.setVisible(bool(self._reimport_offers)) self.reimport_button.setVisible(bool(self._reimport_offers))
self.reimport_button.setEnabled(available) self.reimport_button.setEnabled(available)
@@ -888,7 +888,7 @@ class MainWindow(QWidget):
'native_repair_finished': '原生修复已结束,正在核对结果'} 'native_repair_finished': '原生修复已结束,正在核对结果'}
if stage in phases: if stage in phases:
self.icdb_phase.setText(f'{block or ""} · {phases[stage]}') self.icdb_phase.setText(f'{block or ""} · {phases[stage]}')
if block and stage in {'PASS', 'FAIL', 'BLOCKED', 'TIMEOUT', 'SKIPPED', 'CHECKED', 'REPAIRED'}: if block and stage in {'PASS', 'FAIL', 'BLOCKED', 'TIMEOUT', 'SKIPPED', 'CHECKED', 'REPAIRED', 'CANCELLED'}:
row = self._row_by_name.get(block) row = self._row_by_name.get(block)
if row is not None: if row is not None:
detail = str(event.get('detail') or event.get('error') or '').strip() detail = str(event.get('detail') or event.get('error') or '').strip()
+77 -28
View File
@@ -56,7 +56,7 @@ class VerifyRequest:
# A reserved iCDB range is a host-wide prerequisite failure. Do not # A reserved iCDB range is a host-wide prerequisite failure. Do not
# launch a PCB that is guaranteed to time out; batch orchestration will # launch a PCB that is guaranteed to time out; batch orchestration will
# record this item and continue with the next one. # record this item and continue with the next one.
strict_port_check: bool = True strict_port_check: bool = False
# A mapped drive can be invisible to an elevated/private worker on Win10. # A mapped drive can be invisible to an elevated/private worker on Win10.
# Preserve the parent session's mapping identity so the worker can restore # Preserve the parent session's mapping identity so the worker can restore
# it before launching Library Manager/PCB. # it before launching Library Manager/PCB.
@@ -135,7 +135,8 @@ def classify_output(exit_code: int | None, output: str, *, timed_out: bool = Fal
from .icdb_recovery import parse_session_loss from .icdb_recovery import parse_session_loss
if parse_session_loss(output): if parse_session_loss(output):
return 'FAIL' return 'FAIL'
if exit_code == 0 and SUCCESS_TEXT.search(output) and not ERROR_TEXT.search(output): diagnostic_text = re.sub(r'\b0\s+errors?\b', '', output, flags=re.I)
if exit_code == 0 and SUCCESS_TEXT.search(output) and not ERROR_TEXT.search(diagnostic_text):
return 'PASS' return 'PASS'
if ERROR_TEXT.search(output): if ERROR_TEXT.search(output):
return 'FAIL' return 'FAIL'
@@ -157,7 +158,8 @@ def preflight(request):
if len(projects) != 1: if len(projects) != 1:
raise ValueError(f'{name}: 缺少或无法唯一确定 Work 下的工程 PRJ') raise ValueError(f'{name}: 缺少或无法唯一确定 Work 下的工程 PRJ')
project = absolute_preserving_drive(projects[0]) project = absolute_preserving_drive(projects[0])
content = project.read_text(encoding='utf-8', errors='replace') from .backup_recovery import _project_text
content = _project_text(project)
refs = re.findall(r'^KEY PCBDesignPath "([^"]+)"', content, re.M) refs = re.findall(r'^KEY PCBDesignPath "([^"]+)"', content, re.M)
if not refs: if not refs:
raise ValueError(f'{name}: 工程没有 PCBDesignPath') raise ValueError(f'{name}: 工程没有 PCBDesignPath')
@@ -220,7 +222,17 @@ def _stop_worker(process, *, timeout=5):
try: try:
process.wait(timeout=timeout) process.wait(timeout=timeout)
except Exception: except Exception:
pass try:
process.kill() # Automation clients only; never the native tree.
process.wait(timeout=5)
except Exception:
pass
try:
if hasattr(process, 'stop_automation_clients'):
process.stop_automation_clients()
return process.poll() is not None
except Exception:
return False
def _normalize_bridge_result(probe): def _normalize_bridge_result(probe):
@@ -480,7 +492,7 @@ def native_lm_verify_enabled():
} }
def _cleanup_session_processes(root, *, lm_pid, target_pid, pcb, pcb_baseline, def _cleanup_session_processes(root, *, lm_pid, target_pid, pcb, pcb_baseline, launcher_pid=None,
progress=None): progress=None):
"""Record native release or retention after automation has stopped.""" """Record native release or retention after automation has stopped."""
from .mentor_adapter import cleanup_verify_processes from .mentor_adapter import cleanup_verify_processes
@@ -504,7 +516,7 @@ def _cleanup_session_processes(root, *, lm_pid, target_pid, pcb, pcb_baseline,
return cleanup_verify_processes( return cleanup_verify_processes(
lm_pid, lm_pid,
target_pid, target_pid,
None, launcher_pid,
expected_pcb=pcb, expected_pcb=pcb,
baseline_pids=pcb_baseline, baseline_pids=pcb_baseline,
emit=emit, emit=emit,
@@ -554,7 +566,7 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
result = _run_verify_serialized( result = _run_verify_serialized(
request, progress=progress, flag_reader=flag_reader, request, progress=progress, flag_reader=flag_reader,
process_runner=process_runner, port_check=port_check, process_runner=process_runner, port_check=port_check,
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt) dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt, stop=stop)
if (request.auto_repair and result.status not in {'TIMEOUT', 'BLOCKED'} if (request.auto_repair and result.status not in {'TIMEOUT', 'BLOCKED'}
and result.error_category == 'ICDB_REPAIR_REQUIRED' and result.error_category == 'ICDB_REPAIR_REQUIRED'
and result.evidence_path): and result.evidence_path):
@@ -639,7 +651,9 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
release_confirmed = (release.get('worker_exited') is True release_confirmed = (release.get('worker_exited') is True
and release.get('safe_to_continue') is True and release.get('block') == request.block_name 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()) and Path(release['library']).resolve() == Path(request.lmc_file).resolve())
if (release.get('worker_exited') is True and release.get('block') == request.block_name if (release.get('worker_exited') is True and not release.get('error')
and not release.get('close_errors') and not release.get('automation_release', {}).get('error')
and release.get('block') == request.block_name
and Path(release['library']).resolve() == Path(request.lmc_file).resolve()): and Path(release['library']).resolve() == Path(request.lmc_file).resolve()):
remaining_clients = tuple(pid for pid in release.get('remaining_pids', []) remaining_clients = tuple(pid for pid in release.get('remaining_pids', [])
if type(pid) is int and pid > 0) if type(pid) is int and pid > 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, 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() timing = RunTimings()
result = _run_verify(request, timing=timing, progress=progress, flag_reader=flag_reader, result = _run_verify(request, timing=timing, progress=progress, flag_reader=flag_reader,
process_runner=process_runner, port_check=port_check, process_runner=process_runner, port_check=port_check,
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt) dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt, stop=stop)
if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP'} and result.evidence_path: 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') job_path = result.evidence_path.with_name('request.json')
if job_path.is_file(): if job_path.is_file():
timing.begin('failure_diagnostics') 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: if recovery and RECOVERY_ACTION not in detail:
detail = (detail + '\n' + recovery_detail(recovery)).strip() detail = (detail + '\n' + recovery_detail(recovery)).strip()
result = replace(result, stderr=detail, error_category=ERROR_CODE) 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: if recovery and result.evidence_path:
try: try:
record_path = result.evidence_path.parent/'diagnostics/icdb-recovery.json' 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, 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. """Refresh one CBB and record its evidence.
``flag_reader`` is a read-only probe returning an authoritative ``BridgeResult``. ``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 pass
return replace(result, evidence_path=result_path) return replace(result, evidence_path=result_path)
if stop is not None and stop.is_set():
return finish(VerifyResult('CANCELLED', stderr='已取消,未启动校验。'))
timing.begin('preflight') timing.begin('preflight')
try: try:
project, pcb = preflight(request) project, pcb = preflight(request)
@@ -809,8 +826,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
if progress: if progress:
progress({'stage': 'content_check_done', 'block': request.block_name, 'status': 'PASS'}) progress({'stage': 'content_check_done', 'block': request.block_name, 'status': 'PASS'})
# The design server needs a port in 10000-10100; a system reservation there # Sampling cannot establish that the whole native port range is unusable.
# blocks every item, so fail fast with the fix instead of timing out.
from .mentor_adapter import icdb_ports_bindable from .mentor_adapter import icdb_ports_bindable
check_ports = port_check or icdb_ports_bindable check_ports = port_check or icdb_ports_bindable
ports_ok, ports_detail = check_ports() 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() Path(job['start_gate']).touch()
while process.poll() is None: 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(): if events.exists():
with events.open(encoding='utf-8') as stream: with events.open(encoding='utf-8') as stream:
stream.seek(offset) stream.seek(offset)
@@ -1043,7 +1063,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
'observation': last_post_verify_observation, 'observation': last_post_verify_observation,
}) })
return finish(VerifyResult(status, stderr=detail, safe_to_continue=False)) 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) time.sleep(.2)
worker_result = root/'outcome.json' worker_result = root/'outcome.json'
if not worker_result.exists(): 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)) return finish(VerifyResult('FAIL', stderr=str(error), safe_to_continue=False))
finally: finally:
close_errors = [] close_errors = []
worker_exited = False
automation_release = {'safe_to_continue': False}
if 'dialog_agent' in locals() and dialog_agent is not None: if 'dialog_agent' in locals() and dialog_agent is not None:
try: try:
dialog_agent.close() dialog_agent.close()
@@ -1065,15 +1087,37 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
close_errors.append(str(error)) close_errors.append(str(error))
if 'process' in locals(): if 'process' in locals():
try: 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() process.close()
except Exception as error: except Exception as error:
close_errors.append(str(error)) close_errors.append(str(error))
if 'process' in locals(): if 'process' in locals():
try: 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( release_result = _cleanup_session_processes(
root, root,
lm_pid=lm_pid, lm_pid=lm_pid,
target_pid=target_pid, target_pid=target_pid,
launcher_pid=launcher_pid,
pcb=pcb, pcb=pcb,
pcb_baseline=pcb_baseline, pcb_baseline=pcb_baseline,
progress=progress, progress=progress,
@@ -1090,17 +1134,22 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
if close_errors: if close_errors:
release_result = {**(release_result or {}), 'safe_to_continue': False, release_result = {**(release_result or {}), 'safe_to_continue': False,
'close_errors': close_errors} '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: try:
(root/'session-release.json').write_text(json.dumps({ (root/'session-release.json').write_text(json.dumps({
**(release_result or {}), 'block': request.block_name, **(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)}, 'worker_pid': getattr(process, 'pid', None)},
ensure_ascii=False, default=str, indent=2), encoding='utf-8') ensure_ascii=False, default=str, indent=2), encoding='utf-8')
except OSError: except OSError:
pass pass
if not release_result or not release_result.get('safe_to_continue'): if not release_result or not release_result.get('safe_to_continue'):
if 'result' in locals(): 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()) stderr=(result.stderr + '\nPCB_RELEASE_UNCONFIRMED: 未确认原生会话退出').strip())
recovery = {'desktop': job['desktop'], 'project': str(project), recovery = {'desktop': job['desktop'], 'project': str(project),
'pcb': str(pcb), 'release': release_result, '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) result = VerifyResult('FAIL', stderr=str(error), safe_to_continue=False)
results.append(result) results.append(result)
# Never start another writer after an unconfirmed native shutdown. # 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: if queue_stop and stop is not None:
stop.set() stop.set()
if progress: progress(request.block_name, result) if progress: progress(request.block_name, result)
+1 -1
View File
@@ -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') 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) result = run_verify(request(tmp_path), port_check=lambda: (True, ''), flag_reader=must_not_query)
assert result.status == 'FAIL' 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): def test_supervisor_crash_stops_registered_save_helper_but_not_native(tmp_path):
+4
View File
@@ -144,6 +144,10 @@ def test_idle_guard_queries_supported_native_process_names(recovery_files, monke
queries.append(query) queries.append(query)
return [] return []
monkeypatch.setattr(win32com.client, 'GetObject', lambda _: EmptyProcesses()) 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') _idle_check(request.lmc_file, original, original.parent/'PCB/A.pcb')
assert any("Name='viewdraw.exe'" in query for query in queries) assert any("Name='viewdraw.exe'" in query for query in queries)
+243
View File
@@ -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()<deadline:
time.sleep(.05)
assert ready.exists()
for pid in json.loads(ready.read_text()):
handles.append(win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_TERMINATE, False, pid))
supervisor.terminate(); supervisor.wait(5)
assert worker.wait(10) == 75 and cancel.is_file()
assert win32process.GetExitCodeProcess(handles[0]) == 259
assert win32process.GetExitCodeProcess(handles[1]) != 259
finally:
for p in (supervisor, worker):
if p.poll() is None: p.terminate()
p.wait(5)
for h in handles:
if win32process.GetExitCodeProcess(h) == 259: win32process.TerminateProcess(h, 0)
h.Close()
+23
View File
@@ -172,3 +172,26 @@ def test_authoritative_status_map_never_reuses_previous_scan_status(tmp_path, mo
assert first == {'A': 'PENDING'} assert first == {'A': 'PENDING'}
assert second == {'A': 'READY'} assert second == {'A': 'READY'}
assert calls == ['A', 'A'] assert calls == ['A', 'A']
def test_retry_rechecks_failed_scan_without_library_changes(tmp_path):
lmc = tmp_path/'library.lmc'; lmc.write_bytes(b'library')
checkpoint = tmp_path/'scan.jsonl'
first = BatchStatusSession(FakeBridge(timeout_name='A')).scan(['A', 'B'], lmc, checkpoint)
assert first[0].status == 'TIMEOUT'
bridge = FakeBridge()
second = BatchStatusSession(bridge).scan(['A', 'B'], lmc, checkpoint)
assert bridge.requests == ['A']
assert second[0].status == 'READY'
def test_missing_x86_runtime_does_not_restart_for_every_cbb(tmp_path):
class BrokenBridge(FakeBridge):
def query(self, library, name, **kwargs):
self.requests.append(name)
raise BridgeResponseError('状态桥进程失败: -1073741515')
lmc = tmp_path/'library.lmc'; lmc.write_bytes(b'library')
bridge = BrokenBridge()
result = BatchStatusSession(bridge).scan(['A', 'B', 'C'], lmc, tmp_path/'scan.jsonl')
assert bridge.requests == ['A']
assert [row.status for row in result] == ['UNAVAILABLE'] * 3
+11 -11
View File
@@ -200,14 +200,14 @@ def test_worker_attempts_normal_close_after_idle_integration_failure(tmp_path, m
assert not any(event['stage'] == 'save_start' for event in events) assert not any(event['stage'] == 'save_start' for event in events)
def test_stop_requests_cooperative_cancel_without_terminating_busy_client(tmp_path): def test_stop_cancels_then_stops_automation_client_after_deadline(tmp_path):
calls = [] calls = []
class BusyWorker: class BusyWorker:
def request_stop(self): calls.append('cancel') def request_stop(self): calls.append('cancel')
def wait(self, timeout): raise TimeoutError('native Save still running') def wait(self, timeout): raise TimeoutError('native Save still running')
def kill(self): calls.append('kill') def kill(self): calls.append('kill')
runner._stop_worker(BusyWorker(), timeout=0) runner._stop_worker(BusyWorker(), timeout=0)
assert calls == ['cancel'] assert calls == ['cancel', 'kill']
def test_status_server_close_allows_eof_cleanup_before_termination(tmp_path): def test_status_server_close_allows_eof_cleanup_before_termination(tmp_path):
@@ -225,21 +225,22 @@ def test_status_server_close_allows_eof_cleanup_before_termination(tmp_path):
assert marker.is_file() assert marker.is_file()
def test_shared_symbol_database_owner_blocks_content_check_and_pcb(tmp_path, monkeypatch): def test_shared_address_does_not_block_actual_content_check(tmp_path, monkeypatch):
from test_verify_runner import fixture, request from test_verify_runner import fixture, request
fixture(tmp_path) fixture(tmp_path)
address = tmp_path/'SymbolLibs/__ReusableBlocksSymb/cdbsvr/sAddress.adr' address = tmp_path/'SymbolLibs/__ReusableBlocksSymb/cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True) address.parent.mkdir(parents=True)
address.write_bytes(b'unknown native owner') address.write_bytes(b'unknown native owner')
req = request(tmp_path, libspec='EE', dms_login_config='login') req = request(tmp_path, libspec='EE', dms_login_config='login')
outcome = runner.run_verify(req, process_runner=lambda *args: pytest.fail('must not launch importer')) calls = []
assert outcome.status == 'BLOCKED' outcome = runner.run_verify(req, process_runner=lambda *args:
assert outcome.safe_to_continue is False (calls.append(args) or (1, 'ERROR: shared database unavailable', '', False)))
assert '__ReusableBlocksSymb' in outcome.stderr assert calls and outcome.status == 'FAIL' and outcome.safe_to_continue
assert 'shared database unavailable' in outcome.stderr
assert address.read_bytes() == b'unknown native owner' assert address.read_bytes() == b'unknown native owner'
def test_shared_symbol_database_must_be_released_before_pass(tmp_path, monkeypatch): def test_shared_address_is_diagnostic_after_successful_native_execution(tmp_path, monkeypatch):
from test_verify_worker_stability import exercise_worker from test_verify_worker_stability import exercise_worker
from cbb_refresh_verify import mentor_adapter as adapter from cbb_refresh_verify import mentor_adapter as adapter
job, events, execute = exercise_worker(tmp_path, monkeypatch) job, events, execute = exercise_worker(tmp_path, monkeypatch)
@@ -250,9 +251,8 @@ def test_shared_symbol_database_must_be_released_before_pass(tmp_path, monkeypat
address.write_bytes(b'shared owner retained') address.write_bytes(b'shared owner retained')
return original(*args, **kwargs) return original(*args, **kwargs)
monkeypatch.setattr(adapter.subprocess, 'Popen', helper) monkeypatch.setattr(adapter.subprocess, 'Popen', helper)
with pytest.raises(RuntimeError, match='ICDB_RELEASE_UNCONFIRMED'): assert execute()['status'] == 'PASS'
execute() assert any(event['stage'] == 'icdb_address_remaining' for event in events)
assert not any(event['stage'] == 'complete' for event in events)
def test_cooperative_supervisor_loss_keeps_pending_save_helper_alive(tmp_path): def test_cooperative_supervisor_loss_keeps_pending_save_helper_alive(tmp_path):
+1 -1
View File
@@ -303,7 +303,7 @@ def test_supervisor_enriches_generic_failure_from_fresh_native_log(tmp_path, mon
monkeypatch.setattr('cbb_refresh_verify.verify_diagnostics.capture_failure_logs_with_timeout', failure_logs_main) monkeypatch.setattr('cbb_refresh_verify.verify_diagnostics.capture_failure_logs_with_timeout', failure_logs_main)
result = runner.run_verify(request(tmp_path), port_check=lambda: (True, '')) result = runner.run_verify(request(tmp_path), port_check=lambda: (True, ''))
assert result.error_category == 'ICDB_REPAIR_REQUIRED' assert result.error_category == 'ICDB_REPAIR_REQUIRED'
assert result.safe_to_continue is False assert result.safe_to_continue is True
assert 'opening failed' in result.stderr assert 'opening failed' in result.stderr
assert '200091-CBB' in result.stderr assert '200091-CBB' in result.stderr
assert '__ReusableBlocksSymb' in result.stderr assert '__ReusableBlocksSymb' in result.stderr
+8 -9
View File
@@ -27,12 +27,11 @@ def test_network_timeout_cannot_remove_database_advertisement(tmp_path, monkeypa
@pytest.mark.parametrize('state', ['LIVE', 'UNREACHABLE', 'INVALID']) @pytest.mark.parametrize('state', ['LIVE', 'UNREACHABLE', 'INVALID'])
def test_existing_database_owner_blocks_before_pcb_launch(tmp_path, monkeypatch, state): def test_address_probe_result_is_not_a_substitute_for_native_verify(tmp_path, monkeypatch, state):
job, events, execute = exercise_worker(tmp_path, monkeypatch) job, events, execute = exercise_worker(tmp_path, monkeypatch)
monkeypatch.setattr(adapter, 'prepare_icdb_address', lambda *a, **k: {'status': state}) monkeypatch.setattr(adapter, 'prepare_icdb_address', lambda *a, **k: {'status': state})
with pytest.raises(RuntimeError, match='ICDB_SESSION_UNCONFIRMED'): assert execute()['status'] == 'PASS'
execute() assert any(e['stage'] == 'pcb_launch' for e in events)
assert not any(e['stage'] == 'pcb_launch' for e in events)
@pytest.mark.parametrize('text', [ @pytest.mark.parametrize('text', [
@@ -114,7 +113,7 @@ def test_desktop_abort_does_not_kill_native_process_tree(monkeypatch):
assert worker.handle in terminated assert worker.handle in terminated
def test_saved_pcb_with_retained_icdb_address_cannot_pass(tmp_path, monkeypatch): def test_saved_pcb_with_address_records_remains_an_execution_result_for_bridge_validation(tmp_path, monkeypatch):
job, events, execute = exercise_worker(tmp_path, monkeypatch) job, events, execute = exercise_worker(tmp_path, monkeypatch)
original = adapter.subprocess.Popen original = adapter.subprocess.Popen
def helper(*a, **k): def helper(*a, **k):
@@ -123,9 +122,8 @@ def test_saved_pcb_with_retained_icdb_address_cannot_pass(tmp_path, monkeypatch)
address.write_text('still owned', encoding='ascii') address.write_text('still owned', encoding='ascii')
return original(*a, **k) return original(*a, **k)
monkeypatch.setattr(adapter.subprocess, 'Popen', helper) monkeypatch.setattr(adapter.subprocess, 'Popen', helper)
with pytest.raises(RuntimeError, match='ICDB_RELEASE_UNCONFIRMED'): assert execute()['status'] == 'PASS'
execute() assert any(e['stage'] == 'icdb_address_remaining' for e in events)
assert not any(e['stage'] == 'complete' for e in events)
def test_retained_pcb_after_close_cannot_pass_or_be_killed(tmp_path, monkeypatch): def test_retained_pcb_after_close_cannot_pass_or_be_killed(tmp_path, monkeypatch):
@@ -189,7 +187,8 @@ def test_supervisor_rejects_pass_when_native_release_is_unconfirmed(tmp_path, mo
def test_existing_pcb_session_blocks_before_mutating_project(tmp_path, monkeypatch): def test_existing_pcb_session_blocks_before_mutating_project(tmp_path, monkeypatch):
job, events, execute = exercise_worker(tmp_path, monkeypatch) job, events, execute = exercise_worker(tmp_path, monkeypatch)
monkeypatch.setattr(adapter, 'pcb_processes', lambda: ((20, 'ExpeditionPCB.exe', 'user design'),)) monkeypatch.setattr(adapter, 'pcb_processes', lambda:
((20, 'ExpeditionPCB.exe', f'ExpeditionPCB.exe "{job["pcb"]}"'),))
with pytest.raises(RuntimeError, match='PCB_SESSION_ACTIVE'): with pytest.raises(RuntimeError, match='PCB_SESSION_ACTIVE'):
execute() execute()
assert not events assert not events
+2 -2
View File
@@ -71,8 +71,8 @@ def test_repair_finishes_without_calling_verify(case, monkeypatch):
assert result.recovery_attempts[0]['validation_passed'] is False assert result.recovery_attempts[0]['validation_passed'] is False
@pytest.mark.parametrize('stage,expected_safe', [('PCB_STARTING', True), ('back_annotation', False)]) @pytest.mark.parametrize('stage,expected_safe', [('PCB_STARTING', True), ('back_annotation', True)])
def test_only_released_startup_failure_can_continue_from_icdb_diagnosis(tmp_path, monkeypatch, stage, expected_safe): def test_released_failure_can_continue_from_icdb_diagnosis(tmp_path, monkeypatch, stage, expected_safe):
import json import json
from cbb_refresh_verify import verify_runner as runner from cbb_refresh_verify import verify_runner as runner
library = tmp_path/'library.lmc'; library.touch() library = tmp_path/'library.lmc'; library.touch()
+5 -4
View File
@@ -27,7 +27,7 @@ def test_native_inspection_holds_lock_without_opening_pcb(case, monkeypatch, old
result = runner.run_verify(request) result = runner.run_verify(request)
assert result.status == 'CHECKED' and result.recovery_attempts == () assert result.status == 'CHECKED' and result.recovery_attempts == ()
assert result.library_flag == 'UNKNOWN' assert result.library_flag == 'UNKNOWN'
assert result.safe_to_continue is (not old_address) assert result.safe_to_continue is True
@pytest.mark.parametrize('fault', ['missing', 'generic', 'assertion', 'wrong_database', 'stale_verdict', 'not_exited']) @pytest.mark.parametrize('fault', ['missing', 'generic', 'assertion', 'wrong_database', 'stale_verdict', 'not_exited'])
@@ -50,7 +50,7 @@ def test_unconfirmed_native_inspection_never_repairs(case, monkeypatch, fault):
assert result.status == 'BLOCKED' and not result.recovery_attempts assert result.status == 'BLOCKED' and not result.recovery_attempts
def test_native_fault_repairs_once_then_full_verification_with_old_address(case, monkeypatch): def test_native_fault_repairs_once_without_running_separate_verification(case, monkeypatch):
from cbb_refresh_verify import verify_runner as runner, native_repair from cbb_refresh_verify import verify_runner as runner, native_repair
from test_native_repair import complete_native_success from test_native_repair import complete_native_success
request, project, address = case request, project, address = case
@@ -71,5 +71,6 @@ def test_native_fault_repairs_once_then_full_verification_with_old_address(case,
monkeypatch.setattr(native_repair, 'repair_release_state', lambda req, target, result: result['release']) monkeypatch.setattr(native_repair, 'repair_release_state', lambda req, target, result: result['release'])
monkeypatch.setattr(runner, '_run_verify_serialized', verify) monkeypatch.setattr(runner, '_run_verify_serialized', verify)
result = runner.run_verify(request) result = runner.run_verify(request)
assert calls == ['inspect', 'repair', 'verify'] assert calls == ['inspect', 'repair']
assert result.status == 'PASS' and len(result.recovery_attempts) == 1 assert result.status == 'REPAIRED' and len(result.recovery_attempts) == 1
assert result.library_flag == 'UNKNOWN' and not result.recovery_attempts[0]['validation_passed']
+5 -4
View File
@@ -80,19 +80,20 @@ def test_restart_shows_unfinished_without_starting_worker(qtbot, tmp_path):
assert 'Block' in window.output.toPlainText() assert 'Block' in window.output.toPlainText()
def test_persistent_owner_blocker_prevents_native_load_and_offers_checked_release(qtbot, tmp_path, monkeypatch): def test_historical_record_does_not_prevent_catalog_load_and_offers_checked_release(qtbot, tmp_path, monkeypatch):
import pytest import pytest
import cbb_refresh_verify.library_lock as locks import cbb_refresh_verify.library_lock as locks
from cbb_refresh_verify.ui.main_window import MainWindow from cbb_refresh_verify.ui.main_window import MainWindow
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch() library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
locks.blocker_path(library).write_text('{}', encoding='utf-8') locks.blocker_path(library).write_text('{}', encoding='utf-8')
window = MainWindow(reader=lambda _: pytest.fail('unconfirmed owner reopened'), data_root=tmp_path/'data') reads = []
window = MainWindow(reader=lambda path: (reads.append(path) or LibraryReadResult(())), data_root=tmp_path/'data')
qtbot.addWidget(window) qtbot.addWidget(window)
window.lmc_edit.setText(str(library)); window.load_library() window.lmc_edit.setText(str(library)); window.load_library()
qtbot.waitUntil(lambda: not window.busy) qtbot.waitUntil(lambda: not window.busy)
assert window.loaded_path is None assert window.loaded_path == str(library) and reads
assert window.release_library_button.isEnabled() assert window.release_library_button.isEnabled()
assert '释放检查' in window.status_label.text() assert locks.blocker_path(library).read_text() == '{}'
calls = [] calls = []
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes) monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
monkeypatch.setattr(locks, 'release_retained_library', lambda *a: monkeypatch.setattr(locks, 'release_retained_library', lambda *a:
+6 -2
View File
@@ -849,18 +849,22 @@ def test_repair_release_uses_real_process_query_contract(tmp_path, monkeypatch,
queried = [] queried = []
names = ('ExpeditionPCB.exe', 'LibraryManager.exe', 'iCDBProjectBackup.exe', names = ('ExpeditionPCB.exe', 'LibraryManager.exe', 'iCDBProjectBackup.exe',
'ReuseBlockImporter.exe', 'cscript.exe') 'ReuseBlockImporter.exe', 'cscript.exe')
queries = {"SELECT ProcessId, ParentProcessId, ExecutablePath, CommandLine " queries = {"SELECT ProcessId,Name,CommandLine,ExecutablePath,ParentProcessId "
f"FROM Win32_Process WHERE Name='{name}'": name for name in names} f"FROM Win32_Process WHERE Name='{name}'": name for name in names}
def query(wql): def query(wql):
name = queries[wql] name = queries[wql]
queried.append(name) queried.append(name)
return ([SimpleNamespace(ProcessId='456', ParentProcessId='1', return ([SimpleNamespace(ProcessId='456', ParentProcessId='1', Name=name,
ExecutablePath=f'C:\\Mentor\\{name}', CommandLine=f'{name} target')] ExecutablePath=f'C:\\Mentor\\{name}', CommandLine=f'{name} target')]
if name == owner else []) if name == owner else [])
def service(moniker): def service(moniker):
assert moniker == 'winmgmts:' assert moniker == 'winmgmts:'
return SimpleNamespace(ExecQuery=query) return SimpleNamespace(ExecQuery=query)
monkeypatch.setattr(win32com.client, 'GetObject', service) monkeypatch.setattr(win32com.client, 'GetObject', service)
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])))
# Keep pcb_processes, _processes, _process_details and release validation real. # Keep pcb_processes, _processes, _process_details and release validation real.
state = repair_release_state(request, target, complete_native_success(target)) state = repair_release_state(request, target, complete_native_success(target))
assert 'error' not in state assert 'error' not in state
+14 -4
View File
@@ -8,7 +8,8 @@ from cbb_refresh_verify.runtime_timing import parse_save_progress
@pytest.mark.parametrize('save_ok', [True, False]) @pytest.mark.parametrize('save_ok', [True, False])
def test_packaged_vbs_measures_real_save_call_and_preserves_failure_gate(tmp_path, save_ok): @pytest.mark.parametrize('other_document', [True, False])
def test_packaged_vbs_measures_real_save_call_and_preserves_failure_gate(tmp_path, save_ok, other_document):
# Execute the real helper in its target 32-bit host. Only external COM # Execute the real helper in its target 32-bit host. Only external COM
# object creation is replaced; Save/Validate/Close order and timers are real. # object creation is replaced; Save/Validate/Close order and timers are real.
script = Path(__file__).parents[1] / 'src/cbb_refresh_verify/save_verified_block.vbs' script = Path(__file__).parents[1] / 'src/cbb_refresh_verify/save_verified_block.vbs'
@@ -39,14 +40,20 @@ Class FakeDoc
IsSaved = True IsSaved = True
End Function End Function
Public Function Close(saveChanges) Public Function Close(saveChanges)
closedDoc = True
Close = True Close = True
End Function End Function
End Class End Class
Class FakeApp Class FakeApp
Public Property Get ActiveDocument Public Property Get ActiveDocument
Set ActiveDocument = New FakeDoc If closedDoc And Not OTHER_DOCUMENT Then
Set ActiveDocument = Nothing
Else
Set ActiveDocument = New FakeDoc
End If
End Property End Property
Public Sub Quit() Public Sub Quit()
WScript.Echo "TEST_QUIT"
End Sub End Sub
End Class End Class
Class FakeLic Class FakeLic
@@ -55,7 +62,8 @@ Class FakeLic
End Function End Function
End Class End Class
''' '''
source = source.replace('Option Explicit', 'Option Explicit\n' + classes.replace('SAVE_RETURN', str(save_ok))) source = source.replace('Option Explicit', 'Option Explicit\nDim closedDoc\n'
+ classes.replace('SAVE_RETURN', str(save_ok)).replace('OTHER_DOCUMENT', str(other_document)))
source = source.replace('GetObject(, "MGCPCB.Application")', 'New FakeApp') source = source.replace('GetObject(, "MGCPCB.Application")', 'New FakeApp')
source = source.replace('CreateObject("MGCPCBAutomationLicensing.Application")', 'New FakeLic') source = source.replace('CreateObject("MGCPCBAutomationLicensing.Application")', 'New FakeLic')
harness = tmp_path/'save_harness.vbs' harness = tmp_path/'save_harness.vbs'
@@ -66,11 +74,13 @@ End Class
parsed = parse_save_progress(completed.stdout) parsed = parse_save_progress(completed.stdout)
assert parsed['timings_seconds']['save'] >= .08 assert parsed['timings_seconds']['save'] >= .08
if save_ok: 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 'SAVE_OK' in parsed['markers']
assert 'CLOSE_OK' in parsed['markers'] assert 'CLOSE_OK' in parsed['markers']
assert parsed['timings_seconds']['post_save_check'] >= 0 assert parsed['timings_seconds']['post_save_check'] >= 0
assert parsed['timings_seconds']['close'] >= 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: else:
assert completed.returncode == 4, completed.stderr assert completed.returncode == 4, completed.stderr
assert 'SAVE_OK' not in parsed['markers'] assert 'SAVE_OK' not in parsed['markers']
+10 -10
View File
@@ -499,7 +499,7 @@ def test_parallelism_rejected_for_shared_library(tmp_path):
run_batch([], max_workers=2) 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.""" """A timed-out item must not leave a Mentor process holding the library."""
fixture(tmp_path) fixture(tmp_path)
killed = [] killed = []
@@ -508,9 +508,9 @@ def test_timeout_stops_automation_and_blocks_next_item(tmp_path, monkeypatch):
def __init__(self, command, name): def __init__(self, command, name):
self.name = name self.name = name
self.desktop = None self.desktop = None
def poll(self): return None def poll(self): return self.returncode
returncode = None 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 wait(self, timeout=5): return 0
def close(self): pass 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 result.status == 'TIMEOUT'
assert killed == [True] 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): 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() desktop = object()
returncode = None returncode = None
def __init__(self, command, name): pass def __init__(self, command, name): pass
def poll(self): return None def poll(self): return self.returncode
def kill(self): killed.append(True) def kill(self): killed.append(True); self.returncode = 1
def wait(self, timeout=5): return 1 def wait(self, timeout=5): return 1
def close(self): pass def close(self): pass
@@ -598,8 +598,8 @@ def test_unknown_dialog_writes_snapshot_before_current_item_fails(tmp_path, monk
companion_pids = [701] companion_pids = [701]
returncode = None returncode = None
def __init__(self, command, name): self.name = name def __init__(self, command, name): self.name = name
def poll(self): return None def poll(self): return self.returncode
def kill(self): killed.append(True) def kill(self): killed.append(True); self.returncode = 1
def wait(self, timeout=5): return 1 def wait(self, timeout=5): return 1
def close(self): pass 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() 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) fixture(tmp_path)
class FakeWorker: class FakeWorker:
def __init__(self, command, name): 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 def close(self): pass
import cbb_refresh_verify.desktop_worker as desktop_worker import cbb_refresh_verify.desktop_worker as desktop_worker
monkeypatch.setattr(desktop_worker, 'DesktopWorker', FakeWorker) 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) progress=lambda event: None)
assert result.status == 'BLOCKED' assert result.status == 'BLOCKED'
assert '保留' in result.stderr assert '保留' in result.stderr