Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6327ad10a2 | ||
|
|
1acfbd6374 | ||
|
|
aea6192ef9 | ||
|
|
53118bae19 | ||
|
|
beb2b06fdf | ||
|
|
4ebe098ef0 | ||
|
|
00db1cf5f2 | ||
|
|
477a5a46e3 | ||
|
|
2587d33c5a | ||
|
|
223655fe00 | ||
|
|
29959e2988 | ||
|
|
e14a864b37 |
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 部署依赖,没有伪造状态,也未加入新的全功能禁用入口。
|
||||
@@ -0,0 +1,40 @@
|
||||
# ICDB 批量检查
|
||||
|
||||
## 当前行为
|
||||
|
||||
应用原“非 READY ICDB 检查与修复”入口改为“ICDB 批量检查”。检查可见非 READY 工程,有勾选时仅处理可见勾选项,READY 即使被勾选也排除。普通 CBB 校验、中心库管理和手动“版本历史与备份…”继续使用各自入口。
|
||||
|
||||
检查通过原生 Project Backup 加载所选工程,收集本次 Output 和占用结论,不启动 PCB,不调用 Repair、Restore 或版本选择。检查入口即使收到旧请求的 `auto_repair=True` 也只执行检查;其原生请求始终携带 `inspection_only=True`。内部显式恢复辅助 API 及其既有测试保留,应用批量检查不再调用它们。
|
||||
|
||||
结果分为:
|
||||
|
||||
- 未发现异常:返回 CHECKED,仅表示本次原生检查未发现已识别的 ICDB 异常,不推定 CBB READY。
|
||||
- 发现 ICDB 问题:保留 FAIL 和明确的 ICDB 故障分类,不执行修复。
|
||||
- 工程占用:记录占用,不把它解释成数据库损坏。
|
||||
- 无法确认:缺少有效工程、输出不完整、目标不符、未知错误等均保留原始证据,不显示健康。
|
||||
|
||||
本项检查的原生进程确认退出后,发现问题、占用或未知结果可继续下一项;本次检查尚未退出或缺少退出证据时停止剩余批次,不强制终止原生进程。用户取消也停止队列。需要修复或回退时,由用户通过原生备份窗口选择操作。
|
||||
|
||||
## 去除检查路径的修复限制
|
||||
|
||||
目标绑定复用手动原生入口的唯一主 PRJ 和明确的工程内 `iCDBDir`。检查不要求 PCB、Layout 或 `icdb.dat` 预先存在,也不借用 Repair 的地址记录唯一性和多个数据库候选排除规则。缺失或损坏由原生加载检查给出结论;无法识别的结果保留为未知。
|
||||
|
||||
原生 worker 的检查模式不再因本机存在其他 PCB/Library Manager 而直接拒绝,也不执行 Repair 专用的数据库独占准入;它仍在启动前检查所选工程的文件链接,目标是否占用由原生 Output 判定。
|
||||
|
||||
检查使用实际库协调锁,忽略历史协调检查点,不自动归档旧记录或删除地址文件。释放必须有明确的原生退出证据,或 worker 明确报告“尚未启动原生进程”;结果字段/PID 缺失不推定释放。该调整只覆盖新检查路径,不能据此宣称维护/管理/释放检查中的所有过宽条件均已解决。
|
||||
|
||||
## 界面及报告
|
||||
|
||||
批量检查不再显示手动备份要求、自动修复承诺或“修复并校验通过”计数。确认清单、进度、备注、汇总及完整/异常/JSON 报告均按检查目标和检查分类输出。占用和未知备注不加“ICDB 问题”标签。默认副本恢复仍排除缺少 PCB 的工程,检查候选可以包含它们。
|
||||
|
||||
## 验证边界
|
||||
|
||||
本轮先以失败测试确认旧入口会打开 PCB、可进入 Repair、使用修复准入及误标未知结果,再修改入口。测试覆盖健康、明确故障、占用、未知、异常修复返回、缺少退出证据、明确未启动、取消、队列继续、缺 PCB/Layout/icdb、多数据库、READY 排除、仅检查汇总和报告。
|
||||
|
||||
全量测试、冻结模块一致性、启动冒烟及隔离库实际按钮记录保存在 `diagnostics/icdb-batch-check-20261104/`;最终包的 `BUILD.json` 记录实际结果。隔离验证只执行新批量检查,不在原库运行 Repair/Restore。
|
||||
|
||||
最终全量 **1304 passed**,270.79 秒,退出码 0,1 条既有 pywinauto STA 警告;编译和差异检查通过。冻结的 14 个关键 Python 模块及两个 VBS 与源码一致,启动/退出、Unicode/UNC 协议及包内 x86 运行库加载通过。独立审查发现的修复准入误用和缺字段推定释放均以先失败后通过的回归修正,复审无剩余必要 P1/P2。
|
||||
|
||||
最终冻结包通过真实按钮在自有隔离库的 PENDING `IP101GR` 上检查,原生返回数据库不一致且未占用,应用记录 `ICDB_REPAIR_REQUIRED`、`safe_to_continue=true`,汇总“发现问题 1”。原生请求为 `inspection_only=true`,返回 `repair_requested=false`,没有 PCB 请求或恢复尝试。原生及应用均正常退出,中心库 LMC 和工程 PRJ、DXP、icdb.dat、PCB、LayoutDB 六个文件的 SHA-256 前后一致。
|
||||
|
||||
原生加载检查不能保证 PCB 实际打开一定正常,也不能替代普通 CBB 校验。现场自动修复问题不作成功结论;工单和 WIP PR 保持开放。
|
||||
@@ -0,0 +1,47 @@
|
||||
# 工单 #4 与独立操作复核
|
||||
|
||||
复核基准:最新工单 [#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 被全局进程检查拦截。
|
||||
|
||||
只读打开对应私有桌面后确认:原生主窗口及 RichEdit Output 控件均存在,但主窗口和 Output 连 WM_NULL 都返回 1460(超时)。不是已经取得 ICDB 损坏结论后修复失败,而是原生检查本身无响应,且本应用没有提供足够的阶段证据。没有向该原库发出新的 Repair、恢复、删除地址文件或强制结束操作。
|
||||
|
||||
原有逻辑还把“存在历史检查点”直接解释为整个库只能维护,普通校验默认自动 Repair,并把地址记录存在直接解释为会话未释放。这些产品耦合与用户最新要求冲突。
|
||||
|
||||
## 12 项仍需修改或验收
|
||||
|
||||
| 工单项 | 当前结论 | 后续工作及验收 |
|
||||
| --- | --- | --- |
|
||||
| K2-1 状态桥前置检查 | 仍缺少批次级能力诊断;在原生刷新后才检查权威 READY | 批次开始只诊断一次并明确说明状态不可读取;不能因此封锁 ICDB 和库管理。不能把原生调用完成当作 READY。 |
|
||||
| K2-1b x86 运行库部署 | 发布候选中的桥为 x86,导入 `mfc140.dll/MSVCP140.dll/VCRUNTIME140.dll`,未随包提供 x86 MFC | 选择静态链接或正式部署 x86 运行库;干净 Windows 实机验证。x64 Python/Qt 的同名 DLL 不能替代。 |
|
||||
| K2-2 未知弹窗分级 | 输入法误报已有过滤;真正未知交互弹窗仍使当前项失败并停批 | 区分无交互辅助窗口与实际模态提示;后者记录具体原因,正常释放后才继续独立项,不能盲点未知确认按钮。 |
|
||||
| K2-3 取消与超时 | 协作式取消已存在;看门狗和 `_stop_worker` 仍可能返回时客户端活着 | 检查当前 automation client/保存客户端是否实际退出,防止迟到 Save/Close;不得以删除历史记录代替停止仍在写入的任务。 |
|
||||
| K2-6 ICDB 自动维护 | 隔离副本曾成功执行 Repair;本次原库原生检查无响应,不能验收 | 当前修复:独立维护、独立校验、缩小检查范围、记录原生等待阶段。仍需一致副本上的真实按钮验收;原生窗口挂起成因待查。 |
|
||||
| K2-4 跨机共享库并发 | sidecar 排他句柄只协调遵守协议的工具,Mentor 不参与 | 明确共享库操作协议,基于实际原生文件占用处理冲突;两台机器同时写同一工程的验证尚未完成。 |
|
||||
| K2-5 地址记录及全局 PCB 拦截 | 地址文件和历史记录的普通校验硬拦截在本次拆除;“任意 PCB 已开即拒绝”仍存在 | 改为按工程身份判断占用;独立 CBB 不应相互禁用;跨会话 COM 绑定需实际验证后调整。 |
|
||||
| K2-7 Windows 10 | 当前没有 Win10 实机完成证据 | 在 Win10 + EE7.9.5 验证私有桌面、启动、保存、释放及 READY;不能以 Win11 回归替代。 |
|
||||
| K2-8 内容文本与 PRJ 编码 | 探针确认成功文本含 `0 errors` 仍返回 FAIL;preflight 仍按 UTF-8 读取 | 复用已有工程编码读取器,区分零错误计数与真实错误;补 UTF-16、ACP 和真正失败样本。 |
|
||||
| K2-9 CentralLibrary 改写与说明 | 写入前已有原始 `pcb.prj` 证据副本和原子替换;旧“没有直接改写”说明不准确 | 核对异常回退与说明,按用户要求提示手动备份,不能重新加上自动整库备份。 |
|
||||
| K3-1 初次扫描规模 | 状态指纹与逐项 preflight 仍有全库开销;本次只缩小了维护检查范围 | 首屏增量读取、扫描进度和取消;381/3000 项及网络盘测量仍需做。 |
|
||||
| K3-2 队列恢复 | 已有状态/管理检查点,但没有完整校验队列的确认续跑 | 保存目标、已完成项和具体结果,重启后由用户决定继续;管理写操作不得自动重放。 |
|
||||
|
||||
共 12 项:5 项 P0、7 项原工单 P1/规模化条目。它们不等于 12 个已复现的代码错误:包含明确缺陷、部分修复、部署风险及缺少实机验收。优先处理操作解耦、原生检查无响应、桥部署、取消后仍存活的客户端;其余独立提交,不混在一次维护修复中。
|
||||
|
||||
## 本次实现与验证范围
|
||||
|
||||
普通校验默认不调用 Repair;历史检查点不再切换清单读取方式或禁用普通校验。合作式库锁跟随实际客户端释放,不为普通校验创建新的永久诊断阻止记录;已有历史记录保留。已退出的只读原生检查不会因为旧地址记录而锁住管理入口。实际仍存活或尚未确认退出的客户端继续保有执行锁;监督工作进程已经退出、只剩已记录的原生 PID 时,重试会检查这些 PID 是否实际退出,校验和维护均可直接重试,不要求先运行另一个功能。工作进程仍在运行时不采用这一简化判定。
|
||||
|
||||
维护成功报告 `REPAIRED / UNKNOWN` 和“待单独校验”,不自动重开 PCB、不执行反标注、不标为 READY。历史备份恢复仍需核对版本。维护预检查只扫描当前 Work、相关共享符号数据库及中心库定义,并保持链接、文件集合变化和独占句柄检查。扫描真实原库的 5,218 项用时 14.109 秒(只读,未启动原生工具);原用户流程的两层预检查合计约 76 秒,不能把这两个口径直接当作完整维护耗时对比。
|
||||
|
||||
验证证据在 `diagnostics/independent-operations-20261104/`(原始现场记录不提交):
|
||||
|
||||
- 操作拆分后的相关回归 509 项通过;审查发现并补正真实客户端仍在写入时的执行锁保留,以及直接重试维护的入口问题。
|
||||
- 执行锁、维护、占用、校验、导出保护和恢复等相关回归 **214 passed**,退出码 0;最后“无需修复”展示与独立入口回归 **37 passed**,退出码 0。不是对最终源码重新跑完整 Python 套件的声明。
|
||||
- 独立静态审查的必要问题已修正。编译及差异检查通过。
|
||||
- 冻结包核对 10 个关键模块与当前源码一致,并运行无原生写入的启动/正常退出冒烟。构建元数据明确保留 `native_acceptance=false`、`release_ready=false`。
|
||||
|
||||
本轮没有重启现场挂起的原生进程、强制结束该进程、在原库执行新的自动修复,或将单元测试当成 ICDB 实机验收。原生窗口长时间无响应的具体内部原因仍未查明;此文档不能作为原生自动修复已验收的证明。
|
||||
@@ -0,0 +1,31 @@
|
||||
# 原生版本历史、备份与回退入口
|
||||
|
||||
## 用户操作
|
||||
|
||||
在“ICDB 维护”页勾选一个非 READY CBB,点击“版本历史与备份…”。应用将所选工程的唯一 PRJ 传给已安装的 `iCDBProjectBackup.exe -p`,打开可见的原生窗口。当前 Layout 数据缺失但 PRJ 仍在时也可以进入。
|
||||
|
||||
版本列表、备份详情、操作日志和 Restore backup 由原生窗口提供。选择版本、手动保存/自动保存分支以及恢复确认均由用户操作;应用不代点 Restore、Repair、删除或清理菜单。用户已报告手工回退能够走通,本轮接入该原生入口,不把手工成功当作自动 Repair 验收通过。
|
||||
|
||||
原生窗口正常关闭后重新读取受影响 CBB 的权威状态。窗口关闭仅记为 `CLOSED`,始终记录 `restore_confirmed=false`,不自动执行校验,不伪造 PASS/READY。需要验证恢复后的工程时,单独使用“检验”页。
|
||||
|
||||
## 会话与独立操作
|
||||
|
||||
- 可见原生窗口由独立辅助进程启动和监督;Qt 线程不等待原生会话,清单搜索、筛选、横向页面和库切换保持可用。
|
||||
- 使用 Windows Job 跟踪本次原生进程及后代,根进程退出但后代仍在时继续等待。Job 不设置 kill-on-close;关闭本应用不强制关闭原生窗口。
|
||||
- 实际会话持有现有中心库协调锁,同库写入等待该会话关闭;其他库不因这个窗口禁用。没有新增历史 ICDB 失败标记作为普通校验前置条件。
|
||||
- 状态或结果文件写入失败不结束原生监督。辅助进程退出后,只有返回身份一致且 `safe_to_continue=true` 才清除应用内会话和路径租约;缺失、损坏或释放未确认时保留同库冲突,可通过已有“检查占用…”取得新的释放证明。
|
||||
- 切换到同一共享上的其他库时,旧会话结束会把临时盘符所有权交给当前租约,避免断开当前路径。关闭应用时为仍打开的原生窗口保留所需盘符。
|
||||
|
||||
## 本机验证
|
||||
|
||||
证据目录:`diagnostics/native-backup-ui-20261104/`(本地诊断目录,不包含原库发布副本)。
|
||||
|
||||
源码实际按钮验证使用自有隔离库 `C:/Temp/CbbTabsRelease20261104/library/mentor_lib.lmc` 的 `1GPHY_8212`,由测试夹具提供 PENDING 清单状态,确认原生 Output 加载同一 PRJ、报告工程未使用、完成备份目录加载,再向该原生空闲窗口发送正常关闭。未点击 Restore/Repair,也未操作原库。详见 `source-acceptance.json`。
|
||||
|
||||
冻结候选包读取真实权威清单时,`1GPHY_8212` 为 READY,其维护入口按规则禁用。随后选择同一隔离库中实际 PENDING 的 `IP101GR`,验证真实 Qt 按钮、原生备份列表加载、正常关闭和应用状态刷新;最终仍为“待校验”,应用正常退出。原生 Output 明确报告该隔离副本的数据库不一致,本轮只验证入口,不点击 Repair/Restore,也不将此报错当作自动修复已通过。记录在 `frozen-acceptance.json`。
|
||||
|
||||
相关功能回归 88 项通过;最终全量回归 **1260 passed**,188.94 秒,退出码 0,1 条既有 pywinauto STA 警告。冻结的 13 个关键 Python 模块及两个 VBS 与源码一致,冻结启动/退出冒烟、Unicode/UNC 协议和包内 x86 运行库加载通过。全量回归、冻结模块一致性和启动冒烟结果分别保存在 `pytest-final.log`、`frozen-result.json`;最终构建记录随包保存到 `BUILD.json`。一次按系统 GBK 模式运行的全量测试因既有测试未指定 UTF-8 读取原生日志而失败,保留 `pytest-locale-failure.log`,最终回归使用 `python -X utf8 -m pytest -q`。
|
||||
|
||||
## 验收边界
|
||||
|
||||
本轮覆盖“应用入口 → 原生备份列表加载 → 用户可操作窗口 → 正常关闭 → 状态刷新”。不自动回退数据,不以本轮打开/关闭试验代替恢复后的保存关闭与 READY 验收。现场失联故障的完整自动修复、Win10 干净系统和跨机共享库并发仍未验收;ICDB 自动修复研究按用户要求暂停。工单和 WIP PR 保持开放。
|
||||
@@ -0,0 +1,32 @@
|
||||
# 按本次工程启动错误决定 ICDB 维护
|
||||
|
||||
## 问题
|
||||
|
||||
旧的显式维护入口对 `maintenance=True` 恒定返回“需要维护”,所有可见非 READY 候选都先进入 Project Backup 检查。虽然 Repair 仍要求原生检查明确报告故障,这一流程没有先确认 PCB 是否实际打不开,也会让健康工程进入维护环境和占用检查。
|
||||
|
||||
非 READY 表示未通过 CBB 校验,不能作为 ICDB 损坏证据;普通服务器、授权、COM、路径及内容错误也不能据此转换成 ICDB 修复。
|
||||
|
||||
## 调整后的流程
|
||||
|
||||
1. 维护按钮保持针对可见非 READY 候选。每项先通过既有 `diagnostic_only` 路径实际打开所选 PCB:核对工程/中心库身份,不改工程路径、不执行集成、不保存、不提交 Cert、不运行普通 CBB 校验。
|
||||
2. 同一工程正常打开并确认会话释放后返回 CHECKED,备注为“无需 ICDB 修复”,不启动 Project Backup,不推定 READY。
|
||||
3. 普通失败保留原状态和原始错误。没有完整 ICDB 原生失联特征、数据库路径或会话信息时,不进入维护。历史地址、协调检查点或旧诊断文件不代替本轮启动证据。
|
||||
4. 仅本轮诊断 FAIL、会话已释放,且失联报错数据库属于当前工程时进入原生维护。共享库、其他工程、未知目标、超时及取消结果不自动修复当前 CBB。
|
||||
5. 原生维护取得锁及工程证明后,再核对目标必须与本次报错数据库相同。原生检查仍需确认空闲且明确要求修复,才调用既有单次 Repair 路径。目标不一致时不启动原生工具,不因已释放的单项错误阻塞其他独立 CBB。
|
||||
6. 诊断在文档身份确认后和关闭完成后各复查本轮日志,避免延迟写入的启动错误被误判为健康。日志沿用启动前基线和增量判定,不从历史日志猜测故障。
|
||||
|
||||
普通“检验”按钮继续独立执行,不要求先通过 ICDB 维护;手动“版本历史与备份…”继续直接进入可见原生窗口,由用户选择版本。此修改只调整维护触发条件,不宣称修复了原生 Repair 内部失败。
|
||||
|
||||
## 测试与边界
|
||||
|
||||
先新增回归测试,在旧代码上验证健康工程及普通错误仍会进入 Project Backup 的失败,再实现入口修正。测试覆盖完整失联特征、无会话/只含错误码、共享库/其他工程、目标变化、正常打开、未释放、超时、取消、旧诊断文件、日志写入失败和延迟启动错误。
|
||||
|
||||
关联回归 151 项通过,后续新增的报告失败及等价路径用例纳入最终回归;维护入口专项最终 21 项通过。最终全量 **1283 passed**,643.89 秒,退出码 0,1 条既有 pywinauto STA 警告。编译和差异检查通过,冻结的 13 个关键 Python 模块及两个 VBS 与源码一致,启动/正常退出、Unicode/UNC 编解码和包内 x86 运行库加载通过。
|
||||
|
||||
独立静态审查发现目标的字面路径比较可能误拒绝映射盘与 UNC 身份,已改为比较两边解析后的工程及数据库路径,实际原生启动路径保持不变;等价路径回归先失败后通过。真实网络共享与 Win10 验收仍保留。复审无剩余必要 P1/P2。
|
||||
|
||||
关联回归、全量回归、构建与冻结检查保存在 `diagnostics/icdb-startup-gate-20261104/`,最终测试包的 `BUILD.json` 记录实际执行结果及源码哈希。
|
||||
|
||||
最终冻结包通过实际按钮在自有隔离库的 PENDING `IP101GR` 上再次打开手动备份列表、正常关闭并刷新为“待校验”,应用正常退出。没有点击 Repair/Restore;该试验用于确认手动入口独立性,不作为新的启动诊断或自动修复实机验收。
|
||||
|
||||
本轮不对原中心库执行 Repair/Restore,不以模拟诊断或隔离副本备份窗口打开成功代替现场自动修复验收。ICDB 自动修复内部问题仍未验收,工单及 WIP PR 保持开放。
|
||||
@@ -0,0 +1,26 @@
|
||||
# 阻塞范围收紧记录
|
||||
|
||||
本轮处理的是“一个 CBB 出问题后把整批和其他库一起停掉”的误阻塞。
|
||||
|
||||
## 已收紧
|
||||
|
||||
- 批次继续条件保持按实际释放证据判断。单项 FAIL、ICDB 检查发现问题或普通内容错误,只要本次原生/自动化客户端已经退出并返回 `safe_to_continue=true`,下一项继续;只有进程仍存活、退出状态无法确认或共享写入安全无法证明时才停止后续写操作。
|
||||
- 管理失败状态现在绑定实际中心库。切换到另一个中心库会清除旧库的 `_management_unsafe`,不会把库 A 的失败带到库 B;释放检查完成回调也只清除同一库的状态。
|
||||
- 显式维护的原生占用检查按目标 PRJ 命令行过滤无关 PCB/Library Manager。旧的零参数占用探针仍兼容,目标路径可用时不再被其他 CBB 阻塞。
|
||||
- 释放证明支持目标 CBB 范围。提供目标名称时,只检查该 Work 工程的地址记录、主要数据库文件和命令行包含该工程的原生客户端;其他 CBB 的 `sAddress.adr` 不再阻塞当前恢复。无目标范围的全库释放检查继续保守处理。
|
||||
- 释放接口新增参数保持旧调用兼容;旧插件或测试没有 `block_name` 参数时继续走全库证明路径。
|
||||
- UI 比较中心库身份不再对不可达 UNC 路径调用会访问网络的 `Path.resolve()`。网络共享暂时不可达时保持可用状态和错误提示,不在界面刷新中抛异常。
|
||||
|
||||
## 仍然必须停止的情况
|
||||
|
||||
- 当前项的 PCB、Project Backup、保存助手、Importer 或管理工作进程仍在运行。
|
||||
- 进程查询失败、原生窗口身份不明、退出状态缺失,或库锁/共享写入归属无法确认。
|
||||
- 用户明确点击取消,当前批次停止后续项目。
|
||||
|
||||
这些停止条件保护共享数据库和原生写入现场;移除它们会把一个仍在写入的工程与下一个 CBB 并行运行,可能造成更大范围的数据损坏。
|
||||
|
||||
## 验证
|
||||
|
||||
新增回归覆盖单项已释放失败继续批次、切库清除管理阻塞、目标 CBB 过滤无关进程/地址、旧释放接口兼容和不可达 UNC 路径。最终全量回归 **1309 passed**,1 条既有 pywinauto STA 警告;`compileall` 与 `git diff --check` 通过。
|
||||
|
||||
本轮没有修改图标等其他工作区文件,也没有对现场中心库执行写入、Repair 或 Restore。
|
||||
@@ -0,0 +1,36 @@
|
||||
# Issue 5:私有桌面泄露
|
||||
|
||||
## 现象
|
||||
|
||||
原生 worker 创建私有 Windows Desktop 后,如果 Job Object 创建或 worker 进程启动失败,构造函数直接抛出异常,已创建的 Desktop 和 Job 句柄没有释放。重复触发失败会留下孤立的私有桌面对象,表现为桌面资源持续增加、后续同名或同类原生任务启动异常。
|
||||
|
||||
状态读取路径还有一个相同的边界:`read_library_flag` 在进入资源清理保护前加载 UI 依赖;依赖加载异常时,刚创建的私有桌面无法执行 `CloseDesktop`。
|
||||
|
||||
## 根因
|
||||
|
||||
1. `DesktopWorker.__init__` 的资源申请跨越多个可能失败的步骤,但没有事务式回滚。
|
||||
2. 进程句柄、Job 句柄和 Desktop 句柄的释放顺序没有覆盖构造阶段异常。
|
||||
3. `read_library_flag` 的依赖导入位于 `CreateDesktop` 之后、`try/finally` 之前。
|
||||
|
||||
## 解决方案
|
||||
|
||||
- 在 `DesktopWorker` 构造开始时初始化资源字段,并把 Desktop、Job、worker 创建放入同一异常边界。
|
||||
- 构造失败时按 worker、Job、Desktop 顺序回滚;已启动的 worker 先终止,避免留下无父级的原生进程。
|
||||
- 在状态读取创建 Desktop 前完成 UI 依赖加载,确保依赖异常不会产生未受保护的 Desktop。
|
||||
- 增加回归测试,模拟 worker 启动失败并断言 Desktop、Job 均已关闭。
|
||||
|
||||
## 影响范围
|
||||
|
||||
- 只影响原生 worker 启动失败和状态读取依赖加载失败时的清理路径。
|
||||
- 正常任务的私有桌面、Job Object、进程树和数据库释放策略不变。
|
||||
- 不会切换用户输入桌面,也不会改变中心库写入策略。
|
||||
|
||||
## 验证
|
||||
|
||||
- `python -m pytest -q tests/test_desktop_worker.py tests/test_dialog_agent.py tests/test_native_inspection_release_regressions.py tests/test_verify_diagnostics.py`:33 passed。
|
||||
- `python -m compileall -q src tests`:通过。
|
||||
- `git diff --check`:通过。
|
||||
|
||||
## 分支
|
||||
|
||||
`codex/desktop-leak-pr`
|
||||
@@ -0,0 +1,24 @@
|
||||
# ICDB 失败后的副本恢复入口
|
||||
|
||||
原生修复失败、缺少有效备份,或 Repair 后完整校验失败时,结果窗口提供“选择副本恢复…”;主窗口保留“选择工程副本恢复失败项…”,允许关闭结果窗口后继续。单纯占用、未知诊断、仅检查或成功结果不提示替换。
|
||||
|
||||
入口固定使用本次失败任务的库、名称和分区,不使用用户后来勾选的其他条目。切换中心库使旧入口失效。选择的是库外完整工程的 PRJ 文件,相关 PCB、数据库和依赖资料仍由现有来源检查验证。
|
||||
|
||||
点击入口只打开来源选择窗口。用户明确确认手动备份、目标库、目标条目及副本后,才在后台检查释放,并复用现有原生移除/导入流程;不自动备份整个库,不自动删除目录代替原生操作。自动校验默认开启。
|
||||
|
||||
释放检查继续要求原生所有者退出、数据库地址记录处理完毕及独占可读。WMI 查询通过最多 10 秒的只读助手执行,超时不当作空闲;同时检查脚本与校验/修复工作进程。检查不通过显示具体原因、保留阻止记录和恢复入口。未完成的管理写入仍不自动重放。
|
||||
|
||||
原维护失败记录保持原样。副本恢复建立独立 `reimport-recovery/*/recovery.json`,关联原证据、来源、释放检查和管理结果。上传成功但校验失败继续显示失败;上传并取得 READY 后显示“副本恢复校验通过,版本待核对”,不改称原 ICDB 无损修复成功。
|
||||
|
||||
按用户要求精简界面:默认只展示目标、副本选择、备份确认和操作结果。开发流程说明已移除,诊断细节和证据路径放入默认收起的日志。恢复执行前仍明确说明先移除原条目再导入副本。
|
||||
|
||||
## 验收边界
|
||||
|
||||
- 核心流程专项测试 57 项通过;随后新增的两项主窗口取消/退出复核回归均先复现失败再通过。
|
||||
- 完整回归记录为 **1,194 passed / 1 failed**(1,013.66 秒)。该运行启动后用户要求精简 UI,已收集的测试仍断言旧文案“尚未修复成功”,运行时加载的界面已使用“修复未完成”,因此失败。未把该次结果标成全量通过。
|
||||
- 最终界面与更新后的测试重新验证 **77 passed**(43.00 秒),包含该失败用例及新增的日志默认收起检查。其余产品逻辑未在此期间修改。
|
||||
- 编译、差异检查、独立审查通过。最终冻结构建及启动/正常退出、占用辅助进程冒烟通过,EXE 内 5 个关键模块与当前源码一致。记录在 `diagnostics/copy-reimport-20261104/`。
|
||||
|
||||
本次验证覆盖 Qt 真实事件循环中的按钮、取消、来源确认、后台等待及故障分支,原生写入边界使用替身,不把这些测试当作 Mentor 修复验收。
|
||||
|
||||
既有隔离副本仍有 `IP101GR/Work/database/cdbsvr/sAddress.adr`,因此完整库释放条件目前不满足。该情况不能通过忽略地址或强制清除检查点解决,需要先处理对应工程。此前 `1GPHY_8212` 的原始 Repair 后 BackAnnotate 失败结论保持不变,工单未关闭。
|
||||
@@ -0,0 +1,52 @@
|
||||
# 原生占用检查候选:完整修复验收失败
|
||||
|
||||
本记录更新此前 `2026-11-04-icdb-review-fixes.md` 的维护入口说明。工单 #2 保持未解决;本候选不合并、不发布正式版、不关闭工单。
|
||||
|
||||
## 本轮改动
|
||||
|
||||
- 维护入口先调用原生 iCDB Project Backup 的工程加载/占用检查,不先打开 PCB。旧 `sAddress.adr` 只是待核实证据,不再单凭它阻断检查,也不删除或改写该文件。
|
||||
- 仅本轮 Output 明确绑定目标工程、目标数据库,确认未占用且要求 Repair,原生检查正常退出,并再次通过工程身份和占用检查,才调用一次 Repair。其他工程、共享库、未知错误或未释放会话均阻止后续操作。
|
||||
- WMI 占用查询在独立只读辅助进程执行,最多 10 秒;超时是未知,不是空闲。文件扫描在后台运行并支持取消。原生准备阶段预算 60 秒,另加原生操作超时及 5 秒监督余量;取消后再次核对,避免迟到启动。
|
||||
- 停止请求传入维护流程,原生写入不强杀;释放未确认时停止后续批次。仅检查结果使用 `CHECKED`,不计入修复成功。READY 即使已勾选也不进入维护。
|
||||
- 精确的 verified/once-verified Reusable Block BackAnnotate 拒绝归类为 `CBB_REIMPORT_REQUIRED`,不再被后续释放告警掩盖。该分类不会执行重导入,也不改变 `safe_to_continue`;原生错误及释放错误都保留在报告中。
|
||||
- 历史版本选择继续通过应用弹窗;只有完整校验及权威 READY 通过才允许成功。历史恢复仍标记版本待核对。
|
||||
|
||||
## 隔离环境实测
|
||||
|
||||
证据根目录:`diagnostics/native-occupancy-20261104/`(含本机路径和原生日志,不纳入 Git)。测试通过实际应用维护按钮和版本选择弹窗完成,没有以手工分阶段调用替代验收。
|
||||
|
||||
一致副本包含 38,954 个文件、1,220,129,120 字节。复制期间源文件集合/大小/修改时间一致,253 个主要文件 SHA-256 核对通过;追加目标 PRJ/PCB 后,最终再次核对原库的 255 个已记录文件,全部未变化。原库未执行写操作。
|
||||
|
||||
最终尝试 `source-ui-fourth`,目标 `1GPHY_8212`:
|
||||
|
||||
1. 原生检查明确返回未占用,并指出当前数据库不一致、要求 Repair。
|
||||
2. 原生 Repair 创建自身备份,完成数据库检查、整理和关闭,返回 `Project should now be fixed.`,并确认退出释放。
|
||||
3. 应用弹窗选择用户已授权的最后手动保存版本(2026/9/24 15:15),重新打开同一工程。
|
||||
4. SynchCES、LoadCES 通过;BackAnnotation 为 Required,实际调用被 Mentor 拒绝:`Back Annotation is not allowed on verified (or once verified) Reusable Blocks.`
|
||||
5. 未完成保存与 READY 校验。最终 **FAIL / UNKNOWN / REPAIR_VALIDATION_FAILED**,`validation_passed=false`、`safe_to_continue=false`。原生 Repair 完成不等于整体修复成功。
|
||||
6. 失败关闭助手记录 Close/Quit 成功,但最终释放检查仍看到 PID 21968,因此保留检查点并停止批次。后续只读复查该原生进程已消失;这不追溯修改原失败结果。测试应用关闭结果对话框后正常退出。
|
||||
|
||||
实测界面响应记录:614 次 WM_NULL 检查,200 毫秒超时 0 次,最大约 78 毫秒。这只证明本次运行的界面响应,不保证任意网络故障下所有系统调用可立即取消。
|
||||
|
||||
关键证据:
|
||||
|
||||
- `source-ui-fourth/acceptance.json`:`accepted=false`。
|
||||
- `source-ui-fourth/evidence/maintenance-43479c21aa59/result.json`:完整维护结果。
|
||||
- `source-ui-fourth/evidence/maintenance-43479c21aa59/native-repair/repair-result.json`:原生 Repair 证据。
|
||||
- `source-ui-fourth/evidence/verify-99a675e0399c/`:重新打开、集成拒绝、正常关闭及释放未确认记录。
|
||||
- `source-ui-fourth/ui-responsiveness.json`、`version-choice.png`、`finished.png`。
|
||||
- `source-final-check.json`:原库 255 个哈希均保持不变。
|
||||
|
||||
## 代码与冻结候选验证
|
||||
|
||||
- `python -X utf8 -m pytest -q --tb=short`:**1,176 passed**,302.56 秒;1 条既有 pywinauto STA 警告。
|
||||
- `compileall`、`git diff --check`、独立只读代码审查通过。
|
||||
- PyInstaller 构建通过;冻结程序创建主窗口及正常退出通过,新 `--owner-probe` 在冻结程序中返回有效结果。
|
||||
- EXE 内 11 个变更模块与当前源码编译结果一致。验证脚本及结果在证据根目录的 `check_candidate.py`、`frozen-result.json`。
|
||||
- 本地候选目录:`dist/issue2-native-occupancy-candidate/`。冻结包完整故障修复链路未执行,不能称为已验收的修复包。
|
||||
|
||||
## 尚未解决
|
||||
|
||||
已验证或曾验证的 CBB 注册状态限制仍阻止 BackAnnotate。不能跳过 Required 操作、强行设置 READY 或把移除/重导入偷偷加入 ICDB Repair。此前隔离试验的独立重导入路径见 `2026-11-03-field-feedback.md`,其行为涉及库条目更新,不能据此宣称本次无损修复通过。
|
||||
|
||||
本轮没有完成 Windows 10/11 双系统验收;冻结包的完整现场故障链路仍需验证。程序测试和启动冒烟均不能代替上述失败的实际验收。
|
||||
@@ -0,0 +1,45 @@
|
||||
# 三页界面与原生检查、退出修正
|
||||
|
||||
界面按“检验 / ICDB 维护 / 中心库管理”横向切换,共用中心库、清单、搜索和选择状态。默认收起运行日志,长状态信息限制高度,避免纵向堆叠操作区或报错撑长窗口。1000×620 布局预览保存在本轮诊断目录中。
|
||||
|
||||
## 本轮现场日志定位
|
||||
|
||||
用户运行的是 `29959e2` 冻结包。2026-11-04 14:21(北京时间)的维护在原生检查启动后报 `(2, 'EnumWindows', '系统找不到指定的文件。')`,并没有调用 Repair。随后手动释放检查发现 `1GPHY_8212`、`IP101GR` 的地址记录仍存在;它们不能直接当作已释放或直接删除。第二次在准备检查时取消,助手没有及时结束文件扫描。
|
||||
|
||||
## 修正
|
||||
|
||||
- 在实际空私有桌面复现了 Win32 旧错误码问题:先 `SetLastError(2)` 再枚举空桌面,pywin32 会报与现场相同的错误。现在枚举前清零旧错误;真实枚举异常继续上报,不把未知错误当作空闲。
|
||||
- 将取消信号传入修复助手的文件扫描。文件标记最多每 100 毫秒读取一次,取消后锁存;原生启动、Repair 命令和确认前仍立即读取取消信号。冻结实测曾因逐文件读取取消标记而在启动前超时,节流后已推进至实际原生检查和 Repair。
|
||||
- 手动备份模式下,助手只在启动前执行一次完整目标保护,移除原先自动备份取消后留下的重复检查。同一保护内复用初始完整扫描作地址和文件选择,取得全部独占读句柄后再做第二次完整扫描;地址变化或原生文件集合增删均停止。没有复用跨操作的旧快照。
|
||||
- 发出唯一正常关闭请求前仍严格确认任务进程、工程、私有桌面、空闲窗口和地址状态。关闭后只等待进程、启动器及地址释放,不再因退出途中 WMI 暂时缺少命令行而提前报身份未确认,也不再次关闭窗口。未实际退出仍保留未释放状态。
|
||||
|
||||
## 已有验证记录
|
||||
|
||||
本轮证据目录为 `diagnostics/tabs-release-20261104/`,含本机路径,不提交原始数据。
|
||||
|
||||
- 初轮完整回归 1,200 项通过,2 项旧测试替身未接收取消参数;同步接口后维护模块 48 项通过。
|
||||
- 扫描优化后的维护、原生修复等相关测试 225 项通过;随后退出等待等 91 项通过。包含实际私有桌面的 Win32 回归,而不只是窗口模拟。
|
||||
- 冻结程序取消试验 `frozen-cancel-local`:预检查中取消约 0.61 秒返回,未启动原生 Repair,应用正常退出。
|
||||
- 源码实际入口 `source-optimized`:原生确认未占用并要求修复,Repair 成功,按用户授权恢复最后手动保存版本;最终因 verified/once-verified CBB 禁止 BackAnnotate 失败。PCB 正常关闭,没有附加 PCB 释放未确认错误。
|
||||
- 冻结实际入口 `frozen-polling`:原生检查及 Repair 已完成,取消标记只读取 214 次、耗时 0.313 秒。随后 PCB 因数据库服务器启动晚于客户端截止时间而加载失败。服务器日志显示它后来实际启动并自行关闭,不据此宣称完整修复通过。
|
||||
- 同一次失败退出中,先记录了 `startup_close_requested`,随后 WMI 缺少进程信息导致 `STARTUP_PROCESS_UNCONFIRMED`,下一秒却已确认进程退出;该具体时序已转为回归测试。
|
||||
|
||||
最终完整回归:**1,207 passed**,588.26 秒,仅既有 pywinauto STA 警告;记录在 `pytest-final.log` / `pytest-final-result.json`。最终冻结构建、启动退出冒烟和 6 个关键模块的源码一致性检查通过。独立审查未发现剩余必要缺陷。
|
||||
|
||||
最终冻结实际入口为 `frozen-local-final`,使用 `C:\Temp\CbbTabsRelease20261104\library` 的独立副本:原生 `NOT_IN_USE` 且明确要求修复 → Repair 完成并释放 → 重新打开同一 PCB → 用户已授权的最后手动保存版本(2026/9/24 15:15)→ SynchCES / LoadCES → BackAnnotate 被原生拒绝。最终 **FAIL / UNKNOWN / REPAIR_VALIDATION_FAILED**,未取得 READY;退出记录确认进程结束,没有附加 `PCB_RELEASE_UNCONFIRMED`。应用正常退出返回 0。此前服务器迟启动的失败记录保留,不能从一次对照断定其全部成因。
|
||||
|
||||
原库 255 个已记录主要文件哈希复核全部未变,见 `source-final-check.json`。
|
||||
|
||||
最终包的 `frozen-cancel-final` 再次验证取消:约 1.16 秒返回,检查助手报告 `CANCELLED`,批次保持 `BLOCKED`,未启动 Repair,应用正常退出。取消只证明操作已停止,不计作修复成功。
|
||||
|
||||
## 验收限制
|
||||
|
||||
原库未执行本轮自动化写入。第一套 F 盘测试副本出现目录枚举属性与直接读取属性不一致,被链接检查阻止,未绕过检查。测试随后迁移到独立本机目录;`C:\Users` 目录会被 Mentor 转成共享路径,因此最终试验选择独立的 `C:\Temp` 路径,并保留前序失败记录。
|
||||
|
||||
完整 ICDB 修复仍必须取得权威 READY;原生 Repair 成功、能够取消、正常关闭或界面测试通过都不能替代该验收。未合并发布,工单保持未解决。
|
||||
|
||||
## 结果展示收尾
|
||||
|
||||
实际冻结运行截图还暴露了结果弹窗包含长路径和 COM 异常、错误列挤压 CBB 名称的问题。结果正文改为简短计数、用户可理解的失败原因和副本恢复入口;原始异常、统计明细及日志路径保留在可展开详情和日志中。名称与结果列共同分配可用宽度,长内容不再把表格撑出窗口。历史备份待核对和待选 PCB 版本仍直接提示。
|
||||
|
||||
该收尾只调整展示,不改变占用检查、关闭、Repair、校验或恢复行为。以已保存的真实失败结果回放检查布局,未额外写入原生库。相关界面、筛选和副本恢复回归 84 项通过;记录为 `pytest-presentation.log` / `pytest-presentation-result.json`。原先完整回归 1,207 项及冻结原生流程的失败结论仍分别保留,不能把展示回放当作新增原生验收。
|
||||
@@ -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('<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(
|
||||
[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'],
|
||||
@@ -12,7 +27,7 @@ a = Analysis(
|
||||
[(str(verify_probe_path), 'tools/status_bridge/bin')]
|
||||
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(assets_root / 'cbb_refresh_verify.ico'), 'cbb_refresh_verify/assets'),
|
||||
(str(assets_root / 'cbb_refresh_verify.png'), 'cbb_refresh_verify/assets'),
|
||||
|
||||
@@ -50,6 +50,8 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(prog="CbbRefreshVerify")
|
||||
parser.add_argument('--verify-worker', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--repair-worker', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--owner-probe', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--native-backup-worker', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--management-worker', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--dialog-agent', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS)
|
||||
@@ -60,6 +62,12 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
parser.add_argument('--mentor-bin', default='', help=argparse.SUPPRESS)
|
||||
parser.add_argument("--smoke-test", action="store_true", help=argparse.SUPPRESS); parser.add_argument("--data-root", type=Path, help=argparse.SUPPRESS)
|
||||
args = parser.parse_args(list(argv) if argv is not None else None)
|
||||
if args.owner_probe:
|
||||
from .owner_probe import owner_probe_main
|
||||
return owner_probe_main(args.owner_probe)
|
||||
if args.native_backup_worker:
|
||||
from .native_backup import native_backup_worker_main
|
||||
return native_backup_worker_main(args.native_backup_worker)
|
||||
if args.management_worker:
|
||||
from .native_management import management_worker_main
|
||||
return management_worker_main(args.management_worker)
|
||||
|
||||
@@ -211,7 +211,8 @@ class BatchStatusSession:
|
||||
queried = 0
|
||||
for index, name in enumerate(names):
|
||||
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)
|
||||
continue
|
||||
try:
|
||||
@@ -231,7 +232,9 @@ class BatchStatusSession:
|
||||
except BridgeResponseError as error:
|
||||
message = str(error)
|
||||
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 (
|
||||
"路径不匹配", "请求标识不匹配", "CBB 标识不匹配",
|
||||
)) or "mismatch" in lower_message)
|
||||
|
||||
@@ -22,7 +22,7 @@ def launch_save_helper(command, **kwargs):
|
||||
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.
|
||||
|
||||
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
|
||||
# document. Killing a pending automation client can abandon it.
|
||||
Path(cancel_path).touch()
|
||||
return
|
||||
if not stop_clients:
|
||||
return
|
||||
threading.Event().wait(5)
|
||||
with _automation_clients_lock:
|
||||
for helper in _automation_clients:
|
||||
try:
|
||||
@@ -48,7 +50,7 @@ def start_supervisor_watchdog(supervisor_pid, *, cancel_path=None):
|
||||
pass
|
||||
finally:
|
||||
parent.Close()
|
||||
if cancel_path is None:
|
||||
if cancel_path is None or stop_clients:
|
||||
os._exit(75)
|
||||
|
||||
thread = threading.Thread(target=watch, name='supervisor-watchdog', daemon=True)
|
||||
@@ -72,27 +74,52 @@ class DesktopWorker:
|
||||
def __init__(self, command, name, *, interactive_input=False):
|
||||
self.name = name
|
||||
self.interactive_input = bool(interactive_input)
|
||||
self.desktop = None if self.interactive_input else win32service.CreateDesktop(
|
||||
name, 0, win32con.GENERIC_ALL, None)
|
||||
# Track the session, but never use kill-on-close: PCB descendants can
|
||||
# still own a database transaction when the Python supervisor exits.
|
||||
self.job = win32job.CreateJobObject(None, '')
|
||||
self.job_bound = False
|
||||
self.desktop = None
|
||||
self.job = None
|
||||
self.handle = None
|
||||
self.companions = []
|
||||
self.companion_pids = []
|
||||
startup = win32process.STARTUPINFO()
|
||||
# subprocess.STARTUPINFO does NOT pass lpDesktop to CreateProcess.
|
||||
startup.lpDesktop = startup_desktop_name(name, interactive_input=self.interactive_input)
|
||||
self.handle, thread, self.pid, _ = win32process.CreateProcess(
|
||||
command[0], subprocess.list2cmdline(command), None, None, False,
|
||||
win32con.CREATE_NO_WINDOW, None, None, startup)
|
||||
thread.Close()
|
||||
self.job_bound = False
|
||||
# Track the session, but never use kill-on-close: PCB descendants can
|
||||
# still own a database transaction when the Python supervisor exits.
|
||||
try:
|
||||
win32job.AssignProcessToJobObject(self.job, self.handle)
|
||||
self.job_bound = True
|
||||
self.desktop = None if self.interactive_input else win32service.CreateDesktop(
|
||||
name, 0, win32con.GENERIC_ALL, None)
|
||||
self.job = win32job.CreateJobObject(None, '')
|
||||
startup = win32process.STARTUPINFO()
|
||||
# subprocess.STARTUPINFO does NOT pass lpDesktop to CreateProcess.
|
||||
startup.lpDesktop = startup_desktop_name(name, interactive_input=self.interactive_input)
|
||||
self.handle, thread, self.pid, _ = win32process.CreateProcess(
|
||||
command[0], subprocess.list2cmdline(command), None, None, False,
|
||||
win32con.CREATE_NO_WINDOW, None, None, startup)
|
||||
thread.Close()
|
||||
try:
|
||||
win32job.AssignProcessToJobObject(self.job, self.handle)
|
||||
self.job_bound = True
|
||||
except Exception:
|
||||
# Kill-through-job is a cleanup guarantee, not a launch requirement.
|
||||
self.job_bound = False
|
||||
except Exception:
|
||||
# Kill-through-job is a cleanup guarantee, not a launch requirement.
|
||||
self.job_bound = False
|
||||
if self.handle is not None:
|
||||
try:
|
||||
win32process.TerminateProcess(self.handle, 1)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
self.handle.Close()
|
||||
except Exception:
|
||||
pass
|
||||
if self.job is not None:
|
||||
try:
|
||||
self.job.Close()
|
||||
except Exception:
|
||||
pass
|
||||
if self.desktop is not None:
|
||||
try:
|
||||
self.desktop.CloseDesktop()
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
|
||||
def start_companion(self, command):
|
||||
startup = win32process.STARTUPINFO()
|
||||
@@ -118,9 +145,38 @@ class DesktopWorker:
|
||||
return int(pid)
|
||||
|
||||
def poll(self):
|
||||
if getattr(self, '_closed', False):
|
||||
return self._exit_code
|
||||
code = win32process.GetExitCodeProcess(self.handle)
|
||||
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
|
||||
def returncode(self):
|
||||
return self.poll()
|
||||
@@ -132,12 +188,9 @@ class DesktopWorker:
|
||||
except Exception:
|
||||
pass
|
||||
# The worker is now stopped and cannot spawn another save helper.
|
||||
from .mentor_adapter import _process_details, _terminate_pid
|
||||
try:
|
||||
for pid, _exe, command, parent in _process_details('cscript.exe'):
|
||||
if (int(parent or 0) == self.pid
|
||||
and 'save_verified_block.vbs' in str(command).casefold()):
|
||||
_terminate_pid(pid) # single automation process, no /T
|
||||
self.wait(timeout=5)
|
||||
self.stop_automation_clients()
|
||||
except Exception:
|
||||
pass
|
||||
for companion in self.companions:
|
||||
@@ -162,6 +215,8 @@ class DesktopWorker:
|
||||
return self.poll()
|
||||
|
||||
def close(self):
|
||||
if getattr(self, '_closed', False):
|
||||
return
|
||||
# Releasing Python resources must not kill native database owners.
|
||||
try:
|
||||
if self.poll() is None:
|
||||
@@ -177,7 +232,9 @@ class DesktopWorker:
|
||||
pass
|
||||
self.companions.clear()
|
||||
self.companion_pids.clear()
|
||||
self._exit_code = self.poll()
|
||||
self.handle.Close()
|
||||
self._closed = True
|
||||
# Native processes keep their desktop alive if manual recovery is needed.
|
||||
self.job.Close()
|
||||
if self.desktop is not None:
|
||||
|
||||
@@ -32,7 +32,7 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
session. Unknown windows, live database addresses and other desktops are
|
||||
retained. WM_CLOSE is cooperative; no save prompt is accepted or killed.
|
||||
"""
|
||||
import win32con, win32gui, win32process
|
||||
import win32api, win32con, win32gui, win32process
|
||||
from .mentor_adapter import _process_details
|
||||
from .native_repair_ui import _current_desktop_name
|
||||
from .icdb_ownership import unreleased_addresses
|
||||
@@ -86,18 +86,19 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
break
|
||||
time.sleep(.2)
|
||||
continue
|
||||
_, executable, command, _ = records[0]
|
||||
args = _command_args(command)
|
||||
if (Path(executable).name.casefold() != 'expeditionpcb.exe'
|
||||
or '-reusablecircuit' not in [a.casefold() for a in args]
|
||||
or expected not in [os.path.normcase(os.path.abspath(a)) for a in args[1:]]):
|
||||
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
|
||||
if not sent:
|
||||
_, executable, command, _ = records[0]
|
||||
args = _command_args(command)
|
||||
if (Path(executable).name.casefold() != 'expeditionpcb.exe'
|
||||
or '-reusablecircuit' not in [a.casefold() for a in args]
|
||||
or expected not in [os.path.normcase(os.path.abspath(a)) for a in args[1:]]):
|
||||
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
|
||||
windows = []
|
||||
def observe(hwnd, _):
|
||||
if (win32process.GetWindowThreadProcessId(hwnd)[1] == pcb_pid
|
||||
and win32gui.IsWindowVisible(hwnd)):
|
||||
windows.append(hwnd)
|
||||
win32api.SetLastError(0)
|
||||
win32gui.EnumWindows(observe, None)
|
||||
main = [w for w in windows if win32gui.GetClassName(w).startswith('Afx:')
|
||||
and win32gui.GetWindowText(w).strip() in (
|
||||
@@ -112,6 +113,7 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
if window['class'] == 'Internet Explorer_Hidden' and window['title'] == '':
|
||||
window['rect'] = list(win32gui.GetWindowRect(window['hwnd']))
|
||||
window['children'] = []
|
||||
win32api.SetLastError(0)
|
||||
win32gui.EnumChildWindows(window['hwnd'],
|
||||
lambda hwnd, _: window['children'].append(int(hwnd)), None)
|
||||
left, top, right, bottom = window['rect']
|
||||
@@ -126,6 +128,7 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
and win32gui.GetWindow(hwnd, win32con.GW_CHILD)):
|
||||
documents.append(hwnd)
|
||||
if len(main) == 1:
|
||||
win32api.SetLastError(0)
|
||||
win32gui.EnumChildWindows(main[0], child, None)
|
||||
addresses = unreleased_addresses(job['lmc_file'], job['project'], job['pcb'])
|
||||
if len(main) == 1 and not unknown and not documents and not addresses:
|
||||
@@ -135,6 +138,9 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
# Observe exit even when the caller requested no extra wait.
|
||||
continue
|
||||
result['detail'] = 'STARTUP_IDLE_UNCONFIRMED: 等待空闲窗口和数据库释放'
|
||||
# After the single owned WM_CLOSE, WMI may lose the executable/
|
||||
# command fields before removing the PID. Only observe exit here;
|
||||
# never issue another close or treat missing fields as release.
|
||||
if time.monotonic() >= deadline:
|
||||
if sent:
|
||||
result['detail'] = 'STARTUP_EXIT_UNCONFIRMED: 已请求正常关闭,但 PCB 尚未退出'
|
||||
|
||||
@@ -15,17 +15,25 @@ def maintenance_counts(results):
|
||||
version_choice = sum(attempt.get('status') == 'PCB_VERSION_CHOICE_REQUIRED'
|
||||
and attempt.get('native_status') == 'REPAIRED'
|
||||
and attempt.get('validation_passed') is False for attempt in attempts)
|
||||
pending = sum(attempt.get('status') == 'REPAIRED_UNVERIFIED'
|
||||
and attempt.get('native_status') == 'REPAIRED' for attempt in attempts)
|
||||
return {'total': len(results), 'passed': sum(r.status == 'PASS' for r in results),
|
||||
'checked_without_repair': sum(r.status == 'PASS' and not r.recovery_attempts for r in results),
|
||||
'checked_without_repair': sum(r.status == 'CHECKED' for r in results),
|
||||
'issues_found': sum(r.error_category == 'ICDB_REPAIR_REQUIRED' for r in results),
|
||||
'in_use': sum(r.error_category == 'ICDB_DATABASE_IN_USE' for r in results),
|
||||
'unconfirmed': sum(r.status not in ('CHECKED', 'SKIPPED', 'CANCELLED')
|
||||
and r.error_category not in ('ICDB_REPAIR_REQUIRED', 'ICDB_DATABASE_IN_USE') for r in results),
|
||||
'cancelled': sum(r.status == 'CANCELLED' for r in results),
|
||||
'skipped': sum(r.status == 'SKIPPED' for r in results),
|
||||
'repaired': repaired, 'review_required': review,
|
||||
'version_choice_required': version_choice,
|
||||
'repair_unconfirmed': len(attempts)-repaired-review-version_choice}
|
||||
'repaired_unverified': pending,
|
||||
'repair_unconfirmed': len(attempts)-repaired-review-version_choice-pending}
|
||||
|
||||
|
||||
def write_maintenance_report(requests, results, batch_report, skipped_names):
|
||||
path = batch_report.with_name(batch_report.name.replace('batch-', 'icdb-', 1)).with_suffix('.json')
|
||||
record = {'operation': 'visible_non_ready_icdb_check_and_repair',
|
||||
record = {'operation': 'visible_non_ready_icdb_batch_check', 'automatic_repair': False,
|
||||
'library': str(requests[0].lmc_file), 'includes_ready': False,
|
||||
'target_names': [request.block_name for request in requests],
|
||||
'shared_database_repair_supported': False,
|
||||
|
||||
@@ -78,13 +78,14 @@ def _persist_blocker(library, status='OWNER_RELEASE_UNCONFIRMED', *, lease_id):
|
||||
|
||||
|
||||
class LibraryLock:
|
||||
def __init__(self, library, *, safe_to_release=None):
|
||||
def __init__(self, library, *, safe_to_release=None, checkpoint=True):
|
||||
library = Path(library).resolve()
|
||||
self.library = library
|
||||
self.path = library.with_name('.' + library.stem + '.cbb-upload.lock')
|
||||
self.key = _key(self.path)
|
||||
self.entered = False
|
||||
self.safe_to_release = safe_to_release
|
||||
self.checkpoint = checkpoint
|
||||
self.maintenance_guard = None
|
||||
self.maintenance_mutex = None
|
||||
|
||||
@@ -96,6 +97,17 @@ class LibraryLock:
|
||||
return lease
|
||||
|
||||
def __enter__(self):
|
||||
with _guard:
|
||||
owner = _owners.get(self.key)
|
||||
if owner and owner['retained'] and owner['depth'] == 0 and owner.get('release_probe'):
|
||||
try:
|
||||
released = owner['release_probe']() is True
|
||||
except Exception:
|
||||
released = False
|
||||
if released:
|
||||
owner['handle'].Close()
|
||||
del _owners[self.key]
|
||||
owner = None
|
||||
if self.maintenance_guard is not None:
|
||||
return _enter_maintenance(self)
|
||||
import win32con, win32file
|
||||
@@ -106,7 +118,7 @@ class LibraryLock:
|
||||
raise LibraryBusy(f'中心库被其他任务占用:{self.path}')
|
||||
owner['depth'] += 1
|
||||
else:
|
||||
if has_blocker(self.library):
|
||||
if self.checkpoint and has_blocker(self.library):
|
||||
raise LibraryBusy(f'中心库存在未解除的会话阻止记录,请先执行释放检查:{blocker_path(self.library)}')
|
||||
try:
|
||||
lease_id = uuid4().hex
|
||||
@@ -127,12 +139,15 @@ class LibraryLock:
|
||||
# it explicitly before complete-copy metadata is captured.
|
||||
import pywintypes
|
||||
win32file.SetFileTime(handle, None, None, pywintypes.Time(datetime.now()))
|
||||
_persist_blocker(self.library, 'OPERATION_IN_PROGRESS', lease_id=lease_id)
|
||||
if self.checkpoint:
|
||||
_persist_blocker(self.library, 'OPERATION_IN_PROGRESS', lease_id=lease_id)
|
||||
except Exception:
|
||||
handle.Close()
|
||||
raise
|
||||
_owners[self.key] = {'thread': threading.get_ident(), 'depth': 1,
|
||||
'handle': handle, 'retained': False, 'lease_id': lease_id}
|
||||
'handle': handle, 'retained': False, 'lease_id': lease_id,
|
||||
'checkpoint': self.checkpoint,
|
||||
'release_probe': self.safe_to_release if not self.checkpoint else None}
|
||||
self.entered = True
|
||||
return self
|
||||
|
||||
@@ -162,6 +177,20 @@ class LibraryLock:
|
||||
if not self.entered:
|
||||
return
|
||||
owner = _owners[self.key]
|
||||
if not owner.get('checkpoint', True):
|
||||
if self.safe_to_release is not None:
|
||||
try:
|
||||
released = self.safe_to_release() is True
|
||||
except Exception:
|
||||
released = False
|
||||
if not released:
|
||||
owner['retained'] = True
|
||||
owner['depth'] -= 1
|
||||
self.entered = False
|
||||
if owner['depth'] == 0 and not owner['retained']:
|
||||
owner['handle'].Close()
|
||||
del _owners[self.key]
|
||||
return
|
||||
checkpoint = checkpoint_record(blocker_path(self.library))
|
||||
if checkpoint is not None and 'export_analysis' in checkpoint:
|
||||
owner['retained'] = True
|
||||
@@ -237,7 +266,7 @@ def _enter_maintenance(lease):
|
||||
raise LibraryBusy('本进程库锁仍在使用或检查点身份不符')
|
||||
handle = existing['handle']
|
||||
else:
|
||||
if record is not None and _supervisor_alive(record['pid']):
|
||||
if record is not None and record['pid'] != os.getpid() and _supervisor_alive(record['pid']):
|
||||
raise LibraryBusy('原监督进程仍存在,不能接续其库锁')
|
||||
handle = win32file.CreateFile(str(lease.path), win32con.GENERIC_READ | win32con.GENERIC_WRITE,
|
||||
0, None, win32con.OPEN_ALWAYS, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
||||
@@ -286,9 +315,10 @@ def owned_snapshot(path):
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _prove_library_released(library):
|
||||
def _prove_library_released(library, block_name=None):
|
||||
"""Hold all native database read handles during explicit lease release."""
|
||||
import pythoncom, win32com.client, win32con, win32file
|
||||
import win32con, win32file
|
||||
from .owner_probe import query_owners
|
||||
from .scoped_manifest import scan_tree
|
||||
from .native_management import _retained_workers
|
||||
from .native_export_guard import assert_retained_exports_idle, prove_export_copies_released
|
||||
@@ -299,21 +329,38 @@ def _prove_library_released(library):
|
||||
from .com_runtime import initialize_com, uninitialize_com
|
||||
initialized = initialize_com()
|
||||
try:
|
||||
service = win32com.client.GetObject('winmgmts:')
|
||||
names = ('LibraryManager.exe', 'ExpeditionPCB.exe', 'viewdraw.exe',
|
||||
'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe', 'CleanWGLib.exe', *sorted(_OWNER_NAMES))
|
||||
query = 'SELECT ProcessId, Name FROM Win32_Process WHERE ' + ' OR '.join(
|
||||
f"Name='{name}'" for name in names)
|
||||
owners = [{'pid': int(item.ProcessId), 'name': str(item.Name)} for item in service.ExecQuery(query)]
|
||||
service = None
|
||||
if owners:
|
||||
raise LibraryBusy(f'原生进程仍存在,不能解除协调阻止:{owners}')
|
||||
'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe', 'CleanWGLib.exe',
|
||||
'cscript.exe', 'wscript.exe', 'python.exe', 'pythonw.exe',
|
||||
'CbbRefreshVerify.exe', *sorted(_OWNER_NAMES))
|
||||
scope_root = (Path(library).resolve().parent/'ReusableBlocksLP'/block_name/'Work').resolve() if block_name else None
|
||||
def check_owners():
|
||||
owners = []
|
||||
for item in query_owners(names):
|
||||
if item['pid'] == os.getpid():
|
||||
continue
|
||||
if scope_root is not None and item.get('command'):
|
||||
command = str(item['command']).casefold().replace('/', '\\')
|
||||
if str(scope_root).casefold().replace('/', '\\') not in command:
|
||||
continue
|
||||
automation = item['name'].casefold() in ('python.exe', 'pythonw.exe', 'cbbrefreshverify.exe')
|
||||
command = item['command'].casefold()
|
||||
if not automation or not command or any(flag in command for flag in (
|
||||
'--verify-worker', '--repair-worker', '--management-worker')):
|
||||
owners.append(item)
|
||||
if owners:
|
||||
raise LibraryBusy(f'原生进程仍存在,不能解除协调阻止:{owners}')
|
||||
return owners
|
||||
check_owners()
|
||||
entries = scan_tree(Path(library).parent)
|
||||
addresses = [str(path) for path in entries if path.name.casefold() == 'saddress.adr']
|
||||
addresses = [str(path) for path in entries if path.name.casefold() == 'saddress.adr'
|
||||
and (scope_root is None or path.resolve().is_relative_to(scope_root))]
|
||||
if addresses:
|
||||
raise LibraryBusy(f'库中仍有数据库地址记录,不能自动解除:{addresses}')
|
||||
native = [path for path in entries if path.is_file()
|
||||
and (path.suffix.casefold() == '.lmc' or path.name.casefold() in ('icdb.dat', 'layoutdb.lyt'))]
|
||||
native = [path for path in entries if path.is_file() and (
|
||||
path.suffix.casefold() == '.lmc'
|
||||
or (path.name.casefold() in ('icdb.dat', 'layoutdb.lyt')
|
||||
and (scope_root is None or path.resolve().is_relative_to(scope_root))))]
|
||||
if Path(library).resolve() not in native:
|
||||
raise LibraryBusy('目标库身份缺失,不能解除协调阻止。')
|
||||
with ExitStack() as stack:
|
||||
@@ -322,13 +369,14 @@ def _prove_library_released(library):
|
||||
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
|
||||
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
||||
stack.callback(handle.Close)
|
||||
owners = check_owners()
|
||||
yield {'native_owners': owners, 'addresses': addresses, 'export_copies': export_copies,
|
||||
'exclusive_files': [str(path) for path in native]}
|
||||
finally:
|
||||
uninitialize_com(initialized)
|
||||
|
||||
|
||||
def release_retained_library(library, evidence_dir):
|
||||
def release_retained_library(library, evidence_dir, *, block_name=None):
|
||||
"""Explicit user-requested release, after fresh owner/address/access proof.
|
||||
|
||||
The upload sidecar is never deleted. This acknowledges process release,
|
||||
@@ -358,7 +406,9 @@ def release_retained_library(library, evidence_dir):
|
||||
win32con.OPEN_ALWAYS, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
||||
except Exception as error:
|
||||
raise LibraryBusy('其他进程仍持有库锁,不能解除。') from error
|
||||
with _prove_library_released(library) as proof:
|
||||
proof_context = (_prove_library_released(library, block_name=block_name)
|
||||
if block_name else _prove_library_released(library))
|
||||
with proof_context as proof:
|
||||
marker = blocker_path(library)
|
||||
checkpoints = (marker, marker.with_suffix('.pending'))
|
||||
if any(path.exists() and checkpoint_record(path) is None for path in checkpoints):
|
||||
|
||||
@@ -9,11 +9,13 @@ import json
|
||||
import os
|
||||
from pathlib import Path, PureWindowsPath
|
||||
import re
|
||||
import stat
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
def assert_native_idle():
|
||||
import win32com.client
|
||||
def assert_native_idle(target=None):
|
||||
from .owner_probe import query_owners
|
||||
from .failed_session import _command_args
|
||||
from .native_management import _retained_workers
|
||||
from .native_export_guard import assert_retained_exports_idle
|
||||
from .native_engineering_identity import _OWNER_NAMES
|
||||
@@ -23,23 +25,37 @@ def assert_native_idle():
|
||||
names = ('ExpeditionPCB.exe', 'LibraryManager.exe', 'viewdraw.exe', 'iCDBProjectBackup.exe',
|
||||
'ReuseBlockImporter.exe', 'CleanWGLib.exe', 'cscript.exe', 'wscript.exe',
|
||||
'python.exe', 'pythonw.exe', 'CbbRefreshVerify.exe', *sorted(_OWNER_NAMES))
|
||||
service = win32com.client.GetObject('winmgmts:')
|
||||
query = 'SELECT ProcessId, Name, CommandLine FROM Win32_Process WHERE ' + ' OR '.join(
|
||||
f"Name='{name}'" for name in names)
|
||||
owners = []
|
||||
for item in service.ExecQuery(query):
|
||||
if int(item.ProcessId) == os.getpid():
|
||||
for item in query_owners(names):
|
||||
if item['pid'] == os.getpid():
|
||||
continue
|
||||
name, command = str(item.Name).casefold(), str(item.CommandLine or '').casefold()
|
||||
name, command = item['name'].casefold(), item['command'].casefold()
|
||||
automation = name in ('python.exe', 'pythonw.exe', 'cbbrefreshverify.exe')
|
||||
if not automation or not command or any(flag in command for flag in (
|
||||
'--verify-worker', '--repair-worker', '--management-worker')):
|
||||
owners.append({'pid': int(item.ProcessId), 'name': str(item.Name),
|
||||
'command': str(item.CommandLine or '')})
|
||||
owners.append(item)
|
||||
if target is not None:
|
||||
expected = os.path.normcase(os.path.abspath(str(target.project)))
|
||||
scoped = []
|
||||
for item in owners:
|
||||
command = str(item.get('command') or '')
|
||||
if not command:
|
||||
scoped.append(item)
|
||||
elif expected in [os.path.normcase(os.path.abspath(arg)) for arg in _command_args(command)[1:]]:
|
||||
scoped.append(item)
|
||||
owners = scoped
|
||||
if owners:
|
||||
raise ValueError(f'MAINTENANCE_OWNER_ACTIVE: 请正常关闭原生程序/操作助手:{owners}')
|
||||
|
||||
|
||||
def _assert_native_idle_for(target):
|
||||
"""Keep test/third-party zero-argument idle probes compatible."""
|
||||
import inspect
|
||||
if not inspect.signature(assert_native_idle).parameters:
|
||||
return assert_native_idle()
|
||||
return assert_native_idle(target)
|
||||
|
||||
|
||||
def address_snapshot(paths):
|
||||
from .scoped_manifest import hash_file
|
||||
return {str(path.resolve()): {'sha256': hash_file(path), 'size': path.stat().st_size,
|
||||
@@ -47,11 +63,32 @@ def address_snapshot(paths):
|
||||
for path in paths}
|
||||
|
||||
|
||||
def _scoped_addresses(request):
|
||||
def maintenance_entries(request, *, check=None):
|
||||
from .verify_runner import preflight
|
||||
from .scoped_manifest import scan_tree
|
||||
project, _ = preflight(request)
|
||||
root = Path(request.lmc_file).parent
|
||||
entries = scan_tree(project.parent, check=check)
|
||||
shared = root/'SymbolLibs/__ReusableBlocksSymb'
|
||||
if shared.exists():
|
||||
entries.update(scan_tree(shared, check=check))
|
||||
for library in root.glob('*.lmc'):
|
||||
info = library.lstat()
|
||||
if (info.st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT
|
||||
or not stat.S_ISREG(info.st_mode)):
|
||||
raise ValueError(f'不支持通过文件链接维护:{library}')
|
||||
entries[library] = info
|
||||
return entries
|
||||
|
||||
|
||||
def _scoped_addresses(request, *, check=None, entries=None):
|
||||
from .scoped_manifest import scan_tree
|
||||
root = Path(request.lmc_file).parent
|
||||
addresses = []
|
||||
for path in scan_tree(root):
|
||||
if entries is None:
|
||||
entries = maintenance_entries(request, check=check)
|
||||
if check is not None: check()
|
||||
for path in entries:
|
||||
if path.name.casefold() != 'saddress.adr':
|
||||
continue
|
||||
parts = tuple(part.casefold() for part in path.relative_to(root).parts)
|
||||
@@ -85,7 +122,7 @@ def maintenance_project_files(project, pcb):
|
||||
return (project,)
|
||||
|
||||
|
||||
def select_maintenance_target(request):
|
||||
def select_maintenance_target(request, *, check=None, entries=None):
|
||||
from .verify_runner import preflight
|
||||
from .backup_recovery import _project_text
|
||||
from .native_repair import RepairTarget
|
||||
@@ -93,7 +130,8 @@ def select_maintenance_target(request):
|
||||
if request.maintenance is not True:
|
||||
raise ValueError('MAINTENANCE_INTENT_REQUIRED')
|
||||
project, pcb = preflight(request)
|
||||
scan_tree(project.parent)
|
||||
if entries is None:
|
||||
entries = maintenance_entries(request, check=check)
|
||||
candidates = []
|
||||
for candidate in maintenance_project_files(project, pcb):
|
||||
if not candidate.is_file():
|
||||
@@ -113,7 +151,7 @@ def select_maintenance_target(request):
|
||||
if not (database/'icdb.dat').is_file():
|
||||
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED: 缺少 icdb.dat')
|
||||
candidates.append(RepairTarget(candidate, candidate.parent/'database'))
|
||||
addresses = _scoped_addresses(request)
|
||||
addresses = _scoped_addresses(request, check=check, entries=entries)
|
||||
if not addresses:
|
||||
# A crashed project may retain its internal open state after the server
|
||||
# advertisement disappears. Explicit maintenance must still inspect it.
|
||||
@@ -133,11 +171,19 @@ def select_maintenance_target(request):
|
||||
|
||||
|
||||
@contextmanager
|
||||
def maintenance_target_guard(request, expected=None):
|
||||
def maintenance_target_guard(request, expected=None, *, stop=None):
|
||||
"""Simultaneously hold native database files, preserving every address."""
|
||||
import win32con, win32file
|
||||
from .scoped_manifest import scan_tree, hash_file
|
||||
target, project, pcb, addresses = select_maintenance_target(request)
|
||||
def check():
|
||||
if stop is not None and stop.is_set():
|
||||
raise ValueError('MAINTENANCE_CANCELLED: 已取消占用检查')
|
||||
check()
|
||||
library_root = Path(request.lmc_file).parent
|
||||
# Share one complete snapshot for target/address selection and file locks.
|
||||
# Refresh it again while the handles are held; do not reuse across guards.
|
||||
entries = maintenance_entries(request, check=check)
|
||||
target, project, pcb, addresses = select_maintenance_target(request, check=check, entries=entries)
|
||||
baseline = address_snapshot(addresses)
|
||||
context = {'library': str(Path(request.lmc_file).resolve()), 'block': request.block_name,
|
||||
'project': str(target.project.resolve()), 'database': str(target.database.resolve()),
|
||||
@@ -146,40 +192,159 @@ def maintenance_target_guard(request, expected=None):
|
||||
for p in (pcb, *maintenance_project_files(project, pcb))}}
|
||||
if expected is not None and context != expected:
|
||||
raise ValueError('MAINTENANCE_SOURCE_CHANGED: 目标或地址记录在检查后变化')
|
||||
assert_native_idle()
|
||||
entries = scan_tree(Path(request.lmc_file).parent)
|
||||
files = [path for path in entries if path.is_file() and (
|
||||
path.suffix.casefold() == '.lmc' or path.name.casefold() in ('icdb.dat', 'layoutdb.lyt'))]
|
||||
_assert_native_idle_for(target)
|
||||
check()
|
||||
def native_files(snapshot):
|
||||
return {path for path, info in snapshot.items() if stat.S_ISREG(info.st_mode) and (
|
||||
path.suffix.casefold() == '.lmc' or path.name.casefold() in ('icdb.dat', 'layoutdb.lyt'))}
|
||||
files = native_files(entries)
|
||||
with ExitStack() as stack:
|
||||
for path in files:
|
||||
for path in sorted(files):
|
||||
check()
|
||||
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
|
||||
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
||||
stack.callback(handle.Close)
|
||||
assert_native_idle()
|
||||
current_addresses = _scoped_addresses(request)
|
||||
_assert_native_idle_for(target)
|
||||
current = maintenance_entries(request, check=check)
|
||||
if native_files(current) != files:
|
||||
raise ValueError('MAINTENANCE_SOURCE_CHANGED: 检查期间库文件集合发生变化')
|
||||
current_addresses = _scoped_addresses(request, check=check, entries=current)
|
||||
if address_snapshot(current_addresses) != baseline:
|
||||
raise ValueError('MAINTENANCE_SOURCE_CHANGED: 地址记录在检查期间变化')
|
||||
yield {'target': target, 'context': context, 'project': project, 'pcb': pcb}
|
||||
|
||||
|
||||
def maintenance_needed(request):
|
||||
# An explicit maintenance request must reach native inspection even when
|
||||
# no address/checkpoint remains. Selection and ownership are guarded later.
|
||||
if request.maintenance is True:
|
||||
return True
|
||||
from .library_lock import has_blocker
|
||||
from .icdb_ownership import unreleased_addresses
|
||||
from .verify_runner import preflight
|
||||
if has_blocker(request.lmc_file):
|
||||
return True
|
||||
project, pcb = preflight(request)
|
||||
return bool(unreleased_addresses(request.lmc_file, project, pcb))
|
||||
def run_icdb_check(request, *, progress=None, stop=None):
|
||||
"""Inspect through Project Backup; never launch PCB, Repair or Restore."""
|
||||
from .verify_runner import VerifyResult
|
||||
from .library_lock import LibraryLock, LibraryBusy
|
||||
from .native_repair import run_native_repair, RepairTarget
|
||||
from .native_backup import native_backup_project
|
||||
from .backup_recovery import _project_text
|
||||
from .native_occupancy import confirmed_inspection
|
||||
root = Path(request.evidence_dir).resolve()/('icdb-check-'+uuid4().hex[:12])
|
||||
library_root = Path(request.lmc_file).resolve().parent
|
||||
if root.is_relative_to(library_root) or library_root.is_relative_to(root):
|
||||
return VerifyResult('FAIL', error_category='ICDB_INSPECTION_UNCONFIRMED',
|
||||
stderr='检查记录目录需位于中心库之外。')
|
||||
record = {'operation': 'icdb_batch_check', 'automatic_repair': False,
|
||||
'library': str(request.lmc_file), 'block': request.block_name}
|
||||
released = True
|
||||
def check():
|
||||
if stop is not None and stop.is_set():
|
||||
raise InterruptedError('已取消检查。')
|
||||
def save(result):
|
||||
report = root/'result.json'
|
||||
recorded = replace(result, evidence_path=report)
|
||||
try:
|
||||
report.write_text(json.dumps({**record, 'result': asdict(recorded)},
|
||||
ensure_ascii=False, default=str, indent=2), encoding='utf-8')
|
||||
except OSError as error:
|
||||
import logging
|
||||
logging.getLogger(__name__).warning('icdb_check_report_unavailable path=%s error=%s', report, error)
|
||||
return result
|
||||
return recorded
|
||||
try:
|
||||
check()
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
with LibraryLock(request.lmc_file, checkpoint=False, safe_to_release=lambda: released):
|
||||
project = native_backup_project(request.lmc_file, request.block_name)
|
||||
values = re.findall(r'^KEY iCDBDir "([^"\r\n]*)"', _project_text(project), re.M)
|
||||
if (len(values) != 1 or not values[0] or PureWindowsPath(values[0]).drive
|
||||
or PureWindowsPath(values[0]).root
|
||||
or (project.parent/values[0]).resolve() != (project.parent/'database').resolve()):
|
||||
raise ValueError('无法确认工程的 ICDB 数据库路径。')
|
||||
target = RepairTarget(project, project.parent/'database')
|
||||
record['target'] = asdict(target)
|
||||
check()
|
||||
if progress:
|
||||
progress({'stage': 'icdb_ownership_check', 'block': request.block_name,
|
||||
'detail': '正在检查 ICDB 状态'})
|
||||
released = False
|
||||
inspection = run_native_repair(target, root/'native-inspection',
|
||||
mentor_bin=request.mentor_bin, timeout_seconds=min(30, request.timeout_seconds),
|
||||
progress=progress, inspection_only=True, stop=stop)
|
||||
record['native_inspection'] = inspection
|
||||
released = (inspection.get('release', {}).get('native_exited') is True
|
||||
or inspection.get('native_started') is False
|
||||
and inspection.get('native_pid') is None and inspection.get('worker_pid') is None)
|
||||
if ((stop is not None and stop.is_set())
|
||||
or inspection.get('status') in ('CANCELLED', 'CANCELLED_UNRELEASED')):
|
||||
return save(VerifyResult('CANCELLED', safe_to_continue=released, stderr='已取消 ICDB 检查。'))
|
||||
if not confirmed_inspection(target, inspection):
|
||||
return save(VerifyResult('FAIL', safe_to_continue=released,
|
||||
error_category='ICDB_INSPECTION_UNCONFIRMED',
|
||||
stderr='无法确认 ICDB 状态。' + str(inspection.get('detail', ''))))
|
||||
if inspection['status'] == 'IN_USE':
|
||||
return save(VerifyResult('BLOCKED', safe_to_continue=released,
|
||||
error_category='ICDB_DATABASE_IN_USE', stderr='工程正在使用,暂未完成 ICDB 检查。'))
|
||||
if inspection['repair_required']:
|
||||
return save(VerifyResult('FAIL', safe_to_continue=released,
|
||||
error_category='ICDB_REPAIR_REQUIRED', stderr='发现 ICDB 问题,未执行修复。'))
|
||||
return save(VerifyResult('CHECKED', safe_to_continue=released,
|
||||
stdout='ICDB 检查未发现异常,无需修复。'))
|
||||
except InterruptedError:
|
||||
return save(VerifyResult('CANCELLED', safe_to_continue=released, stderr='已取消 ICDB 检查。'))
|
||||
except LibraryBusy as error:
|
||||
return save(VerifyResult('BLOCKED', safe_to_continue=False,
|
||||
error_category='LIBRARY_IN_USE', stderr=str(error)))
|
||||
except Exception as error:
|
||||
return save(VerifyResult('FAIL', safe_to_continue=released,
|
||||
error_category='ICDB_INSPECTION_UNCONFIRMED', stderr=f'无法确认 ICDB 状态:{error}'))
|
||||
|
||||
|
||||
def run_existing_address_maintenance(request, *, verify, progress=None):
|
||||
def run_diagnosed_maintenance(request, *, diagnose, progress=None, stop=None):
|
||||
"""Open PCB once; only a current matching native fault admits maintenance."""
|
||||
from .verify_runner import VerifyResult
|
||||
from .icdb_recovery import parse_session_loss
|
||||
from .native_repair import select_repair_target
|
||||
if stop is not None and stop.is_set():
|
||||
return VerifyResult('CANCELLED', stderr='已取消,未打开工程或请求修复。')
|
||||
if progress:
|
||||
progress({'stage': 'icdb_startup_check', 'block': request.block_name,
|
||||
'detail': '尝试打开工程,依据本次原生报错判断是否需要 ICDB 维护'})
|
||||
startup = diagnose(replace(request, maintenance=False, auto_repair=False,
|
||||
diagnostic_only=True, native_lm_verify=False, post_repair_proof=None))
|
||||
def finish(result):
|
||||
if startup.evidence_path:
|
||||
report = startup.evidence_path.with_name('maintenance-result.json')
|
||||
recorded = replace(result, evidence_path=report)
|
||||
try:
|
||||
report.write_text(json.dumps({'block_name': request.block_name,
|
||||
'startup_evidence': str(startup.evidence_path), **asdict(recorded)},
|
||||
ensure_ascii=False, default=str, indent=2), encoding='utf-8')
|
||||
except OSError as error:
|
||||
import logging
|
||||
logging.getLogger(__name__).warning('maintenance_result_write_failed path=%s error=%s', report, error)
|
||||
else:
|
||||
result = recorded
|
||||
return result
|
||||
if startup.status == 'PASS' and startup.safe_to_continue:
|
||||
return finish(replace(startup, status='CHECKED', library_flag='UNKNOWN',
|
||||
stdout='工程打开正常,无需 ICDB 修复;未执行 CBB 校验。'))
|
||||
if startup.status == 'PASS':
|
||||
return finish(replace(startup, status='FAIL', stderr='工程打开后未确认会话释放,未请求 ICDB 修复。'))
|
||||
if startup.status != 'FAIL' or not startup.safe_to_continue:
|
||||
return startup
|
||||
# Do not search prior evidence directories or treat an error-code label,
|
||||
# address/checkpoint file, timeout or generic server error as a diagnosis.
|
||||
diagnosis = parse_session_loss(startup.stderr)
|
||||
if diagnosis is None:
|
||||
return startup
|
||||
try:
|
||||
target = select_repair_target(request, diagnosis)
|
||||
except (ValueError, OSError) as error:
|
||||
return finish(replace(startup, stderr=f'{startup.stderr}\n{error}',
|
||||
error_stage='icdb_target_check'))
|
||||
if stop is not None and stop.is_set():
|
||||
return finish(replace(startup, status='CANCELLED', stderr='已取消,未请求 ICDB 修复。'))
|
||||
return run_existing_address_maintenance(request, diagnosed_target=target, startup_result=startup,
|
||||
progress=progress, stop=stop)
|
||||
|
||||
|
||||
def run_existing_address_maintenance(request, *, diagnosed_target, startup_result, progress=None, stop=None):
|
||||
from .library_lock import LibraryLock
|
||||
from .native_repair import (run_native_repair, native_success_confirmed, repair_release_state,
|
||||
_native_identity_and_exit_confirmed)
|
||||
from .native_repair import run_native_repair, native_success_confirmed, repair_release_state
|
||||
from .verify_runner import VerifyResult
|
||||
root = Path(request.evidence_dir).resolve()/('maintenance-' + uuid4().hex[:12])
|
||||
library_root = Path(request.lmc_file).resolve().parent
|
||||
@@ -187,7 +352,8 @@ def run_existing_address_maintenance(request, *, verify, progress=None):
|
||||
return VerifyResult('BLOCKED', stderr='维护证据必须位于目标库之外', safe_to_continue=False)
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
record = {'operation': 'explicit_project_maintenance', 'library': str(request.lmc_file),
|
||||
'block': request.block_name, 'stage': 'preflight'}
|
||||
'block': request.block_name, 'stage': 'preflight',
|
||||
'startup_diagnosis': asdict(startup_result)}
|
||||
report = root/'result.json'
|
||||
owner_safe = False
|
||||
recovery = None
|
||||
@@ -199,45 +365,58 @@ def run_existing_address_maintenance(request, *, verify, progress=None):
|
||||
record['result'] = asdict(result)
|
||||
report.write_text(json.dumps(record, ensure_ascii=False, default=str, indent=2), encoding='utf-8')
|
||||
return result
|
||||
def native_event(event):
|
||||
emit(event['stage'], **{key: value for key, value in event.items() if key != 'stage'})
|
||||
try:
|
||||
if stop is not None and stop.is_set():
|
||||
return save(VerifyResult('CANCELLED', stderr='维护已取消,未启动原生操作'))
|
||||
emit('preflight', detail='正在核对工程、库文件和进程占用;可请求取消')
|
||||
lease = LibraryLock.for_maintenance(request.lmc_file, root/'takeover',
|
||||
lambda: maintenance_target_guard(request), safe_to_release=lambda: owner_safe)
|
||||
lambda: maintenance_target_guard(request, stop=stop), safe_to_release=lambda: owner_safe)
|
||||
with lease:
|
||||
owner_safe = True # Admission completed; no native client exists yet.
|
||||
checked = lease.maintenance_proof
|
||||
target, context = checked['target'], checked['context']
|
||||
record['maintenance_context'] = context
|
||||
emit('icdb_diagnosis_start', detail='已取得库锁,检查原生启动;不执行集成或保存')
|
||||
diagnostic_request = replace(request, maintenance=False, auto_repair=False,
|
||||
diagnostic_only=True, post_repair_proof=None, native_lm_verify=False,
|
||||
interactive_input=False, libspec='', dms_login_config='', evidence_dir=root/'diagnosis')
|
||||
diagnosis = verify(diagnostic_request)
|
||||
record['preflight_diagnosis'] = asdict(diagnosis)
|
||||
evidence = diagnosis.evidence_path
|
||||
if (evidence is None or not Path(evidence).is_file()
|
||||
or not Path(evidence).resolve().is_relative_to((root/'diagnosis').resolve())):
|
||||
raise ValueError('ICDB_DIAGNOSIS_UNCONFIRMED: 缺少本轮诊断证据,未调用 Repair')
|
||||
owner_safe = diagnosis.safe_to_continue
|
||||
if diagnosis.status == 'PASS' and owner_safe:
|
||||
emit('icdb_diagnosis_complete', detail='本轮启动未发现 ICDB 故障,未调用 Repair')
|
||||
return save(replace(diagnosis, library_flag='UNKNOWN', library_flag_detail='',
|
||||
stdout='ICDB 启动检查通过;未执行集成、保存或原生 Repair。', recovery_attempts=()))
|
||||
if diagnosis.error_category != 'ICDB_REPAIR_REQUIRED' or diagnosis.status in ('BLOCKED', 'TIMEOUT'):
|
||||
return save(replace(diagnosis, status='BLOCKED' if diagnosis.status == 'PASS' else diagnosis.status,
|
||||
stderr=(diagnosis.stderr + '\n未确认 ICDB 故障,未调用原生 Repair。').strip(),
|
||||
recovery_attempts=()))
|
||||
# Only this run's structured native lost-session diagnosis may
|
||||
# authorize Repair, and it must identify this exact database.
|
||||
fault = json.loads((Path(evidence).parent/'diagnostics/icdb-recovery.json').read_text('utf-8'))
|
||||
if (fault.get('error_code') != 'ICDB_REPAIR_REQUIRED' or fault.get('scope') != 'project'
|
||||
or not fault.get('session') or not fault.get('database_path')
|
||||
or Path(fault['database_path']).resolve() != target.database.resolve()):
|
||||
raise ValueError('ICDB_DIAGNOSIS_UNCONFIRMED: 故障证据未绑定当前数据库')
|
||||
record['confirmed_fault'] = fault
|
||||
# A diagnostic worker may have failed to release its native owner.
|
||||
# Recheck every owner and the exact target before dispatch.
|
||||
with maintenance_target_guard(request, context): pass
|
||||
if (target.project.resolve() != diagnosed_target.project.resolve()
|
||||
or target.database.resolve() != diagnosed_target.database.resolve()):
|
||||
return save(VerifyResult('FAIL', safe_to_continue=owner_safe,
|
||||
error_category='ICDB_TARGET_MISMATCH', error_stage='preflight',
|
||||
stderr='本次打开报错的数据库与维护目标不一致,未请求 ICDB 修复。'))
|
||||
if stop is not None and stop.is_set():
|
||||
raise ValueError('MAINTENANCE_CANCELLED: 已取消,未启动原生检查')
|
||||
emit('icdb_ownership_check', detail='调用原生 Project Backup 检查占用及恢复要求,不执行 Repair')
|
||||
owner_safe = False
|
||||
emit('icdb_diagnosis_confirmed', detail='本轮原生日志已确认目标数据库失联,进入 Repair')
|
||||
inspection = run_native_repair(target, root/'native-inspection',
|
||||
mentor_bin=request.mentor_bin, timeout_seconds=min(30, request.timeout_seconds),
|
||||
progress=native_event, maintenance_context=context, inspection_only=True, stop=stop)
|
||||
record['native_inspection'] = inspection
|
||||
owner_safe = (inspection.get('release', {}).get('native_exited') is True
|
||||
or inspection.get('native_pid') is None and inspection.get('worker_pid') is None)
|
||||
from .native_occupancy import confirmed_inspection
|
||||
if not confirmed_inspection(target, inspection):
|
||||
return save(VerifyResult('BLOCKED', safe_to_continue=owner_safe,
|
||||
error_category='ICDB_INSPECTION_UNCONFIRMED',
|
||||
stderr='原生占用检查未确认或已取消,未请求 Repair。' + str(inspection.get('detail', inspection.get('status')))))
|
||||
if inspection['status'] == 'IN_USE':
|
||||
return save(VerifyResult('BLOCKED', safe_to_continue=owner_safe,
|
||||
error_category='ICDB_DATABASE_IN_USE', stderr='原生工具确认工程正在使用,未请求 Repair。'))
|
||||
# Native loading may retire an old address itself. Permit only
|
||||
# disappearance, never a new/changed advertisement or project.
|
||||
with maintenance_target_guard(request, stop=stop) as refreshed:
|
||||
updated = refreshed['context']
|
||||
if ({k: v for k, v in context.items() if k != 'addresses'}
|
||||
!= {k: v for k, v in updated.items() if k != 'addresses'}
|
||||
or any(context['addresses'].get(k) != v for k, v in updated['addresses'].items())):
|
||||
raise ValueError('MAINTENANCE_SOURCE_CHANGED: 原生检查后工程或地址身份变化')
|
||||
context = updated
|
||||
record['post_inspection_context'] = context
|
||||
if not inspection['repair_required']:
|
||||
return save(VerifyResult('CHECKED', safe_to_continue=owner_safe,
|
||||
stdout='检查完成,无需修复。'))
|
||||
if stop is not None and stop.is_set():
|
||||
raise ValueError('MAINTENANCE_CANCELLED: 已取消,未开始 Repair')
|
||||
emit('icdb_diagnosis_confirmed', detail='本轮原生检查明确要求修复当前数据库,且确认未占用')
|
||||
native_root = root/'native-repair'; native_root.mkdir()
|
||||
attempt = native_root/'attempt.json'
|
||||
with attempt.open('x', encoding='utf-8') as stream:
|
||||
@@ -246,53 +425,25 @@ def run_existing_address_maintenance(request, *, verify, progress=None):
|
||||
emit('native_repair_start', detail='核对占用后由官方工具检查/修复;应用不自动备份')
|
||||
# Repeat immediately before dispatch; the worker repeats before
|
||||
# launching the native process as well.
|
||||
with maintenance_target_guard(request, context): pass
|
||||
with maintenance_target_guard(request, context, stop=stop): pass
|
||||
owner_safe = False
|
||||
recovery = run_native_repair(target, native_root, mentor_bin=request.mentor_bin,
|
||||
timeout_seconds=max(60, request.timeout_seconds), progress=progress,
|
||||
maintenance_context=context)
|
||||
assert_native_idle()
|
||||
timeout_seconds=max(60, request.timeout_seconds), progress=native_event,
|
||||
maintenance_context=context, stop=stop)
|
||||
_assert_native_idle_for(target)
|
||||
recovery = {**recovery, 'native_status': recovery.get('status'), 'validation_passed': False}
|
||||
recovery['release'] = repair_release_state(request, target, recovery)
|
||||
safe = recovery['release'].get('safe_to_continue') is True
|
||||
confirmed = recovery.get('status') == 'REPAIRED' and safe and native_success_confirmed(target, recovery)
|
||||
evidence = recovery.get('evidence')
|
||||
completed_failure = (recovery.get('status') in ('MISSING_HEALTHY_BACKUP', 'NATIVE_REPAIR_FAILED')
|
||||
and isinstance(evidence, dict) and evidence.get('failure_complete') is True
|
||||
and _native_identity_and_exit_confirmed(target, recovery))
|
||||
# Physical release is necessary, but does not approve historical
|
||||
# restoration/unknown/busy outcomes or an incomplete failure report.
|
||||
owner_safe = safe and (confirmed or completed_failure)
|
||||
# Release follows actual clients, not the repair/content verdict.
|
||||
owner_safe = safe or (recovery['release'].get('native_exited') is True
|
||||
and recovery['release'].get('database_exclusive') is True
|
||||
and recovery['release'].get('remaining_pids') == [])
|
||||
if confirmed:
|
||||
emit('repair_verify', detail='原生修复及释放已确认,重新打开同一工程校验')
|
||||
from .post_repair_consent import PostRepairProof
|
||||
owner_safe = False
|
||||
proof = PostRepairProof.create(request, target, recovery)
|
||||
verified = verify(replace(request, maintenance=False, auto_repair=False,
|
||||
diagnostic_only=False, post_repair_proof=proof,
|
||||
interactive_input=False, native_lm_verify=False))
|
||||
owner_safe = verified.safe_to_continue
|
||||
good = verified.status == 'PASS' and verified.library_flag == 'GREEN' and owner_safe
|
||||
recovery.update(status='REPAIRED' if good else 'REPAIR_VALIDATION_FAILED',
|
||||
validation_passed=good, validation_evidence=str(verified.evidence_path or ''))
|
||||
if good and verified.evidence_path:
|
||||
restored = Path(verified.evidence_path).parent/'pcb-version-restoration.json'
|
||||
if restored.exists():
|
||||
version = json.loads(restored.read_text(encoding='utf-8'))
|
||||
if (version.get('confirm_sent') is not True or version.get('historical_restore') is not True
|
||||
or Path(version['project']).resolve() != checked['project'].resolve()
|
||||
or version.get('choice') not in ('last_user_saved', 'autosave')):
|
||||
raise ValueError('PCB_VERSION_RESTORATION_EVIDENCE_INVALID')
|
||||
recovery.update(status='RESTORED_REVIEW_REQUIRED', pcb_version=version)
|
||||
verified = replace(verified, stdout=verified.stdout +
|
||||
f'\n已按用户选择恢复 PCB({version["date"]})并通过校验;版本待核对。')
|
||||
if verified.error_category == 'PCB_VERSION_CHOICE_REQUIRED':
|
||||
owner_safe = False
|
||||
good = False
|
||||
recovery.update(status='PCB_VERSION_CHOICE_REQUIRED', validation_passed=False)
|
||||
verified = replace(verified, safe_to_continue=False,
|
||||
stderr='ICDB原生修复已完成;PCB需选择恢复版本,尚未校验通过。\n' + verified.stderr)
|
||||
return save(replace(verified, status='PASS' if good else 'FAIL',
|
||||
recovery_attempts=(recovery,)))
|
||||
emit('native_repair_complete', detail='原生 ICDB 修复完成,CBB 待单独校验')
|
||||
recovery['status'] = 'REPAIRED_UNVERIFIED'
|
||||
return save(VerifyResult('REPAIRED', safe_to_continue=owner_safe,
|
||||
stdout='原生 ICDB 修复完成,CBB 待单独校验。', recovery_attempts=(recovery,)))
|
||||
if recovery.get('status') == 'REPAIRED':
|
||||
recovery['status'] = 'UNCONFIRMED'; owner_safe = False
|
||||
return save(VerifyResult('FAIL', stderr=f'{recovery["status"]}: {recovery.get("detail", "原生维护未确认修复")}',
|
||||
|
||||
@@ -217,23 +217,12 @@ def launch_pcb_process(command, cwd):
|
||||
|
||||
|
||||
def _process_details(name):
|
||||
queries = {
|
||||
'ExpeditionPCB.exe': "SELECT ProcessId, ParentProcessId, ExecutablePath, CommandLine FROM Win32_Process WHERE Name='ExpeditionPCB.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:
|
||||
if name not in {'ExpeditionPCB.exe', 'LibraryManager.exe', 'iCDBProjectBackup.exe',
|
||||
'ReuseBlockImporter.exe', 'cscript.exe', 'viewdraw.exe'}:
|
||||
raise ValueError(f'Unsupported process query: {name}')
|
||||
import win32com.client
|
||||
service = win32com.client.GetObject('winmgmts:')
|
||||
return [
|
||||
(int(p.ProcessId), str(p.ExecutablePath or ''), str(p.CommandLine or ''),
|
||||
int(p.ParentProcessId or 0))
|
||||
for p in service.ExecQuery(queries[name])
|
||||
]
|
||||
from .owner_probe import query_owners
|
||||
return [(row['pid'], row['executable'], row['command'], row['parent'])
|
||||
for row in query_owners((name,))]
|
||||
|
||||
|
||||
def _processes(name):
|
||||
@@ -616,11 +605,15 @@ def execute_job(job, emit):
|
||||
|
||||
root = Path(job['root'])
|
||||
block_root = Path(job['project']).parent.parent
|
||||
# COM publishes a shared active application. Never attach while another
|
||||
# native PCB session (including a retained failure) is still running.
|
||||
pcb_before = {pid for pid, _, _ in pcb_processes()}
|
||||
if pcb_before:
|
||||
raise RuntimeError(f'PCB_SESSION_ACTIVE: 已有 PCB 会话,请正常关闭后再校验: {sorted(pcb_before)}')
|
||||
# Unrelated designs stay open; COM and save helpers still require the exact
|
||||
# project identity before any integration or save call.
|
||||
from .failed_session import _command_args
|
||||
existing = tuple(pcb_processes())
|
||||
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.
|
||||
mapped_drive = str(job.get('mapped_drive') or '')
|
||||
mapped_remote_root = str(job.get('mapped_remote_root') or '')
|
||||
@@ -630,13 +623,7 @@ def execute_job(job, emit):
|
||||
emit(stage='mapped_drive_context', **mapping)
|
||||
emit(stage='backup_skipped', reason='manual_backup_policy', source=str(block_root),
|
||||
detail='应用不自动备份;请在操作前手动备份。')
|
||||
from .icdb_ownership import database_directories, unreleased_addresses
|
||||
for database in database_directories(job['lmc_file'], job['project'], job['pcb']):
|
||||
icdb_address = prepare_icdb_address(database, root, emit=emit)
|
||||
if icdb_address.get('status') != 'ABSENT':
|
||||
raise RuntimeError(
|
||||
'ICDB_SESSION_UNCONFIRMED: 数据库存在服务器地址记录,无法确认独占使用;'
|
||||
'已保留地址文件,请先检查原 PCB/iCDB 会话。' + str(icdb_address))
|
||||
from .icdb_ownership import unreleased_addresses
|
||||
from .verify_diagnostics import collect_preflight_diagnostics, collect_native_failure_logs
|
||||
diagnostics = collect_preflight_diagnostics(job['pcb'], root)
|
||||
emit(stage='preflight_diagnostics', non_blocking=True,
|
||||
@@ -778,6 +765,8 @@ def execute_job(job, emit):
|
||||
if job.get('diagnostic_only'):
|
||||
# The diagnostic opens only to establish current native evidence.
|
||||
# Do not refresh integration, save/commit Cert, or edit PRJ paths.
|
||||
if detail := native_error():
|
||||
raise RuntimeError(detail)
|
||||
pi = doc = app = None
|
||||
gc.collect()
|
||||
from .failed_session import close_failed_document
|
||||
@@ -795,6 +784,8 @@ def execute_job(job, emit):
|
||||
if time.monotonic() >= release_deadline:
|
||||
raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: 原生会话或数据库仍占用')
|
||||
time.sleep(.2)
|
||||
if detail := native_error():
|
||||
raise RuntimeError(detail)
|
||||
completed = True
|
||||
emit(stage='diagnostic_complete', status='PASS')
|
||||
return {'status': 'PASS', 'stdout': 'ICDB 启动检查通过;未执行集成或保存,已关闭工程。'}
|
||||
@@ -826,6 +817,8 @@ def execute_job(job, emit):
|
||||
emit(stage='save_helper', helper_pid=helper.pid)
|
||||
last_markers = ()
|
||||
while helper.poll() is None:
|
||||
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
|
||||
raise RuntimeError('VERIFY_CANCELLED: 已停止等待保存客户端')
|
||||
try:
|
||||
current = tuple(line.strip() for line in (root/'save.log').read_text(encoding='utf-8', errors='replace').splitlines() if line.strip())
|
||||
except OSError:
|
||||
@@ -862,7 +855,7 @@ def execute_job(job, emit):
|
||||
raise RuntimeError(f'PCB_RELEASE_UNCONFIRMED: 未确认 PCB 退出: {released}')
|
||||
addresses = unreleased_addresses(job['lmc_file'], job['project'], job['pcb'])
|
||||
if addresses:
|
||||
raise RuntimeError(f'ICDB_RELEASE_UNCONFIRMED: PCB 已退出但数据库地址记录仍存在;保留文件并停止批次: {addresses}')
|
||||
emit(stage='icdb_address_remaining', addresses=addresses, non_blocking=True)
|
||||
cert_pcb = block_root/'Cert'/Path(job['pcb']).relative_to(block_root/'Work')
|
||||
cert_evidence = collect_cert_evidence(block_root, cert_project, cert_pcb)
|
||||
emit(stage='cert_diagnostics', **cert_evidence)
|
||||
@@ -945,6 +938,14 @@ def cleanup_verify_processes(lm_pid, worker_pid, worker_parent_pid=None, *,
|
||||
if (expected_pcb and int(pid) not in baseline
|
||||
and is_reusable_circuit_pcb(executable, command, expected_pcb)):
|
||||
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)}
|
||||
remaining = sorted(tracked & alive)
|
||||
result = {'safe_to_continue': not remaining, 'remaining_pids': remaining}
|
||||
@@ -990,7 +991,7 @@ def worker_main(request_path):
|
||||
try:
|
||||
if job.get('supervisor_pid'):
|
||||
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
|
||||
if start_gate is not None:
|
||||
gate_deadline = time.monotonic() + 15
|
||||
@@ -1448,11 +1449,12 @@ def read_library_flag(library, name, *, timeout_seconds=90, log_path=None):
|
||||
if not executable.is_file():
|
||||
return FLAG_UNKNOWN, f'找不到 Library Manager: {executable}'
|
||||
|
||||
from pywinauto import Desktop
|
||||
from pywinauto.controls.common_controls import TreeViewWrapper
|
||||
|
||||
deadline = time.monotonic() + timeout_seconds
|
||||
desktop_name = 'CbbFlagRead_' + os.urandom(5).hex()
|
||||
desktop = win32service.CreateDesktop(desktop_name, 0, win32con.GENERIC_ALL, None)
|
||||
from pywinauto import Desktop
|
||||
from pywinauto.controls.common_controls import TreeViewWrapper
|
||||
|
||||
handle = None
|
||||
pid = None
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
"""Open the official backup UI; version selection and writes stay native."""
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
def native_backup_executable(mentor_bin=''):
|
||||
from .mentor_paths import discover_sdd_home
|
||||
home = discover_sdd_home(mentor_bin)
|
||||
executable = home/'iCDB/win32/bin/iCDBProjectBackup.exe' if home else None
|
||||
if executable is None or not executable.is_file():
|
||||
raise ValueError('未找到 iCDB Project Backup,请检查 Mentor 安装位置。')
|
||||
return executable
|
||||
|
||||
|
||||
def native_backup_project(library, block):
|
||||
from .verify_runner import INVALID_NAME_CHARS
|
||||
library = Path(library).absolute()
|
||||
if not block or block in ('.', '..') or any(c in block for c in INVALID_NAME_CHARS):
|
||||
raise ValueError('CBB 名称非法。')
|
||||
if not library.is_file():
|
||||
raise ValueError('中心库文件不存在。')
|
||||
work = library.parent/'ReusableBlocksLP'/block/'Work'
|
||||
expected = library.parent.resolve()/'ReusableBlocksLP'/block/'Work'
|
||||
if work.resolve() != expected:
|
||||
raise ValueError('工程路径通过链接指向其他位置。')
|
||||
projects = list(work.glob('*.prj'))
|
||||
if len(projects) != 1 or not projects[0].is_file():
|
||||
raise ValueError('无法唯一确定所选 CBB 的工程 PRJ。')
|
||||
project = projects[0]
|
||||
if (project.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT
|
||||
or not project.resolve().is_relative_to(expected)):
|
||||
raise ValueError('工程文件通过链接指向其他位置。')
|
||||
return project
|
||||
|
||||
|
||||
@dataclass
|
||||
class NativeBackupSession:
|
||||
process: object
|
||||
job: Path
|
||||
library: Path
|
||||
block: str
|
||||
path_lease: object = None
|
||||
|
||||
|
||||
def launch_native_backup(request):
|
||||
project = native_backup_project(request.lmc_file, request.block_name)
|
||||
native_backup_executable(request.mentor_bin)
|
||||
root = Path(request.evidence_dir).resolve()/('native-backup-'+uuid4().hex[:12])
|
||||
library_root = Path(request.lmc_file).resolve().parent
|
||||
if root.is_relative_to(library_root) or library_root.is_relative_to(root):
|
||||
raise ValueError('运行记录目录需位于中心库之外。')
|
||||
root.mkdir(parents=True)
|
||||
job = root/'request.json'
|
||||
job.write_text(json.dumps({'library': str(request.lmc_file), 'block': request.block_name,
|
||||
'project': str(project), 'mentor_bin': request.mentor_bin}, ensure_ascii=False), 'utf-8')
|
||||
command = ([sys.executable] if getattr(sys, 'frozen', False) else
|
||||
[sys.executable, '-m', 'cbb_refresh_verify'])+['--native-backup-worker', str(job)]
|
||||
process = subprocess.Popen(command, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
||||
return NativeBackupSession(process, job, Path(request.lmc_file), request.block_name)
|
||||
|
||||
|
||||
class _NativeBackupProcess:
|
||||
"""Track this visible tool and its descendants without killing on close."""
|
||||
def __init__(self, command, cwd):
|
||||
import win32con, win32job, win32process
|
||||
self.job = win32job.CreateJobObject(None, '')
|
||||
startup = win32process.STARTUPINFO()
|
||||
try:
|
||||
self.handle, thread, self.pid, _ = win32process.CreateProcess(
|
||||
command[0], subprocess.list2cmdline(command), None, None, False,
|
||||
win32con.CREATE_SUSPENDED, None, str(cwd), startup)
|
||||
except Exception:
|
||||
self.job.Close()
|
||||
raise
|
||||
try:
|
||||
win32job.AssignProcessToJobObject(self.job, self.handle)
|
||||
win32process.ResumeThread(thread)
|
||||
except Exception:
|
||||
# No native code has run while suspended; there can be no DB write.
|
||||
win32process.TerminateProcess(self.handle, 1)
|
||||
self.handle.Close(); self.job.Close()
|
||||
raise
|
||||
finally:
|
||||
thread.Close()
|
||||
|
||||
def poll(self):
|
||||
import win32process
|
||||
code = win32process.GetExitCodeProcess(self.handle)
|
||||
return None if code == 259 else code
|
||||
|
||||
def session_pids(self):
|
||||
import win32job
|
||||
return win32job.QueryInformationJobObject(self.job, win32job.JobObjectBasicProcessIdList)
|
||||
|
||||
def close(self):
|
||||
self.handle.Close(); self.job.Close()
|
||||
|
||||
|
||||
def native_backup_worker_main(job, *, process_factory=None):
|
||||
from .library_lock import LibraryLock
|
||||
from .management import _write_json
|
||||
job = Path(job)
|
||||
result = {'status': 'FAILED', 'safe_to_continue': True, 'restore_confirmed': False}
|
||||
native = None
|
||||
def write_evidence(name, value):
|
||||
try:
|
||||
_write_json(job.with_name(name), value)
|
||||
except Exception as error:
|
||||
# Evidence storage must never end supervision of a live transaction.
|
||||
result['evidence_error'] = str(error)
|
||||
try:
|
||||
record = json.loads(job.read_text('utf-8'))
|
||||
library, block = Path(record['library']), record['block']
|
||||
result.update(library=str(library), block=block)
|
||||
project = native_backup_project(library, block)
|
||||
if project != Path(record['project']):
|
||||
raise ValueError('工程身份已变化,未打开原生工具。')
|
||||
executable = native_backup_executable(record.get('mentor_bin', ''))
|
||||
released = True
|
||||
with LibraryLock(library, checkpoint=False, safe_to_release=lambda: released):
|
||||
native = (process_factory or _NativeBackupProcess)([str(executable), '-p', str(project)], project.parent)
|
||||
released = False
|
||||
result.update(status='OPEN', native_pid=native.pid, project=str(project), safe_to_continue=False)
|
||||
write_evidence('state.json', result)
|
||||
waiting = False
|
||||
while True:
|
||||
try:
|
||||
pids, exit_code = native.session_pids(), native.poll()
|
||||
except Exception as error:
|
||||
write_evidence('state.json', {**result,
|
||||
'status': 'RELEASE_UNCONFIRMED', 'detail': str(error)})
|
||||
time.sleep(.5)
|
||||
continue # Keep the lease while the live session cannot be observed.
|
||||
if not pids and exit_code is not None:
|
||||
break
|
||||
if exit_code is not None and not waiting:
|
||||
waiting = True
|
||||
write_evidence('state.json', {**result, 'status': 'WAITING_RELEASE'})
|
||||
time.sleep(.25)
|
||||
released = True
|
||||
result.update(status='CLOSED', native_exit_code=exit_code, safe_to_continue=True)
|
||||
return 0 if result['native_exit_code'] == 0 else 1
|
||||
except Exception as error:
|
||||
result.update(status='FAILED', detail=str(error), safe_to_continue=native is None)
|
||||
return 1
|
||||
finally:
|
||||
write_evidence('result.json', result)
|
||||
if native is not None:
|
||||
native.close() # No kill-on-close: never interrupt a native transaction.
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Interpret the current Project Backup loading session, before any Repair."""
|
||||
import ntpath
|
||||
import re
|
||||
|
||||
|
||||
def _same(left, right):
|
||||
return ntpath.normcase(ntpath.normpath(str(left))) == ntpath.normcase(ntpath.normpath(str(right)))
|
||||
|
||||
|
||||
def classify_inspection(project, database, output):
|
||||
result = {'status': 'UNCONFIRMED', 'repair_required': False}
|
||||
if not isinstance(output, str):
|
||||
return result
|
||||
loaded = re.findall(r'Loading project file \[([^\]\r\n]+)\]\.', output)
|
||||
if len(loaded) != 1 or not _same(loaded[0], project):
|
||||
return result
|
||||
checking = 'Checking if project is in use.'
|
||||
if checking not in output:
|
||||
return result
|
||||
current = output.rsplit(checking, 1)[1]
|
||||
if re.search(r'\bProject is in use\b', current, re.I):
|
||||
return {**result, 'status': 'IN_USE'}
|
||||
if ("Project is not in use. Full iCDB Project Backup's functionality is available." not in current
|
||||
or 'Backup information loaded correctly.' not in current):
|
||||
return result
|
||||
# This exact native error was captured from the isolated EE7.9.5 project.
|
||||
# A generic 'try Repair' or an old error before the latest check is not proof.
|
||||
inconsistency_pattern = (
|
||||
r"Project database \[([^\]\r\n]+)\] is inconsistent\. It has been manually copied while the iCDB Server was running\. "
|
||||
r"Please use iCDB Project Backup 'Repair project' functionality to fix this issue\.")
|
||||
inconsistent = re.findall(inconsistency_pattern, current)
|
||||
from .icdb_recovery import _session_losses
|
||||
losses = list(_session_losses(current))
|
||||
if (len(inconsistent) > 1 or any(not _same(path, database) for path in inconsistent)
|
||||
or len(losses) > 1 or any(not lost.get('session') or lost.get('scope') != 'project'
|
||||
or not _same(lost.get('database_path', ''), database) for lost in losses)):
|
||||
return result
|
||||
required = bool(inconsistent or losses)
|
||||
remaining = re.sub(inconsistency_pattern, '', current)
|
||||
if required:
|
||||
remaining = remaining.replace('Please try to repair the project!', '')
|
||||
if re.search(r'\berror\b|try to repair|inconsistent|corrupt', remaining, re.I):
|
||||
return result
|
||||
return {'status': 'NOT_IN_USE', 'repair_required': bool(required)}
|
||||
|
||||
|
||||
def confirmed_inspection(target, record):
|
||||
"""Only an exact, exited, inspection-only native process grants a verdict."""
|
||||
if (not isinstance(record, dict) or record.get('inspection_only') is not True
|
||||
or record.get('repair_requested') is not False
|
||||
or type(record.get('native_pid')) is not int or record['native_pid'] <= 0
|
||||
or record.get('native_exit_code') != 0
|
||||
or record.get('release', {}).get('native_exited') is not True
|
||||
or not _same(record.get('project', ''), target.project)
|
||||
or not _same(record.get('database', ''), target.database)
|
||||
or record.get('unknown_dialogs')):
|
||||
return False
|
||||
expected = classify_inspection(target.project, target.database, record.get('output'))
|
||||
return (expected['status'] in ('NOT_IN_USE', 'IN_USE')
|
||||
and record.get('status') == expected['status']
|
||||
and record.get('repair_required') is expected['repair_required'])
|
||||
@@ -253,8 +253,11 @@ def repair_release_state(request, target, native_result):
|
||||
|
||||
|
||||
def run_native_repair(target, root, *, mentor_bin='', timeout_seconds=300, progress=None,
|
||||
maintenance_context=None):
|
||||
maintenance_context=None, inspection_only=False, stop=None):
|
||||
"""Supervise the GUI on its own desktop; a repair timeout never kills it."""
|
||||
if stop is not None and stop.is_set():
|
||||
return {'status': 'CANCELLED', 'native_started': False,
|
||||
'detail': '原生操作启动前已取消', 'release': {'safe_to_continue': True}}
|
||||
from .desktop_worker import DesktopWorker
|
||||
root = Path(root)
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
@@ -264,16 +267,23 @@ def run_native_repair(target, root, *, mentor_bin='', timeout_seconds=300, progr
|
||||
job_path.write_text(json.dumps({'project': str(target.project), 'database': str(target.database),
|
||||
'root': str(root), 'mentor_bin': str(mentor_bin or ''), 'timeout': timeout_seconds,
|
||||
'cancel_signal': str(cancel), 'supervisor_pid': os.getpid(), 'desktop': desktop,
|
||||
'maintenance_context': maintenance_context},
|
||||
'maintenance_context': maintenance_context, 'inspection_only': inspection_only},
|
||||
ensure_ascii=False), encoding='utf-8')
|
||||
command = ([sys.executable] if getattr(sys, 'frozen', False) else
|
||||
[sys.executable, '-m', 'cbb_refresh_verify']) + ['--repair-worker', str(job_path)]
|
||||
worker = DesktopWorker(command, desktop)
|
||||
worker.bind_cancellation(cancel)
|
||||
deadline = time.monotonic()+max(1, float(timeout_seconds))+5
|
||||
# Worker admission includes filesystem/ownership checks before the native
|
||||
# timeout begins. Bound that preparation separately; never extend on polls.
|
||||
deadline = time.monotonic()+60+max(1, float(timeout_seconds))+5
|
||||
event_count = 0
|
||||
cancelled = False
|
||||
try:
|
||||
while worker.poll() is None and time.monotonic()<deadline:
|
||||
if not cancelled and stop is not None and stop.is_set():
|
||||
worker.request_stop()
|
||||
cancelled = True
|
||||
deadline = min(deadline, time.monotonic()+5)
|
||||
event_file = root/'repair-events.jsonl'
|
||||
if progress and event_file.is_file():
|
||||
lines = event_file.read_text('utf-8').splitlines()
|
||||
@@ -287,11 +297,13 @@ def run_native_repair(target, root, *, mentor_bin='', timeout_seconds=300, progr
|
||||
outcome = root/'repair-result.json'
|
||||
if worker.poll() is None or not outcome.is_file():
|
||||
worker.request_stop()
|
||||
return {'status': 'TIMEOUT_UNRELEASED', 'worker_pid': worker.pid, 'desktop': desktop,
|
||||
return {'status': 'CANCELLED_UNRELEASED' if cancelled else 'TIMEOUT_UNRELEASED', 'worker_pid': worker.pid, 'desktop': desktop,
|
||||
'release': {'safe_to_continue': False},
|
||||
'detail': '原生修复尚未确认结束,保留操作并停止批次', 'evidence_path': str(root)}
|
||||
result = json.loads(outcome.read_text('utf-8'))
|
||||
if worker.returncode != 0 and result.get('status') == 'REPAIRED':
|
||||
if cancelled:
|
||||
result.update(status='CANCELLED', repair_required=False)
|
||||
if worker.returncode != 0 and result.get('status') in ('REPAIRED', 'NOT_IN_USE', 'IN_USE'):
|
||||
result['status'] = 'UNCONFIRMED'
|
||||
return {**result, 'evidence_path': str(root)}
|
||||
finally:
|
||||
|
||||
@@ -98,7 +98,7 @@ def _repair_command(executable):
|
||||
|
||||
|
||||
def _windows(pid):
|
||||
import win32gui, win32process
|
||||
import win32api, win32gui, win32process
|
||||
windows = []
|
||||
def observe(hwnd, _):
|
||||
if win32process.GetWindowThreadProcessId(hwnd)[1] != pid or not win32gui.IsWindowVisible(hwnd):
|
||||
@@ -109,10 +109,14 @@ def _windows(pid):
|
||||
children.append({'hwnd': handle, 'text': win32gui.GetWindowText(handle),
|
||||
'class': win32gui.GetClassName(handle), 'id': win32gui.GetDlgCtrlID(handle),
|
||||
'enabled': bool(win32gui.IsWindowEnabled(handle))})
|
||||
# Empty window lists are valid. pywin32 otherwise interprets a stale
|
||||
# thread error (observed ERROR_FILE_NOT_FOUND) as an enum failure.
|
||||
win32api.SetLastError(0)
|
||||
win32gui.EnumChildWindows(hwnd, child, None)
|
||||
windows.append({'hwnd': hwnd, 'title': win32gui.GetWindowText(hwnd),
|
||||
'class': win32gui.GetClassName(hwnd), 'enabled': bool(win32gui.IsWindowEnabled(hwnd)),
|
||||
'children': children})
|
||||
win32api.SetLastError(0)
|
||||
win32gui.EnumWindows(observe, None)
|
||||
return windows
|
||||
|
||||
@@ -180,15 +184,98 @@ def _native_evidence(project, database, pid, started_ns, baseline, *, output_tex
|
||||
'restore_tail': restore_log[-8192:]}
|
||||
|
||||
|
||||
def _inspect_project(job, process, emit):
|
||||
"""Observe this process's native query; never send a Repair/menu command."""
|
||||
import win32con, win32gui
|
||||
from .native_occupancy import classify_inspection
|
||||
project, database = Path(job['project']), Path(job['database'])
|
||||
result = {'status': 'UNCONFIRMED', 'project': str(project), 'database': str(database),
|
||||
'native_pid': process.pid, 'inspection_only': True, 'repair_requested': False,
|
||||
'repair_required': False, 'output': ''}
|
||||
deadline = time.monotonic() + max(1, float(job['timeout']))
|
||||
closing = False
|
||||
last_state = None
|
||||
# Reserve a short cooperative-close grace after the inspection deadline.
|
||||
while process.poll() is None and time.monotonic() < deadline + 3:
|
||||
windows = [w for w in _windows(process.pid) if not (
|
||||
w['title'] == '' and w['class'] in ('UAC_InputIndicatorOverlayWnd', 'UAC Input Indicator'))]
|
||||
shells = [w for w in windows if w['class'].startswith('Afx:') and w['title'] == 'iCDB Project Backup']
|
||||
exact = [w for w in windows if w['class'].startswith('Afx:')
|
||||
and w['title'].casefold() == ('iCDB Project Backup - '+str(project)).casefold()]
|
||||
# EE7.9 can keep the generic shell title while loading the requested PRJ.
|
||||
# Its Output still binds the project; waiting only for the decorated title
|
||||
# turns a valid session into a false timeout.
|
||||
mains = exact or shells
|
||||
main = mains[0] if len(mains) == 1 else None
|
||||
unknown = [w for w in windows if w is not main and w not in shells]
|
||||
if unknown:
|
||||
result.update(status='UNCONFIRMED', unknown_dialogs=unknown)
|
||||
break
|
||||
current = _native_output(windows)
|
||||
state = {'main_found': main is not None, 'output_readable': current is not None,
|
||||
'windows': windows}
|
||||
if state != last_state:
|
||||
(Path(job['root'])/'inspection-state.json').write_text(
|
||||
json.dumps(state, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
emit(stage='native_occupancy_wait', main_found=state['main_found'], output_readable=state['output_readable'])
|
||||
last_state = state
|
||||
if current is not None:
|
||||
result['output'] = current
|
||||
cancelled = Path(job['cancel_signal']).exists()
|
||||
expired = time.monotonic() >= deadline
|
||||
verdict = classify_inspection(project, database, current)
|
||||
if cancelled:
|
||||
result.update(status='CANCELLED', repair_required=False)
|
||||
if not closing and main and main['enabled'] and (cancelled or expired or verdict['status'] != 'UNCONFIRMED'):
|
||||
if not cancelled and not expired: result.update(verdict)
|
||||
emit(stage='native_occupancy', **result)
|
||||
win32gui.PostMessage(main['hwnd'], win32con.WM_CLOSE, 0, 0)
|
||||
closing = True
|
||||
time.sleep(.2)
|
||||
exited = process.poll() is not None
|
||||
result['native_exit_code'] = process.poll()
|
||||
result['release'] = {'native_exited': exited,
|
||||
'addresses': [str(database/'cdbsvr/sAddress.adr')] if (database/'cdbsvr/sAddress.adr').exists() else [],
|
||||
'safe_to_continue': exited and result['status'] == 'NOT_IN_USE'}
|
||||
if not exited:
|
||||
result.update(status='TIMEOUT_UNRELEASED', repair_required=False)
|
||||
result['detail'] = ('原生检查窗口未返回 Output,未执行 Repair。'
|
||||
if not result['output'] else '原生检查工具未退出,未执行 Repair。')
|
||||
return result
|
||||
|
||||
|
||||
class _CancellationFile:
|
||||
def __init__(self, path):
|
||||
self.path = Path(path)
|
||||
self._next_poll = 0.0
|
||||
self._cancelled = False
|
||||
self.polls = 0
|
||||
self.poll_seconds = 0.0
|
||||
|
||||
def is_set(self):
|
||||
# scan_tree checks between every entry. Avoid issuing tens of
|
||||
# thousands of filesystem requests just to observe one IPC flag.
|
||||
# The direct checks before Popen/Repair remain immediate.
|
||||
now = time.monotonic()
|
||||
if not self._cancelled and now >= self._next_poll:
|
||||
self._cancelled = self.path.exists()
|
||||
finished = time.monotonic()
|
||||
self.polls += 1
|
||||
self.poll_seconds += finished-now
|
||||
self._next_poll = finished + .1
|
||||
return self._cancelled
|
||||
|
||||
|
||||
def repair_worker_main(job_path):
|
||||
import win32con, win32gui
|
||||
from .native_repair import RepairTarget, check_repair_access
|
||||
from .mentor_paths import discover_sdd_home
|
||||
from .icdb_recovery import snapshot_log
|
||||
job = json.loads(Path(job_path).read_text('utf-8'))
|
||||
stop = _CancellationFile(job['cancel_signal'])
|
||||
root = Path(job['root'])
|
||||
project, database = Path(job['project']), Path(job['database'])
|
||||
result = {'status': 'BLOCKED', 'project': str(project), 'database': str(database),
|
||||
result = {'status': 'BLOCKED', 'native_started': False, 'project': str(project), 'database': str(database),
|
||||
'release': {'safe_to_continue': False}}
|
||||
process = None
|
||||
def emit(**event):
|
||||
@@ -208,9 +295,9 @@ def repair_worker_main(job_path):
|
||||
if home is None:
|
||||
raise ValueError('NATIVE_REPAIR_UNAVAILABLE: 未找到 Mentor 安装目录')
|
||||
executable = home/'iCDB/win32/bin/iCDBProjectBackup.exe'
|
||||
command_id = _repair_command(executable)
|
||||
command_id = None if job.get('inspection_only') else _repair_command(executable)
|
||||
from .mentor_adapter import pcb_processes, _process_details
|
||||
if pcb_processes() or _process_details('LibraryManager.exe'):
|
||||
if not job.get('inspection_only') and (pcb_processes() or _process_details('LibraryManager.exe')):
|
||||
raise ValueError('REPAIR_DATABASE_IN_USE')
|
||||
maintenance_context = job.get('maintenance_context')
|
||||
if maintenance_context is not None:
|
||||
@@ -218,22 +305,43 @@ def repair_worker_main(job_path):
|
||||
from .verify_runner import VerifyRequest
|
||||
maintenance_request = VerifyRequest(Path(maintenance_context['library']),
|
||||
maintenance_context['block'], root, maintenance=True)
|
||||
with maintenance_target_guard(maintenance_request, maintenance_context) as checked:
|
||||
if (checked['target'].project.resolve() != project.resolve()
|
||||
or checked['target'].database.resolve() != database.resolve()):
|
||||
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED')
|
||||
check_repair_access(RepairTarget(project, database))
|
||||
emit(stage='backup_skipped', reason='manual_backup_policy',
|
||||
detail='应用不自动备份;Mentor 原生修复仍可能生成自身备份。')
|
||||
emit(stage='native_preflight', detail='正在核对本次原生工具的目标及占用')
|
||||
if job.get('inspection_only'):
|
||||
from .scoped_manifest import scan_tree
|
||||
def check_cancelled():
|
||||
if stop.is_set():
|
||||
raise InterruptedError('检查已取消')
|
||||
scan_tree(project.parent, check=check_cancelled)
|
||||
else:
|
||||
check_repair_access(RepairTarget(project, database))
|
||||
emit(stage='backup_skipped', reason='manual_backup_policy',
|
||||
detail='应用不自动备份;Mentor 原生修复仍可能生成自身备份。')
|
||||
if Path(job['cancel_signal']).exists():
|
||||
raise ValueError('REPAIR_CANCELLED_BEFORE_LAUNCH')
|
||||
if maintenance_context is not None:
|
||||
with maintenance_target_guard(maintenance_request, maintenance_context): pass
|
||||
# Manual backup policy leaves no mutation between preparation and
|
||||
# launch. Run the complete guard once here, retaining its identity,
|
||||
# address and exclusive-access checks immediately before Popen.
|
||||
with maintenance_target_guard(maintenance_request, maintenance_context, stop=stop) as checked:
|
||||
if (checked['target'].project.resolve() != project.resolve()
|
||||
or checked['target'].database.resolve() != database.resolve()):
|
||||
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED')
|
||||
emit(stage='native_preflight_complete', cancellation_polls=stop.polls,
|
||||
cancellation_poll_seconds=round(stop.poll_seconds, 3))
|
||||
if Path(job['cancel_signal']).exists():
|
||||
raise ValueError('REPAIR_CANCELLED_BEFORE_LAUNCH')
|
||||
baseline = snapshot_log(project.parent/'Log Files/ProjectBackupLog.txt')
|
||||
started_ns = time.time_ns()
|
||||
if Path(job['cancel_signal']).exists():
|
||||
raise ValueError('REPAIR_CANCELLED_BEFORE_LAUNCH')
|
||||
process = subprocess.Popen([str(executable), '-p', str(project)], cwd=str(project.parent))
|
||||
result['native_started'] = True
|
||||
result['native_pid'] = process.pid
|
||||
emit(stage='native_started', pid=process.pid, project=str(project))
|
||||
if job.get('inspection_only'):
|
||||
result = _inspect_project(job, process, emit)
|
||||
(root/'repair-result.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
return 0 if result['status'] in ('NOT_IN_USE', 'IN_USE') else 1
|
||||
deadline = time.monotonic()+max(1, float(job['timeout']))
|
||||
invoked = confirmed = closing = False
|
||||
evidence = None
|
||||
@@ -336,6 +444,8 @@ def repair_worker_main(job_path):
|
||||
detail='原生 Repair 未取得完整成功/释放证据,未重试校验')
|
||||
except Exception as error:
|
||||
result.update(detail=str(error), status='RETAINED' if process and process.poll() is None else 'BLOCKED')
|
||||
result['preflight_cancellation'] = {'polls': stop.polls,
|
||||
'seconds': round(stop.poll_seconds, 3)}
|
||||
# Never terminate a repair or its database owner. Retained PID/desktop is
|
||||
# reported to the parent, including unknown native prompts.
|
||||
(root/'repair-result.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
|
||||
@@ -229,6 +229,14 @@ class LibraryPathLease:
|
||||
"""Keep the Mentor drive available to a retained native session."""
|
||||
self._retained_for_recovery = True
|
||||
|
||||
def transfer_ownership(self, other) -> None:
|
||||
"""Keep a shared mapping alive for the currently loaded library."""
|
||||
if (isinstance(other, LibraryPathLease) and not other._closed
|
||||
and self.created and self.drive.upper() == other.drive.upper()
|
||||
and self.remote_root and _same_remote(self.remote_root, other.remote_root)):
|
||||
other.created, other._backend = True, self._backend
|
||||
self.created = False
|
||||
|
||||
def close(self) -> None:
|
||||
if self._closed:
|
||||
return
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Bound WMI enumeration in a read-only helper, never in the Qt thread."""
|
||||
from pathlib import Path
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
|
||||
def query_owners(names, *, timeout_seconds=10):
|
||||
names = tuple(names)
|
||||
if not names or any(not re.fullmatch(r'[\w.-]+\.exe', name, re.I) for name in names):
|
||||
raise ValueError('OWNER_QUERY_INVALID')
|
||||
with tempfile.TemporaryDirectory(prefix='cbb-owner-probe-') as directory:
|
||||
job = Path(directory)/'request.json'
|
||||
job.write_text(json.dumps({'names': names}), encoding='utf-8')
|
||||
command = ([sys.executable] if getattr(sys, 'frozen', False) else
|
||||
[sys.executable, '-m', 'cbb_refresh_verify']) + ['--owner-probe', str(job)]
|
||||
try:
|
||||
result = subprocess.run(command, timeout=max(.1, min(10, timeout_seconds)),
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
||||
except subprocess.TimeoutExpired as error:
|
||||
# This helper only enumerates processes; it never launches Mentor
|
||||
# or acquires a native database session.
|
||||
raise RuntimeError('OWNER_QUERY_TIMEOUT: 进程查询超时,占用状态无法确认') from error
|
||||
try:
|
||||
record = json.loads(job.with_name('result.json').read_text('utf-8'))
|
||||
rows = record['owners']
|
||||
if result.returncode != 0 or record['names'] != list(names) or not isinstance(rows, list):
|
||||
raise ValueError('invalid result')
|
||||
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}
|
||||
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')
|
||||
return rows
|
||||
except (OSError, ValueError, KeyError, TypeError, AttributeError) as error:
|
||||
raise RuntimeError('OWNER_QUERY_UNCONFIRMED: 进程查询未返回有效证据') from error
|
||||
|
||||
|
||||
def owner_probe_main(job):
|
||||
import pythoncom
|
||||
import win32com.client
|
||||
job = Path(job)
|
||||
names = json.loads(job.read_text('utf-8'))['names']
|
||||
if not names or any(not re.fullmatch(r'[\w.-]+\.exe', name, re.I) for name in names):
|
||||
return 1
|
||||
pythoncom.CoInitialize()
|
||||
try:
|
||||
service = win32com.client.GetObject('winmgmts:')
|
||||
query = 'SELECT ProcessId,Name,CommandLine,ExecutablePath,ParentProcessId FROM Win32_Process WHERE ' + ' OR '.join(
|
||||
f"Name='{name}'" for name in names)
|
||||
rows = [{'pid': int(item.ProcessId), 'name': str(item.Name),
|
||||
'command': str(item.CommandLine or ''), 'executable': str(item.ExecutablePath or ''),
|
||||
'parent': int(item.ParentProcessId or 0)} for item in service.ExecQuery(query)]
|
||||
service = None
|
||||
job.with_name('result.json').write_text(json.dumps({'names': names, 'owners': rows}), encoding='utf-8')
|
||||
return 0
|
||||
finally:
|
||||
pythoncom.CoUninitialize()
|
||||
@@ -199,7 +199,13 @@ def _validate_current_processes(job, prelaunch, target_pid, launcher_pid, worker
|
||||
or not is_reusable_circuit_pcb(launcher[2], launcher[3], job['pcb'])):
|
||||
raise ValueError('POST_REPAIR_PROCESS_IDENTITY_MISMATCH')
|
||||
allowed = {target_pid, launcher_pid, worker_pid, int(job['supervisor_pid']), *companion_pids}
|
||||
if any(r[0] not in allowed for r in rows): raise ValueError('POST_REPAIR_FOREIGN_OWNER')
|
||||
foreign = [r for r in rows if r[0] not in allowed]
|
||||
if foreign:
|
||||
from .management import _write_json
|
||||
_write_json(Path(job['root'])/'foreign-owners.json', {'allowed_pids': sorted(allowed),
|
||||
'observed': [{'pid': r[0], 'name': r[1], 'executable': r[2], 'command': r[3], 'parent_pid': r[4]}
|
||||
for r in foreign]})
|
||||
raise ValueError(f'POST_REPAIR_FOREIGN_OWNER: {[(r[0], r[1]) for r in foreign]}')
|
||||
|
||||
|
||||
class ConsentController:
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Explicit copy-based recovery after failed maintenance; never auto-replay."""
|
||||
from dataclasses import asdict
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
def offers_reimport(result):
|
||||
return (result.status == 'FAIL' and result.evidence_path is not None
|
||||
and any(attempt.get('status') in {
|
||||
'REPAIR_VALIDATION_FAILED', 'MISSING_HEALTHY_BACKUP', 'NATIVE_REPAIR_FAILED'}
|
||||
for attempt in result.recovery_attempts))
|
||||
|
||||
|
||||
def run_reimport_recovery(requests, *, previous_evidence, evidence_dir,
|
||||
adapter=None, stop=None, progress=None):
|
||||
from .management import ManagementResult, _write_json, source_project, run_management_batch
|
||||
from .library_lock import release_retained_library
|
||||
requests = tuple(requests)
|
||||
if not requests or stop is not None and stop.is_set():
|
||||
return []
|
||||
library = requests[0].library.resolve()
|
||||
evidence_dir = Path(evidence_dir).resolve()
|
||||
if evidence_dir.is_relative_to(library.parent) or library.parent.is_relative_to(evidence_dir):
|
||||
raise ValueError('恢复记录必须位于目标库之外。')
|
||||
root = evidence_dir/('reimport-' + uuid4().hex)
|
||||
root.mkdir(parents=True)
|
||||
report = root/'recovery.json'
|
||||
record = {'library': str(library), 'previous_evidence': previous_evidence,
|
||||
'requests': [asdict(r) for r in requests], 'original_repair_succeeded': False}
|
||||
stage = 'preflight'
|
||||
def save(stage, **extra):
|
||||
record.update(stage=stage, **extra)
|
||||
_write_json(report, record)
|
||||
def cancelled():
|
||||
if stop is not None and stop.is_set():
|
||||
save('cancelled', management_started=False)
|
||||
return True
|
||||
return False
|
||||
try:
|
||||
save(stage, management_started=False)
|
||||
for request in requests:
|
||||
if (request.operation != 'update' or request.library.resolve() != library
|
||||
or not previous_evidence.get(request.name)):
|
||||
raise ValueError('恢复目标与原失败项不一致。')
|
||||
source, _, _ = source_project(request.source, request.top_level_block)
|
||||
if (source.parent.is_relative_to(library.parent)
|
||||
or library.parent.is_relative_to(source.parent)):
|
||||
raise ValueError('请选择目标中心库之外的完整工程副本。')
|
||||
if cancelled(): return []
|
||||
stage = 'release_check'
|
||||
save(stage)
|
||||
if progress: progress({'stage': stage, 'detail': '正在检查原生会话释放,尚未替换条目'})
|
||||
import inspect
|
||||
block_name = requests[0].name if len(requests) == 1 else None
|
||||
if 'block_name' in inspect.signature(release_retained_library).parameters:
|
||||
proof = release_retained_library(library, root/'release', block_name=block_name)
|
||||
else:
|
||||
proof = release_retained_library(library, root/'release')
|
||||
if proof.get('status') != 'RELEASE_CONFIRMED':
|
||||
raise ValueError('原生会话释放未确认,未开始导入。')
|
||||
save('released', release=proof)
|
||||
if cancelled(): return []
|
||||
stage = 'management'
|
||||
save(stage, management_started=True)
|
||||
results = run_management_batch(requests, adapter=adapter, stop=stop, progress=progress)
|
||||
save('complete', results=[asdict(result) for result in results],
|
||||
version_review_required=True)
|
||||
return results
|
||||
except Exception as error:
|
||||
save('release_failed' if stage == 'release_check' else 'failed', detail=str(error))
|
||||
guidance = ('请正常关闭提示中的原生程序;若提示数据库地址记录,请先对对应工程执行 ICDB 维护,再重试副本恢复。'
|
||||
if stage == 'release_check' else '')
|
||||
return [ManagementResult(r.operation, r.library, r.name, r.partition, r.source,
|
||||
r.auto_verify, stage, 'BLOCKED' if stage != 'management' else 'RECOVERY_REQUIRED',
|
||||
False, f'副本恢复未完成:{error}。{guidance}原修复失败记录仍保留。', report) for r in requests]
|
||||
@@ -1,5 +1,5 @@
|
||||
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)
|
||||
Set app = GetObject(, "MGCPCB.Application")
|
||||
Set doc = app.ActiveDocument
|
||||
@@ -55,6 +55,13 @@ WScript.Echo "CLOSE_OK"
|
||||
Set pi = Nothing
|
||||
Set doc = 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
|
||||
app.Quit
|
||||
LogElapsed "quit", measuredStart
|
||||
|
||||
@@ -136,7 +136,7 @@ def _coordination_checkpoint(path):
|
||||
return checkpoint_record(path) is not None
|
||||
|
||||
|
||||
def scan_tree(root, *, scope=None, exclude=None):
|
||||
def scan_tree(root, *, scope=None, exclude=None, check=None):
|
||||
"""Refuse links/special files; optionally prune trees outside semantic scope.
|
||||
|
||||
Copies always call this without a scope, validating complete membership.
|
||||
@@ -148,8 +148,10 @@ def scan_tree(root, *, scope=None, exclude=None):
|
||||
entries = {}
|
||||
folders = [root]
|
||||
while folders:
|
||||
if check is not None: check()
|
||||
with os.scandir(folders.pop()) as scanned:
|
||||
for entry in scanned:
|
||||
if check is not None: check()
|
||||
path = Path(entry.path)
|
||||
if exclude is not None and path.is_relative_to(exclude):
|
||||
continue
|
||||
|
||||
@@ -5,12 +5,21 @@ import time
|
||||
from collections import Counter
|
||||
from dataclasses import replace
|
||||
|
||||
from PySide6.QtCore import QObject, QThreadPool, Signal, Qt
|
||||
from PySide6.QtCore import QObject, QThreadPool, Signal, Qt, QTimer
|
||||
from PySide6.QtGui import QColor, QIcon
|
||||
from PySide6.QtWidgets import (QWidget, QLineEdit, QPushButton, QFormLayout,
|
||||
QTextEdit, QFileDialog, QHBoxLayout, QLabel, QSpinBox, QMessageBox, QToolButton,
|
||||
QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox, QGroupBox, QVBoxLayout, QProgressBar, QComboBox)
|
||||
QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox, QVBoxLayout, QProgressBar, QComboBox,
|
||||
QTabBar, QStackedWidget, QSizePolicy)
|
||||
from PySide6.QtWidgets import QStyle
|
||||
|
||||
|
||||
def _path_key(value):
|
||||
"""Compare local and unavailable UNC paths without touching the network."""
|
||||
raw = str(value or '')
|
||||
if not raw:
|
||||
return ''
|
||||
return os.path.normcase(os.path.normpath(os.path.abspath(raw)))
|
||||
try:
|
||||
from dx_productivity.trial_task_center.ui.workers import ServiceWorker
|
||||
except ImportError:
|
||||
@@ -48,7 +57,7 @@ def application_icon_path():
|
||||
class MainWindow(QWidget):
|
||||
def __init__(self, reader=None, verifier=None, logging_context=None, data_root=None,
|
||||
authoritative_status=True, path_lease_factory=None, status_refresher=None,
|
||||
management_adapter=None):
|
||||
management_adapter=None, native_backup_launcher=None):
|
||||
super().__init__()
|
||||
self.setWindowTitle('CBB 刷新校验')
|
||||
icon_path = application_icon_path()
|
||||
@@ -65,8 +74,19 @@ class MainWindow(QWidget):
|
||||
self.management_adapter = management_adapter or NativeManagementAdapter()
|
||||
self.management_capabilities = self.management_adapter.capabilities()
|
||||
self._management_unsafe = False
|
||||
self._management_unsafe_library = None
|
||||
self._management_operation_library = None
|
||||
self._maintenance_recovery_view = False
|
||||
self._reload_after_maintenance = False
|
||||
self._reimport_offers = ()
|
||||
self._batch_requests = ()
|
||||
self._batch_records = {}
|
||||
self._reimport_summary_action = None
|
||||
self.native_backup_launcher = native_backup_launcher
|
||||
self._native_backup_session = None
|
||||
self.native_backup_timer = QTimer(self)
|
||||
self.native_backup_timer.setInterval(400)
|
||||
self.native_backup_timer.timeout.connect(self._poll_native_backup)
|
||||
if reader is not None:
|
||||
self.reader = reader
|
||||
elif authoritative_status and os.environ.get('CBB_STATUS_BRIDGE_MODE', 'authoritative').casefold() != 'legacy':
|
||||
@@ -116,9 +136,10 @@ class MainWindow(QWidget):
|
||||
self.advanced_panel.setVisible(False)
|
||||
self.advanced_toggle.toggled.connect(self.advanced_panel.setVisible)
|
||||
self.cbb_table = QTableWidget(0, 4)
|
||||
self.cbb_table.setHorizontalHeaderLabels(['CBB 名称', '分区', '状态', '环境检查'])
|
||||
self.cbb_table.setHorizontalHeaderLabels(['CBB 名称', '分区', '状态', '备注'])
|
||||
self.cbb_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
|
||||
for column in (1, 2, 3):
|
||||
self.cbb_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch)
|
||||
for column in (1, 2):
|
||||
self.cbb_table.horizontalHeader().setSectionResizeMode(column, QHeaderView.ResizeToContents)
|
||||
self.cbb_table.setSelectionBehavior(QTableWidget.SelectRows)
|
||||
self.cbb_table.setMinimumHeight(150)
|
||||
@@ -141,10 +162,13 @@ class MainWindow(QWidget):
|
||||
self.browse_button = QPushButton('选择'); self.browse_button.clicked.connect(self.choose_library)
|
||||
self.selected_batch_button = QPushButton('批量校验已选'); self.selected_batch_button.clicked.connect(self.verify_selected)
|
||||
self.batch_button = QPushButton('校验可见非 READY'); self.batch_button.clicked.connect(self.verify_all)
|
||||
self.icdb_repair_button = QPushButton('非 READY ICDB 检查与修复'); self.icdb_repair_button.clicked.connect(self.repair_icdb_all)
|
||||
self.icdb_repair_button.setToolTip('忽略 READY 项(包括已勾选项);先检查启动,仅本轮日志确认 ICDB 失联时才修复。')
|
||||
self.icdb_repair_button = QPushButton('ICDB 批量检查'); self.icdb_repair_button.clicked.connect(self.repair_icdb_all)
|
||||
self.icdb_repair_button.setToolTip('检查可见的非 READY 工程;有勾选时仅检查勾选项。')
|
||||
self.backup_restore_button = QPushButton('从备份恢复 CBB…')
|
||||
self.backup_restore_button.clicked.connect(self.restore_backup)
|
||||
self.reimport_button = QPushButton('选择工程副本恢复失败项…')
|
||||
self.reimport_button.clicked.connect(self.reimport_failed)
|
||||
self.reimport_button.hide()
|
||||
self.stop_button = QPushButton('当前项完成后停止'); self.stop_button.clicked.connect(self.request_stop)
|
||||
self.logs_button = QPushButton('打开日志目录'); self.logs_button.clicked.connect(self.open_logs)
|
||||
self.recovery_button = QPushButton('打开异常证据'); self.recovery_button.setEnabled(False)
|
||||
@@ -163,41 +187,58 @@ class MainWindow(QWidget):
|
||||
self.status_label = QLabel('请选择并读取中心库。校验期间可以使用其他前台应用。')
|
||||
self.status_label.setWordWrap(True)
|
||||
self.status_label.setMinimumHeight(self.status_label.fontMetrics().lineSpacing()*2)
|
||||
self.status_label.setMaximumHeight(self.status_label.fontMetrics().lineSpacing()*3 + 4)
|
||||
self.status_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
|
||||
self.output = QTextEdit(); self.output.setReadOnly(True)
|
||||
# Integration emits repeated status snapshots. Keep the visible
|
||||
# diagnostic buffer bounded so a 3,000-CBB run cannot grow the GUI
|
||||
# document without limit.
|
||||
self.output.document().setMaximumBlockCount(2000)
|
||||
layout = QFormLayout(self)
|
||||
row = QHBoxLayout(); row.addWidget(self.lmc_edit); row.addWidget(self.browse_button); row.addWidget(self.load_button)
|
||||
layout.addRow('中心库 .lmc', row)
|
||||
self.output.setMaximumHeight(180)
|
||||
layout = QVBoxLayout(self)
|
||||
row = QHBoxLayout(); row.addWidget(QLabel('中心库')); row.addWidget(self.lmc_edit)
|
||||
row.addWidget(self.browse_button); row.addWidget(self.load_button)
|
||||
layout.addLayout(row)
|
||||
self.library_notice = QLabel()
|
||||
self.library_notice.setWordWrap(True)
|
||||
self.library_notice.setTextFormat(Qt.PlainText)
|
||||
self.library_notice.setStyleSheet('QLabel { color: #8a4b08; background: #fff3d6; padding: 6px; }')
|
||||
self.library_notice.hide()
|
||||
layout.addRow(self.library_notice)
|
||||
layout.addRow(self.advanced_toggle); layout.addRow(self.advanced_panel)
|
||||
layout.addWidget(self.library_notice)
|
||||
self.section_tabs = QTabBar()
|
||||
self.section_tabs.setExpanding(True)
|
||||
for name in ('检验', 'ICDB 维护', '中心库管理'):
|
||||
self.section_tabs.addTab(name)
|
||||
layout.addWidget(self.section_tabs)
|
||||
filters = QHBoxLayout()
|
||||
for widget in (self.search_edit, self.status_filter, self.select_visible_button, self.clear_selection_button):
|
||||
filters.addWidget(widget)
|
||||
layout.addRow('搜索 / 筛选', filters)
|
||||
layout.addRow(self.counts_label)
|
||||
layout.addRow('CBB 清单(勾选后可批量)', self.cbb_table); layout.addRow('超时', self.timeout_spin)
|
||||
layout.addRow(QLabel('逐个刷新:命令行启动 ReusableCircuit PCB → Project Integration → 保存并关闭,全程不切换桌面、不移动鼠标。'
|
||||
'填写 LibSpec 与 DMS 登录配置后,会先执行一次 ReuseBlockImporter 内容检查。'))
|
||||
layout.addLayout(filters)
|
||||
layout.addWidget(self.counts_label)
|
||||
layout.addWidget(self.cbb_table, 1)
|
||||
self.section_stack = QStackedWidget()
|
||||
self.section_stack.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum)
|
||||
self.section_tabs.currentChanged.connect(self.section_stack.setCurrentIndex)
|
||||
verify_page = QWidget()
|
||||
verify_layout = QVBoxLayout(verify_page); verify_layout.setContentsMargins(0, 0, 0, 0)
|
||||
controls = QHBoxLayout()
|
||||
for widget in (self.selected_batch_button, self.batch_button, self.stop_button, self.logs_button): controls.addWidget(widget)
|
||||
layout.addRow(controls)
|
||||
maintenance = QGroupBox('数据库维护')
|
||||
for widget in (self.selected_batch_button, self.batch_button): controls.addWidget(widget)
|
||||
controls.addStretch(); controls.addWidget(QLabel('超时')); controls.addWidget(self.timeout_spin)
|
||||
controls.addWidget(self.advanced_toggle)
|
||||
verify_layout.addLayout(controls); verify_layout.addWidget(self.advanced_panel)
|
||||
self.section_stack.addWidget(verify_page)
|
||||
maintenance = QWidget()
|
||||
maintenance_layout = QVBoxLayout(maintenance)
|
||||
maintenance_layout.setContentsMargins(0, 0, 0, 0)
|
||||
self.native_backup_button = QPushButton('版本历史与备份…')
|
||||
self.native_backup_button.setToolTip('勾选一个非 READY CBB,打开原生备份列表并选择回退版本。')
|
||||
self.native_backup_button.clicked.connect(self.open_native_backup)
|
||||
maintenance_layout.addWidget(self.native_backup_button)
|
||||
maintenance_row = QHBoxLayout()
|
||||
maintenance_row.addWidget(self.icdb_repair_button)
|
||||
description = QLabel('处理可见非 READY 项;有勾选时仅处理勾选中的可用项。未确认不等于损坏。\n操作前请手动备份;应用不自动备份。无法确认会话安全时停止。')
|
||||
description.setWordWrap(True)
|
||||
maintenance_row.addWidget(description, 1)
|
||||
maintenance_row.addWidget(self.backup_restore_button)
|
||||
maintenance_row.addWidget(self.reimport_button)
|
||||
maintenance_layout.addLayout(maintenance_row)
|
||||
maintenance_layout.addWidget(self.backup_restore_button)
|
||||
self.icdb_progress = QProgressBar()
|
||||
self.icdb_progress.setVisible(False)
|
||||
self.icdb_phase = QLabel('')
|
||||
@@ -205,12 +246,13 @@ class MainWindow(QWidget):
|
||||
self.icdb_phase.setVisible(False)
|
||||
maintenance_layout.addWidget(self.icdb_progress)
|
||||
maintenance_layout.addWidget(self.icdb_phase)
|
||||
layout.addRow(maintenance)
|
||||
management = QGroupBox('CBB 管理(可处理 READY 项)')
|
||||
self.section_stack.addWidget(maintenance)
|
||||
management = QWidget()
|
||||
management_layout = QVBoxLayout(management)
|
||||
management_layout.setContentsMargins(0, 0, 0, 0)
|
||||
management_buttons = QHBoxLayout()
|
||||
self.add_button = QPushButton('新增 CBB…')
|
||||
self.update_button = QPushButton('用工程替换已选 CBB…(原生重新导入)')
|
||||
self.update_button = QPushButton('用工程替换已选 CBB…')
|
||||
self.remove_button = QPushButton('移除已选…')
|
||||
for operation, widget in (('add', self.add_button), ('update', self.update_button), ('remove', self.remove_button)):
|
||||
widget.clicked.connect(lambda _=False, op=operation: self.manage_cbb(op))
|
||||
@@ -222,12 +264,20 @@ class MainWindow(QWidget):
|
||||
management_layout.insertWidget(0, self.management_capability_label)
|
||||
self.unfinished_label = QLabel(); self.unfinished_label.setWordWrap(True)
|
||||
management_layout.addWidget(self.unfinished_label)
|
||||
self.release_library_button = QPushButton('检查会话释放并解除协调阻止…')
|
||||
self.release_library_button = QPushButton('检查占用…')
|
||||
self.release_library_button.clicked.connect(self.check_library_release)
|
||||
management_layout.addWidget(self.release_library_button)
|
||||
layout.addRow(management)
|
||||
layout.addRow(self.status_label); layout.addRow(self.output)
|
||||
layout.addRow(self.recovery_button)
|
||||
management_buttons.addWidget(self.release_library_button)
|
||||
self.section_stack.addWidget(management)
|
||||
layout.addWidget(self.section_stack)
|
||||
layout.addWidget(self.status_label)
|
||||
self.runtime_log_toggle = QToolButton(); self.runtime_log_toggle.setText('查看运行日志')
|
||||
self.runtime_log_toggle.setCheckable(True)
|
||||
self.runtime_log_toggle.toggled.connect(self.output.setVisible)
|
||||
self.output.hide()
|
||||
footer = QHBoxLayout()
|
||||
for widget in (self.stop_button, self.runtime_log_toggle, self.logs_button, self.recovery_button):
|
||||
footer.addWidget(widget)
|
||||
layout.addLayout(footer); layout.addWidget(self.output)
|
||||
self.lmc_edit.textChanged.connect(self._invalidate)
|
||||
for field in (self.libspec_edit, self.dms_edit, self.mentor_bin_edit):
|
||||
field.textChanged.connect(lambda _text: self._update())
|
||||
@@ -236,6 +286,7 @@ class MainWindow(QWidget):
|
||||
self._update()
|
||||
|
||||
def _invalidate(self):
|
||||
self._reimport_offers = ()
|
||||
if self.loaded_path is not None and self.lmc_edit.text() != self.loaded_path:
|
||||
self._release_library_lease()
|
||||
self.loaded_path = None; self.mentor_lmc_path = None; self.cbb_table.setRowCount(0); self._row_by_name = {}
|
||||
@@ -246,6 +297,8 @@ class MainWindow(QWidget):
|
||||
|
||||
def _release_library_lease(self):
|
||||
lease, self.library_lease = self.library_lease, None
|
||||
if self._native_backup_session is not None and self._native_backup_session.path_lease is lease:
|
||||
return # The visible native session still needs this mapping.
|
||||
if lease is None:
|
||||
return
|
||||
try:
|
||||
@@ -257,11 +310,17 @@ class MainWindow(QWidget):
|
||||
def _update(self):
|
||||
# The refresh flow needs only the library and a CBB; LibSpec/DMS config
|
||||
# are optional and only enable the extra contents check.
|
||||
ready = not self.busy and not self._management_unsafe and self.loaded_path == self.lmc_edit.text() and self.cbb_table.rowCount() > 0
|
||||
self.batch_button.setEnabled(ready and not self._maintenance_recovery_view and bool(self._eligible_names()))
|
||||
self.selected_batch_button.setEnabled(ready and not self._maintenance_recovery_view and bool(self._eligible_names(checked_only=True)))
|
||||
ready = not self.busy and self.loaded_path == self.lmc_edit.text() and self.cbb_table.rowCount() > 0
|
||||
selected = self.selected_records()
|
||||
native_target = self._native_backup_target()
|
||||
self.native_backup_button.setEnabled(ready and self._native_backup_session is None
|
||||
and native_target is not None)
|
||||
ready = ready and not self._native_backup_same_library()
|
||||
self.batch_button.setEnabled(ready and bool(self._eligible_names()))
|
||||
self.selected_batch_button.setEnabled(ready and bool(self._eligible_names(checked_only=True)))
|
||||
self.icdb_repair_button.setEnabled(ready and bool(self._maintenance_names()))
|
||||
self.backup_restore_button.setEnabled(ready and not self._maintenance_recovery_view and bool(self._maintenance_names()))
|
||||
self.backup_restore_button.setEnabled(ready and bool(
|
||||
self._eligible_names(checked_only=bool(self.selected_records()))))
|
||||
self.release_library_button.setEnabled(not self.busy and bool(self.lmc_edit.text().strip()))
|
||||
reasons = []
|
||||
for operation, widget in (('add', self.add_button), ('update', self.update_button), ('remove', self.remove_button)):
|
||||
@@ -271,11 +330,10 @@ class MainWindow(QWidget):
|
||||
if reason:
|
||||
reasons.append(reason)
|
||||
self.management_capability_label.setText('\n'.join(dict.fromkeys(reasons)))
|
||||
notice = ('该库有未确认的会话记录,新增、替换、移除和普通校验已暂停。'
|
||||
'请先执行 ICDB 维护;仍有数据库地址记录时,单独点击释放检查不会解除阻止。'
|
||||
if self._maintenance_recovery_view else
|
||||
'上次管理操作尚未确认安全释放,已暂停库操作。请先查看异常证据并检查会话释放。'
|
||||
if self._management_unsafe else '')
|
||||
current_library = _path_key(self.mentor_lmc_path or self.lmc_edit.text()) if self.lmc_edit.text().strip() else None
|
||||
notice = ('上次管理操作尚未确认安全释放,请检查该操作的结果。'
|
||||
if (self._management_unsafe and self._management_unsafe_library is not None
|
||||
and current_library == _path_key(self._management_unsafe_library)) else '')
|
||||
self.library_notice.setText(notice)
|
||||
self.library_notice.setVisible(bool(notice))
|
||||
for widget in (self.lmc_edit, self.browse_button, self.load_button, self.cbb_table,
|
||||
@@ -286,6 +344,13 @@ class MainWindow(QWidget):
|
||||
self.counts_label.setText(f'可见 {counts["visible"]} / {len(self._records_by_name)} · '
|
||||
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.setText('取消当前任务并停止队列')
|
||||
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.setEnabled(available)
|
||||
self.reimport_button.setToolTip(self.management_capabilities['update'].reason)
|
||||
if self._reimport_summary_action is not None:
|
||||
self._reimport_summary_action.setEnabled(available)
|
||||
|
||||
def _show_unfinished_management(self):
|
||||
from cbb_refresh_verify.management import unfinished_operations
|
||||
@@ -310,17 +375,36 @@ class MainWindow(QWidget):
|
||||
if library.is_dir():
|
||||
library = select_library_file(library)
|
||||
def completed(result):
|
||||
self._management_unsafe = False
|
||||
current_library = _path_key(self.mentor_lmc_path or self.lmc_edit.text().strip())
|
||||
if current_library == _path_key(library):
|
||||
self._management_unsafe = False
|
||||
self._management_unsafe_library = None
|
||||
session = self._native_backup_session
|
||||
if session is not None and session.library == library and session.process.poll() is not None:
|
||||
self._release_native_backup_session(session)
|
||||
message = f'原生会话释放检查通过。请审查未完成任务后重新读取中心库。\n{result["evidence_path"]}'
|
||||
self.status_label.setText(message); self.output.append(message)
|
||||
self._start(lambda: release_retained_library(library, self.data_root/'release-checks'), completed)
|
||||
block_name = None
|
||||
if len(self._batch_requests) == 1:
|
||||
block_name = self._batch_requests[0].block_name
|
||||
elif len(self.selected_records()) == 1:
|
||||
block_name = self.selected_records()[0].name
|
||||
import inspect
|
||||
if 'block_name' in inspect.signature(release_retained_library).parameters:
|
||||
action = lambda: release_retained_library(library, self.data_root/'release-checks',
|
||||
block_name=block_name)
|
||||
else:
|
||||
action = lambda: release_retained_library(library, self.data_root/'release-checks')
|
||||
self._start(action, completed)
|
||||
|
||||
def _management_block_reason(self, operation):
|
||||
if self.busy:
|
||||
return '当前任务尚未结束,请等待后再执行库管理操作。'
|
||||
if self._maintenance_recovery_view:
|
||||
return '库的会话释放尚未确认,管理操作已禁用;请先执行 ICDB 维护并查看逐项结果。'
|
||||
if self._management_unsafe:
|
||||
if self._native_backup_same_library():
|
||||
return '该库的版本与备份窗口仍在使用,关闭后可执行写入操作。'
|
||||
current_library = _path_key(self.mentor_lmc_path or self.lmc_edit.text()) if self.lmc_edit.text().strip() else None
|
||||
if (self._management_unsafe and self._management_unsafe_library is not None
|
||||
and current_library == _path_key(self._management_unsafe_library)):
|
||||
return '上次管理操作的会话尚未安全释放,请先查看异常证据并执行释放检查。'
|
||||
capability = self.management_capabilities[operation]
|
||||
if not capability.supported:
|
||||
@@ -337,7 +421,6 @@ class MainWindow(QWidget):
|
||||
self.status_label.setText(reason)
|
||||
return
|
||||
from cbb_refresh_verify.management import ManagementRequest
|
||||
from .management_dialog import ManagementDialog
|
||||
records = self.selected_records()
|
||||
if operation != 'add' and not records:
|
||||
return
|
||||
@@ -350,21 +433,60 @@ class MainWindow(QWidget):
|
||||
[request(record.name, 'Logical-Physical' if record.logical_type == 'LP'
|
||||
and record.partition_name in ('Reusable Blocks', 'LP') else record.partition_name)
|
||||
for record in records])
|
||||
self.management_dialog = ManagementDialog(requests, self, adapter=self.management_adapter)
|
||||
self._open_management_dialog(requests)
|
||||
|
||||
def _open_management_dialog(self, requests, *, recovery_from=None):
|
||||
from .management_dialog import ManagementDialog
|
||||
self._global_icdb_run = False
|
||||
self.stop.clear()
|
||||
self._management_is_recovery = bool(recovery_from)
|
||||
self._management_operation_library = _path_key(requests[0].library) if requests else None
|
||||
self.management_dialog = ManagementDialog(requests, self, adapter=self.management_adapter,
|
||||
recovery_from=recovery_from)
|
||||
self._management_results = []
|
||||
self.management_dialog.completed.connect(self._management_completed)
|
||||
self.management_dialog.finished.connect(self._management_closed)
|
||||
self.busy = True; self._update()
|
||||
self.management_dialog.show()
|
||||
|
||||
def reimport_failed(self):
|
||||
if self.busy or not self._reimport_offers or not self.management_capabilities['update'].supported:
|
||||
return
|
||||
from cbb_refresh_verify.management import ManagementRequest
|
||||
requests, previous = [], {}
|
||||
library = Path(self.mentor_lmc_path or self.loaded_path)
|
||||
for req, record, result in self._reimport_offers:
|
||||
if req.lmc_file != library:
|
||||
return
|
||||
partition = ('Logical-Physical' if record.logical_type == 'LP'
|
||||
and record.partition_name in ('Reusable Blocks', 'LP') else record.partition_name)
|
||||
requests.append(ManagementRequest('update', library, record.name, partition,
|
||||
evidence_dir=self.data_root/'management', timeout_seconds=self.timeout_spin.value(),
|
||||
mapped_drive=getattr(self.library_lease, 'drive', ''),
|
||||
mapped_remote_root=getattr(self.library_lease, 'remote_root', '')))
|
||||
previous[record.name] = str(result.evidence_path)
|
||||
self._reload_after_maintenance = False
|
||||
if getattr(self, 'summary', None): self.summary.close()
|
||||
self._open_management_dialog(requests, recovery_from=previous)
|
||||
|
||||
def _management_completed(self, results):
|
||||
self._management_results = results
|
||||
if (getattr(self, '_management_is_recovery', False) and results
|
||||
and all(result.safe_to_continue for result in results)):
|
||||
self._management_unsafe = False
|
||||
self._management_unsafe_library = None
|
||||
self._maintenance_recovery_view = False
|
||||
restored = {result.name for result in results if result.status == 'UPLOADED_VERIFIED'}
|
||||
self._reimport_offers = tuple(offer for offer in self._reimport_offers if offer[1].name not in restored)
|
||||
from .management_dialog import RESULT_LABELS
|
||||
for result in results:
|
||||
self.output.append(f'{result.name}:{RESULT_LABELS.get(result.status, result.status)} '
|
||||
f'{result.detail}\n{result.evidence_path or ""}')
|
||||
if getattr(self, '_management_is_recovery', False) and result.status == 'UPLOADED_VERIFIED':
|
||||
self.output.append('副本恢复校验通过,版本待核对。')
|
||||
if any(not result.safe_to_continue for result in results):
|
||||
self._management_unsafe = True
|
||||
self._management_unsafe_library = self._management_operation_library
|
||||
if self.library_lease:
|
||||
self.library_lease.retain_for_recovery()
|
||||
self.status_label.setText('管理操作需要人工确认恢复/释放;已停止写入,未再次读取原生目录。')
|
||||
@@ -399,7 +521,20 @@ class MainWindow(QWidget):
|
||||
return [r.name for r in records if r.status != 'READY' and r.name not in self.skipped_names]
|
||||
|
||||
def _maintenance_names(self):
|
||||
return self._eligible_names(checked_only=bool(self.selected_records()))
|
||||
records = self.selected_records() or self.visible_records()
|
||||
return [record.name for record in records
|
||||
if record.status != 'READY' and record.name not in self.skipped_names]
|
||||
|
||||
def _native_backup_target(self):
|
||||
selected = self.selected_records()
|
||||
if selected:
|
||||
return selected[0] if len(selected) == 1 and selected[0].status != 'READY' else None
|
||||
row = self.cbb_table.currentRow()
|
||||
if row < 0 or self.cbb_table.isRowHidden(row):
|
||||
return None
|
||||
item = self.cbb_table.item(row, 0)
|
||||
record = self._records_by_name.get(item.text()) if item is not None else None
|
||||
return record if record is not None and record.status != 'READY' else None
|
||||
|
||||
def _check_visible(self, state):
|
||||
self.cbb_table.blockSignals(True)
|
||||
@@ -450,6 +585,11 @@ class MainWindow(QWidget):
|
||||
if self.busy or not self.lmc_edit.text(): return
|
||||
self._maintenance_recovery_view = False
|
||||
self._global_icdb_run = False
|
||||
if self._management_unsafe_library is not None:
|
||||
requested_library = _path_key(self.lmc_edit.text())
|
||||
if requested_library != _path_key(self._management_unsafe_library):
|
||||
self._management_unsafe = False
|
||||
self._management_unsafe_library = None
|
||||
self.icdb_progress.hide(); self.icdb_phase.hide()
|
||||
self._release_library_lease()
|
||||
self.loaded_path = None; self.cbb_table.setRowCount(0); self._row_by_name = {}; self.ready_names = set()
|
||||
@@ -472,21 +612,8 @@ class MainWindow(QWidget):
|
||||
'library_path_lease display=%s mentor=%s drive=%s remote=%s created=%s',
|
||||
lease.display_path, mentor_path, lease.drive or '-',
|
||||
lease.remote_root or '-', lease.created)
|
||||
from cbb_refresh_verify.library_lock import blocker_path, checkpoint_record
|
||||
marker = blocker_path(mentor_path)
|
||||
recovery_view = False
|
||||
if marker.exists() or marker.with_suffix('.pending').exists():
|
||||
from cbb_refresh_verify.models import LibraryReadResult
|
||||
checkpoint = checkpoint_record(marker)
|
||||
if (checkpoint is not None and not marker.with_suffix('.pending').exists()
|
||||
and Path(checkpoint['library']).resolve() == Path(mentor_path).resolve()):
|
||||
result = read_library_fast(mentor_path,
|
||||
status_reader=lambda _, names: {name: 'UNKNOWN' for name in names})
|
||||
recovery_view = True
|
||||
else:
|
||||
result = LibraryReadResult((), '此库检查点损坏或身份不符,保留原记录;请先审查并执行释放检查。')
|
||||
else:
|
||||
result = self.reader(mentor_path)
|
||||
result = self.reader(mentor_path)
|
||||
if self.logging_context:
|
||||
statuses = Counter(record.status for record in result.records)
|
||||
unknown = [record.name for record in result.records if record.status in {'UNKNOWN', 'UNAVAILABLE'}]
|
||||
@@ -599,7 +726,7 @@ class MainWindow(QWidget):
|
||||
|
||||
def _confirm_verify(self, names):
|
||||
from .backup_notice import MANUAL_BACKUP_NOTICE
|
||||
if self.busy or not self.loaded_path or self._maintenance_recovery_view or not names:
|
||||
if self.busy or not self.loaded_path or self._native_backup_same_library() or not names:
|
||||
return
|
||||
if QMessageBox.question(self, '确认批量校验',
|
||||
f'{MANUAL_BACKUP_NOTICE}\n\n目标库:{self.loaded_path}\n'
|
||||
@@ -608,25 +735,95 @@ class MainWindow(QWidget):
|
||||
self._run(names)
|
||||
|
||||
def repair_icdb_all(self):
|
||||
from .backup_notice import MANUAL_BACKUP_NOTICE
|
||||
if self.busy or not self.loaded_path: return
|
||||
names = self._maintenance_names()
|
||||
if not names: return
|
||||
answer = QMessageBox.question(self, '非 READY ICDB 检查与修复',
|
||||
f'{MANUAL_BACKUP_NOTICE}\nMentor 原生修复可能生成自身备份。\n\n当前中心库:{self.loaded_path}\n\n'
|
||||
answer = QMessageBox.question(self, 'ICDB 批量检查',
|
||||
f'当前中心库:{self.loaded_path}\n\n'
|
||||
f'将检查 {len(names)} 个可见非 READY CBB'
|
||||
f'{"(仅勾选项)" if self.selected_records() else ""}。未确认状态不等于损坏。\n'
|
||||
'先取得库锁并核对工程与占用,检查启动但不执行集成或保存。仅本轮原生日志确认 ICDB 失联才修复,再重新打开校验。'
|
||||
'占用、历史版本提示或故障原因未确认时停止,不猜测故障或删除地址文件。READY 项始终忽略。\n'
|
||||
'仅本地固定磁盘:严格确认修复并重新独占检查后,可一次确认本次异常退出的读写访问提示。'
|
||||
'网络盘、UNC 或链接路径不自动确认该提示。\n'
|
||||
'共享符号库不支持自动修复。若原生工具恢复了旧备份,需人工核对版本;'
|
||||
'会话安全无法确认时停止队列。\n\n是否开始检查与修复?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
|
||||
f'{"(仅勾选项)" if self.selected_records() else ""}。\n'
|
||||
'仅检查 ICDB 状态,不执行修复或回退。\n\n是否开始?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
|
||||
if answer == QMessageBox.Yes:
|
||||
self._run(names, maintenance=True)
|
||||
|
||||
def _native_backup_same_library(self):
|
||||
session = self._native_backup_session
|
||||
return session is not None and Path(self.mentor_lmc_path or self.lmc_edit.text()) == session.library
|
||||
|
||||
def open_native_backup(self):
|
||||
if self.busy or not self.loaded_path or self._native_backup_session is not None:
|
||||
return
|
||||
target = self._native_backup_target()
|
||||
if target is None:
|
||||
self.status_label.setText('请勾选一个非 READY CBB。')
|
||||
return
|
||||
from cbb_refresh_verify.native_backup import launch_native_backup
|
||||
request = self._request(target.name)
|
||||
launcher = self.native_backup_launcher or launch_native_backup
|
||||
self._global_icdb_run = False
|
||||
self._reimport_offers = ()
|
||||
self.status_label.setText(f'正在打开 {request.block_name} 的版本与备份…')
|
||||
def opened(session):
|
||||
session.path_lease = self.library_lease
|
||||
self._native_backup_session = session
|
||||
self.native_backup_timer.start()
|
||||
self.status_label.setText(f'正在打开 {session.block} 的原生备份窗口,请在其中选择版本。')
|
||||
self.output.append(f'{session.block} · 原生版本与备份\n{session.job}')
|
||||
self.busy = True; self._update()
|
||||
self.worker = ServiceWorker(lambda: launcher(request))
|
||||
self.worker.signals.succeeded.connect(opened)
|
||||
self.worker.signals.failed.connect(lambda error: self.status_label.setText(f'无法打开版本与备份:{error}'))
|
||||
self.worker.signals.finished.connect(self._finished)
|
||||
self.pool.start(self.worker)
|
||||
|
||||
def _release_native_backup_session(self, session):
|
||||
self._native_backup_session = None
|
||||
if session.path_lease is not None and session.path_lease is not self.library_lease:
|
||||
transfer = getattr(session.path_lease, 'transfer_ownership', None)
|
||||
if transfer is not None:
|
||||
transfer(self.library_lease)
|
||||
session.path_lease.close()
|
||||
|
||||
def _poll_native_backup(self):
|
||||
session = self._native_backup_session
|
||||
if session is None or self.busy or session.process.poll() is None:
|
||||
return
|
||||
self.native_backup_timer.stop()
|
||||
same_library = Path(self.mentor_lmc_path or self.lmc_edit.text()) == session.library
|
||||
def read_result():
|
||||
import json
|
||||
result = json.loads(session.job.with_name('result.json').read_text('utf-8'))
|
||||
if Path(result['library']) != session.library or result['block'] != session.block:
|
||||
raise ValueError('原生会话返回的工程身份不一致。')
|
||||
refresh = (self._read_affected_records((session.block,))
|
||||
if result.get('safe_to_continue') is True and same_library else None)
|
||||
return result, refresh
|
||||
def completed(payload):
|
||||
result, refresh = payload
|
||||
if result.get('safe_to_continue') is not True:
|
||||
unconfirmed(result.get('detail', '未取得会话释放结果。'))
|
||||
return
|
||||
self._release_native_backup_session(session)
|
||||
if refresh is not None:
|
||||
self._apply_refreshed_records(refresh)
|
||||
message = ('原生备份窗口已关闭。需要时可单独运行校验。' if result.get('status') == 'CLOSED'
|
||||
else '原生备份操作未结束:' + result.get('detail', '请检查原生窗口。'))
|
||||
self.status_label.setText(message)
|
||||
self.output.append(f'{session.block} · {message}\n{session.job.with_name("result.json")}')
|
||||
if same_library and session.block in self._row_by_name:
|
||||
self.cbb_table.item(self._row_by_name[session.block], 3).setText(message)
|
||||
def unconfirmed(error):
|
||||
self.status_label.setText('原生窗口退出尚未确认,请关闭窗口后检查释放。')
|
||||
self.output.append(f'{session.block} · 退出尚未确认:{error}\n{session.job}')
|
||||
self.busy = True; self._update()
|
||||
self.worker = ServiceWorker(read_result)
|
||||
self.worker.signals.succeeded.connect(completed)
|
||||
self.worker.signals.failed.connect(unconfirmed)
|
||||
self.worker.signals.finished.connect(self._finished)
|
||||
self.pool.start(self.worker)
|
||||
|
||||
def restore_backup(self):
|
||||
if self.busy or not self.loaded_path or self._maintenance_recovery_view:
|
||||
if self.busy or not self.loaded_path or self._native_backup_same_library():
|
||||
return
|
||||
from .backup_recovery_dialog import BackupRecoveryDialog
|
||||
names = self._eligible_names(checked_only=bool(self.selected_records()))
|
||||
@@ -645,7 +842,7 @@ class MainWindow(QWidget):
|
||||
def _backup_request(self, name):
|
||||
# A still-open dialog must recheck a target after an earlier recovery
|
||||
# or an authoritative refresh changed its eligibility.
|
||||
if self.busy or self._maintenance_recovery_view or name not in self._eligible_names(checked_only=bool(self.selected_records())):
|
||||
if self.busy or self._native_backup_same_library() or name not in self._eligible_names(checked_only=bool(self.selected_records())):
|
||||
raise ValueError('目标需为当前可见、可用的非 READY CBB;请重新选择。')
|
||||
return self._request(name)
|
||||
|
||||
@@ -685,14 +882,19 @@ class MainWindow(QWidget):
|
||||
|
||||
def _run(self, names, *, maintenance=False):
|
||||
if self.busy or not self.loaded_path: return
|
||||
if self._maintenance_recovery_view and not maintenance: return
|
||||
if self._native_backup_same_library():
|
||||
self.status_label.setText('请先关闭该库的版本与备份窗口。')
|
||||
return
|
||||
eligible = set(self._maintenance_names() if maintenance else self._eligible_names())
|
||||
names = [name for name in names if name in eligible]
|
||||
if not names:
|
||||
self.status_label.setText('当前可见选择中没有可校验的非 READY CBB。')
|
||||
self._update()
|
||||
return
|
||||
requests = [replace(self._request(name), maintenance=maintenance) for name in names]
|
||||
requests = [replace(self._request(name), maintenance=maintenance, auto_repair=False) for name in names]
|
||||
self._batch_requests = tuple(requests)
|
||||
self._batch_records = {name: self._records_by_name[name] for name in names}
|
||||
self._reimport_offers = ()
|
||||
self._global_icdb_run = maintenance
|
||||
self._icdb_completed = 0
|
||||
self.icdb_progress.setVisible(maintenance)
|
||||
@@ -704,27 +906,29 @@ class MainWindow(QWidget):
|
||||
self.icdb_phase.setText('准备检查…')
|
||||
self.stop.clear(); self.recovery_path = None; self.recovery_button.setEnabled(False)
|
||||
self.output.clear(); self.status_label.setText(
|
||||
f'正在非 READY ICDB 检查与修复:共 {len(names)} 个 CBB' if maintenance
|
||||
f'正在 ICDB 批量检查:共 {len(names)} 个 CBB' if maintenance
|
||||
else f'正在校验:共 {len(names)} 个 CBB')
|
||||
def action():
|
||||
from cbb_refresh_verify.verify_runner import read_library_flag_if_available, run_verify
|
||||
verify = self.verifier or (lambda req: run_verify(
|
||||
req, progress=lambda e: self.signals.event.emit(e),
|
||||
flag_reader=read_library_flag_if_available,
|
||||
version_prompt=self.signals.version_choice.emit))
|
||||
version_prompt=self.signals.version_choice.emit, stop=self.stop))
|
||||
def verifier(req):
|
||||
if maintenance:
|
||||
self.signals.event.emit({'block': req.block_name, 'stage': 'icdb_check_start'})
|
||||
return verify(req)
|
||||
results = run_batch(requests, verifier=verifier, stop=self.stop,
|
||||
progress=lambda name, result: self.signals.event.emit({'block': name, 'stage': result.status, 'detail': result.stderr, 'evidence': str(result.evidence_path or '')}))
|
||||
progress=lambda name, result: self.signals.event.emit({'block': name, 'stage': result.status,
|
||||
'error_category': result.error_category, 'evidence': str(result.evidence_path or ''),
|
||||
'detail': result.stderr or result.stdout}))
|
||||
report = write_batch_report(requests, results, self.data_root/'reports')
|
||||
if maintenance:
|
||||
from cbb_refresh_verify.icdb_maintenance import write_maintenance_report
|
||||
write_maintenance_report(requests, results, report, ())
|
||||
affected = [req.block_name for req, result in zip(requests, results) if result.status != 'SKIPPED']
|
||||
safe = all(result.safe_to_continue for result in results)
|
||||
refresh = self._read_affected_records(affected) if safe and not self._maintenance_recovery_view else None
|
||||
refresh = self._read_affected_records(affected) if safe else None
|
||||
return results, report, affected, refresh
|
||||
self._start(action, self._batch_done)
|
||||
|
||||
@@ -797,7 +1001,7 @@ class MainWindow(QWidget):
|
||||
(UNKNOWN on read failure). It runs before the worker's finished signal.
|
||||
Search, filter, original logical_type and action-result cells are retained.
|
||||
"""
|
||||
if self.busy or not self.loaded_path or self._maintenance_recovery_view:
|
||||
if self.busy or not self.loaded_path or self._native_backup_same_library():
|
||||
return False
|
||||
targets = tuple(dict.fromkeys(name for name in names if name in self._records_by_name))
|
||||
if not targets:
|
||||
@@ -818,20 +1022,27 @@ class MainWindow(QWidget):
|
||||
self.output.append(line)
|
||||
block = event.get('block'); stage = event.get('stage')
|
||||
if self._global_icdb_run:
|
||||
if stage in {'PASS', 'FAIL', 'BLOCKED', 'TIMEOUT', 'SKIPPED', 'QUEUE_STOP'}:
|
||||
if stage in {'PASS', 'FAIL', 'BLOCKED', 'TIMEOUT', 'SKIPPED', 'QUEUE_STOP', 'CHECKED', 'CANCELLED', 'REPAIRED'}:
|
||||
self._icdb_completed += 1
|
||||
self.icdb_progress.setValue(self._icdb_completed)
|
||||
phases = {'icdb_check_start': '检查工程数据库与校验状态',
|
||||
'icdb_startup_check': '正在尝试打开工程',
|
||||
'icdb_ownership_check': '正在打开原生检查工具',
|
||||
'native_started': '等待原生工具加载工程',
|
||||
'native_occupancy_wait': '等待原生检查结果',
|
||||
'native_repair_complete': '原生修复完成,待单独校验',
|
||||
'native_repair_start': '核对占用并准备原生修复',
|
||||
'native_repair_requested': '正在原生修复',
|
||||
'native_repair_confirmed': '正在原生修复',
|
||||
'native_repair_finished': '原生修复已结束,正在核对结果'}
|
||||
if stage in phases:
|
||||
self.icdb_phase.setText(f'{block or ""} · {phases[stage]}')
|
||||
if block and stage in {'PASS', 'FAIL', 'BLOCKED', 'TIMEOUT', 'SKIPPED'}:
|
||||
if block and stage in {'PASS', 'FAIL', 'BLOCKED', 'TIMEOUT', 'SKIPPED', 'CHECKED', 'REPAIRED', 'CANCELLED'}:
|
||||
row = self._row_by_name.get(block)
|
||||
if row is not None:
|
||||
detail = str(event.get('detail') or event.get('error') or '').strip()
|
||||
if event.get('error_category') == 'ICDB_REPAIR_REQUIRED' and detail:
|
||||
detail = 'ICDB 问题:' + detail
|
||||
label = str(stage) if not detail else f'{stage}: {detail[:96]}'
|
||||
self.cbb_table.item(row, 3).setText(label)
|
||||
self.cbb_table.item(row, 3).setToolTip(detail)
|
||||
@@ -850,8 +1061,10 @@ class MainWindow(QWidget):
|
||||
|
||||
def _batch_done(self, outcome):
|
||||
results, report = outcome[:2]
|
||||
if self._maintenance_recovery_view and self._global_icdb_run and results:
|
||||
self._reload_after_maintenance = all(result.safe_to_continue for result in results)
|
||||
from cbb_refresh_verify.reimport_recovery import offers_reimport
|
||||
self._reimport_offers = tuple((req, self._batch_records[req.block_name], result)
|
||||
for req, result in zip(self._batch_requests, results)
|
||||
if req.maintenance and req.block_name in self._batch_records and offers_reimport(result))
|
||||
if len(outcome) > 2:
|
||||
_, _, affected, refresh = outcome
|
||||
if refresh is None:
|
||||
@@ -866,41 +1079,59 @@ class MainWindow(QWidget):
|
||||
self.recovery_button.setEnabled(self.recovery_path.is_dir())
|
||||
passed = sum(r.status == 'PASS' for r in results)
|
||||
skipped = sum(r.status == 'SKIPPED' for r in results)
|
||||
failed = len(results)-passed-skipped
|
||||
checked = sum(r.status == 'CHECKED' for r in results)
|
||||
repaired = sum(r.status == 'REPAIRED' for r in results)
|
||||
failed = len(results)-passed-skipped-checked-repaired
|
||||
text = (f'已结束:成功 {passed},失败 {failed},预检跳过 {len(self.skipped_names)},'
|
||||
f'队列未执行 {skipped}。\n完整日志:{report}\n仅失败日志:{failure_report_path(report)}')
|
||||
if self._global_icdb_run:
|
||||
from cbb_refresh_verify.icdb_maintenance import maintenance_counts
|
||||
counts = maintenance_counts(results)
|
||||
text = ('非 READY ICDB 检查已结束\n'
|
||||
f'检查/校验通过 {passed},失败/受阻 {failed},队列未执行 {skipped}\n'
|
||||
f'启动检查通过、未修复 {counts["checked_without_repair"]}(不等同于 READY)\n'
|
||||
f'原生修复完成 {counts["repaired"]},恢复备份待复核 {counts["review_required"]},'
|
||||
f'ICDB已修复/PCB版本待选 {counts["version_choice_required"]},'
|
||||
f'修复未确认 {counts["repair_unconfirmed"]}\n'
|
||||
text = ('ICDB 批量检查已结束\n'
|
||||
f'未发现异常 {counts["checked_without_repair"]},发现问题 {counts["issues_found"]},'
|
||||
f'占用 {counts["in_use"]},无法确认 {counts["unconfirmed"]},'
|
||||
f'取消 {counts["cancelled"]},队列未执行 {skipped}\n'
|
||||
f'完整日志:{report}\n仅失败日志:{failure_report_path(report)}')
|
||||
self.icdb_phase.setText('已停止,存在待处理项目' if failed or skipped else '已完成非 READY 检查')
|
||||
self.icdb_phase.setText('批量检查已结束')
|
||||
if any(not result.safe_to_continue for result in results):
|
||||
text += '\n未确认数据库或会话安全,已停止剩余校验。请查看恢复现场。'
|
||||
status_text = text
|
||||
status_text = (f'已结束:通过 {passed},失败/受阻 {failed},'
|
||||
f'仅检查 {checked},未执行 {skipped + len(self.skipped_names)}。')
|
||||
if self._global_icdb_run:
|
||||
status_text = (f'非 READY 检查结束:通过 {passed},失败/受阻 {failed},未执行 {skipped}。\n'
|
||||
f'启动检查通过、未修复 {counts["checked_without_repair"]};'
|
||||
f'原生修复 {counts["repaired"]},恢复备份待复核 {counts["review_required"]},'
|
||||
f'ICDB已修复/PCB版本待选 {counts["version_choice_required"]},'
|
||||
f'修复未确认 {counts["repair_unconfirmed"]}。')
|
||||
status_text = (f'检查结束:未发现异常 {counts["checked_without_repair"]},'
|
||||
f'发现问题 {counts["issues_found"]},占用 {counts["in_use"]},'
|
||||
f'无法确认 {counts["unconfirmed"]},取消 {counts["cancelled"]},未执行 {skipped}。')
|
||||
if repaired and not self._global_icdb_run:
|
||||
status_text += f'\n原生 ICDB 修复完成 {repaired},待单独校验。'
|
||||
first_failure = next((result.stderr for result in results
|
||||
if result.status not in ('PASS', 'SKIPPED') and result.stderr), '')
|
||||
if result.status not in ('PASS', 'SKIPPED', 'CHECKED', 'REPAIRED') and result.stderr), '')
|
||||
if first_failure:
|
||||
explanation = '\n首个未完成原因:' + first_failure[:1500]
|
||||
status_text += explanation
|
||||
text += explanation
|
||||
self.status_label.setText(status_text); self.output.append(text)
|
||||
text += '\n首个未完成原因:' + first_failure
|
||||
if any(result.error_category == 'CBB_REIMPORT_REQUIRED' for result in results):
|
||||
status_text += '\nMentor 不允许对此已验证过的 CBB 反标注,校验未通过。'
|
||||
else:
|
||||
status_text += '\n部分项目未完成,请查看详情。'
|
||||
if any(not result.safe_to_continue for result in results):
|
||||
status_text += '\n后续操作已暂停。'
|
||||
if self._reimport_offers:
|
||||
guidance = '\n修复未完成,可选择工程副本恢复。'
|
||||
text += guidance
|
||||
status_text += guidance
|
||||
self.status_label.setText(status_text.replace('\n', ' ')); self.output.append(text)
|
||||
self.summary = QMessageBox(self)
|
||||
self.summary.setWindowTitle('非 READY ICDB 检查与修复结果' if self._global_icdb_run else 'CBB 校验结果'); self.summary.setText(text)
|
||||
self.summary.setWindowTitle('ICDB 批量检查结果' if self._global_icdb_run else 'CBB 校验结果')
|
||||
self.summary.setText(status_text)
|
||||
self.summary.setDetailedText(text)
|
||||
self.summary.setIcon(QMessageBox.Warning if failed else QMessageBox.Information)
|
||||
self._reimport_summary_action = None
|
||||
if self._reimport_offers:
|
||||
self.summary.setStandardButtons(QMessageBox.Close)
|
||||
self._reimport_summary_action = self.summary.addButton('选择副本恢复…', QMessageBox.ActionRole)
|
||||
self._reimport_summary_action.clicked.connect(self.reimport_failed)
|
||||
self._reimport_summary_action.setEnabled(False) # Enabled after the worker finishes.
|
||||
# Modeless notification: do not force activation or steal keyboard focus.
|
||||
from PySide6.QtCore import Qt
|
||||
self.summary.setTextFormat(Qt.PlainText)
|
||||
self.summary.setAttribute(Qt.WA_ShowWithoutActivating)
|
||||
self.summary.show()
|
||||
|
||||
@@ -917,7 +1148,11 @@ class MainWindow(QWidget):
|
||||
def request_stop(self):
|
||||
if self.version_dialog is not None:
|
||||
self.version_dialog.reject()
|
||||
self.stop.set(); self.status_label.setText('已请求停止;当前 CBB 完成或超时后停止队列。'); self._update()
|
||||
management = getattr(self, 'management_dialog', None)
|
||||
if management is not None and management.isVisible():
|
||||
management.stop.set()
|
||||
self.stop.set(); self.status_label.setText('已请求取消 ICDB 检查。' if self._global_icdb_run else
|
||||
'已请求取消;检查将停止,原生写入只等待安全结束,不强制终止。'); self._update()
|
||||
|
||||
def _failed(self, error):
|
||||
if self.library_lease is not None:
|
||||
@@ -947,5 +1182,10 @@ class MainWindow(QWidget):
|
||||
if self.busy:
|
||||
self.request_stop(); event.ignore()
|
||||
else:
|
||||
if self._native_backup_session is not None:
|
||||
self.native_backup_timer.stop()
|
||||
lease = self._native_backup_session.path_lease
|
||||
if lease is not None:
|
||||
lease.retain_for_recovery()
|
||||
self._release_library_lease()
|
||||
event.accept()
|
||||
@@ -20,10 +20,11 @@ RESULT_LABELS = {
|
||||
STAGE_LABELS = {
|
||||
'prepare_identity': '正在核对来源工程内容',
|
||||
'catalog_before': '正在核对原生目录', 'baseline': '正在记录中心库内容基线',
|
||||
'stage_source': '正在复制并检查来源工程', 'native_remove': '正在原生移除',
|
||||
'removed': '原条目已移除', 'native_add': '正在原生上传', 'uploaded': '上传身份已确认',
|
||||
'stage_source': '正在复制并检查来源工程', 'native_remove': '正在移除',
|
||||
'removed': '原条目已移除', 'native_add': '正在上传', 'uploaded': '上传已确认',
|
||||
'verify': '正在校验上传结果', 'verified': '校验已返回', 'copy': '正在准备来源副本',
|
||||
'hash': '正在校验主要文件',
|
||||
'release_check': '正在检查工程是否被占用',
|
||||
}
|
||||
|
||||
|
||||
@@ -34,13 +35,19 @@ class ManagementSignals(QObject):
|
||||
class ManagementDialog(QDialog):
|
||||
completed = Signal(object)
|
||||
|
||||
def __init__(self, requests, parent=None, *, adapter=None, runner=None):
|
||||
def __init__(self, requests, parent=None, *, adapter=None, runner=None, recovery_from=None):
|
||||
super().__init__(parent)
|
||||
self.templates = tuple(requests)
|
||||
self.template = self.templates[0]
|
||||
self.operation = self.template.operation
|
||||
self.adapter = adapter
|
||||
self.recovery_from = dict(recovery_from or {})
|
||||
self.runner = runner or run_management_batch
|
||||
if self.recovery_from and runner is None:
|
||||
from ..reimport_recovery import run_reimport_recovery
|
||||
self.runner = lambda requests, **kwargs: run_reimport_recovery(requests,
|
||||
previous_evidence=self.recovery_from,
|
||||
evidence_dir=self.template.evidence_dir.parent/'reimport-recovery', **kwargs)
|
||||
self.busy = False
|
||||
self.executed = False
|
||||
self.stop = Event()
|
||||
@@ -62,16 +69,26 @@ class ManagementDialog(QDialog):
|
||||
self.status_label = QLabel(MANUAL_BACKUP_NOTICE + ' 更新会先移除再重新导入,失败时请使用手动备份恢复。')
|
||||
self.status_label.setWordWrap(True)
|
||||
self.output = QTextEdit(); self.output.setReadOnly(True)
|
||||
self.output.document().setMaximumBlockCount(2000)
|
||||
self.output.hide()
|
||||
self.logs_button = QPushButton('查看日志')
|
||||
self.logs_button.setCheckable(True)
|
||||
self.logs_button.toggled.connect(self.output.setVisible)
|
||||
if self.recovery_from:
|
||||
self.setWindowTitle('从副本恢复 CBB')
|
||||
self.status_label.setText('修复未完成。请选择完整工程副本(.prj)。所列 CBB 将替换为副本中的版本。\n'
|
||||
+ MANUAL_BACKUP_NOTICE)
|
||||
self.output.append('\n'.join(f'原失败记录 {name}:{path}' for name, path in self.recovery_from.items()))
|
||||
self.execute_button = QPushButton('预览并确认执行…')
|
||||
self.execute_button.clicked.connect(self._execute)
|
||||
self.stop_button = QPushButton('当前项结束后停止'); self.stop_button.setEnabled(False)
|
||||
self.stop_button.clicked.connect(self.stop.set)
|
||||
self.close_button = QPushButton('关闭'); self.close_button.clicked.connect(self.reject)
|
||||
layout = QVBoxLayout(self)
|
||||
layout.addWidget(QLabel(f'目标库:{self.template.library}\n操作记录:{self.template.evidence_dir}'))
|
||||
layout.addWidget(QLabel(f'目标库:{self.template.library}'))
|
||||
layout.addWidget(self.table)
|
||||
layout.addWidget(self.sources_button); layout.addWidget(self.auto_verify)
|
||||
layout.addWidget(self.status_label); layout.addWidget(self.output)
|
||||
layout.addWidget(self.status_label); layout.addWidget(self.logs_button); layout.addWidget(self.output)
|
||||
buttons = QHBoxLayout()
|
||||
for widget in (self.execute_button, self.stop_button, self.close_button): buttons.addWidget(widget)
|
||||
layout.addLayout(buttons)
|
||||
@@ -132,9 +149,12 @@ class ManagementDialog(QDialog):
|
||||
description = ('同名更新会原生移除并重新导入;导入失败需要使用手动备份恢复。' if self.operation == 'update'
|
||||
else '将通过原生操作移除所列 CBB;恢复时需要使用手动备份。' if self.operation == 'remove'
|
||||
else '新增同名冲突会拒绝覆盖,完整来源工程将先复制到暂存区。')
|
||||
if self.recovery_from:
|
||||
description = ('将用所选副本替换这些 CBB。操作会先移除原条目,再导入副本;'
|
||||
'导入失败时需要用备份恢复。请确认副本版本。')
|
||||
answer = QMessageBox.question(self, '确认管理操作',
|
||||
f'{MANUAL_BACKUP_NOTICE}\n{description}\n\n目标库:{self.template.library}\n{preview}\n\n'
|
||||
f'操作记录与检查点:{self.template.evidence_dir}\n确认继续执行?', QMessageBox.Yes | QMessageBox.No,
|
||||
'确认继续执行?', QMessageBox.Yes | QMessageBox.No,
|
||||
QMessageBox.No)
|
||||
if answer != QMessageBox.Yes:
|
||||
return
|
||||
@@ -155,7 +175,8 @@ class ManagementDialog(QDialog):
|
||||
|
||||
def _progress(self, event):
|
||||
stage = str(event.get('stage', ''))
|
||||
text = f'{event.get("block", "")} {STAGE_LABELS.get(stage, RESULT_LABELS.get(stage, stage))}'
|
||||
text = f'{event.get("block", "")} {STAGE_LABELS.get(stage, RESULT_LABELS.get(stage, "正在处理"))}'
|
||||
self.output.append(str(event))
|
||||
if 'copied_files' in event:
|
||||
text += f' {event["copied_files"]}/{event.get("total_files", "?")}'
|
||||
elif 'hashed_files' in event:
|
||||
@@ -163,14 +184,20 @@ class ManagementDialog(QDialog):
|
||||
self.status_label.setText(text)
|
||||
|
||||
def _result(self, results):
|
||||
lines = []
|
||||
lines, summaries = [], []
|
||||
for result in results:
|
||||
text = f'{result.name}:{RESULT_LABELS.get(result.status, result.status)} — {result.detail}'
|
||||
summary = f'{result.name}:{RESULT_LABELS.get(result.status, result.status)}'
|
||||
text = f'{summary} — {result.detail}'
|
||||
if self.recovery_from and result.status == 'UPLOADED_VERIFIED':
|
||||
summary += ',版本待核对。'
|
||||
elif result.status not in ('UPLOADED', 'UPLOADED_VERIFIED', 'REMOVED'):
|
||||
summary += ',详情请查看日志。'
|
||||
summaries.append(summary)
|
||||
if result.evidence_path:
|
||||
text += f'\n记录:{result.evidence_path}'
|
||||
lines.append(text)
|
||||
message = '\n'.join(lines) if lines else '队列已取消,未执行任何项。'
|
||||
self.status_label.setText(message); self.output.append(message)
|
||||
self.status_label.setText('\n'.join(summaries) if summaries else message); self.output.append(message)
|
||||
self.completed.emit(results)
|
||||
|
||||
def _failed(self, error):
|
||||
|
||||
@@ -56,13 +56,13 @@ class VerifyRequest:
|
||||
# A reserved iCDB range is a host-wide prerequisite failure. Do not
|
||||
# launch a PCB that is guaranteed to time out; batch orchestration will
|
||||
# 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.
|
||||
# Preserve the parent session's mapping identity so the worker can restore
|
||||
# it before launching Library Manager/PCB.
|
||||
mapped_drive: str = ''
|
||||
mapped_remote_root: str = ''
|
||||
auto_repair: bool = True
|
||||
auto_repair: bool = False
|
||||
maintenance: bool = False
|
||||
post_repair_proof: object | None = field(default=None, repr=False, compare=False)
|
||||
diagnostic_only: bool = False
|
||||
@@ -135,7 +135,8 @@ def classify_output(exit_code: int | None, output: str, *, timed_out: bool = Fal
|
||||
from .icdb_recovery import parse_session_loss
|
||||
if parse_session_loss(output):
|
||||
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'
|
||||
if ERROR_TEXT.search(output):
|
||||
return 'FAIL'
|
||||
@@ -157,7 +158,8 @@ def preflight(request):
|
||||
if len(projects) != 1:
|
||||
raise ValueError(f'{name}: 缺少或无法唯一确定 Work 下的工程 PRJ')
|
||||
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)
|
||||
if not refs:
|
||||
raise ValueError(f'{name}: 工程没有 PCBDesignPath')
|
||||
@@ -220,7 +222,17 @@ def _stop_worker(process, *, timeout=5):
|
||||
try:
|
||||
process.wait(timeout=timeout)
|
||||
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):
|
||||
@@ -270,6 +282,11 @@ def classify_failure_category(detail):
|
||||
from .icdb_recovery import ERROR_CODE, parse_session_loss
|
||||
if ERROR_CODE.casefold() in lower or parse_session_loss(text):
|
||||
return ERROR_CODE
|
||||
if 'back annotation is not allowed on verified (or once verified) reusable blocks.' in lower:
|
||||
# Preserve the native integration failure even when shutdown adds a
|
||||
# secondary release warning. This category does not grant permission
|
||||
# to reimport or change safe_to_continue.
|
||||
return 'CBB_REIMPORT_REQUIRED'
|
||||
if any(code in lower for code in (
|
||||
'pcb_release_unconfirmed', 'icdb_release_unconfirmed',
|
||||
'icdb_session_unconfirmed', 'pcb_session_active', 'database_recovery_required')):
|
||||
@@ -475,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):
|
||||
"""Record native release or retention after automation has stopped."""
|
||||
from .mentor_adapter import cleanup_verify_processes
|
||||
@@ -499,7 +516,7 @@ def _cleanup_session_processes(root, *, lm_pid, target_pid, pcb, pcb_baseline,
|
||||
return cleanup_verify_processes(
|
||||
lm_pid,
|
||||
target_pid,
|
||||
None,
|
||||
launcher_pid,
|
||||
expected_pcb=pcb,
|
||||
baseline_pids=pcb_baseline,
|
||||
emit=emit,
|
||||
@@ -507,7 +524,7 @@ def _cleanup_session_processes(root, *, lm_pid, target_pid, pcb, pcb_baseline,
|
||||
|
||||
|
||||
def run_verify(request, *, 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):
|
||||
# Cover contents checking, native work and final state reads with one
|
||||
# session-wide mutex. The worker-stage lock below is reentrant on Windows.
|
||||
import win32event, win32con
|
||||
@@ -517,6 +534,12 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
|
||||
acquired = False
|
||||
library_lock = None
|
||||
release_confirmed = True
|
||||
remaining_clients = ()
|
||||
def clients_released():
|
||||
if release_confirmed:
|
||||
return True
|
||||
from .library_lock import _supervisor_alive
|
||||
return bool(remaining_clients) and not any(_supervisor_alive(pid) for pid in remaining_clients)
|
||||
try:
|
||||
acquired = win32event.WaitForSingleObject(mutex, 0) in (
|
||||
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
||||
@@ -524,28 +547,21 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
|
||||
return VerifyResult('BLOCKED', stderr='已有 CBB 校验任务运行,请等待结束。',
|
||||
safe_to_continue=False)
|
||||
if request.maintenance:
|
||||
from .maintenance_entry import maintenance_needed, run_existing_address_maintenance
|
||||
try:
|
||||
needed = maintenance_needed(request)
|
||||
except (ValueError, OSError) as error:
|
||||
return VerifyResult('BLOCKED', stderr=str(error), safe_to_continue=False)
|
||||
if needed:
|
||||
return run_existing_address_maintenance(request, progress=progress,
|
||||
verify=lambda req: _run_verify_serialized(req, progress=progress, flag_reader=flag_reader,
|
||||
process_runner=process_runner, port_check=port_check,
|
||||
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt))
|
||||
from .maintenance_entry import run_icdb_check
|
||||
return run_icdb_check(request, progress=progress, stop=stop)
|
||||
from .library_lock import LibraryLock, LibraryBusy
|
||||
if Path(request.lmc_file).is_file():
|
||||
try:
|
||||
library_lock = LibraryLock(request.lmc_file, safe_to_release=lambda: release_confirmed)
|
||||
library_lock = LibraryLock(request.lmc_file, checkpoint=False,
|
||||
safe_to_release=clients_released)
|
||||
library_lock.__enter__()
|
||||
except LibraryBusy as error:
|
||||
return VerifyResult('BLOCKED', stderr=str(error), safe_to_continue=False)
|
||||
return VerifyResult('FAIL', stderr=str(error), error_category='LIBRARY_IN_USE')
|
||||
release_confirmed = False
|
||||
result = _run_verify_serialized(
|
||||
request, progress=progress, flag_reader=flag_reader,
|
||||
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'}
|
||||
and result.error_category == 'ICDB_REPAIR_REQUIRED'
|
||||
and result.evidence_path):
|
||||
@@ -624,6 +640,20 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
|
||||
except OSError:
|
||||
pass # Keep the native/repair errors even if evidence storage fails.
|
||||
release_confirmed = result.safe_to_continue
|
||||
if not release_confirmed and result.evidence_path:
|
||||
try:
|
||||
release = json.loads(result.evidence_path.with_name('session-release.json').read_text('utf-8'))
|
||||
release_confirmed = (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())
|
||||
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()):
|
||||
remaining_clients = tuple(pid for pid in release.get('remaining_pids', [])
|
||||
if type(pid) is int and pid > 0)
|
||||
except (OSError, ValueError, KeyError):
|
||||
pass
|
||||
return result
|
||||
finally:
|
||||
try:
|
||||
@@ -637,12 +667,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')
|
||||
@@ -668,8 +709,7 @@ def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_
|
||||
detail = result.stderr
|
||||
if recovery and RECOVERY_ACTION not in detail:
|
||||
detail = (detail + '\n' + recovery_detail(recovery)).strip()
|
||||
result = replace(result, safe_to_continue=False, stderr=detail,
|
||||
error_category=ERROR_CODE)
|
||||
result = replace(result, stderr=detail, error_category=ERROR_CODE)
|
||||
if recovery and result.evidence_path:
|
||||
try:
|
||||
record_path = result.evidence_path.parent/'diagnostics/icdb-recovery.json'
|
||||
@@ -707,7 +747,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``.
|
||||
@@ -739,6 +779,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)
|
||||
@@ -747,17 +789,6 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
finally:
|
||||
timing.end('preflight')
|
||||
|
||||
from .icdb_ownership import unreleased_addresses
|
||||
try:
|
||||
addresses = unreleased_addresses(request.lmc_file, project, pcb)
|
||||
if addresses:
|
||||
return finish(VerifyResult('BLOCKED', safe_to_continue=False,
|
||||
stderr='ICDB_SESSION_UNCONFIRMED: 原生数据库所有权未释放,未开始内容检查或校验:'
|
||||
+ '; '.join(addresses)))
|
||||
except OSError as error:
|
||||
return finish(VerifyResult('BLOCKED', safe_to_continue=False,
|
||||
stderr=f'ICDB_SESSION_UNCONFIRMED: 无法确认数据库所有权:{error}'))
|
||||
|
||||
content_check_enabled = not request.diagnostic_only and bool(str(request.libspec).strip() and str(request.dms_login_config).strip())
|
||||
if content_check_enabled:
|
||||
try:
|
||||
@@ -790,8 +821,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()
|
||||
@@ -879,6 +909,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)
|
||||
@@ -1024,7 +1058,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():
|
||||
@@ -1039,6 +1073,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()
|
||||
@@ -1046,15 +1082,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,
|
||||
@@ -1065,16 +1123,28 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
from .icdb_ownership import unreleased_addresses
|
||||
addresses = unreleased_addresses(request.lmc_file, project, pcb)
|
||||
if addresses:
|
||||
release_result = {**(release_result or {}), 'safe_to_continue': False,
|
||||
'icdb_address': addresses[0], 'icdb_addresses': addresses}
|
||||
release_result = {**(release_result or {}), 'icdb_addresses': addresses}
|
||||
except OSError as error:
|
||||
close_errors.append(str(error))
|
||||
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': 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,
|
||||
@@ -1143,7 +1213,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)
|
||||
@@ -1167,11 +1237,21 @@ def write_failure_report(requests, results, root, *, path=None):
|
||||
root = Path(root); root.mkdir(parents=True, exist_ok=True)
|
||||
path = Path(path) if path else root/('failures-' + time.strftime('%Y%m%d-%H%M%S') + '-' + uuid4().hex[:6] + '.log')
|
||||
failed = [(req, result) for req, result in zip(requests, results)
|
||||
if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP'}]
|
||||
if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP'}
|
||||
and not (result.status in {'CHECKED', 'REPAIRED'} and result.safe_to_continue)]
|
||||
passed = sum(result.status == 'PASS' for result in results)
|
||||
skipped = len(results)-passed-len(failed)
|
||||
lines = ['CBB Verify 失败清单', f'总数: {len(results)} 成功: {passed} 失败: {len(failed)} 未执行: {skipped}',
|
||||
checked = sum(result.status == 'CHECKED' and result.safe_to_continue for result in results)
|
||||
repaired = sum(result.status == 'REPAIRED' and result.safe_to_continue for result in results)
|
||||
skipped = len(results)-passed-len(failed)-checked-repaired
|
||||
lines = ['CBB Verify 失败清单', f'总数: {len(results)} 成功: {passed} 失败: {len(failed)} 未执行: {skipped} 仅检查未修复: {checked} ICDB已修复待校验: {repaired}',
|
||||
'CBB\t状态\t错误分类\t失败阶段\t桥状态\t原始错误\t证据\t实际耗时(秒)']
|
||||
if requests and all(req.maintenance for req in requests):
|
||||
from .icdb_maintenance import maintenance_counts
|
||||
counts = maintenance_counts(results)
|
||||
lines[:2] = ['ICDB 检查异常清单',
|
||||
f'总数: {len(results)} 未发现异常: {checked} 发现问题: {counts["issues_found"]} '
|
||||
f'占用: {counts["in_use"]} 无法确认: {counts["unconfirmed"]} '
|
||||
f'取消: {counts["cancelled"]} 未执行: {counts["skipped"]}']
|
||||
for req, result in failed:
|
||||
timings = ' '.join(f'{key}={value:.3f}s' +
|
||||
('(unfinished)' if key in result.incomplete_timing_phases else '')
|
||||
@@ -1192,6 +1272,8 @@ def write_batch_report(requests, results, root):
|
||||
path = root/('batch-' + time.strftime('%Y%m%d-%H%M%S') + '-' + uuid4().hex[:6] + '.log')
|
||||
lines = ['CBB Verify 批量结果',
|
||||
'流程: LMC 原生 Verify / ReusableCircuit PCB -> Project Integration -> Save/Close -> IsVerifiedReuseBlock READY(金标准)']
|
||||
if requests and all(req.maintenance for req in requests):
|
||||
lines = ['ICDB 批量检查结果', '流程: 原生 Project Backup 加载检查;不执行 Repair、Restore 或 CBB 校验。']
|
||||
for req, result in zip(requests, results):
|
||||
detail = _report_field(result.stderr or result.stdout.strip()[:200])
|
||||
seconds = ' '.join(f'{key}={value:.3f}s' +
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
"""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_item_failure_with_confirmed_release_does_not_stop_unrelated_items(tmp_path):
|
||||
from cbb_refresh_verify.verify_runner import VerifyRequest, VerifyResult
|
||||
library = tmp_path/'library.lmc'; library.touch()
|
||||
requests = [VerifyRequest(library, name, tmp_path/'evidence') for name in ('A', 'B')]
|
||||
calls = []
|
||||
def verify(request):
|
||||
calls.append(request.block_name)
|
||||
return VerifyResult('FAIL' if request.block_name == 'A' else 'PASS',
|
||||
stderr='单项失败但会话已释放' if request.block_name == 'A' else '',
|
||||
safe_to_continue=True)
|
||||
results = runner.run_batch(requests, verifier=verify)
|
||||
assert calls == ['A', 'B']
|
||||
assert [result.status for result in results] == ['FAIL', 'PASS']
|
||||
|
||||
|
||||
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()
|
||||
@@ -172,3 +172,26 @@ def test_authoritative_status_map_never_reuses_previous_scan_status(tmp_path, mo
|
||||
assert first == {'A': 'PENDING'}
|
||||
assert second == {'A': 'READY'}
|
||||
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
|
||||
@@ -0,0 +1,56 @@
|
||||
import pytest
|
||||
|
||||
|
||||
def test_constructor_releases_private_desktop_when_process_launch_fails(monkeypatch):
|
||||
import cbb_refresh_verify.desktop_worker as module
|
||||
|
||||
class Handle:
|
||||
def __init__(self):
|
||||
self.closed = False
|
||||
|
||||
def Close(self):
|
||||
self.closed = True
|
||||
|
||||
def CloseDesktop(self):
|
||||
self.closed = True
|
||||
|
||||
desktop = Handle()
|
||||
job = Handle()
|
||||
|
||||
monkeypatch.setattr(module.win32service, 'CreateDesktop', lambda *args: desktop)
|
||||
monkeypatch.setattr(module.win32job, 'CreateJobObject', lambda *args: job)
|
||||
monkeypatch.setattr(module.win32process, 'STARTUPINFO', lambda: type('Startup', (), {})())
|
||||
monkeypatch.setattr(module.win32process, 'CreateProcess',
|
||||
lambda *args: (_ for _ in ()).throw(RuntimeError('launch failed')))
|
||||
|
||||
with pytest.raises(RuntimeError, match='launch failed'):
|
||||
module.DesktopWorker(['worker.exe'], 'PrivateDesk')
|
||||
|
||||
assert desktop.closed is True
|
||||
assert job.closed is True
|
||||
|
||||
|
||||
def test_library_flag_loads_ui_dependencies_before_creating_private_desktop(monkeypatch, tmp_path):
|
||||
import builtins
|
||||
import win32service
|
||||
import cbb_refresh_verify.mentor_adapter as module
|
||||
|
||||
created = []
|
||||
original_import = builtins.__import__
|
||||
executable = tmp_path / 'LibraryManager.exe'
|
||||
executable.touch()
|
||||
|
||||
def deny_pywinauto(name, *args, **kwargs):
|
||||
if name == 'pywinauto' or name.startswith('pywinauto.'):
|
||||
raise ImportError('pywinauto unavailable')
|
||||
return original_import(name, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(builtins, '__import__', deny_pywinauto)
|
||||
monkeypatch.setattr(module, 'library_manager_path', lambda: executable)
|
||||
monkeypatch.setattr(win32service, 'CreateDesktop',
|
||||
lambda *args: created.append(args))
|
||||
|
||||
with pytest.raises(ImportError, match='pywinauto unavailable'):
|
||||
module.read_library_flag('library.lmc', 'Block')
|
||||
|
||||
assert created == []
|
||||
@@ -90,6 +90,26 @@ def test_requested_close_without_exit_is_not_reported_closed(tmp_path, monkeypat
|
||||
assert records
|
||||
|
||||
|
||||
@pytest.mark.parametrize('exits', [True, False])
|
||||
def test_after_owned_close_transient_empty_command_waits_for_exit(tmp_path, monkeypatch, exits):
|
||||
from types import SimpleNamespace
|
||||
import win32gui
|
||||
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||
ticks = [0.0]
|
||||
def post(hwnd, message, *_):
|
||||
messages.append((hwnd, message))
|
||||
records[0] = (12, '', '', 11) # WMI during process teardown.
|
||||
def advance(seconds):
|
||||
ticks[0] += seconds
|
||||
if exits: records.clear()
|
||||
monkeypatch.setattr(win32gui, 'PostMessage', post)
|
||||
monkeypatch.setattr(failed_session, 'time', SimpleNamespace(monotonic=lambda: ticks[0], sleep=advance))
|
||||
result = failed_session.close_failed_startup(job, 12, timeout_seconds=1)
|
||||
assert ticks[0] > 0 and len(messages) == 1
|
||||
assert result['status'] == ('CLOSED' if exits else 'RETAINED')
|
||||
assert 'STARTUP_PROCESS_UNCONFIRMED' not in result.get('detail', '')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('obstacle', ['address', 'dialog', 'process'])
|
||||
def test_startup_close_waits_for_native_state_transitions(tmp_path, monkeypatch, obstacle):
|
||||
from types import SimpleNamespace
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
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 = []
|
||||
class BusyWorker:
|
||||
def request_stop(self): calls.append('cancel')
|
||||
def wait(self, timeout): raise TimeoutError('native Save still running')
|
||||
def kill(self): calls.append('kill')
|
||||
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):
|
||||
@@ -225,21 +225,22 @@ def test_status_server_close_allows_eof_cleanup_before_termination(tmp_path):
|
||||
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
|
||||
fixture(tmp_path)
|
||||
address = tmp_path/'SymbolLibs/__ReusableBlocksSymb/cdbsvr/sAddress.adr'
|
||||
address.parent.mkdir(parents=True)
|
||||
address.write_bytes(b'unknown native owner')
|
||||
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'))
|
||||
assert outcome.status == 'BLOCKED'
|
||||
assert outcome.safe_to_continue is False
|
||||
assert '__ReusableBlocksSymb' in outcome.stderr
|
||||
calls = []
|
||||
outcome = runner.run_verify(req, process_runner=lambda *args:
|
||||
(calls.append(args) or (1, 'ERROR: shared database unavailable', '', False)))
|
||||
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'
|
||||
|
||||
|
||||
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 cbb_refresh_verify import mentor_adapter as adapter
|
||||
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')
|
||||
return original(*args, **kwargs)
|
||||
monkeypatch.setattr(adapter.subprocess, 'Popen', helper)
|
||||
with pytest.raises(RuntimeError, match='ICDB_RELEASE_UNCONFIRMED'):
|
||||
execute()
|
||||
assert not any(event['stage'] == 'complete' for event in events)
|
||||
assert execute()['status'] == 'PASS'
|
||||
assert any(event['stage'] == 'icdb_address_remaining' for event in events)
|
||||
|
||||
|
||||
def test_cooperative_supervisor_loss_keeps_pending_save_helper_alive(tmp_path):
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
"""Batch ICDB inspection never opens PCB or dispatches Repair."""
|
||||
from dataclasses import replace
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from test_maintenance_entry import case, no_native_launch
|
||||
from test_maintenance_diagnosis import inspection
|
||||
|
||||
|
||||
@pytest.mark.parametrize('scenario,status,category,safe', [
|
||||
('healthy', 'CHECKED', '', True),
|
||||
('fault', 'FAIL', 'ICDB_REPAIR_REQUIRED', True),
|
||||
('busy', 'BLOCKED', 'ICDB_DATABASE_IN_USE', True),
|
||||
('unknown', 'FAIL', 'ICDB_INSPECTION_UNCONFIRMED', True),
|
||||
('unexpected_repair', 'FAIL', 'ICDB_INSPECTION_UNCONFIRMED', True),
|
||||
('missing_exit_proof', 'FAIL', 'ICDB_INSPECTION_UNCONFIRMED', False),
|
||||
('not_launched', 'FAIL', 'ICDB_INSPECTION_UNCONFIRMED', True),
|
||||
('unreleased', 'FAIL', 'ICDB_INSPECTION_UNCONFIRMED', False),
|
||||
('cancelled', 'CANCELLED', '', True),
|
||||
])
|
||||
def test_batch_check_only_loads_native_inspection(case, monkeypatch, scenario, status, category, safe):
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair, maintenance_entry as entry
|
||||
from test_native_occupancy import output
|
||||
request, _, address = case
|
||||
calls = []
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: pytest.fail('check opened PCB'))
|
||||
monkeypatch.setattr(entry, 'assert_native_idle', lambda: pytest.fail('check used host-wide owner gate'))
|
||||
def native(target, root, **kw):
|
||||
assert kw['inspection_only'] is True and not kw.get('maintenance_context')
|
||||
calls.append('inspect')
|
||||
record = inspection(target, fault=scenario == 'fault')
|
||||
if scenario == 'busy':
|
||||
record.update(status='IN_USE', output=output(target.project, target.database, busy=True))
|
||||
if scenario in ('unknown', 'unreleased'):
|
||||
record.update(status='UNCONFIRMED', output='No conclusive native response')
|
||||
if scenario == 'unreleased': record['release']['native_exited'] = False
|
||||
if scenario == 'cancelled': record.update(status='CANCELLED')
|
||||
if scenario == 'unexpected_repair': record.update(status='REPAIRED', repair_requested=True)
|
||||
if scenario == 'missing_exit_proof': return {}
|
||||
if scenario == 'not_launched': return {'status': 'BLOCKED', 'native_started': False}
|
||||
return record
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', native)
|
||||
result = runner.run_verify(replace(request, auto_repair=True))
|
||||
assert calls == ['inspect']
|
||||
assert (result.status, result.error_category, result.safe_to_continue) == (status, category, safe)
|
||||
assert result.library_flag == 'UNKNOWN' and result.recovery_attempts == ()
|
||||
assert address.read_bytes() == b'old server address - preserved'
|
||||
record = json.loads(result.evidence_path.read_text('utf-8'))
|
||||
assert record['operation'] == 'icdb_batch_check' and record['automatic_repair'] is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize('case_type', ['no_layout', 'no_pcb', 'no_icdb', 'ambiguous_repair_targets'])
|
||||
def test_inspection_does_not_require_repair_admission(case, monkeypatch, case_type):
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair
|
||||
request, project, address = case
|
||||
if case_type == 'no_layout': (project.parent/'PCB/Layout/LayoutDB.lyt').unlink()
|
||||
if case_type == 'no_pcb': (project.parent/'PCB/IP101GR.pcb').unlink()
|
||||
if case_type == 'no_icdb': (project.parent/'database/icdb.dat').unlink()
|
||||
if case_type == 'ambiguous_repair_targets':
|
||||
address.unlink()
|
||||
(project.parent/'PCB/pcb.prj').write_text('KEY iCDBDir "database"\n')
|
||||
db = project.parent/'PCB/database'; db.mkdir(); (db/'icdb.dat').touch()
|
||||
calls = []
|
||||
def native(target, *a, **kw):
|
||||
assert kw['inspection_only'] is True and target.project == project
|
||||
calls.append('inspect')
|
||||
return inspection(target)
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', native)
|
||||
result = runner.run_verify(request)
|
||||
assert calls == ['inspect']
|
||||
assert result.recovery_attempts == ()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('before_launch', [True, False])
|
||||
def test_cancellation_never_dispatches_repair_or_reports_a_clean_check(case, monkeypatch, before_launch):
|
||||
from threading import Event
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair
|
||||
request, _, _ = case
|
||||
stop = Event(); calls = []
|
||||
if before_launch: stop.set()
|
||||
def native(target, *a, **kw):
|
||||
assert kw['inspection_only'] is True
|
||||
calls.append('inspect'); stop.set()
|
||||
return inspection(target)
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', native)
|
||||
result = runner.run_verify(request, stop=stop)
|
||||
assert result.status == 'CANCELLED' and result.safe_to_continue
|
||||
assert calls == ([] if before_launch else ['inspect'])
|
||||
|
||||
|
||||
def test_released_icdb_fault_continues_the_check_batch(case, monkeypatch):
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair
|
||||
request, _, _ = case
|
||||
calls = []
|
||||
def native(target, root, **kw):
|
||||
assert kw['inspection_only'] is True
|
||||
calls.append('inspect')
|
||||
return inspection(target, fault=len(calls) == 1)
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', native)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: pytest.fail('check opened PCB'))
|
||||
results = runner.run_batch([request, request])
|
||||
assert calls == ['inspect', 'inspect']
|
||||
assert [result.status for result in results] == ['FAIL', 'CHECKED']
|
||||
|
||||
|
||||
def test_inspection_ignores_other_pcb_and_skips_exclusive_repair_probe(tmp_path, monkeypatch):
|
||||
import win32con
|
||||
from test_native_repair import repair_worker_fixture
|
||||
from test_native_occupancy import output
|
||||
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
|
||||
data = json.loads(job.read_text('utf-8')); data['inspection_only'] = True
|
||||
job.write_text(json.dumps(data), encoding='utf-8')
|
||||
monkeypatch.setattr('cbb_refresh_verify.mentor_adapter.pcb_processes', lambda: [(999, 'other.pcb', '')])
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_repair.check_repair_access',
|
||||
lambda *a: pytest.fail('inspection used exclusive Repair admission'))
|
||||
monkeypatch.setattr(ui, '_repair_command', lambda *a: pytest.fail('inspection resolved Repair command'))
|
||||
monkeypatch.setattr(ui, '_native_output', lambda *_: output(data['project'], data['database'], busy=True))
|
||||
assert ui.repair_worker_main(job) == 0
|
||||
assert actions == [(100, win32con.WM_CLOSE)]
|
||||
|
||||
|
||||
def test_ui_check_summary_reports_findings_and_never_claims_repair(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
requests, prompts = [], []
|
||||
window = load_window(qtbot, tmp_path, monkeypatch,
|
||||
verifier=lambda req: (requests.append(req) or VerifyResult('FAIL',
|
||||
error_category='ICDB_REPAIR_REQUIRED', stderr='发现 ICDB 问题,未执行修复。')),
|
||||
status_refresher=lambda names, _: {name: 'PENDING' for name in names})
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: (prompts.append(a[2]) or QMessageBox.Yes))
|
||||
window.search_edit.setText('Beta')
|
||||
window.icdb_repair_button.click(); qtbot.waitUntil(lambda: not window.busy)
|
||||
assert requests[0].maintenance and not requests[0].auto_repair
|
||||
assert '批量检查' in window.icdb_repair_button.text()
|
||||
assert not any('手动备份' in text for text in prompts)
|
||||
assert window.summary.windowTitle() == 'ICDB 批量检查结果'
|
||||
assert '发现问题 1' in window.summary.text()
|
||||
assert '修复并校验通过' not in window.summary.detailedText()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('category,label', [('ICDB_DATABASE_IN_USE', '占用 1'),
|
||||
('ICDB_INSPECTION_UNCONFIRMED', '无法确认 1')])
|
||||
def test_busy_or_unknown_inspection_is_not_labelled_as_database_damage(qtbot, tmp_path, monkeypatch, category, label):
|
||||
from test_ui_filters import load_window
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
window = load_window(qtbot, tmp_path, monkeypatch,
|
||||
verifier=lambda _: VerifyResult('FAIL', error_category=category, stderr='暂未完成检查。'),
|
||||
status_refresher=lambda names, _: {name: 'PENDING' for name in names})
|
||||
window.search_edit.setText('Beta')
|
||||
window.icdb_repair_button.click(); qtbot.waitUntil(lambda: not window.busy)
|
||||
assert label in window.summary.text()
|
||||
assert 'ICDB 问题' not in window.cbb_table.item(window._row_by_name['Beta'], 3).text()
|
||||
|
||||
|
||||
def test_missing_pcb_is_skipped_from_icdb_batch_check_and_restore(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
from cbb_refresh_verify.models import CbbRecord
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
calls = []
|
||||
window = load_window(qtbot, tmp_path, monkeypatch,
|
||||
records=(CbbRecord('Missing', 'Power', status='PENDING'),),
|
||||
verifier=lambda req: (calls.append(req.block_name) or VerifyResult('CHECKED')),
|
||||
status_refresher=lambda names, _: {name: 'PENDING' for name in names})
|
||||
assert not window.icdb_repair_button.isEnabled()
|
||||
assert not window.batch_button.isEnabled() and not window.backup_restore_button.isEnabled()
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_missing_project_rows_are_excluded_from_icdb_batch_check(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
from cbb_refresh_verify.models import CbbRecord
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
window = load_window(qtbot, tmp_path, monkeypatch,
|
||||
records=(CbbRecord('Missing', 'Power', status='PENDING'),
|
||||
CbbRecord('Good', 'Power', status='PENDING')),
|
||||
verifier=lambda req: VerifyResult('CHECKED'),
|
||||
status_refresher=lambda names, _: {name: 'PENDING' for name in names})
|
||||
window.skipped_names.add('Missing')
|
||||
window._update()
|
||||
assert window._maintenance_names() == ['Good']
|
||||
|
||||
|
||||
def test_check_reports_describe_inspection_without_pcb_verification(case, tmp_path):
|
||||
from cbb_refresh_verify.verify_runner import write_batch_report, failure_report_path, VerifyResult
|
||||
request, _, _ = case
|
||||
report = write_batch_report([request], [VerifyResult('FAIL',
|
||||
error_category='ICDB_REPAIR_REQUIRED', stderr='发现 ICDB 问题,未执行修复。')], tmp_path/'reports')
|
||||
full = report.read_text('utf-8-sig')
|
||||
failed = failure_report_path(report).read_text('utf-8-sig')
|
||||
assert 'ICDB 批量检查' in full and 'Project Integration' not in full
|
||||
assert 'ICDB 检查异常' in failed and '发现问题: 1' in failed
|
||||
assert 'ICDB已修复待校验' not in failed
|
||||
@@ -258,7 +258,7 @@ def test_native_log_capture_generates_only_fresh_repair_evidence(tmp_path, name)
|
||||
assert log.read_text('utf-8') == ERROR
|
||||
|
||||
|
||||
def test_contents_session_loss_stops_batch_before_any_pcb_launch(tmp_path, monkeypatch):
|
||||
def test_contents_session_loss_records_each_item_without_launching_pcb_or_repair(tmp_path, monkeypatch):
|
||||
from test_verify_runner import fixture, request
|
||||
fixture(tmp_path)
|
||||
monkeypatch.setattr(runner, 'resolve_importer', lambda *_: Path('ReuseBlockImporter.exe'))
|
||||
@@ -269,11 +269,12 @@ def test_contents_session_loss_stops_batch_before_any_pcb_launch(tmp_path, monke
|
||||
results = runner.run_batch([request(tmp_path, libspec='EE', dms_login_config='login')]*2,
|
||||
verifier=lambda req: runner.run_verify(req, process_runner=content_check,
|
||||
port_check=lambda: pytest.fail('PCB must not start')))
|
||||
assert len(calls) == 1
|
||||
assert len(calls) == 2
|
||||
assert results[0].error_category == 'ICDB_REPAIR_REQUIRED'
|
||||
assert results[0].safe_to_continue is False
|
||||
assert results[0].safe_to_continue is True
|
||||
assert 'Repair project' in results[0].stderr
|
||||
assert results[1].status == 'SKIPPED'
|
||||
assert results[1].status == 'FAIL'
|
||||
assert results[1].error_category == 'ICDB_REPAIR_REQUIRED'
|
||||
|
||||
|
||||
def test_supervisor_enriches_generic_failure_from_fresh_native_log(tmp_path, monkeypatch):
|
||||
@@ -302,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)
|
||||
result = runner.run_verify(request(tmp_path), port_check=lambda: (True, ''))
|
||||
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 '200091-CBB' in result.stderr
|
||||
assert '__ReusableBlocksSymb' in result.stderr
|
||||
|
||||
@@ -27,12 +27,11 @@ def test_network_timeout_cannot_remove_database_advertisement(tmp_path, monkeypa
|
||||
|
||||
|
||||
@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)
|
||||
monkeypatch.setattr(adapter, 'prepare_icdb_address', lambda *a, **k: {'status': state})
|
||||
with pytest.raises(RuntimeError, match='ICDB_SESSION_UNCONFIRMED'):
|
||||
execute()
|
||||
assert not any(e['stage'] == 'pcb_launch' for e in events)
|
||||
assert execute()['status'] == 'PASS'
|
||||
assert any(e['stage'] == 'pcb_launch' for e in events)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('text', [
|
||||
@@ -114,7 +113,7 @@ def test_desktop_abort_does_not_kill_native_process_tree(monkeypatch):
|
||||
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)
|
||||
original = adapter.subprocess.Popen
|
||||
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')
|
||||
return original(*a, **k)
|
||||
monkeypatch.setattr(adapter.subprocess, 'Popen', helper)
|
||||
with pytest.raises(RuntimeError, match='ICDB_RELEASE_UNCONFIRMED'):
|
||||
execute()
|
||||
assert not any(e['stage'] == 'complete' for e in events)
|
||||
assert execute()['status'] == 'PASS'
|
||||
assert any(e['stage'] == 'icdb_address_remaining' for e in events)
|
||||
|
||||
|
||||
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):
|
||||
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'):
|
||||
execute()
|
||||
assert not events
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from test_maintenance_entry import case
|
||||
|
||||
|
||||
def test_verify_defaults_to_no_repair_and_does_not_retain_a_failure_lock(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import verify_runner as runner, library_lock as locks, native_repair
|
||||
library = tmp_path / 'library.lmc'; library.touch()
|
||||
req = runner.VerifyRequest(library, 'CBB', tmp_path / 'evidence')
|
||||
assert req.auto_repair is False
|
||||
marker = locks.blocker_path(library)
|
||||
marker.write_text('historical diagnostic record')
|
||||
calls = []
|
||||
result = runner.VerifyResult('FAIL', stderr='ICDB_REPAIR_REQUIRED: session lost',
|
||||
error_category='ICDB_REPAIR_REQUIRED', safe_to_continue=True)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: (calls.append('verify') or result))
|
||||
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **k: pytest.fail('verify requested Repair'))
|
||||
assert runner.run_verify(req) is result
|
||||
assert runner.run_verify(req) is result
|
||||
assert calls == ['verify', 'verify']
|
||||
assert marker.read_text() == 'historical diagnostic record'
|
||||
assert locks._key(tmp_path / '.library.cbb-upload.lock') not in locks._owners
|
||||
|
||||
|
||||
def test_catalog_checkpoint_does_not_disable_ordinary_verify(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
calls = []
|
||||
window = load_window(qtbot, tmp_path, monkeypatch,
|
||||
verifier=lambda req: (calls.append(req) or VerifyResult('FAIL', stderr='ICDB_REPAIR_REQUIRED: lost',
|
||||
error_category='ICDB_REPAIR_REQUIRED', safe_to_continue=True)),
|
||||
status_refresher=lambda names, _: {name: 'PENDING' for name in names})
|
||||
window._maintenance_recovery_view = True
|
||||
window._management_unsafe = True
|
||||
window.search_edit.setText('Beta'); window.select_visible_button.click(); window._update()
|
||||
assert window.selected_batch_button.isEnabled()
|
||||
window.verify_selected(); qtbot.waitUntil(lambda: not window.busy)
|
||||
assert len(calls) == 1 and not calls[0].maintenance and not calls[0].auto_repair
|
||||
assert window.selected_batch_button.isEnabled()
|
||||
assert 'ICDB' in window.cbb_table.item(window._row_by_name['Beta'], 3).text()
|
||||
|
||||
|
||||
def test_management_release_block_is_scoped_to_the_loaded_library(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
from cbb_refresh_verify.management import Capability
|
||||
adapter = type('Adapter', (), {
|
||||
'capabilities': lambda self: {name: Capability(True, 'available')
|
||||
for name in ('add', 'update', 'remove')}})()
|
||||
window = load_window(qtbot, tmp_path, monkeypatch, management_adapter=adapter)
|
||||
window._management_unsafe = True
|
||||
window._management_unsafe_library = (tmp_path/'library-a.lmc').resolve()
|
||||
window.lmc_edit.setText(str(tmp_path/'library-b.lmc'))
|
||||
window.loaded_path = str(tmp_path/'library-b.lmc')
|
||||
window.mentor_lmc_path = Path(window.loaded_path)
|
||||
window.select_visible_button.click()
|
||||
window._update()
|
||||
assert window.add_button.isEnabled()
|
||||
assert '上次管理操作' not in window._management_block_reason('update')
|
||||
|
||||
|
||||
def test_loading_a_different_library_clears_old_management_block(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
window = load_window(qtbot, tmp_path, monkeypatch)
|
||||
old = (tmp_path/'library-a.lmc').resolve()
|
||||
window._management_unsafe = True
|
||||
window._management_unsafe_library = old
|
||||
window.lmc_edit.setText(str(tmp_path/'library-b.lmc'))
|
||||
window.load_library()
|
||||
qtbot.waitUntil(lambda: not window.busy)
|
||||
assert not window._management_unsafe
|
||||
assert window._management_unsafe_library is None
|
||||
|
||||
|
||||
def test_targeted_native_idle_ignores_unrelated_native_command(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import maintenance_entry as entry
|
||||
from cbb_refresh_verify.native_repair import RepairTarget
|
||||
project = tmp_path/'target.prj'; project.touch()
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda names: [
|
||||
{'pid': 10, 'name': 'ExpeditionPCB.exe', 'command': 'ExpeditionPCB.exe other.pcb'},
|
||||
])
|
||||
entry.assert_native_idle(RepairTarget(project, tmp_path/'database'))
|
||||
|
||||
|
||||
def test_maintenance_guard_does_not_scan_other_cbb_projects(case, monkeypatch):
|
||||
from cbb_refresh_verify import maintenance_entry as entry
|
||||
from cbb_refresh_verify import scoped_manifest as manifests
|
||||
req, project, _ = case
|
||||
scans = []
|
||||
scan = manifests.scan_tree
|
||||
monkeypatch.setattr(manifests, 'scan_tree', lambda root, **kw: (scans.append(Path(root)) or scan(root, **kw)))
|
||||
with entry.maintenance_target_guard(req):
|
||||
pass
|
||||
assert req.lmc_file.parent not in scans
|
||||
assert scans.count(project.parent) == 2
|
||||
|
||||
|
||||
def test_repair_finishes_without_calling_verify(case, monkeypatch):
|
||||
from cbb_refresh_verify import native_repair, verify_runner as runner
|
||||
from test_maintenance_entry import patch_verification_after_fault, run_legacy_maintenance
|
||||
from test_native_repair import complete_native_success
|
||||
req, _, address = case
|
||||
def repair(target, *a, **kw):
|
||||
address.unlink()
|
||||
return complete_native_success(target)
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', repair)
|
||||
monkeypatch.setattr(native_repair, 'repair_release_state', lambda req, target, result: result['release'])
|
||||
patch_verification_after_fault(monkeypatch, runner, lambda *a, **k: pytest.fail('maintenance started CBB verification'))
|
||||
result = run_legacy_maintenance(req)
|
||||
assert result.status == 'REPAIRED' and result.safe_to_continue
|
||||
assert result.library_flag == 'UNKNOWN'
|
||||
assert result.recovery_attempts[0]['validation_passed'] is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize('stage,expected_safe', [('PCB_STARTING', True), ('back_annotation', True)])
|
||||
def test_released_failure_can_continue_from_icdb_diagnosis(tmp_path, monkeypatch, stage, expected_safe):
|
||||
import json
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
library = tmp_path/'library.lmc'; library.touch()
|
||||
evidence = tmp_path/'evidence'; evidence.mkdir()
|
||||
report = evidence/'result.json'; report.write_text('{}')
|
||||
(evidence/'session-release.json').write_text(json.dumps({'library': str(library),
|
||||
'block': 'CBB', 'worker_exited': True, 'safe_to_continue': True}))
|
||||
failure = runner.VerifyResult('FAIL', stderr='ICDB_REPAIR_REQUIRED: lost session',
|
||||
error_stage=stage, safe_to_continue=False, evidence_path=report)
|
||||
monkeypatch.setattr(runner, '_run_verify', lambda *a, **k: failure)
|
||||
result = runner._run_verify_serialized(runner.VerifyRequest(library, 'CBB', evidence))
|
||||
assert result.status == 'FAIL' and result.error_category == 'ICDB_REPAIR_REQUIRED'
|
||||
assert result.safe_to_continue is expected_safe
|
||||
|
||||
|
||||
def test_live_writer_keeps_execution_lock_without_a_permanent_diagnostic_blocker(tmp_path, monkeypatch):
|
||||
import win32con, win32file
|
||||
from cbb_refresh_verify import library_lock as locks, verify_runner as runner
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k:
|
||||
runner.VerifyResult('TIMEOUT', safe_to_continue=False))
|
||||
result = runner.run_verify(runner.VerifyRequest(library, 'CBB', tmp_path/'evidence'))
|
||||
lock = locks.LibraryLock(library)
|
||||
try:
|
||||
assert not result.safe_to_continue and not locks.blocker_path(library).exists()
|
||||
with pytest.raises(Exception):
|
||||
win32file.CreateFile(str(lock.path), win32con.GENERIC_READ | win32con.GENERIC_WRITE,
|
||||
0, None, win32con.OPEN_ALWAYS, 0, None)
|
||||
finally:
|
||||
with locks._guard:
|
||||
owner = locks._owners.pop(lock.key, None)
|
||||
if owner: owner['handle'].Close()
|
||||
|
||||
|
||||
def test_healthy_native_inspection_with_old_address_does_not_lock_management(case, monkeypatch):
|
||||
from cbb_refresh_verify import native_repair, verify_runner as runner, library_lock as locks
|
||||
from test_native_occupancy import output
|
||||
request, project, address = case
|
||||
def inspect(target, *a, **kw):
|
||||
assert kw['inspection_only']
|
||||
return {'inspection_only': True, 'repair_requested': False, 'repair_required': False,
|
||||
'status': 'NOT_IN_USE', 'native_pid': 777, 'native_exit_code': 0,
|
||||
'project': str(target.project), 'database': str(target.database),
|
||||
'output': output(target.project, target.database), 'release': {'native_exited': True}}
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', inspect)
|
||||
result = runner.run_verify(request)
|
||||
assert result.status == 'CHECKED' and result.safe_to_continue and address.exists()
|
||||
assert not result.stderr and '无需修复' in result.stdout
|
||||
assert not locks.blocker_path(request.lmc_file).exists()
|
||||
with locks.LibraryLock(request.lmc_file): pass
|
||||
|
||||
|
||||
@pytest.mark.parametrize('operation', ['verify', 'maintenance'])
|
||||
def test_retained_execution_lease_can_retry_after_its_actual_client_exits(tmp_path, operation):
|
||||
from contextlib import contextmanager
|
||||
from cbb_refresh_verify.library_lock import LibraryLock, LibraryBusy
|
||||
library = tmp_path/'library.lmc'; library.touch()
|
||||
released = [False]
|
||||
with LibraryLock(library, checkpoint=False, safe_to_release=lambda: released[0]): pass
|
||||
with pytest.raises(LibraryBusy):
|
||||
with LibraryLock(library, checkpoint=False): pass
|
||||
released[0] = True
|
||||
@contextmanager
|
||||
def guard(): yield {'target': 'isolated fixture'}
|
||||
lock = (LibraryLock(library, checkpoint=False) if operation == 'verify' else
|
||||
LibraryLock.for_maintenance(library, tmp_path/'archive', guard, safe_to_release=lambda: True))
|
||||
with lock: pass
|
||||
+68
-15
@@ -65,28 +65,25 @@ def test_verification_refuses_uploader_exclusive_lock_before_native_work(tmp_pat
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: pytest.fail('native work bypassed lock'))
|
||||
try:
|
||||
result = runner.run_verify(runner.VerifyRequest(library, 'Block', tmp_path/'out'))
|
||||
assert result.status == 'BLOCKED' and not result.safe_to_continue
|
||||
assert result.status == 'FAIL' and result.safe_to_continue
|
||||
finally:
|
||||
handle.Close()
|
||||
|
||||
|
||||
def test_unsafe_verify_retains_lease_and_persistent_blocker(tmp_path, monkeypatch):
|
||||
def test_unsafe_verify_records_failure_without_persistent_library_blocker(tmp_path, monkeypatch):
|
||||
import json
|
||||
import cbb_refresh_verify.verify_runner as runner
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
evidence = tmp_path/'out'; evidence.mkdir()
|
||||
(evidence/'session-release.json').write_text(json.dumps({'library': str(library),
|
||||
'block': 'Block', 'worker_exited': True, 'safe_to_continue': True}))
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k:
|
||||
runner.VerifyResult('FAIL', safe_to_continue=False))
|
||||
runner.VerifyResult('FAIL', safe_to_continue=False, evidence_path=evidence/'result.json'))
|
||||
result = runner.run_verify(runner.VerifyRequest(library, 'Block', tmp_path/'out'))
|
||||
assert not result.safe_to_continue
|
||||
assert locks.blocker_path(library).is_file()
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
with locks.LibraryLock(library): pass
|
||||
# Simulate OS handle loss on process exit; persistent marker still blocks.
|
||||
with locks._guard:
|
||||
owner = locks._owners.pop(str((tmp_path/'.lib.cbb-upload.lock').resolve()).casefold(), None)
|
||||
if owner: owner['handle'].Close()
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
with locks.LibraryLock(library): pass
|
||||
assert not locks.blocker_path(library).exists()
|
||||
with locks.LibraryLock(library): pass
|
||||
|
||||
|
||||
def test_explicit_release_requires_fresh_proof_and_never_deletes_sidecar(tmp_path, monkeypatch):
|
||||
@@ -118,9 +115,8 @@ def test_explicit_release_requires_fresh_proof_and_never_deletes_sidecar(tmp_pat
|
||||
|
||||
def test_release_proof_checks_addresses_and_exclusive_databases(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import win32com.client
|
||||
from types import SimpleNamespace
|
||||
monkeypatch.setattr(win32com.client, 'GetObject', lambda *_: SimpleNamespace(ExecQuery=lambda *_: []))
|
||||
import cbb_refresh_verify.owner_probe as probe
|
||||
monkeypatch.setattr(probe, 'query_owners', lambda *_: [])
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
address = tmp_path/'database/cdbsvr/sAddress.adr'; address.parent.mkdir(parents=True)
|
||||
address.touch()
|
||||
@@ -138,6 +134,63 @@ def test_release_proof_checks_addresses_and_exclusive_databases(tmp_path, monkey
|
||||
assert proof['exclusive_files'] == [str(library)]
|
||||
|
||||
|
||||
def test_scoped_release_ignores_another_cbb_address(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import cbb_refresh_verify.owner_probe as probe
|
||||
monkeypatch.setattr(probe, 'query_owners', lambda *_: [])
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
other = tmp_path/'ReusableBlocksLP/Other/Work/database/cdbsvr/sAddress.adr'
|
||||
other.parent.mkdir(parents=True); other.touch()
|
||||
with locks._prove_library_released(library, block_name='Target') as proof:
|
||||
assert proof['addresses'] == []
|
||||
|
||||
|
||||
def test_release_probe_timeout_does_not_clear_retained_checkpoint(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import cbb_refresh_verify.owner_probe as probe
|
||||
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
|
||||
with locks.LibraryLock(library, safe_to_release=lambda: False) as lease: pass
|
||||
marker = locks.blocker_path(library)
|
||||
before = marker.read_bytes()
|
||||
def timeout(*args): raise RuntimeError('OWNER_QUERY_TIMEOUT')
|
||||
monkeypatch.setattr(probe, 'query_owners', timeout)
|
||||
try:
|
||||
with pytest.raises(RuntimeError, match='OWNER_QUERY_TIMEOUT'):
|
||||
locks.release_retained_library(library, tmp_path/'release')
|
||||
assert marker.read_bytes() == before
|
||||
finally:
|
||||
with locks._guard:
|
||||
owner = locks._owners.pop(lease.key, None)
|
||||
if owner: owner['handle'].Close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('name,command', [
|
||||
('cscript.exe', 'cscript.exe close_failed_block.vbs'),
|
||||
('python.exe', 'python.exe -m cbb_refresh_verify --repair-worker job.json'),
|
||||
])
|
||||
def test_release_proof_waits_for_late_operation_helpers(tmp_path, monkeypatch, name, command):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import cbb_refresh_verify.owner_probe as probe
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
monkeypatch.setattr(probe, 'query_owners', lambda names:
|
||||
[{'pid': 123456, 'name': name, 'command': command}] if name in names else [])
|
||||
with pytest.raises(locks.LibraryBusy, match='123456'):
|
||||
with locks._prove_library_released(library): pass
|
||||
|
||||
|
||||
def test_release_rechecks_owners_after_database_handles_are_acquired(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import cbb_refresh_verify.owner_probe as probe
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
calls = []
|
||||
def query(names):
|
||||
calls.append(1)
|
||||
return [] if len(calls) == 1 else [{'pid': 123456, 'name': 'cscript.exe', 'command': 'helper'}]
|
||||
monkeypatch.setattr(probe, 'query_owners', query)
|
||||
with pytest.raises(locks.LibraryBusy, match='123456'):
|
||||
with locks._prove_library_released(library): pass
|
||||
|
||||
|
||||
def test_public_verify_initializes_com_in_its_operation_thread(tmp_path, monkeypatch):
|
||||
import ctypes
|
||||
import cbb_refresh_verify.verify_runner as runner
|
||||
|
||||
@@ -1,81 +1,84 @@
|
||||
"""Exercise the production diagnosis gate; do not spoof callback names."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
"""Native occupancy must precede repair even when old addresses remain."""
|
||||
import pytest
|
||||
from test_maintenance_entry import case, no_native_launch
|
||||
from test_maintenance_entry import case, no_native_launch, startup_failure, run_legacy_maintenance
|
||||
from test_native_occupancy import output
|
||||
|
||||
|
||||
def diagnostic_result(req, *, error='', database=None):
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
root = req.evidence_dir/'probe'; root.mkdir(parents=True, exist_ok=True)
|
||||
result = VerifyResult('FAIL' if error else 'PASS', error_category=error,
|
||||
evidence_path=root/'result.json', safe_to_continue=not error)
|
||||
result.evidence_path.write_text('{}', encoding='utf-8')
|
||||
if error == 'ICDB_REPAIR_REQUIRED':
|
||||
record = {'error_code': error, 'scope': 'project', 'session': 'test-session',
|
||||
'database_path': str(database)}
|
||||
(root/'diagnostics').mkdir(exist_ok=True)
|
||||
(root/'diagnostics/icdb-recovery.json').write_text(json.dumps(record), encoding='utf-8')
|
||||
return result
|
||||
def inspection(target, *, fault=False):
|
||||
return {'inspection_only': True, 'repair_requested': False, 'native_pid': 777,
|
||||
'native_exit_code': 0, 'project': str(target.project), 'database': str(target.database),
|
||||
'output': output(target.project, target.database, fault=fault),
|
||||
'status': 'NOT_IN_USE', 'repair_required': fault, 'release': {'native_exited': True}}
|
||||
|
||||
|
||||
def test_diagnosis_holds_library_lock_and_healthy_never_repair(case, monkeypatch):
|
||||
@pytest.mark.parametrize('old_address', [False, True])
|
||||
def test_diagnosed_native_inspection_holds_lock_after_opening_pcb(case, monkeypatch, old_address):
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair, library_lock
|
||||
request, project, address = case
|
||||
address.unlink()
|
||||
def worker(req, **kw):
|
||||
key = library_lock.LibraryLock(req.lmc_file).key
|
||||
assert key in library_lock._owners
|
||||
if not old_address: address.unlink()
|
||||
calls = []
|
||||
def startup(req, **kw):
|
||||
assert req.diagnostic_only
|
||||
calls.append('open')
|
||||
return startup_failure(req)
|
||||
def native(target, root, **kw):
|
||||
assert calls == ['open']
|
||||
key = library_lock.LibraryLock(request.lmc_file).key
|
||||
assert library_lock._owners[key]['depth'] > 0
|
||||
assert req.diagnostic_only and not req.auto_repair and not req.maintenance
|
||||
assert not req.native_lm_verify and not req.libspec
|
||||
return diagnostic_result(req)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', worker)
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **k: pytest.fail('healthy repair'))
|
||||
result = runner.run_verify(request)
|
||||
assert result.status == 'PASS' and result.recovery_attempts == ()
|
||||
assert kw['inspection_only'] is True
|
||||
assert kw['timeout_seconds'] <= 30
|
||||
return inspection(target)
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', native)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', startup)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status == 'CHECKED' and result.recovery_attempts == ()
|
||||
assert result.library_flag == 'UNKNOWN'
|
||||
assert not library_lock.has_blocker(request.lmc_file)
|
||||
assert result.safe_to_continue is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fault', ['missing', 'generic', 'assertion', 'wrong_database', 'outside_evidence'])
|
||||
def test_unconfirmed_diagnosis_never_repairs(case, monkeypatch, fault):
|
||||
@pytest.mark.parametrize('fault', ['missing', 'generic', 'assertion', 'wrong_database', 'stale_verdict', 'not_exited'])
|
||||
def test_unconfirmed_native_inspection_never_repairs(case, monkeypatch, fault):
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair
|
||||
request, project, address = case
|
||||
address.unlink()
|
||||
def worker(req, **kw):
|
||||
if fault == 'assertion': raise AssertionError('diagnostic failure')
|
||||
if fault == 'missing': return runner.VerifyResult('PASS')
|
||||
if fault == 'generic': return diagnostic_result(req, error='DATABASE_SAFETY_STOP')
|
||||
if fault == 'outside_evidence':
|
||||
from dataclasses import replace
|
||||
req = replace(req, evidence_dir=request.evidence_dir/'old-run')
|
||||
return diagnostic_result(req, error='ICDB_REPAIR_REQUIRED',
|
||||
database=project.parent/('wrong' if fault == 'wrong_database' else 'database'))
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', worker)
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **k: pytest.fail('unconfirmed repair'))
|
||||
result = runner.run_verify(request)
|
||||
assert result.status != 'PASS' and result.recovery_attempts == ()
|
||||
def native(target, root, **kw):
|
||||
assert kw['inspection_only'] is True
|
||||
if fault == 'assertion': raise AssertionError('probe failed')
|
||||
if fault == 'missing': return {}
|
||||
record = inspection(target, fault=True)
|
||||
if fault == 'generic': record['output'] = 'DATABASE_SAFETY_STOP'
|
||||
if fault == 'wrong_database': record['database'] = str(project.parent/'other')
|
||||
if fault == 'stale_verdict': record['output'] += 'Checking if project is in use.'
|
||||
if fault == 'not_exited': record['release']['native_exited'] = False
|
||||
return record
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', native)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status == 'BLOCKED' and not result.recovery_attempts
|
||||
|
||||
|
||||
def test_diagnostic_fault_repairs_once_then_full_verification(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 test_native_repair import complete_native_success
|
||||
request, project, address = case
|
||||
address.unlink()
|
||||
calls = []
|
||||
def worker(req, **kw):
|
||||
calls.append('diagnose' if req.diagnostic_only else 'verify')
|
||||
if req.diagnostic_only:
|
||||
return diagnostic_result(req, error='ICDB_REPAIR_REQUIRED', database=project.parent/'database')
|
||||
assert req.post_repair_proof is not None and not req.auto_repair
|
||||
return runner.VerifyResult('PASS', library_flag='GREEN')
|
||||
def repair(target, *a, **kw):
|
||||
def native(target, root, **kw):
|
||||
if kw.get('inspection_only'):
|
||||
assert address.exists()
|
||||
calls.append('inspect')
|
||||
return inspection(target, fault=True)
|
||||
calls.append('repair')
|
||||
address.unlink() # Simulated native repair release only.
|
||||
return complete_native_success(target)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', worker)
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', repair)
|
||||
def verify(req, **kw):
|
||||
if req.diagnostic_only:
|
||||
calls.append('open')
|
||||
return startup_failure(req)
|
||||
assert req.post_repair_proof is not None and not req.diagnostic_only and not req.auto_repair
|
||||
calls.append('verify')
|
||||
return runner.VerifyResult('PASS', library_flag='GREEN')
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', native)
|
||||
monkeypatch.setattr(native_repair, 'repair_release_state', lambda req, target, result: result['release'])
|
||||
result = runner.run_verify(request)
|
||||
assert calls == ['diagnose', 'repair', 'verify']
|
||||
assert result.status == 'PASS' and len(result.recovery_attempts) == 1
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert calls == ['open', 'inspect', 'repair']
|
||||
assert result.status == 'REPAIRED' and len(result.recovery_attempts) == 1
|
||||
assert result.library_flag == 'UNKNOWN' and not result.recovery_attempts[0]['validation_passed']
|
||||
+101
-42
@@ -39,6 +39,8 @@ def case(tmp_path, monkeypatch):
|
||||
(work/'PCB/pcb.prj').write_text('KEY CentralLibrary "old.lmc"\n')
|
||||
monkeypatch.setattr(entry, 'assert_native_idle', lambda: None)
|
||||
request = VerifyRequest(library, 'IP101GR', tmp_path/'evidence', maintenance=True)
|
||||
monkeypatch.setattr('cbb_refresh_verify.verify_runner._run_verify_serialized',
|
||||
lambda req, **kw: startup_failure(req))
|
||||
yield request, project, address
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
key = locks.LibraryLock(library).key
|
||||
@@ -47,26 +49,46 @@ def case(tmp_path, monkeypatch):
|
||||
if owner: owner['handle'].Close()
|
||||
|
||||
|
||||
def startup_failure(request):
|
||||
"""Stub the PCB process boundary with a complete current native failure."""
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
database = request.lmc_file.parent/'ReusableBlocksLP'/request.block_name/'Work/database'
|
||||
return VerifyResult('FAIL', safe_to_continue=True, error_category='ICDB_REPAIR_REQUIRED',
|
||||
stderr=("The last server session on different server machine lost the connection to the database. "
|
||||
"Please use iCDB Project Backup 'Repair project' functionality to fix this issue. "
|
||||
f"Machine:[fixture-server] Path:[{database}] session:[fixture-current-session]"))
|
||||
|
||||
|
||||
def run_legacy_maintenance(request, **kwargs):
|
||||
"""Keep explicit recovery helper coverage separate from the batch-check API."""
|
||||
from cbb_refresh_verify import verify_runner as runner, maintenance_entry as entry
|
||||
if not request.maintenance:
|
||||
return runner.run_verify(request, **kwargs)
|
||||
return entry.run_diagnosed_maintenance(request,
|
||||
diagnose=lambda probe: runner.run_verify(probe, **kwargs),
|
||||
progress=kwargs.get('progress'), stop=kwargs.get('stop'))
|
||||
|
||||
|
||||
def patch_verification_after_fault(monkeypatch, runner, verify):
|
||||
"""Inject native startup evidence, then exercise the production repair gate."""
|
||||
def worker(req, **kwargs):
|
||||
if not req.diagnostic_only:
|
||||
return verify(req, **kwargs)
|
||||
project, pcb = runner.preflight(req)
|
||||
root = req.evidence_dir/'native-startup'; root.mkdir(parents=True, exist_ok=True)
|
||||
(root/'diagnostics').mkdir(exist_ok=True)
|
||||
(root/'diagnostics/icdb-recovery.json').write_text(json.dumps({
|
||||
'error_code': 'ICDB_REPAIR_REQUIRED', 'scope': 'project', 'session': 'fixture',
|
||||
'database_path': str(project.parent/'database')}), encoding='utf-8')
|
||||
evidence = root/'result.json'; evidence.write_text('{}', encoding='utf-8')
|
||||
return runner.VerifyResult('FAIL', error_category='ICDB_REPAIR_REQUIRED',
|
||||
safe_to_continue=False, evidence_path=evidence)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', worker)
|
||||
"""Inject only native process boundaries; production interprets the Output."""
|
||||
from cbb_refresh_verify import native_repair
|
||||
from test_native_occupancy import output
|
||||
repair = native_repair.run_native_repair
|
||||
def native(target, root, **kw):
|
||||
if not kw.get('inspection_only'):
|
||||
return repair(target, root, **kw)
|
||||
return {'inspection_only': True, 'repair_requested': False, 'native_pid': 777,
|
||||
'native_exit_code': 0, 'project': str(target.project), 'database': str(target.database),
|
||||
'output': output(target.project, target.database, fault=True),
|
||||
'status': 'NOT_IN_USE', 'repair_required': True, 'release': {'native_exited': True}}
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', native)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized',
|
||||
lambda req, **kw: startup_failure(req) if req.diagnostic_only else verify(req, **kw))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('pcb_config', ['standard', 'legacy_template'])
|
||||
@pytest.mark.parametrize('advertisement', ['present', 'absent'])
|
||||
def test_explicit_maintenance_enters_official_repair_once_without_lostsession_fabrication(case, monkeypatch, pcb_config, advertisement):
|
||||
def test_diagnosed_maintenance_enters_official_repair_once(case, monkeypatch, pcb_config, advertisement):
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair
|
||||
from test_native_repair import complete_native_success
|
||||
request, project, address = case
|
||||
@@ -96,9 +118,10 @@ def test_explicit_maintenance_enters_official_repair_once_without_lostsession_fa
|
||||
assert req.lmc_file == request.lmc_file and req.block_name == request.block_name
|
||||
return runner.VerifyResult('PASS', library_flag='GREEN')
|
||||
patch_verification_after_fault(monkeypatch, runner, verify)
|
||||
result = runner.run_verify(request)
|
||||
assert calls == ['repair', 'verify'] and result.status == 'PASS'
|
||||
assert result.recovery_attempts[0]['validation_passed'] is True
|
||||
result = run_legacy_maintenance(request)
|
||||
assert calls == ['repair'] and result.status == 'REPAIRED'
|
||||
assert result.recovery_attempts[0]['validation_passed'] is False
|
||||
assert result.library_flag == 'UNKNOWN'
|
||||
record = json.loads(result.evidence_path.read_text(encoding='utf-8'))
|
||||
assert record['operation'] == 'explicit_project_maintenance'
|
||||
assert 'session' not in record['maintenance_context']
|
||||
@@ -116,6 +139,34 @@ def test_addressless_target_binds_unique_project_and_rejects_new_address(case):
|
||||
with maintenance_target_guard(request, context): pass
|
||||
|
||||
|
||||
def test_guard_reuses_full_tree_scan_but_still_refreshes_before_yield(case, monkeypatch):
|
||||
from cbb_refresh_verify.maintenance_entry import maintenance_target_guard
|
||||
import cbb_refresh_verify.scoped_manifest as manifests
|
||||
request, project, _ = case
|
||||
scans = []
|
||||
original = manifests.scan_tree
|
||||
def scan(root, **kwargs):
|
||||
scans.append(Path(root))
|
||||
return original(root, **kwargs)
|
||||
monkeypatch.setattr(manifests, 'scan_tree', scan)
|
||||
with maintenance_target_guard(request): pass
|
||||
assert request.lmc_file.parent not in scans
|
||||
assert scans.count(project.parent) == 2
|
||||
|
||||
|
||||
def test_guard_rejects_new_native_database_appearing_during_checks(case, monkeypatch):
|
||||
import cbb_refresh_verify.maintenance_entry as entry
|
||||
request, _, _ = case
|
||||
calls = []
|
||||
def idle():
|
||||
calls.append(1)
|
||||
if len(calls) == 2:
|
||||
(request.lmc_file.parent/'new.lmc').write_bytes(b'new native store')
|
||||
monkeypatch.setattr(entry, 'assert_native_idle', idle)
|
||||
with pytest.raises(ValueError, match='MAINTENANCE_SOURCE_CHANGED'):
|
||||
with entry.maintenance_target_guard(request): pass
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reference', ['', 'KEY ProjectFile "../Other.prj"\n',
|
||||
'KEY ProjectFile "../IP101GR.prj"\nKEY ProjectFile "../IP101GR.prj"\n'])
|
||||
def test_addressless_target_requires_exact_pcb_back_reference(case, reference):
|
||||
@@ -172,12 +223,15 @@ def test_optional_pcb_project_appearance_invalidates_maintenance_proof(case):
|
||||
with maintenance_target_guard(request, before): pass
|
||||
|
||||
|
||||
def test_ordinary_verify_still_blocks_existing_address_without_repair(case, monkeypatch):
|
||||
def test_ordinary_verify_calls_native_verifier_despite_existing_address(case, monkeypatch):
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair
|
||||
request, _, address = case
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **k: pytest.fail('ordinary verify must not repair'))
|
||||
result = runner.run_verify(replace(request, maintenance=False))
|
||||
assert result.status == 'BLOCKED' and not result.safe_to_continue
|
||||
calls = []
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k:
|
||||
(calls.append('verify') or runner.VerifyResult('FAIL', stderr='native ICDB problem')))
|
||||
result = run_legacy_maintenance(replace(request, maintenance=False))
|
||||
assert calls == ['verify'] and result.status == 'FAIL' and result.safe_to_continue
|
||||
assert address.read_bytes() == b'old server address - preserved'
|
||||
|
||||
|
||||
@@ -205,7 +259,7 @@ def test_maintenance_guard_blocks_before_native(case, monkeypatch, obstacle):
|
||||
monkeypatch.setattr(entry, 'address_snapshot', mutate)
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **k: pytest.fail('guard bypass'))
|
||||
try:
|
||||
result = runner.run_verify(request)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status == 'BLOCKED' and not result.safe_to_continue
|
||||
assert result.error_stage == 'preflight'
|
||||
finally:
|
||||
@@ -254,7 +308,7 @@ def test_nonrepair_outcomes_never_verify_or_count_success(case, monkeypatch, sta
|
||||
'status': status, 'release': {'safe_to_continue': False}, 'detail': 'native result'})
|
||||
monkeypatch.setattr(native_repair, 'repair_release_state', lambda *a: {'safe_to_continue': False})
|
||||
patch_verification_after_fault(monkeypatch, runner, lambda *a, **k: pytest.fail('unsafe or nonrepair outcome reopened'))
|
||||
result = runner.run_verify(request)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status != 'PASS' and not result.safe_to_continue
|
||||
assert result.recovery_attempts[0]['status'] == status
|
||||
|
||||
@@ -268,7 +322,7 @@ def test_native_success_cannot_bypass_remaining_address(case, monkeypatch):
|
||||
# Native release queries remain mocked, actual address/exclusive checks stay real.
|
||||
monkeypatch.setattr('cbb_refresh_verify.mentor_adapter.pcb_processes', lambda: [])
|
||||
monkeypatch.setattr('cbb_refresh_verify.mentor_adapter._process_details', lambda name: [])
|
||||
result = runner.run_verify(request)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status != 'PASS' and not result.safe_to_continue
|
||||
|
||||
|
||||
@@ -285,7 +339,8 @@ def test_explicit_worker_requires_positive_native_idle_before_repair(tmp_path, m
|
||||
values['maintenance_context'] = {'library': str(tmp_path/'lib.lmc'), 'block': 'CBB1'}
|
||||
job.write_text(json.dumps(values))
|
||||
@contextmanager
|
||||
def guard(*args):
|
||||
def guard(*args, stop=None):
|
||||
assert stop is not None
|
||||
yield {'target': RepairTarget(Path(values['project']), Path(values['database']))}
|
||||
monkeypatch.setattr(entry, 'maintenance_target_guard', guard)
|
||||
monkeypatch.setattr(ui, '_native_output', lambda windows: output)
|
||||
@@ -294,7 +349,7 @@ def test_explicit_worker_requires_positive_native_idle_before_repair(tmp_path, m
|
||||
assert any(message == win32con.WM_COMMAND for _, message in actions) is expected
|
||||
|
||||
|
||||
def test_worker_rechecks_address_after_complete_backup_before_native_launch(tmp_path, monkeypatch):
|
||||
def test_worker_rechecks_address_after_access_probe_before_native_launch(tmp_path, monkeypatch):
|
||||
from test_native_repair import repair_worker_fixture
|
||||
import cbb_refresh_verify.maintenance_entry as entry
|
||||
from cbb_refresh_verify.native_repair import RepairTarget
|
||||
@@ -302,15 +357,19 @@ def test_worker_rechecks_address_after_complete_backup_before_native_launch(tmp_
|
||||
values = json.loads(job.read_text()); values['maintenance_context'] = {'library': str(tmp_path/'lib.lmc'), 'block': 'CBB1'}
|
||||
job.write_text(json.dumps(values))
|
||||
calls = []
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_repair.check_repair_access',
|
||||
lambda *_: calls.append('access'))
|
||||
@contextmanager
|
||||
def guard(*args):
|
||||
def guard(*args, stop=None):
|
||||
assert stop is not None
|
||||
calls.append('guard')
|
||||
if len(calls) == 2: raise ValueError('address changed during complete backup')
|
||||
assert calls == ['access', 'guard']
|
||||
raise ValueError('address changed after access probe')
|
||||
yield {'target': RepairTarget(Path(values['project']), Path(values['database']))}
|
||||
monkeypatch.setattr(entry, 'maintenance_target_guard', guard)
|
||||
monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **k: pytest.fail('mutation must stop native launch'))
|
||||
ui.repair_worker_main(job)
|
||||
assert calls == ['guard', 'guard']
|
||||
assert calls == ['access', 'guard']
|
||||
assert 'address changed' in json.loads((root/'repair-result.json').read_text())['detail']
|
||||
|
||||
|
||||
@@ -342,11 +401,11 @@ def test_independent_cbb_address_does_not_select_or_block_current_project(case):
|
||||
|
||||
|
||||
@pytest.mark.parametrize('status,complete,expected_safe', [
|
||||
('RESTORED_REVIEW_REQUIRED', True, False), ('DATABASE_BUSY', True, False),
|
||||
('UNKNOWN_DIALOG', True, False), ('UNCONFIRMED', True, False),
|
||||
('MISSING_HEALTHY_BACKUP', False, False), ('NATIVE_REPAIR_FAILED', False, False),
|
||||
('RESTORED_REVIEW_REQUIRED', True, True), ('DATABASE_BUSY', True, True),
|
||||
('UNKNOWN_DIALOG', True, True), ('UNCONFIRMED', True, True),
|
||||
('MISSING_HEALTHY_BACKUP', False, True), ('NATIVE_REPAIR_FAILED', False, True),
|
||||
('MISSING_HEALTHY_BACKUP', True, True), ('NATIVE_REPAIR_FAILED', True, True)])
|
||||
def test_physical_release_alone_does_not_authorize_queue(case, monkeypatch, status, complete, expected_safe):
|
||||
def test_failed_content_does_not_block_other_items_after_actual_release(case, monkeypatch, status, complete, expected_safe):
|
||||
from cbb_refresh_verify import native_repair, verify_runner as runner, library_lock
|
||||
from test_native_repair import complete_native_success
|
||||
request, _, address = case
|
||||
@@ -359,7 +418,7 @@ def test_physical_release_alone_does_not_authorize_queue(case, monkeypatch, stat
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', repair)
|
||||
monkeypatch.setattr(native_repair, 'repair_release_state', lambda req, target, result: result['release'])
|
||||
patch_verification_after_fault(monkeypatch, runner, lambda *a, **k: pytest.fail('nonrepair outcome reopened'))
|
||||
result = runner.run_verify(request)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status != 'PASS'
|
||||
assert result.safe_to_continue is expected_safe
|
||||
assert result.recovery_attempts[0]['status'] == status
|
||||
@@ -378,11 +437,11 @@ def test_successful_icdb_repair_then_version_choice_reports_partial_completion(c
|
||||
patch_verification_after_fault(monkeypatch, runner, lambda *a, **k: runner.VerifyResult('FAIL',
|
||||
error_category='PCB_VERSION_CHOICE_REQUIRED', stderr='PCB版本待选:最后用户保存/自动保存 2026/9/24 23:06',
|
||||
safe_to_continue=False, evidence_path=request.evidence_dir/'verify/result.json'))
|
||||
result = runner.run_verify(request)
|
||||
assert result.status == 'FAIL' and not result.safe_to_continue
|
||||
assert 'ICDB原生修复已完成' in result.stderr and '尚未校验通过' in result.stderr
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status == 'REPAIRED' and result.safe_to_continue
|
||||
assert '待单独校验' in result.stdout
|
||||
assert result.recovery_attempts[0]['native_status'] == 'REPAIRED'
|
||||
assert result.recovery_attempts[0]['status'] == 'PCB_VERSION_CHOICE_REQUIRED'
|
||||
assert result.recovery_attempts[0]['status'] == 'REPAIRED_UNVERIFIED'
|
||||
assert result.recovery_attempts[0]['validation_passed'] is False
|
||||
|
||||
|
||||
@@ -399,7 +458,7 @@ def test_user_chosen_pcb_history_is_not_reported_as_lossless_repair(case, monkey
|
||||
'choice': 'last_user_saved', 'date': '2026/9/24 23:06', 'confirm_sent': True, 'historical_restore': True}))
|
||||
return runner.VerifyResult('PASS', library_flag='GREEN', evidence_path=root/'result.json')
|
||||
patch_verification_after_fault(monkeypatch, runner, verify)
|
||||
result = runner.run_verify(request)
|
||||
assert result.status == 'PASS'
|
||||
assert result.recovery_attempts[0]['status'] == 'RESTORED_REVIEW_REQUIRED'
|
||||
assert result.recovery_attempts[0]['pcb_version']['choice'] == 'last_user_saved'
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status == 'REPAIRED' and result.library_flag == 'UNKNOWN'
|
||||
assert result.recovery_attempts[0]['status'] == 'REPAIRED_UNVERIFIED'
|
||||
assert not (request.evidence_dir/'verify').exists()
|
||||
@@ -111,3 +111,29 @@ def test_diagnostic_waits_for_normal_exit_after_close_returns(tmp_path, monkeypa
|
||||
lambda *a, **kw: {'status': 'CLOSED'})
|
||||
assert execute()['status'] == 'PASS'
|
||||
assert len(observations) >= 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize('when', ['document_ready', 'closing'])
|
||||
def test_diagnostic_checks_late_startup_errors_before_declaring_healthy(tmp_path, monkeypatch, when):
|
||||
from cbb_refresh_verify import mentor_adapter as adapter
|
||||
job, events, execute = diagnostic_worker(tmp_path, monkeypatch)
|
||||
job['diagnostic_only'] = True
|
||||
source = Path(job['pcb']).parent/'LogFiles/PCBLogFile.txt'
|
||||
def late_fault():
|
||||
source.parent.mkdir(exist_ok=True)
|
||||
source.write_text("The last server session on different server machine lost the connection to the database. "
|
||||
f"Machine:[fixture] Path:[{Path(job['project']).parent/'database'}] session:[current]", encoding='utf-8')
|
||||
def document(*a, **kw):
|
||||
if when == 'document_ready': late_fault()
|
||||
return None, None, object()
|
||||
closes = []
|
||||
def close(*a, **kw):
|
||||
closes.append(True)
|
||||
if when == 'closing': late_fault()
|
||||
return {'status': 'CLOSED'}
|
||||
monkeypatch.setattr('cbb_refresh_verify.pcb_bridge.wait_for_target_document', document)
|
||||
monkeypatch.setattr('cbb_refresh_verify.failed_session.close_failed_document', close)
|
||||
with pytest.raises(RuntimeError, match='ICDB_REPAIR_REQUIRED'):
|
||||
execute()
|
||||
assert len(closes) == 1
|
||||
assert not any(e['stage'] == 'diagnostic_complete' for e in events)
|
||||
@@ -0,0 +1,185 @@
|
||||
"""Project Backup is reached only after a current, released PCB startup fault."""
|
||||
from dataclasses import replace
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from test_maintenance_entry import case, no_native_launch, run_legacy_maintenance
|
||||
|
||||
|
||||
def fault_text(database):
|
||||
return ("The last server session on different server machine lost the connection to the database. "
|
||||
"Please use iCDB Project Backup 'Repair project' functionality to fix this issue. "
|
||||
f"Machine:[fixture-server] Path:[{database}] session:[fixture-current-session]")
|
||||
|
||||
|
||||
def install_probe(monkeypatch, result, calls):
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
def probe(request, **kwargs):
|
||||
assert request.diagnostic_only and not request.maintenance and not request.auto_repair
|
||||
assert not request.native_lm_verify and request.post_repair_proof is None
|
||||
calls.append('open')
|
||||
return result
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', probe)
|
||||
|
||||
|
||||
def forbid_backup(monkeypatch):
|
||||
from cbb_refresh_verify import native_repair
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair',
|
||||
lambda *a, **k: pytest.fail('Project Backup launched without a current matching startup fault'))
|
||||
|
||||
|
||||
def test_healthy_startup_skips_project_backup_even_with_old_address(case, monkeypatch):
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
request, _, address = case
|
||||
calls = []
|
||||
install_probe(monkeypatch, runner.VerifyResult('PASS', safe_to_continue=True), calls)
|
||||
forbid_backup(monkeypatch)
|
||||
result = run_legacy_maintenance(replace(request, native_lm_verify=True))
|
||||
assert calls == ['open']
|
||||
assert result.status == 'CHECKED' and result.library_flag == 'UNKNOWN'
|
||||
assert result.recovery_attempts == () and result.safe_to_continue
|
||||
assert address.read_bytes() == b'old server address - preserved'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('message', ['License unavailable', 'Could not run server',
|
||||
'COM 已连接,尚无目标文档', 'ICDB_REPAIR_REQUIRED',
|
||||
'PCB 文件损坏', 'Lost connection to server'])
|
||||
def test_generic_startup_errors_remain_failures_without_backup(case, monkeypatch, message):
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
request, _, _ = case
|
||||
calls = []
|
||||
failed = runner.VerifyResult('FAIL', stderr=message, safe_to_continue=True)
|
||||
install_probe(monkeypatch, failed, calls)
|
||||
forbid_backup(monkeypatch)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert calls == ['open'] and result == failed
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reason', ['shared', 'other_project', 'no_session', 'unreleased', 'timeout', 'cancelled'])
|
||||
def test_unmatched_or_unreleased_icdb_fault_never_enters_backup(case, monkeypatch, reason):
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
request, project, _ = case
|
||||
database = (project.parent/'database' if reason not in ('shared', 'other_project') else
|
||||
request.lmc_file.parent/('SymbolLibs/__ReusableBlocksSymb' if reason == 'shared'
|
||||
else 'ReusableBlocksLP/Other/Work/database'))
|
||||
if not database.exists(): database.mkdir(parents=True); (database/'icdb.dat').touch()
|
||||
text = fault_text(database)
|
||||
if reason == 'no_session': text = text.replace('session:[fixture-current-session]', '')
|
||||
failed = runner.VerifyResult('TIMEOUT' if reason == 'timeout' else
|
||||
'CANCELLED' if reason == 'cancelled' else 'FAIL', stderr=text,
|
||||
error_category='ICDB_REPAIR_REQUIRED', safe_to_continue=reason != 'unreleased')
|
||||
calls = []
|
||||
install_probe(monkeypatch, failed, calls)
|
||||
forbid_backup(monkeypatch)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert calls == ['open'] and result.status == failed.status
|
||||
assert not result.recovery_attempts
|
||||
assert result.safe_to_continue is failed.safe_to_continue
|
||||
|
||||
|
||||
def test_only_current_matching_fault_enters_native_maintenance(case, monkeypatch):
|
||||
from cbb_refresh_verify import verify_runner as runner, maintenance_entry as entry
|
||||
request, project, _ = case
|
||||
calls = []
|
||||
failed = runner.VerifyResult('FAIL', stderr=fault_text(project.parent/'database'),
|
||||
error_category='ICDB_REPAIR_REQUIRED', safe_to_continue=True)
|
||||
install_probe(monkeypatch, failed, calls)
|
||||
def maintain(req, *, diagnosed_target, startup_result, **kwargs):
|
||||
assert diagnosed_target.project == project and diagnosed_target.database == project.parent/'database'
|
||||
assert startup_result == failed
|
||||
calls.append('maintenance')
|
||||
return runner.VerifyResult('REPAIRED')
|
||||
monkeypatch.setattr(entry, 'run_existing_address_maintenance', maintain)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert calls == ['open', 'maintenance'] and result.status == 'REPAIRED'
|
||||
|
||||
|
||||
def test_old_saved_diagnosis_does_not_turn_generic_startup_failure_into_repair(case, monkeypatch):
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
request, project, _ = case
|
||||
root = request.evidence_dir/'old'; (root/'diagnostics').mkdir(parents=True)
|
||||
(root/'diagnostics/icdb-recovery.json').write_text(json.dumps({
|
||||
'error_code': 'ICDB_REPAIR_REQUIRED', 'native_message': fault_text(project.parent/'database')}))
|
||||
calls = []
|
||||
failure = runner.VerifyResult('FAIL', stderr='License unavailable', evidence_path=root/'result.json')
|
||||
install_probe(monkeypatch, failure, calls)
|
||||
forbid_backup(monkeypatch)
|
||||
assert run_legacy_maintenance(request) == failure
|
||||
assert calls == ['open']
|
||||
|
||||
|
||||
def test_native_admission_cannot_switch_the_diagnosed_database(case, monkeypatch):
|
||||
from cbb_refresh_verify import maintenance_entry as entry, native_repair
|
||||
from test_maintenance_entry import startup_failure
|
||||
request, project, _ = case
|
||||
forbid_backup(monkeypatch)
|
||||
result = entry.run_existing_address_maintenance(request,
|
||||
diagnosed_target=native_repair.RepairTarget(project, project.parent/'other'),
|
||||
startup_result=startup_failure(request))
|
||||
assert result.status == 'FAIL' and result.safe_to_continue
|
||||
assert result.error_category == 'ICDB_TARGET_MISMATCH'
|
||||
|
||||
|
||||
def test_equivalent_diagnosed_path_keeps_the_native_launch_path(case, monkeypatch):
|
||||
from cbb_refresh_verify import maintenance_entry as entry, native_repair
|
||||
from test_maintenance_entry import startup_failure
|
||||
from test_maintenance_diagnosis import inspection
|
||||
request, project, _ = case
|
||||
seen = []
|
||||
def inspect(target, *args, **kwargs):
|
||||
assert kwargs['inspection_only'] is True
|
||||
seen.append(target.project)
|
||||
return inspection(target)
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', inspect)
|
||||
alias = project.parent/'unused/..'
|
||||
result = entry.run_existing_address_maintenance(request,
|
||||
diagnosed_target=native_repair.RepairTarget(alias/project.name, alias/'database'),
|
||||
startup_result=startup_failure(request))
|
||||
assert result.status == 'CHECKED' and result.safe_to_continue, result
|
||||
assert seen == [project]
|
||||
|
||||
|
||||
def test_unsafe_startup_success_is_not_reported_as_healthy(case, monkeypatch):
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
request, _, _ = case
|
||||
install_probe(monkeypatch, runner.VerifyResult('PASS', safe_to_continue=False), [])
|
||||
forbid_backup(monkeypatch)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status == 'FAIL' and not result.safe_to_continue
|
||||
|
||||
|
||||
def test_report_write_failure_does_not_block_a_released_healthy_project(case, monkeypatch):
|
||||
from pathlib import Path
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
request, _, _ = case
|
||||
evidence = request.evidence_dir/'result.json'; evidence.parent.mkdir(); evidence.write_text('{}')
|
||||
install_probe(monkeypatch, runner.VerifyResult('PASS', evidence_path=evidence), [])
|
||||
forbid_backup(monkeypatch)
|
||||
write = Path.write_text
|
||||
def unavailable(path, *args, **kwargs):
|
||||
if path.name == 'maintenance-result.json': raise PermissionError('report unavailable')
|
||||
return write(path, *args, **kwargs)
|
||||
monkeypatch.setattr(Path, 'write_text', unavailable)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status == 'CHECKED' and result.safe_to_continue
|
||||
assert result.evidence_path == evidence and evidence.read_text() == '{}'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('before_open', [True, False])
|
||||
def test_cancelled_startup_diagnosis_never_requests_repair(case, monkeypatch, before_open):
|
||||
from threading import Event
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
from test_maintenance_entry import startup_failure
|
||||
request, _, _ = case
|
||||
stop = Event()
|
||||
if before_open: stop.set()
|
||||
calls = []
|
||||
def probe(req, **kw):
|
||||
calls.append('open'); stop.set()
|
||||
return startup_failure(req)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', probe)
|
||||
forbid_backup(monkeypatch)
|
||||
result = run_legacy_maintenance(request, stop=stop)
|
||||
assert result.status == 'CANCELLED' and result.safe_to_continue
|
||||
assert calls == ([] if before_open else ['open'])
|
||||
@@ -24,15 +24,18 @@ def test_only_confirmed_maintenance_sets_explicit_flag(qtbot, tmp_path, monkeypa
|
||||
|
||||
|
||||
@pytest.mark.parametrize('marker_kind', ['valid', 'foreign', 'malformed'])
|
||||
def test_blocked_library_recovery_view_is_filesystem_only_and_maintenance_only(qtbot, tmp_path, monkeypatch, marker_kind):
|
||||
def test_old_checkpoint_does_not_force_maintenance_or_disable_verify(qtbot, tmp_path, monkeypatch, marker_kind):
|
||||
from cbb_refresh_verify.library_lock import LibraryLock, blocker_path, _owners, _guard
|
||||
from cbb_refresh_verify.ui.main_window import MainWindow
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
from cbb_refresh_verify.models import LibraryReadResult, CbbRecord
|
||||
import cbb_refresh_verify.ui.main_window as ui
|
||||
library = tmp_path/'library/mentor.lmc'; library.parent.mkdir(); library.touch()
|
||||
(library.parent/'ReusableBlocksLP/IP101GR').mkdir(parents=True)
|
||||
with LibraryLock(library, safe_to_release=lambda: False) as lock: pass
|
||||
with _guard: _owners.pop(lock.key)['handle'].Close()
|
||||
with _guard:
|
||||
owner = _owners.pop(lock.key, None)
|
||||
if owner: owner['handle'].Close()
|
||||
marker = blocker_path(library)
|
||||
if marker_kind == 'malformed': marker.write_text('{}')
|
||||
if marker_kind == 'foreign':
|
||||
@@ -40,31 +43,26 @@ def test_blocked_library_recovery_view_is_filesystem_only_and_maintenance_only(q
|
||||
marker.write_text(json.dumps(record))
|
||||
monkeypatch.setattr(ui, 'preflight_skip_reason', lambda *a: None)
|
||||
calls = []
|
||||
window = MainWindow(reader=lambda *a: pytest.fail('blocked view called native reader'),
|
||||
window = MainWindow(reader=lambda *a: LibraryReadResult((CbbRecord('IP101GR', 'Reusable Blocks', status='PENDING'),)),
|
||||
verifier=lambda req: (calls.append(req) or VerifyResult('BLOCKED', safe_to_continue=False)),
|
||||
status_refresher=lambda *a: pytest.fail('unsafe view refreshed native status'), data_root=tmp_path/'data')
|
||||
status_refresher=lambda *a: {'IP101GR': 'PENDING'}, data_root=tmp_path/'data')
|
||||
qtbot.addWidget(window)
|
||||
window.lmc_edit.setText(str(library)); window.load_library()
|
||||
qtbot.waitUntil(lambda: not window.busy)
|
||||
assert window.release_library_button.isEnabled()
|
||||
if marker_kind != 'valid':
|
||||
assert window.loaded_path is None and not window.icdb_repair_button.isEnabled()
|
||||
return
|
||||
assert window.visible_records()[0].name == 'IP101GR'
|
||||
assert window.visible_records()[0].status == 'UNKNOWN'
|
||||
assert '未确认' in window.status_label.text()
|
||||
assert 'ICDB' in window.management_capability_label.text()
|
||||
assert '会话' in window.add_button.toolTip()
|
||||
assert window.visible_records()[0].status == 'PENDING'
|
||||
assert not window._maintenance_recovery_view
|
||||
window.select_visible_button.click()
|
||||
assert window.icdb_repair_button.isEnabled()
|
||||
assert not any(button.isEnabled() for button in (window.batch_button, window.selected_batch_button,
|
||||
window.backup_restore_button, window.add_button, window.update_button, window.remove_button))
|
||||
window.verify_all(); window.verify_selected(); window.restore_backup(); window.manage_cbb('remove')
|
||||
assert window.refresh_affected_records(['IP101GR']) is False
|
||||
assert calls == [] and not window.busy
|
||||
assert window.batch_button.isEnabled() and window.selected_batch_button.isEnabled()
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
|
||||
window.verify_selected(); qtbot.waitUntil(lambda: not window.busy)
|
||||
assert len(calls) == 1 and calls[0].maintenance is False
|
||||
assert window.selected_batch_button.isEnabled()
|
||||
window.repair_icdb_all(); qtbot.waitUntil(lambda: not window.busy)
|
||||
assert len(calls) == 1 and calls[0].maintenance is True
|
||||
assert len(calls) == 2 and calls[1].maintenance is True
|
||||
assert marker.exists()
|
||||
|
||||
|
||||
def test_maintenance_summary_exposes_first_failure_reason(qtbot, tmp_path):
|
||||
@@ -75,8 +73,12 @@ def test_maintenance_summary_exposes_first_failure_reason(qtbot, tmp_path):
|
||||
window._global_icdb_run = True
|
||||
detail = 'MAINTENANCE_TARGET_UNCONFIRMED: PCB 引用与当前工程不一致'
|
||||
window._batch_done(([VerifyResult('BLOCKED', stderr=detail, safe_to_continue=False)], tmp_path/'batch.log'))
|
||||
assert detail in window.summary.text()
|
||||
assert detail in window.status_label.text()
|
||||
assert detail in window.summary.detailedText()
|
||||
assert detail in window.output.toPlainText()
|
||||
assert detail not in window.summary.text()
|
||||
assert str(tmp_path) not in window.summary.text()
|
||||
assert detail not in window.status_label.text()
|
||||
assert '无法确认 1' in window.summary.text()
|
||||
|
||||
|
||||
def test_safe_maintenance_reloads_authoritative_catalog_after_worker_finishes(qtbot, tmp_path, monkeypatch):
|
||||
@@ -88,11 +90,13 @@ def test_safe_maintenance_reloads_authoritative_catalog_after_worker_finishes(qt
|
||||
library = tmp_path/'library/mentor.lmc'; library.parent.mkdir(); library.touch()
|
||||
(library.parent/'ReusableBlocksLP/IP101GR').mkdir(parents=True)
|
||||
with LibraryLock(library, safe_to_release=lambda: False) as lease: pass
|
||||
with _guard: _owners.pop(lease.key)['handle'].Close()
|
||||
with _guard:
|
||||
owner = _owners.pop(lease.key, None)
|
||||
if owner: owner['handle'].Close()
|
||||
reads = []
|
||||
def reader(path):
|
||||
reads.append(path)
|
||||
return LibraryReadResult((CbbRecord('IP101GR', 'Reusable Blocks', status='READY'),))
|
||||
return LibraryReadResult((CbbRecord('IP101GR', 'Reusable Blocks', status='PENDING'),))
|
||||
def verify(req):
|
||||
assert req.maintenance
|
||||
blocker_path(library).unlink() # Simulate normal cleanup at the injected boundary.
|
||||
@@ -100,12 +104,12 @@ def test_safe_maintenance_reloads_authoritative_catalog_after_worker_finishes(qt
|
||||
monkeypatch.setattr(ui, 'preflight_skip_reason', lambda *a: None)
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
|
||||
window = MainWindow(reader=reader, verifier=verify, data_root=tmp_path/'data',
|
||||
status_refresher=lambda *a: pytest.fail('recovery view must reload after worker completion'))
|
||||
status_refresher=lambda *a: {'IP101GR': 'READY'})
|
||||
qtbot.addWidget(window)
|
||||
window.lmc_edit.setText(str(library)); window.load_library(); qtbot.waitUntil(lambda: not window.busy)
|
||||
assert reads == []
|
||||
assert len(reads) == 1
|
||||
window.search_edit.setText('IP101')
|
||||
window.repair_icdb_all()
|
||||
qtbot.waitUntil(lambda: not window.busy and bool(reads))
|
||||
qtbot.waitUntil(lambda: not window.busy)
|
||||
assert window.visible_records()[0].status == 'READY'
|
||||
assert not window._maintenance_recovery_view and window.search_edit.text() == 'IP101'
|
||||
@@ -80,19 +80,20 @@ def test_restart_shows_unfinished_without_starting_worker(qtbot, tmp_path):
|
||||
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 cbb_refresh_verify.library_lock as locks
|
||||
from cbb_refresh_verify.ui.main_window import MainWindow
|
||||
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
|
||||
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)
|
||||
window.lmc_edit.setText(str(library)); window.load_library()
|
||||
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 '释放检查' in window.status_label.text()
|
||||
assert locks.blocker_path(library).read_text() == '{}'
|
||||
calls = []
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
|
||||
monkeypatch.setattr(locks, 'release_retained_library', lambda *a:
|
||||
|
||||
@@ -19,7 +19,7 @@ def test_management_prompts_for_manual_backup_and_cancel_starts_nothing(qtbot, t
|
||||
assert '完整备份与检查点' not in seen[0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('action', ['verify_all', 'verify_selected', 'repair_icdb_all'])
|
||||
@pytest.mark.parametrize('action', ['verify_all', 'verify_selected'])
|
||||
def test_batch_prompts_once_for_manual_backup_and_cancel_does_not_start(qtbot, tmp_path, monkeypatch, action):
|
||||
from cbb_refresh_verify.ui.main_window import MainWindow
|
||||
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
"""Native backup entry: user owns version choice, restoration and confirmation."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import win32con
|
||||
import win32file
|
||||
|
||||
|
||||
def project_fixture(tmp_path):
|
||||
from cbb_refresh_verify.verify_runner import VerifyRequest
|
||||
library = tmp_path/'library/library.lmc'; library.parent.mkdir(); library.touch()
|
||||
work = library.parent/'ReusableBlocksLP/Block/Work'; work.mkdir(parents=True)
|
||||
project = work/'Block.prj'; project.write_text('KEY iCDBDir "database"\n')
|
||||
return VerifyRequest(library, 'Block', tmp_path/'evidence'), project
|
||||
|
||||
|
||||
def test_backup_entry_can_open_project_without_layout_data(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import native_backup as native
|
||||
request, project = project_fixture(tmp_path)
|
||||
executable = tmp_path/'iCDBProjectBackup.exe'; executable.touch()
|
||||
monkeypatch.setattr(native, 'native_backup_executable', lambda *_: executable)
|
||||
calls = []
|
||||
monkeypatch.setattr(native.subprocess, 'Popen', lambda command, **kw:
|
||||
(calls.append(command) or SimpleNamespace(pid=123, poll=lambda: None)))
|
||||
session = native.launch_native_backup(request)
|
||||
record = json.loads(session.job.read_text('utf-8'))
|
||||
assert record['project'] == str(project)
|
||||
assert calls[0][-2] == '--native-backup-worker'
|
||||
assert calls[0][-1] == str(session.job)
|
||||
assert session.library == request.lmc_file and session.block == 'Block'
|
||||
|
||||
|
||||
def test_native_session_closure_does_not_claim_restore_success(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import native_backup as native
|
||||
from cbb_refresh_verify.library_lock import LibraryLock
|
||||
request, project = project_fixture(tmp_path)
|
||||
executable = tmp_path/'iCDBProjectBackup.exe'; executable.touch()
|
||||
monkeypatch.setattr(native, 'native_backup_executable', lambda *_: executable)
|
||||
job = request.evidence_dir/'request.json'; job.parent.mkdir()
|
||||
job.write_text(json.dumps({'library': str(request.lmc_file), 'block': 'Block',
|
||||
'project': str(project), 'mentor_bin': ''}))
|
||||
calls = []
|
||||
class NativeProcess:
|
||||
pid = 456
|
||||
def __init__(self, command, cwd):
|
||||
calls.append(command)
|
||||
lock = LibraryLock(request.lmc_file)
|
||||
with pytest.raises(Exception):
|
||||
win32file.CreateFile(str(lock.path), win32con.GENERIC_READ | win32con.GENERIC_WRITE,
|
||||
0, None, win32con.OPEN_ALWAYS, 0, None)
|
||||
def poll(self): return 0
|
||||
def session_pids(self): return []
|
||||
def close(self): pass
|
||||
assert native.native_backup_worker_main(job, process_factory=NativeProcess) == 0
|
||||
assert calls == [[str(executable), '-p', str(project)]]
|
||||
result = json.loads(job.with_name('result.json').read_text('utf-8'))
|
||||
assert result['status'] == 'CLOSED' and result['restore_confirmed'] is False
|
||||
assert result['native_exit_code'] == 0 and result['safe_to_continue'] is True
|
||||
with LibraryLock(request.lmc_file): pass
|
||||
|
||||
|
||||
def test_changed_project_identity_is_rejected_before_native_launch(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import native_backup as native
|
||||
request, project = project_fixture(tmp_path)
|
||||
job = request.evidence_dir/'request.json'; job.parent.mkdir()
|
||||
job.write_text(json.dumps({'library': str(request.lmc_file), 'block': 'Block',
|
||||
'project': str(project.parent/'Other.prj'), 'mentor_bin': ''}))
|
||||
assert native.native_backup_worker_main(job,
|
||||
process_factory=lambda *a, **k: pytest.fail('native launch on mismatched project')) == 1
|
||||
assert json.loads(job.with_name('result.json').read_text('utf-8'))['status'] == 'FAILED'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('all_evidence_failed', [False, True])
|
||||
def test_state_log_failure_does_not_abandon_live_native_session(tmp_path, monkeypatch, all_evidence_failed):
|
||||
from cbb_refresh_verify import native_backup as native, management
|
||||
request, project = project_fixture(tmp_path)
|
||||
executable = tmp_path/'iCDBProjectBackup.exe'; executable.touch()
|
||||
monkeypatch.setattr(native, 'native_backup_executable', lambda *_: executable)
|
||||
job = request.evidence_dir/'request.json'; job.parent.mkdir()
|
||||
job.write_text(json.dumps({'library': str(request.lmc_file), 'block': 'Block',
|
||||
'project': str(project), 'mentor_bin': ''}))
|
||||
write = management._write_json
|
||||
def broken_state(path, value):
|
||||
if all_evidence_failed or Path(path).name == 'state.json': raise OSError('state log unavailable')
|
||||
write(path, value)
|
||||
monkeypatch.setattr(management, '_write_json', broken_state)
|
||||
observations = []
|
||||
class NativeProcess:
|
||||
pid = 456
|
||||
def __init__(self, *a): pass
|
||||
def poll(self): return 0
|
||||
def session_pids(self):
|
||||
observations.append(True)
|
||||
return [456] if len(observations) == 1 else []
|
||||
def close(self): pass
|
||||
assert native.native_backup_worker_main(job, process_factory=NativeProcess) == 0
|
||||
assert len(observations) >= 2
|
||||
if not all_evidence_failed:
|
||||
assert json.loads(job.with_name('result.json').read_text('utf-8'))['status'] == 'CLOSED'
|
||||
|
||||
|
||||
def test_native_backup_ui_keeps_catalog_interactive_and_refreshes_after_close(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
requests, refreshes = [], []
|
||||
result = tmp_path/'native/result.json'; result.parent.mkdir()
|
||||
job = result.with_name('request.json'); job.write_text('{}')
|
||||
session = SimpleNamespace(library=Path('test.lmc'), block='Beta', job=job,
|
||||
process=SimpleNamespace(poll=lambda: None))
|
||||
window = load_window(qtbot, tmp_path, monkeypatch,
|
||||
native_backup_launcher=lambda req: (requests.append(req) or session),
|
||||
verifier=lambda _: pytest.fail('native backup must not run Verify'),
|
||||
status_refresher=lambda names, _: (refreshes.append(names) or {n: 'PENDING' for n in names}))
|
||||
window.search_edit.setText('Beta'); window.select_visible_button.click()
|
||||
assert window.native_backup_button.isEnabled()
|
||||
window.native_backup_button.click(); qtbot.waitUntil(lambda: not window.busy)
|
||||
assert len(requests) == 1 and requests[0].block_name == 'Beta'
|
||||
assert window.search_edit.isEnabled() and window.section_tabs.isEnabled()
|
||||
window.section_tabs.setCurrentIndex(2)
|
||||
window.search_edit.setText('Gamma')
|
||||
assert not window.busy
|
||||
result.write_text(json.dumps({'status': 'CLOSED', 'safe_to_continue': True,
|
||||
'library': str(session.library), 'block': session.block, 'native_exit_code': 0,
|
||||
'restore_confirmed': False}))
|
||||
session.process.poll = lambda: 0
|
||||
window._poll_native_backup()
|
||||
qtbot.waitUntil(lambda: not window.busy)
|
||||
assert refreshes == [('Beta',)]
|
||||
assert window.search_edit.text() == 'Gamma'
|
||||
assert 'PASS' not in window.cbb_table.item(window._row_by_name['Beta'], 3).text()
|
||||
|
||||
|
||||
def test_native_backup_selection_requires_one_visible_non_ready_item(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
window = load_window(qtbot, tmp_path, monkeypatch,
|
||||
native_backup_launcher=lambda _: pytest.fail('unexpected launch'))
|
||||
assert not window.native_backup_button.isEnabled()
|
||||
|
||||
|
||||
def test_native_backup_can_use_current_non_ready_row_without_checkbox(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
window = load_window(qtbot, tmp_path, monkeypatch,
|
||||
native_backup_launcher=lambda _: pytest.fail('unexpected launch'))
|
||||
row = window._row_by_name['Beta']
|
||||
window.cbb_table.setCurrentCell(row, 0)
|
||||
window._update()
|
||||
assert window.native_backup_button.isEnabled()
|
||||
window.search_edit.setText('Alpha'); window.select_visible_button.click()
|
||||
assert not window.native_backup_button.isEnabled()
|
||||
window.search_edit.clear(); window.select_visible_button.click()
|
||||
assert not window.native_backup_button.isEnabled()
|
||||
|
||||
|
||||
def test_closing_app_keeps_manual_native_window_and_mapping(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
window = load_window(qtbot, tmp_path, monkeypatch)
|
||||
retained = []
|
||||
lease = SimpleNamespace(retain_for_recovery=lambda: retained.append(True),
|
||||
close=lambda: pytest.fail('mapping released before native session ends'))
|
||||
session = SimpleNamespace(library=Path('test.lmc'), block='Beta', path_lease=lease,
|
||||
process=SimpleNamespace(poll=lambda: None, terminate=lambda: pytest.fail('native UI terminated')))
|
||||
window.library_lease = lease
|
||||
window._native_backup_session = session
|
||||
window.show(); window.close()
|
||||
assert retained == [True] and session.process.poll() is None
|
||||
|
||||
|
||||
def test_native_launch_failure_does_not_poison_other_features(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
def missing(_): raise ValueError('未找到 iCDB Project Backup')
|
||||
window = load_window(qtbot, tmp_path, monkeypatch, native_backup_launcher=missing)
|
||||
window.search_edit.setText('Beta'); window.select_visible_button.click()
|
||||
window.native_backup_button.click(); qtbot.waitUntil(lambda: not window.busy)
|
||||
assert '未找到' in window.status_label.text()
|
||||
assert window.selected_batch_button.isEnabled() and window.native_backup_button.isEnabled()
|
||||
assert not window._management_unsafe
|
||||
|
||||
|
||||
@pytest.mark.parametrize('evidence', ['unconfirmed', 'missing', 'malformed', 'wrong_identity'])
|
||||
def test_unconfirmed_supervisor_exit_keeps_session_conflict_and_mapping(qtbot, tmp_path, monkeypatch, evidence):
|
||||
from test_ui_filters import load_window
|
||||
window = load_window(qtbot, tmp_path, monkeypatch)
|
||||
job = tmp_path/'native/request.json'; job.parent.mkdir(); job.write_text('{}')
|
||||
if evidence != 'missing':
|
||||
job.with_name('result.json').write_text('invalid' if evidence == 'malformed' else json.dumps({
|
||||
'status': 'FAILED', 'safe_to_continue': evidence == 'wrong_identity',
|
||||
'library': 'other.lmc' if evidence == 'wrong_identity' else 'test.lmc',
|
||||
'block': 'Beta', 'detail': 'unconfirmed'}))
|
||||
session = SimpleNamespace(library=Path('test.lmc'), block='Beta', job=job,
|
||||
path_lease=window.library_lease, process=SimpleNamespace(poll=lambda: 1))
|
||||
window._native_backup_session = session
|
||||
window._poll_native_backup(); qtbot.waitUntil(lambda: not window.busy)
|
||||
assert window._native_backup_session is session
|
||||
assert not window.batch_button.isEnabled() and window.search_edit.isEnabled()
|
||||
assert not window.native_backup_timer.isActive()
|
||||
|
||||
|
||||
def test_confirmed_native_close_transfers_mapping_to_current_library(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
from test_network_path import FakeWNet
|
||||
from cbb_refresh_verify.network_path import LibraryPathLease
|
||||
window = load_window(qtbot, tmp_path, monkeypatch)
|
||||
backend = FakeWNet()
|
||||
old = LibraryPathLease.acquire(r'\\server\share\A\library.lmc', backend=backend)
|
||||
current = LibraryPathLease.acquire(r'\\server\share\B\library.lmc', backend=backend)
|
||||
window.library_lease = current
|
||||
job = tmp_path/'request.json'
|
||||
job.with_name('result.json').write_text(json.dumps({'status': 'CLOSED', 'safe_to_continue': True,
|
||||
'library': str(old.mentor_path), 'block': 'Beta'}))
|
||||
window._native_backup_session = SimpleNamespace(library=old.mentor_path, block='Beta', job=job,
|
||||
path_lease=old, process=SimpleNamespace(poll=lambda: 0))
|
||||
window._poll_native_backup(); qtbot.waitUntil(lambda: not window.busy)
|
||||
assert window._native_backup_session is None
|
||||
assert backend.cancelled == [] and current.created
|
||||
window.close()
|
||||
assert backend.cancelled == [current.drive]
|
||||
|
||||
|
||||
def test_native_mapping_ownership_transfers_to_new_library_on_same_share():
|
||||
from test_network_path import FakeWNet
|
||||
from cbb_refresh_verify.network_path import LibraryPathLease
|
||||
backend = FakeWNet()
|
||||
old = LibraryPathLease.acquire(r'\\server\share\A\library.lmc', backend=backend)
|
||||
current = LibraryPathLease.acquire(r'\\server\share\B\library.lmc', backend=backend)
|
||||
assert old.created and not current.created
|
||||
old.transfer_ownership(current)
|
||||
old.close()
|
||||
assert backend.cancelled == [] and current.created
|
||||
current.close()
|
||||
assert backend.cancelled == [current.drive]
|
||||
|
||||
|
||||
def test_native_process_job_waits_for_its_children_without_killing_them(tmp_path):
|
||||
import sys, time
|
||||
from cbb_refresh_verify.native_backup import _NativeBackupProcess
|
||||
pythonw = Path(sys.executable).with_name('pythonw.exe')
|
||||
child = tmp_path/'child.pid'
|
||||
script = tmp_path/'parent.py'
|
||||
script.write_text('import subprocess,sys,time\nfrom pathlib import Path\n'
|
||||
'p=subprocess.Popen([sys.executable,"-c","import time;time.sleep(1)"])\n'
|
||||
f'Path({str(child)!r}).write_text(str(p.pid))\n'
|
||||
'time.sleep(.2)\n', encoding='utf-8')
|
||||
native = _NativeBackupProcess([str(pythonw), str(script)], tmp_path)
|
||||
try:
|
||||
deadline = time.monotonic()+10
|
||||
seen_child = False
|
||||
seen_parent_exit_before_child = False
|
||||
while time.monotonic() < deadline:
|
||||
pids = native.session_pids()
|
||||
assert isinstance(pids, (list, tuple))
|
||||
if child.exists():
|
||||
pid = int(child.read_text())
|
||||
seen_child = seen_child or pid in pids
|
||||
seen_parent_exit_before_child = seen_parent_exit_before_child or native.poll() == 0 and pid in pids
|
||||
if native.poll() == 0 and not pids:
|
||||
break
|
||||
time.sleep(.05)
|
||||
assert seen_child and seen_parent_exit_before_child
|
||||
assert not native.session_pids()
|
||||
finally:
|
||||
native.close()
|
||||
@@ -13,6 +13,7 @@ def export_case(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.native_engineering_identity as identity
|
||||
import win32com.client
|
||||
monkeypatch.setattr(win32com.client, 'GetObject', lambda *_: SimpleNamespace(ExecQuery=lambda *_: []))
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_a, **_k: [])
|
||||
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
|
||||
monkeypatch.setattr(identity, '_retained_exports', [])
|
||||
monkeypatch.setattr(locks, '_supervisor_alive', lambda _: False)
|
||||
@@ -88,12 +89,11 @@ def test_restarted_export_copy_can_release_only_after_fresh_proof(export_case, t
|
||||
|
||||
|
||||
def test_maintenance_idle_guard_recognizes_new_exporter_names(monkeypatch):
|
||||
import win32com.client
|
||||
from cbb_refresh_verify.maintenance_entry import assert_native_idle
|
||||
def query(sql):
|
||||
assert 'icdb2ascii.exe' in sql.casefold() and 'icdbnetserver.exe' in sql.casefold()
|
||||
return [SimpleNamespace(ProcessId=123456, Name='icdb2ascii.exe', CommandLine='export')]
|
||||
monkeypatch.setattr(win32com.client, 'GetObject', lambda *_: SimpleNamespace(ExecQuery=query))
|
||||
def query(names):
|
||||
assert 'icdb2ascii.exe' in [n.casefold() for n in names] and 'icdbnetserver.exe' in [n.casefold() for n in names]
|
||||
return [{'pid': 123456, 'name': 'icdb2ascii.exe', 'command': 'export'}]
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', query)
|
||||
with pytest.raises(ValueError, match='MAINTENANCE_OWNER_ACTIVE'): assert_native_idle()
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def test_empty_private_desktop_does_not_inherit_stale_windows_error(tmp_path):
|
||||
from cbb_refresh_verify.desktop_worker import DesktopWorker
|
||||
script = tmp_path/'enumerate.py'
|
||||
result = tmp_path/'result.json'
|
||||
script.write_text(
|
||||
'import sys,json,win32api,win32gui,win32process\nfrom pathlib import Path\n'
|
||||
f'sys.path.insert(0,{str(Path("src").resolve())!r})\n'
|
||||
'from cbb_refresh_verify.native_repair_ui import _windows\n'
|
||||
'win32api.SetLastError(2)\n'
|
||||
'try:\n record={"windows":_windows(999999)}\n'
|
||||
'except Exception as error:\n record={"error":str(error)}\n'
|
||||
f'Path({str(result)!r}).write_text(json.dumps(record))\n', encoding='utf-8')
|
||||
worker = DesktopWorker([sys.executable, str(script)], 'CbbProbe_' + uuid4().hex[:12])
|
||||
try:
|
||||
assert worker.wait(timeout=20) == 0
|
||||
finally:
|
||||
worker.close()
|
||||
assert json.loads(result.read_text()) == {'windows': []}
|
||||
|
||||
|
||||
def test_real_window_enumeration_errors_still_propagate(monkeypatch):
|
||||
import win32gui, pywintypes
|
||||
from cbb_refresh_verify.native_repair_ui import _windows
|
||||
def denied(*args): raise pywintypes.error(5, 'EnumWindows', 'denied')
|
||||
monkeypatch.setattr(win32gui, 'EnumWindows', denied)
|
||||
with pytest.raises(pywintypes.error): _windows(123)
|
||||
|
||||
|
||||
def test_cancel_reaches_prelaunch_scan(tmp_path, monkeypatch):
|
||||
from contextlib import contextmanager
|
||||
from test_native_repair import repair_worker_fixture
|
||||
from cbb_refresh_verify.native_repair import RepairTarget
|
||||
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
|
||||
data = json.loads(job.read_text('utf-8'))
|
||||
data['maintenance_context'] = {'library': str(tmp_path/'lib.lmc'), 'block': 'CBB1'}
|
||||
job.write_text(json.dumps(data), encoding='utf-8')
|
||||
calls, interrupted = [], []
|
||||
@contextmanager
|
||||
def guard(*args, stop=None, **kwargs):
|
||||
calls.append(1)
|
||||
assert stop is not None, 'worker scan has no cancellation input'
|
||||
if len(calls) == 1:
|
||||
Path(data['cancel_signal']).touch()
|
||||
assert stop.is_set()
|
||||
interrupted.append(1)
|
||||
raise ValueError('MAINTENANCE_CANCELLED')
|
||||
yield {'target': RepairTarget(Path(data['project']), Path(data['database']))}
|
||||
monkeypatch.setattr('cbb_refresh_verify.maintenance_entry.maintenance_target_guard', guard)
|
||||
monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **kw: pytest.fail('cancelled native launch'))
|
||||
assert ui.repair_worker_main(job) == 1
|
||||
assert interrupted == [1] and not actions
|
||||
|
||||
|
||||
def test_worker_uses_one_complete_guard_immediately_before_native_launch(tmp_path, monkeypatch):
|
||||
from contextlib import contextmanager
|
||||
from test_native_repair import repair_worker_fixture
|
||||
from cbb_refresh_verify.native_repair import RepairTarget
|
||||
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
|
||||
data = json.loads(job.read_text('utf-8'))
|
||||
data['maintenance_context'] = {'library': str(tmp_path/'lib.lmc'), 'block': 'CBB1'}
|
||||
job.write_text(json.dumps(data), encoding='utf-8')
|
||||
order = []
|
||||
@contextmanager
|
||||
def guard(*args, stop=None, **kwargs):
|
||||
assert stop is not None
|
||||
order.append('guard')
|
||||
yield {'target': RepairTarget(Path(data['project']), Path(data['database']))}
|
||||
order.append('guard_complete')
|
||||
monkeypatch.setattr('cbb_refresh_verify.maintenance_entry.maintenance_target_guard', guard)
|
||||
popen = ui.subprocess.Popen
|
||||
def launch(*args, **kwargs):
|
||||
order.append('launch')
|
||||
return popen(*args, **kwargs)
|
||||
monkeypatch.setattr(ui.subprocess, 'Popen', launch)
|
||||
ui.repair_worker_main(job)
|
||||
assert order == ['guard', 'guard_complete', 'launch']
|
||||
|
||||
|
||||
def test_file_cancellation_polling_is_bounded_and_latches_cancel(tmp_path, monkeypatch):
|
||||
from types import SimpleNamespace
|
||||
import cbb_refresh_verify.native_repair_ui as ui
|
||||
now = [1.0]
|
||||
monkeypatch.setattr(ui, 'time', SimpleNamespace(monotonic=lambda: now[0]))
|
||||
signal = ui._CancellationFile(tmp_path/'cancel.signal')
|
||||
reads = []
|
||||
signal.path = SimpleNamespace(exists=lambda: reads.append(1) or len(reads) > 1)
|
||||
for _ in range(50000):
|
||||
assert not signal.is_set()
|
||||
assert len(reads) == 1
|
||||
now[0] += .11
|
||||
assert signal.is_set()
|
||||
signal.path = SimpleNamespace(exists=lambda: pytest.fail('cancel must stay latched'))
|
||||
now[0] += 1
|
||||
assert signal.is_set()
|
||||
@@ -0,0 +1,191 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
|
||||
def output(project, database, *, fault=False, busy=False):
|
||||
text = f'Loading project file [{project}].\nChecking if project is in use.\n'
|
||||
if fault:
|
||||
text += (f'Project database [{database}] is inconsistent. It has been manually copied while the iCDB Server was running. '
|
||||
"Please use iCDB Project Backup 'Repair project' functionality to fix this issue.\n")
|
||||
return text + ('Project is in use.\n' if busy else
|
||||
"Project is not in use. Full iCDB Project Backup's functionality is available.\nBackup information loaded correctly.\n")
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fault,busy,status,repair', [
|
||||
(False, False, 'NOT_IN_USE', False), (True, False, 'NOT_IN_USE', True),
|
||||
(True, True, 'IN_USE', False), (False, True, 'IN_USE', False)])
|
||||
def test_native_ownership_and_repair_need_are_separate(tmp_path, fault, busy, status, repair):
|
||||
from cbb_refresh_verify.native_occupancy import classify_inspection
|
||||
project, database = tmp_path/'A.prj', tmp_path/'database'
|
||||
result = classify_inspection(project, database, output(project, database, fault=fault, busy=busy))
|
||||
assert result['status'] == status
|
||||
assert result['repair_required'] is repair
|
||||
|
||||
|
||||
@pytest.mark.parametrize('case', ['progress', 'wrong_project', 'wrong_database', 'stale_verdict', 'generic_repair'])
|
||||
def test_incomplete_or_foreign_output_cannot_authorize_repair(tmp_path, case):
|
||||
from cbb_refresh_verify.native_occupancy import classify_inspection
|
||||
project, database = tmp_path/'A.prj', tmp_path/'database'
|
||||
text = output(project, database, fault=True)
|
||||
if case == 'progress': text = f'Loading project file [{project}].\nChecking if project is in use.'
|
||||
if case == 'wrong_project': text = output(tmp_path/'Other.prj', database, fault=True)
|
||||
if case == 'wrong_database': text = output(project, tmp_path/'other', fault=True)
|
||||
if case == 'stale_verdict': text += 'Checking if project is in use.\n'
|
||||
if case == 'generic_repair': text = output(project, database) + 'Please try to repair the project!'
|
||||
assert classify_inspection(project, database, text)['repair_required'] is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fault,busy', [(False, False), (True, False), (False, True)])
|
||||
def test_inspection_mode_only_observes_and_closes_its_tool(tmp_path, monkeypatch, fault, busy):
|
||||
import win32con
|
||||
from test_native_repair import repair_worker_fixture
|
||||
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
|
||||
data = json.loads(job.read_text('utf-8')); data['inspection_only'] = True
|
||||
job.write_text(json.dumps(data), encoding='utf-8')
|
||||
monkeypatch.setattr(ui, '_repair_command', lambda *a: pytest.fail('inspection resolved Repair command'))
|
||||
monkeypatch.setattr(ui, '_native_output', lambda *_: output(data['project'], data['database'], fault=fault, busy=busy))
|
||||
assert ui.repair_worker_main(job) == 0
|
||||
result = json.loads((root/'repair-result.json').read_text('utf-8'))
|
||||
assert result['status'] == ('IN_USE' if busy else 'NOT_IN_USE')
|
||||
assert result['release']['native_exited'] is True
|
||||
assert result['repair_required'] is (fault and not busy)
|
||||
assert actions == [(100, win32con.WM_CLOSE)]
|
||||
|
||||
|
||||
def test_generic_project_backup_shell_is_accepted_as_the_single_target_window(tmp_path, monkeypatch):
|
||||
import json
|
||||
from test_native_repair import repair_worker_fixture
|
||||
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
|
||||
data = json.loads(job.read_text('utf-8')); data['inspection_only'] = True
|
||||
job.write_text(json.dumps(data), encoding='utf-8')
|
||||
monkeypatch.setattr(ui, '_native_output', lambda windows: (
|
||||
f'Loading project file [{data["project"]}].\nChecking if project is in use.\n'
|
||||
"Project is not in use. Full iCDB Project Backup's functionality is available.\n"
|
||||
'Backup information loaded correctly.'))
|
||||
assert ui.repair_worker_main(job) == 0
|
||||
|
||||
|
||||
def test_only_check_never_counts_as_repair_success():
|
||||
from cbb_refresh_verify.icdb_maintenance import maintenance_counts
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
counts = maintenance_counts([VerifyResult('CHECKED', safe_to_continue=True)])
|
||||
assert counts['passed'] == counts['repaired'] == 0
|
||||
assert counts['checked_without_repair'] == 1
|
||||
|
||||
|
||||
def test_cancelled_probe_returns_within_grace_without_killing_native(tmp_path, monkeypatch):
|
||||
from threading import Event
|
||||
from types import SimpleNamespace
|
||||
from cbb_refresh_verify import native_repair as native
|
||||
from cbb_refresh_verify.native_repair import RepairTarget
|
||||
stop = Event(); ticks = [0.0]; actions = []
|
||||
def sleep(seconds):
|
||||
ticks[0] += seconds
|
||||
stop.set()
|
||||
monkeypatch.setattr(native, 'time', SimpleNamespace(monotonic=lambda: ticks[0], sleep=sleep))
|
||||
class Worker:
|
||||
pid = 123
|
||||
def __init__(self, *a): pass
|
||||
def bind_cancellation(self, p): pass
|
||||
def poll(self): return None
|
||||
def request_stop(self): actions.append('cancel')
|
||||
def close(self): actions.append('close_handles')
|
||||
def kill(self): pytest.fail('native owner must not be killed')
|
||||
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker)
|
||||
result = native.run_native_repair(RepairTarget(tmp_path/'A.prj', tmp_path/'database'),
|
||||
tmp_path/'evidence', timeout_seconds=600, inspection_only=True, stop=stop)
|
||||
assert ticks[0] < 6
|
||||
assert result['status'] == 'CANCELLED_UNRELEASED'
|
||||
assert result['release']['safe_to_continue'] is False
|
||||
assert actions[-1] == 'close_handles'
|
||||
|
||||
|
||||
def test_ui_keeps_processing_events_and_passes_cancel_to_native_task(qtbot, tmp_path, monkeypatch):
|
||||
from threading import Event
|
||||
from PySide6.QtCore import QTimer
|
||||
from test_ui_filters import load_window
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
entered = Event(); cancelled = Event(); ticks = []
|
||||
def verify(req, *, stop, **kw):
|
||||
entered.set()
|
||||
if stop.wait(3): cancelled.set()
|
||||
return VerifyResult('CANCELLED')
|
||||
monkeypatch.setattr('cbb_refresh_verify.verify_runner.run_verify', verify)
|
||||
window = load_window(qtbot, tmp_path, monkeypatch,
|
||||
status_refresher=lambda names, _: {name: 'PENDING' for name in names})
|
||||
window.search_edit.setText('Beta')
|
||||
timer = QTimer(window); timer.setInterval(10); timer.timeout.connect(lambda: ticks.append(True)); timer.start()
|
||||
window.repair_icdb_all()
|
||||
qtbot.waitUntil(entered.is_set)
|
||||
qtbot.waitUntil(lambda: len(ticks) >= 3)
|
||||
assert window.busy and window.stop_button.isEnabled()
|
||||
window.stop_button.click()
|
||||
qtbot.waitUntil(lambda: not window.busy)
|
||||
assert cancelled.is_set()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('extra', ['foreign_session', 'extra_error'])
|
||||
def test_foreign_or_additional_fault_is_never_a_clean_inspection(tmp_path, extra):
|
||||
from cbb_refresh_verify.native_occupancy import classify_inspection
|
||||
project, database = tmp_path/'A.prj', tmp_path/'database'
|
||||
text = output(project, database, fault=extra == 'extra_error')
|
||||
if extra == 'foreign_session':
|
||||
text += ('The last server session on different server machine lost the connection to the database. '
|
||||
'Machine:[SERVER] Path:[C:/Other/Work/database] session:[old]')
|
||||
else:
|
||||
text += 'ERROR: shared symbol database unavailable'
|
||||
assert classify_inspection(project, database, text)['status'] == 'UNCONFIRMED'
|
||||
|
||||
|
||||
def test_unconfirmed_inspection_closes_known_main_at_timeout(tmp_path, monkeypatch):
|
||||
import win32con
|
||||
from test_native_repair import repair_worker_fixture
|
||||
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
|
||||
data = json.loads(job.read_text('utf-8')); data['inspection_only'] = True
|
||||
job.write_text(json.dumps(data), encoding='utf-8')
|
||||
monkeypatch.setattr(ui, '_native_output', lambda *_: 'Unrecognized response')
|
||||
assert ui.repair_worker_main(job) == 1
|
||||
result = json.loads((root/'repair-result.json').read_text('utf-8'))
|
||||
assert result['status'] == 'UNCONFIRMED'
|
||||
assert result['release']['native_exited'] is True
|
||||
assert actions == [(100, win32con.WM_CLOSE)]
|
||||
|
||||
|
||||
def test_directory_scan_honors_cancel_between_entries(tmp_path):
|
||||
from cbb_refresh_verify.scoped_manifest import scan_tree
|
||||
for i in range(10): (tmp_path/f'{i}.dat').touch()
|
||||
calls = []
|
||||
def cancel():
|
||||
calls.append(True)
|
||||
if len(calls) == 3: raise RuntimeError('CANCELLED')
|
||||
with pytest.raises(RuntimeError, match='CANCELLED'):
|
||||
scan_tree(tmp_path, check=cancel)
|
||||
assert len(calls) == 3
|
||||
|
||||
|
||||
def test_cancel_during_final_guard_cannot_launch_native_tool(tmp_path, monkeypatch):
|
||||
from contextlib import contextmanager
|
||||
from test_native_repair import repair_worker_fixture
|
||||
from cbb_refresh_verify.native_repair import RepairTarget
|
||||
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
|
||||
data = json.loads(job.read_text('utf-8'))
|
||||
data['maintenance_context'] = {'library': str(tmp_path/'lib.lmc'), 'block': 'CBB1'}
|
||||
job.write_text(json.dumps(data), encoding='utf-8')
|
||||
calls = []
|
||||
@contextmanager
|
||||
def guard(*a, **kw):
|
||||
calls.append(True)
|
||||
yield {'target': RepairTarget(Path(data['project']), Path(data['database']))}
|
||||
Path(data['cancel_signal']).touch()
|
||||
monkeypatch.setattr('cbb_refresh_verify.maintenance_entry.maintenance_target_guard', guard)
|
||||
monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **kw: pytest.fail('late native launch'))
|
||||
assert ui.repair_worker_main(job) == 1
|
||||
assert len(calls) == 1 and not actions
|
||||
|
||||
|
||||
def test_verified_cbb_refusal_is_not_hidden_by_secondary_release_failure():
|
||||
from cbb_refresh_verify.verify_runner import classify_failure_category
|
||||
detail = ('BackAnnotate: Back Annotation is not allowed on verified (or once verified) Reusable Blocks.'
|
||||
'\nPCB_RELEASE_UNCONFIRMED: not released')
|
||||
assert classify_failure_category(detail) == 'CBB_REIMPORT_REQUIRED'
|
||||
@@ -5,6 +5,7 @@ import pytest
|
||||
|
||||
|
||||
def target_fixture(tmp_path):
|
||||
from dataclasses import replace
|
||||
from test_verify_runner import fixture, request
|
||||
from cbb_refresh_verify.native_repair import select_repair_target
|
||||
work = fixture(tmp_path)
|
||||
@@ -13,7 +14,8 @@ def target_fixture(tmp_path):
|
||||
(database/'icdb.dat').write_bytes(b'original damaged database')
|
||||
diagnosis = {'error_code': 'ICDB_REPAIR_REQUIRED', 'machine': 'OLD-PC',
|
||||
'database_path': str(database), 'session': '2026-10-24 08.22.29-10308', 'scope': 'project'}
|
||||
return request(tmp_path), diagnosis, select_repair_target(request(tmp_path), diagnosis)
|
||||
req = replace(request(tmp_path), auto_repair=True)
|
||||
return req, diagnosis, select_repair_target(req, diagnosis)
|
||||
|
||||
|
||||
def complete_native_success(target):
|
||||
@@ -511,7 +513,8 @@ def test_invoked_busy_native_result_never_reopens_or_continues_queue(tmp_path, m
|
||||
busy = json.loads((root/'repair-result.json').read_text('utf-8'))
|
||||
assert (100, win32con.WM_CLOSE) not in actions
|
||||
assert busy['status'] == 'DATABASE_BUSY' and busy['release']['native_exited'] is False
|
||||
req = request(tmp_path)
|
||||
from dataclasses import replace
|
||||
req = replace(request(tmp_path), auto_repair=True)
|
||||
target = json.loads(job.read_text('utf-8'))
|
||||
evidence = tmp_path/'first/result.json'
|
||||
evidence.parent.mkdir()
|
||||
@@ -846,18 +849,22 @@ def test_repair_release_uses_real_process_query_contract(tmp_path, monkeypatch,
|
||||
queried = []
|
||||
names = ('ExpeditionPCB.exe', 'LibraryManager.exe', 'iCDBProjectBackup.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}
|
||||
def query(wql):
|
||||
name = queries[wql]
|
||||
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')]
|
||||
if name == owner else [])
|
||||
def service(moniker):
|
||||
assert moniker == 'winmgmts:'
|
||||
return SimpleNamespace(ExecQuery=query)
|
||||
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.
|
||||
state = repair_release_state(request, target, complete_native_success(target))
|
||||
assert 'error' not in state
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
from PySide6.QtCore import Qt
|
||||
|
||||
|
||||
def test_three_horizontal_sections_keep_one_catalog_and_only_their_actions(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
window = load_window(qtbot, tmp_path, monkeypatch)
|
||||
window.show()
|
||||
assert [window.section_tabs.tabText(i) for i in range(window.section_tabs.count())] == [
|
||||
'检验', 'ICDB 维护', '中心库管理']
|
||||
window.search_edit.setText('Beta')
|
||||
window.select_visible_button.click()
|
||||
for index, visible, hidden in (
|
||||
(0, window.batch_button, window.icdb_repair_button),
|
||||
(1, window.icdb_repair_button, window.add_button),
|
||||
(2, window.add_button, window.batch_button),
|
||||
):
|
||||
window.section_tabs.setCurrentIndex(index)
|
||||
assert visible.isVisible() and not hidden.isVisible()
|
||||
assert window.cbb_table.isVisible()
|
||||
assert window.search_edit.text() == 'Beta'
|
||||
assert [record.name for record in window.selected_records()] == ['Beta']
|
||||
assert window.minimumSizeHint().height() <= 650
|
||||
|
||||
|
||||
def test_long_status_does_not_expand_the_window(qtbot, tmp_path):
|
||||
from cbb_refresh_verify.ui.main_window import MainWindow
|
||||
window = MainWindow(data_root=tmp_path)
|
||||
qtbot.addWidget(window)
|
||||
window.resize(1000, 650); window.show()
|
||||
window.status_label.setText('错误说明\n' * 80)
|
||||
qtbot.wait(20)
|
||||
assert window.height() <= 650
|
||||
assert window.status_label.height() <= window.status_label.fontMetrics().lineSpacing() * 3 + 4
|
||||
|
||||
|
||||
def test_failure_detail_keeps_catalog_name_readable(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
window = load_window(qtbot, tmp_path, monkeypatch)
|
||||
window.resize(1000, 650); window.show()
|
||||
window.cbb_table.item(0, 3).setText('BackAnnotate: ' + 'long exception ' * 100)
|
||||
qtbot.wait(20)
|
||||
assert window.cbb_table.columnWidth(0) >= 200
|
||||
assert window.cbb_table.horizontalHeader().length() <= window.cbb_table.viewport().width()
|
||||
@@ -0,0 +1,23 @@
|
||||
import subprocess
|
||||
import pytest
|
||||
|
||||
|
||||
def test_wmi_timeout_is_unknown_not_idle(monkeypatch):
|
||||
from cbb_refresh_verify.owner_probe import query_owners
|
||||
def hang(command, **kw):
|
||||
assert 0 < kw['timeout'] <= 10
|
||||
raise subprocess.TimeoutExpired(command, kw['timeout'])
|
||||
monkeypatch.setattr(subprocess, 'run', hang)
|
||||
with pytest.raises(RuntimeError, match='OWNER_QUERY_TIMEOUT'):
|
||||
query_owners(['ExpeditionPCB.exe'])
|
||||
|
||||
|
||||
def test_malformed_wmi_response_is_not_empty_owner_list(monkeypatch):
|
||||
from cbb_refresh_verify.owner_probe import query_owners
|
||||
from pathlib import Path
|
||||
def run(command, **kw):
|
||||
Path(command[-1]).with_name('result.json').write_text('{}')
|
||||
return subprocess.CompletedProcess(command, 0)
|
||||
monkeypatch.setattr(subprocess, 'run', run)
|
||||
with pytest.raises(RuntimeError, match='OWNER_QUERY_UNCONFIRMED'):
|
||||
query_owners(['ExpeditionPCB.exe'])
|
||||
@@ -0,0 +1,242 @@
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import QTimer
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
|
||||
from cbb_refresh_verify.management import Capability, ManagementRequest, ManagementResult
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
|
||||
|
||||
def failed_repair(path, *, safe=False):
|
||||
return VerifyResult('FAIL', error_category='CBB_REIMPORT_REQUIRED',
|
||||
stderr='Back Annotation is not allowed on verified (or once verified) Reusable Blocks.',
|
||||
evidence_path=path, safe_to_continue=safe,
|
||||
recovery_attempts=({'native_status': 'REPAIRED', 'status': 'REPAIR_VALIDATION_FAILED',
|
||||
'validation_passed': False},))
|
||||
|
||||
|
||||
def recovery_window(qtbot, tmp_path, monkeypatch, result=None):
|
||||
from test_ui_filters import load_window
|
||||
adapter = SimpleNamespace(capabilities=lambda: {op: Capability(True, 'available')
|
||||
for op in ('add', 'update', 'remove')})
|
||||
result = result or failed_repair(tmp_path/'maintenance/result.json')
|
||||
window = load_window(qtbot, tmp_path, monkeypatch, management_adapter=adapter,
|
||||
verifier=lambda _: result, status_refresher=lambda names, path: {n: 'PENDING' for n in names})
|
||||
window.search_edit.setText('Beta')
|
||||
window.repair_icdb_all()
|
||||
qtbot.waitUntil(lambda: not window.busy)
|
||||
return window, result
|
||||
|
||||
|
||||
def test_failed_repair_offers_copy_import_bound_to_failed_target(qtbot, tmp_path, monkeypatch):
|
||||
window, failed = recovery_window(qtbot, tmp_path, monkeypatch)
|
||||
assert '副本' in window.summary.text()
|
||||
action = next(b for b in window.summary.buttons() if '副本' in b.text())
|
||||
window.search_edit.setText('Alpha')
|
||||
window.select_visible_button.click()
|
||||
action.click()
|
||||
dialog = window.management_dialog
|
||||
requests = dialog.requests()
|
||||
assert len(requests) == 1 and requests[0].name == 'Beta'
|
||||
assert requests[0].partition == 'Power' and requests[0].operation == 'update'
|
||||
assert requests[0].source is None and requests[0].auto_verify
|
||||
assert '修复未完成' in dialog.status_label.text()
|
||||
assert '手动备份' in dialog.status_label.text()
|
||||
assert str(failed.evidence_path) in dialog.output.toPlainText()
|
||||
dialog.reject()
|
||||
assert failed.status == 'FAIL'
|
||||
assert window.reimport_button.isEnabled()
|
||||
|
||||
|
||||
def test_declining_reimport_confirmation_does_not_check_release_or_write(qtbot, tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
window, _ = recovery_window(qtbot, tmp_path, monkeypatch)
|
||||
window.summary.close()
|
||||
window.reimport_button.click()
|
||||
dialog = window.management_dialog
|
||||
source = tmp_path/'copy/test.prj'; source.parent.mkdir(); source.touch()
|
||||
dialog.add_sources([source])
|
||||
monkeypatch.setattr(locks, 'release_retained_library', lambda *a: pytest.fail('unconfirmed release'))
|
||||
confirmations = []
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **kw:
|
||||
confirmations.append(a[2]) or QMessageBox.No)
|
||||
dialog.execute_button.click()
|
||||
assert not dialog.busy and not dialog.executed
|
||||
assert 'Beta' in confirmations[0] and str(source) in confirmations[0]
|
||||
assert '副本' in confirmations[0] and '先移除' in confirmations[0]
|
||||
dialog.reject()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('result', [VerifyResult('CHECKED'), VerifyResult('PASS', library_flag='GREEN'),
|
||||
VerifyResult('BLOCKED', error_category='ICDB_DATABASE_IN_USE', safe_to_continue=False),
|
||||
VerifyResult('FAIL', stderr='unknown error')])
|
||||
def test_no_reimport_offer_for_unconfirmed_diagnosis_or_success(qtbot, tmp_path, monkeypatch, result):
|
||||
window, _ = recovery_window(qtbot, tmp_path, monkeypatch, result)
|
||||
assert not window.reimport_button.isVisible()
|
||||
assert not any('副本' in b.text() for b in window.summary.buttons())
|
||||
|
||||
|
||||
def test_changing_library_invalidates_old_reimport_offer(qtbot, tmp_path, monkeypatch):
|
||||
window, _ = recovery_window(qtbot, tmp_path, monkeypatch)
|
||||
old_action = next(b for b in window.summary.buttons() if '副本' in b.text())
|
||||
window.lmc_edit.setText('another.lmc')
|
||||
old_action.click()
|
||||
assert not getattr(window, 'management_dialog', None)
|
||||
assert not window.reimport_button.isVisible()
|
||||
|
||||
|
||||
def request(tmp_path):
|
||||
library = tmp_path/'lib/mentor.lmc'; library.parent.mkdir(); library.touch()
|
||||
source = tmp_path/'copy/Block.prj'; source.parent.mkdir(); source.touch()
|
||||
return ManagementRequest('update', library, 'Block', source=source, evidence_dir=tmp_path/'management')
|
||||
|
||||
|
||||
def test_release_failure_preserves_failure_and_never_dispatches_management(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify.reimport_recovery import run_reimport_recovery
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import cbb_refresh_verify.management as management
|
||||
req = request(tmp_path)
|
||||
monkeypatch.setattr(management, 'source_project', lambda *a: (req.source, req.source, 'Block'))
|
||||
def denied(*a): raise locks.LibraryBusy('PCB still active: 123')
|
||||
monkeypatch.setattr(locks, 'release_retained_library', denied)
|
||||
monkeypatch.setattr(management, 'run_management_batch', lambda *a, **kw: pytest.fail('unsafe write'))
|
||||
results = run_reimport_recovery([req], previous_evidence={'Block': tmp_path/'old/result.json'},
|
||||
evidence_dir=tmp_path/'reimport')
|
||||
assert results[0].status == 'BLOCKED' and not results[0].safe_to_continue
|
||||
assert '123' in results[0].detail
|
||||
import json
|
||||
record = json.loads(results[0].evidence_path.read_text('utf-8'))
|
||||
assert record['previous_evidence']['Block'] == str(tmp_path/'old/result.json')
|
||||
assert record['stage'] == 'release_failed'
|
||||
|
||||
|
||||
def test_cancel_during_release_prevents_import(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify.reimport_recovery import run_reimport_recovery
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import cbb_refresh_verify.management as management
|
||||
req = request(tmp_path); stop = Event()
|
||||
monkeypatch.setattr(management, 'source_project', lambda *a: (req.source, req.source, 'Block'))
|
||||
def release(*a):
|
||||
stop.set()
|
||||
return {'status': 'RELEASE_CONFIRMED', 'evidence_path': 'release.json'}
|
||||
monkeypatch.setattr(locks, 'release_retained_library', release)
|
||||
monkeypatch.setattr(management, 'run_management_batch', lambda *a, **kw: pytest.fail('cancelled write'))
|
||||
results = run_reimport_recovery([req], previous_evidence={'Block': 'old.json'},
|
||||
evidence_dir=tmp_path/'reimport', stop=stop)
|
||||
assert results == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize('uploaded_status', ['UPLOADED', 'UPLOADED_VERIFY_FAILED', 'UPLOADED_VERIFIED'])
|
||||
def test_copy_recovery_keeps_native_management_outcome_and_original_evidence(tmp_path, monkeypatch, uploaded_status):
|
||||
from cbb_refresh_verify.reimport_recovery import run_reimport_recovery
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import cbb_refresh_verify.management as management
|
||||
import json
|
||||
req = request(tmp_path)
|
||||
old = tmp_path/'old.json'; old.write_text('{"status":"FAIL"}', encoding='utf-8')
|
||||
before = old.read_bytes()
|
||||
monkeypatch.setattr(management, 'source_project', lambda *a: (req.source, req.source, 'Block'))
|
||||
monkeypatch.setattr(locks, 'release_retained_library', lambda *a:
|
||||
{'status': 'RELEASE_CONFIRMED', 'evidence_path': 'release.json'})
|
||||
expected = ManagementResult('update', req.library, req.name, req.partition, req.source,
|
||||
True, 'complete', uploaded_status, True)
|
||||
monkeypatch.setattr(management, 'run_management_batch', lambda *a, **kw: [expected])
|
||||
results = run_reimport_recovery([req], previous_evidence={'Block': str(old)},
|
||||
evidence_dir=tmp_path/'reimport')
|
||||
assert results == [expected] and old.read_bytes() == before
|
||||
record = json.loads(next((tmp_path/'reimport').glob('*/recovery.json')).read_text('utf-8'))
|
||||
assert record['original_repair_succeeded'] is False
|
||||
assert record['results'][0]['status'] == uploaded_status and record['version_review_required']
|
||||
|
||||
|
||||
def test_incomplete_copy_never_releases_or_removes_target(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify.reimport_recovery import run_reimport_recovery
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
req = request(tmp_path) # Empty PRJ is deliberately incomplete.
|
||||
monkeypatch.setattr(locks, 'release_retained_library', lambda *a: pytest.fail('incomplete source'))
|
||||
results = run_reimport_recovery([req], previous_evidence={'Block': 'old.json'},
|
||||
evidence_dir=tmp_path/'reimport')
|
||||
assert results[0].status == 'BLOCKED' and results[0].stage == 'preflight'
|
||||
|
||||
|
||||
def test_recovery_uses_background_release_then_existing_management(qtbot, tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import cbb_refresh_verify.management as management
|
||||
req = request(tmp_path); entered, finish = Event(), Event(); calls = []
|
||||
monkeypatch.setattr(management, 'source_project', lambda *a: (req.source, req.source, 'Block'))
|
||||
def release(*a):
|
||||
entered.set(); assert finish.wait(5)
|
||||
calls.append('release')
|
||||
return {'status': 'RELEASE_CONFIRMED', 'evidence_path': 'release.json'}
|
||||
monkeypatch.setattr(locks, 'release_retained_library', release)
|
||||
def run(items, **kw):
|
||||
calls.append('management')
|
||||
return [ManagementResult('update', req.library, req.name, req.partition, req.source,
|
||||
True, 'complete', 'UPLOADED_VERIFIED', True)]
|
||||
monkeypatch.setattr(management, 'run_management_batch', run)
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **kw: QMessageBox.Yes)
|
||||
dialog = ManagementDialog([req], recovery_from={'Block': 'old.json'})
|
||||
qtbot.addWidget(dialog)
|
||||
ticks = []
|
||||
timer = QTimer(); timer.setInterval(10); timer.timeout.connect(lambda: ticks.append(1)); timer.start()
|
||||
try:
|
||||
dialog.execute_button.click()
|
||||
qtbot.waitUntil(entered.is_set)
|
||||
qtbot.waitUntil(lambda: len(ticks) >= 3)
|
||||
assert calls == [] and dialog.busy
|
||||
finally:
|
||||
finish.set()
|
||||
qtbot.waitUntil(lambda: not dialog.busy)
|
||||
timer.stop()
|
||||
assert calls == ['release', 'management']
|
||||
assert '版本待核对' in dialog.status_label.text()
|
||||
|
||||
|
||||
def test_recovery_dialog_keeps_internal_details_in_optional_log(qtbot, tmp_path):
|
||||
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
|
||||
req = request(tmp_path)
|
||||
dialog = ManagementDialog([req], recovery_from={'Block': 'old-result.json'})
|
||||
qtbot.addWidget(dialog); dialog.show()
|
||||
assert dialog.output.isHidden()
|
||||
assert not any(word in dialog.status_label.text() for word in ('原生', '证据', '检查点', '记录保留'))
|
||||
detail = 'OWNER_QUERY_TIMEOUT: diagnostic internals'
|
||||
result = ManagementResult('update', req.library, req.name, req.partition, req.source,
|
||||
True, 'release_check', 'BLOCKED', False, detail, tmp_path/'recovery.json')
|
||||
dialog._result([result])
|
||||
assert detail not in dialog.status_label.text()
|
||||
assert '日志' in dialog.status_label.text()
|
||||
dialog.logs_button.click()
|
||||
assert dialog.output.isVisible() and detail in dialog.output.toPlainText()
|
||||
|
||||
|
||||
def test_main_stop_during_recovery_release_cancels_import(qtbot, tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import cbb_refresh_verify.management as management
|
||||
window, _ = recovery_window(qtbot, tmp_path, monkeypatch)
|
||||
window.summary.close(); window.reimport_button.click()
|
||||
dialog = window.management_dialog
|
||||
source = tmp_path/'copy/source.prj'; source.parent.mkdir(); source.touch()
|
||||
dialog.add_sources([source])
|
||||
monkeypatch.setattr(management, 'source_project', lambda *a: (source, source, 'Beta'))
|
||||
entered, finish = Event(), Event()
|
||||
def release(*args):
|
||||
entered.set(); assert finish.wait(5)
|
||||
return {'status': 'RELEASE_CONFIRMED', 'evidence_path': 'release.json'}
|
||||
monkeypatch.setattr(locks, 'release_retained_library', release)
|
||||
dispatched = []
|
||||
monkeypatch.setattr(management, 'run_management_batch', lambda *a, **kw: dispatched.append(a) or [])
|
||||
dialog.execute_button.click()
|
||||
try:
|
||||
qtbot.waitUntil(entered.is_set)
|
||||
window.stop_button.click()
|
||||
assert dialog.stop.is_set()
|
||||
finally:
|
||||
finish.set(); qtbot.waitUntil(lambda: not dialog.busy)
|
||||
dialog.reject()
|
||||
assert dispatched == []
|
||||
|
||||
@@ -8,7 +8,8 @@ from cbb_refresh_verify.runtime_timing import parse_save_progress
|
||||
|
||||
|
||||
@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
|
||||
# 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'
|
||||
@@ -39,14 +40,20 @@ Class FakeDoc
|
||||
IsSaved = True
|
||||
End Function
|
||||
Public Function Close(saveChanges)
|
||||
closedDoc = True
|
||||
Close = True
|
||||
End Function
|
||||
End Class
|
||||
Class FakeApp
|
||||
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
|
||||
Public Sub Quit()
|
||||
WScript.Echo "TEST_QUIT"
|
||||
End Sub
|
||||
End Class
|
||||
Class FakeLic
|
||||
@@ -55,7 +62,8 @@ Class FakeLic
|
||||
End Function
|
||||
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('CreateObject("MGCPCBAutomationLicensing.Application")', 'New FakeLic')
|
||||
harness = tmp_path/'save_harness.vbs'
|
||||
@@ -66,11 +74,13 @@ End Class
|
||||
parsed = parse_save_progress(completed.stdout)
|
||||
assert parsed['timings_seconds']['save'] >= .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']
|
||||
|
||||
+6
-5
@@ -78,7 +78,7 @@ def test_global_icdb_failure_preserves_untargeted_ready_and_stops_queue(qtbot, t
|
||||
assert window.cbb_table.item(1, 2).text() == '未知 / 需确认'
|
||||
assert window.cbb_table.item(2, 3).text().startswith('SKIPPED')
|
||||
|
||||
def test_global_icdb_progress_and_repair_summary(qtbot, tmp_path, monkeypatch):
|
||||
def test_global_icdb_progress_and_check_summary(qtbot, tmp_path, monkeypatch):
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
confirmations = []
|
||||
def confirm(*args, **kwargs):
|
||||
@@ -97,8 +97,9 @@ def test_global_icdb_progress_and_repair_summary(qtbot, tmp_path, monkeypatch):
|
||||
assert '非 READY' in confirmations[0]
|
||||
assert window.icdb_progress.value() == 1
|
||||
assert window.icdb_progress.maximum() == 1
|
||||
assert '恢复备份待复核 1' in window.status_label.text()
|
||||
assert window.summary.windowTitle() == '非 READY ICDB 检查与修复结果'
|
||||
assert '无法确认 1' in window.status_label.text()
|
||||
assert '恢复备份待复核' not in window.status_label.text()
|
||||
assert window.summary.windowTitle() == 'ICDB 批量检查结果'
|
||||
reports = list((tmp_path/'reports').glob('icdb-*.json'))
|
||||
assert len(reports) == 1
|
||||
|
||||
@@ -359,5 +360,5 @@ def test_batch_summary_exposes_failures_only_report(qtbot, tmp_path):
|
||||
qtbot.addWidget(window)
|
||||
report=tmp_path/'reports/batch-20260929-test.log'
|
||||
window._batch_done(([VerifyResult('FAIL',stderr='Mentor error')],report))
|
||||
assert '仅失败日志' in window.summary.text()
|
||||
assert str(report.with_name('failures-20260929-test.log')) in window.summary.text()
|
||||
assert '仅失败日志' in window.summary.detailedText()
|
||||
assert str(report.with_name('failures-20260929-test.log')) in window.summary.detailedText()
|
||||
+10
-10
@@ -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
|
||||
|
||||
Reference in new issue
Block a user