Compare commits

...
Author SHA1 Message Date
阿白叔 6327ad10a2 fix: release private desktop on worker launch failure 2026-11-05 13:56:42 +08:00
阿白叔 1acfbd6374 fix: allow native inspection and backup entry after batch errors 2026-11-05 08:24:53 +08:00
阿白叔 aea6192ef9 fix: narrow cross-item and cross-library blockers 2026-11-05 07:42:49 +08:00
阿白叔 53118bae19 feat: replace automatic ICDB maintenance with batch inspection 2026-11-04 23:40:46 +08:00
阿白叔 beb2b06fdf fix: diagnose PCB startup before ICDB maintenance 2026-11-04 22:53:16 +08:00
阿白叔 4ebe098ef0 feat: open native project history and backup interface 2026-11-04 22:12:24 +08:00
阿白叔 00db1cf5f2 fix: continue released verify batches and bound automation shutdown 2026-11-04 20:51:35 +08:00
阿白叔 477a5a46e3 fix: separate verification and ICDB maintenance with live session leases 2026-11-04 19:16:08 +08:00
阿白叔 2587d33c5a fix: keep maintenance results concise and catalog readable 2026-11-04 17:26:35 +08:00
阿白叔 223655fe00 fix: stabilize ICDB preflight and organize UI into tabs 2026-11-04 17:06:27 +08:00
阿白叔 29959e2988 feat: offer explicit copy recovery after failed ICDB maintenance 2026-11-04 14:16:00 +08:00
阿白叔 e14a864b37 fix: inspect native ICDB occupancy before bounded repair 2026-11-04 12:26:09 +08:00
阿白叔 cb1326688b docs: record reviewed ICDB candidate validation 2026-11-04 10:37:10 +08:00
阿白叔 ef652f3ada fix: guard ICDB diagnostics and exclude READY maintenance targets 2026-11-04 10:27:53 +08:00
阿白叔 8180a8a302 fix: diagnose ICDB before repeatable maintenance repair 2026-11-04 09:14:40 +08:00
阿白叔 c902ffbe9a docs: record frozen ICDB recovery with user-selected PCB version 2026-11-03 18:11:00 +08:00
阿白叔 de952a68d6 fix: inspect addressless ICDB projects and ask for PCB recovery version 2026-11-03 17:42:33 +08:00
阿白叔 c85696080d perf: replace automatic backups with manual backup reminders 2026-11-03 16:44:30 +08:00
阿白叔 7527800128 fix: complete legacy CBB import recovery and guard late native submission 2026-11-03 16:03:14 +08:00
阿白叔 d36b6bcad0 fix: admit linked legacy ICDB projects and explain blocked actions 2026-11-03 13:51:05 +08:00
阿白叔 5eac654c36 docs: record native CRUD frozen acceptance and candidate limits 2026-11-03 13:06:07 +08:00
阿白叔 b26e2f2f62 test: create source fixture for native UIA path admission 2026-11-03 12:54:21 +08:00
96 changed files with 5743 additions and 613 deletions

No files matched your search

+4 -2
View File
@@ -1,4 +1,6 @@
# CBB 中心库上传后校验工具
当前临时分支的备份策略(2026-11-03):应用不再自动备份中心库或 CBB 工程。新增、替换、移除、校验、ICDB 维护和恢复在执行前提示手动备份;请自行保留可用副本。导入暂存、恢复用隔离验证库和轻量操作证据仍会生成,Mentor 原生 Repair 自身的备份行为保持不变。详见[自动备份检查与调整](docs/releases/2026-11-03-manual-backup.md)。此条优先于下方历史版本的备份说明。
当前补丁:**[v0.2.3-beta.1](docs/releases/v0.2.3-beta.1.md)(Beta 预发布,待现场验收)**,替代 0.2.2-beta.1。数据库所有权或关闭状态不确定时停止批次、保留现场;不自动移走地址文件、接管带锁设计或强杀 PCB 进程树。新增全库 ICDB 维护、同名 CBB 完整备份恢复弹窗及严格的原生复核流程。详见 [v0.2.3-beta.1 发布说明](docs/releases/v0.2.3-beta.1.md)。下方日期记录描述历史版本,以本补丁说明为准。
@@ -7,7 +9,7 @@
针对 `The last server session ... lost the connection to the database`,修复分支增加
`ICDB_REPAIR_REQUIRED` 专项识别、共享符号库路径诊断及停止批次处理。现场原生修复步骤及实现边界见
[iCDB 旧服务器会话失联分析](docs/diagnostics/2026-10-27-icdb-lost-server-session.md)。
当前分支会在目标明确、完整备份和所有权释放证据齐全时尝试一次同版本原生 Repair;共享符号库没有 PRJ 入口时停止并要求人工处理。
当前分支会在目标明确、所有权释放和独占访问证据齐全时尝试一次同版本原生 Repair;操作前请手动备份,共享符号库没有 PRJ 入口时停止并要求人工处理。
## 功能边界
@@ -201,7 +203,7 @@ Mentor 桥耗时需在目标机器另行测量。
- `save.log`:`LICENSE_OK / SAVE_OK / IS_SAVED / POST_SAVE_SYNCHRONIZED / CLOSE_OK / QUIT_OK`;
- `result.json`:状态、中心库标志读取结果、阻断原因;
- `image-status-map.json`:按中心库路径隔离的本机动态 `image_id` 校准快照(当前格式 `schema_version=2`);旧版本或无版本缓存会自动忽略并重新校准,日志会记录当前样本、缓存样本、Ready 主 ID、未映射 ID 和逐项决策原因;
- `backup/`:仅本地盘操作前的稳定文件副本;网络盘/UNC 跳过前置递归备份(`backup_skipped`);`database/LogFiles/tmp` 等易变目录和日志文件会排除,备份超时或失败不会阻断 PCB 校验。仅在成功且确认安全后清理该目录,失败时保留已有副本及日志;它不是完整数据库回滚备份。
- `backup/`:历史版本的辅助文件副本;当前分支不再生成,所有路径记录 `backup_skipped / manual_backup_policy`。已有历史副本不由本轮改动清理。
超时采用无进展计时:界面和批量请求默认 600 秒无进展超时;它不是整个 CBB 的固定总时限,而是连续 600 秒没有可观察进展时才终止。PCB/COM 阶段切换、Project Integration 状态变化、保存标记变化和弹窗处理都会刷新计时器;重复的状态轮询不算进展。需要更快失败时仍可在界面将单项预算调低,但 30 秒只适合已确认 PCB 启动稳定的环境。
@@ -0,0 +1,65 @@
# ICDB 持续失败:公开资料与实际入口核对
调查日期:2026-11-03。当前源码 `c856960`。本轮是网上资料检索及只读诊断,没有修改库、服务器设置或产品代码,不能作为修复验收。
## 本机确定的缺口
目前找到最近一次实际失败为隔离完整库 IP101GR 的 2026-11-03 16:19(北京时间)记录:
`diagnostics/feedback-final-ui/evidence/verify-85fd17bc6ed2/result.json`
错误为 `DATABASE_RECOVERY_REQUIRED`,阶段为 `PCB_STARTING`。原生提示询问:
> Continue to open the design with read/write access permission?
提示说明可能是文件系统/网络在 15 秒内未确定谁打开了设计,也可能是上一会话异常退出;要求确认没有其他用户正在使用。它没有证明数据库内容已损坏,也不是本轮原生 Repair 的失败结果。
代码及只读复核证据 `diagnostics/icdb-web-research-20261103/routing-evidence.json`:
1. `maintenance_entry.maintenance_needed` 仅在存在库阻止检查点或数据库地址记录时返回真。
2. 当前 IP101GR 没有地址记录、没有阻止检查点,尽管请求 `maintenance=True`,仍返回 `routes_to_native_repair=false`。
3. `select_maintenance_target` 额外要求恰好一个地址记录;无地址时返回 `需要唯一工程地址记录`,因此只改外层判断也不能打通流程。
4. `verify_runner` 的自动补救仅针对 `ICDB_REPAIR_REQUIRED`;当前读写确认错误归入 `DATABASE_SAFETY_STOP`,不会触发该分支。
5. 修复后一次性读写确认已有 `PostRepairProof` 机制,但只有本轮原生修复成功且释放已核实时才授权。当前入口绕过 Repair,自然没有这份证明。
因此,明确维护不能以“没有 sAddress.adr”推断无需维护。地址记录用于定位/占用判断,不应成为识别异常关闭状态的唯一依据。
## 网上资料:已读取原文
### 原生 Project Repair
[Mentor XP 如何修复文件](https://blog.csdn.net/qq_53931654/article/details/147240707)
原文步骤为打开 iCDB Project Backup,指定损坏工程路径,执行 `Project → Repair`。与本机已经接入的官方工具入口一致。本文是用户经验文章,没有证明当前完整自动链路或 CBB 校验限制已经解决。
本轮首次访问返回脚本验证页,后续正常请求取得正文;正文与截图链接保存在 `native-repair.json` / `native-repair.html`。
### 工程备份恢复
[“Unable to open iCDB connection”的解决方案](https://blog.csdn.net/zhangyang125/article/details/136188112)
原文建议从工程 `ProjectBackup/backups` 选择备份,恢复对应文件后重新打开。文章把复制/转移时文件丢失或损坏列为可能原因。该方案会回退版本,不等于保留最新内容的无损 Repair;仍需用户选择可接受版本,恢复后做工程身份与校验确认。
### 连接/监听地址
[Xpedition 2409 Designer 无法打开 iCDB 连接](https://blog.csdn.net/kkisscj/article/details/144323677)
原文描述在工作目录的 iCDB Server 配置中设置 `Network/Address` 为本机地址,并引用 VX2.8 管理文档。这说明“无法连接 iCDB”也可能是监听配置问题,不能一律解释为损坏。
但文章环境是 Xpedition 2409,本机是 EE7.9.5。现有日志未证实本机出现同类监听失败;本轮没有修改 Server 配置、服务或端口。
### 检索限制和排除项
英文 Google/DuckDuckGo 请求连接超时;Bing 多个精确错误查询无结果或结果无关,360 搜索提供了可进一步核对的中文线索。没有取得可直接适用于 EE7.9.5 当前弹窗的 Siemens 官方支持答复。检索及抓取原文保存在 `diagnostics/icdb-web-research-20261103/`。
标题/推荐摘要中含 “iCDB Server Monitor” 的另一页面,正文实际讨论 Android Studio Monitor,已排除,未把无关搜索结果当作技术依据。本机已有帮助文件检索也未找到能补足该弹窗处理条件的准确段落。
## 建议的修正与验证次序
1. 明确维护入口支持“无地址记录但需要检查”的工程:通过用户所选 CBB、唯一 PRJ/PCB 关系和明确数据库映射绑定目标;多个候选数据库必须明确区分,不能猜测共享库或另一个工程。
2. 在本任务 PCB/启动器正常退出、库锁与数据库独占访问确认后,执行一次原生 Project Repair。不要因为看不到地址文件就直接退回打开 PCB。
3. 仅在原生成功、目标一致、进程与地址释放确认后,使用已有修复后读写授权重新打开。未知或外部占用仍停止,不能把同意读写弹窗作为一般重试策略。
4. 如要求选择 PCB 历史版本,明确记录选择及版本回退;随后验证集成、保存、关闭和权威 READY。
5. 如果数据库检查通过,但仍被“已验证 CBB 不允许重新执行 BackAnnotate”阻止,应作为独立的 CBB 注册/校验状态问题处理。此前完整依赖库中“原生重新导入 → 自动校验 → READY”已通过,但不能把重新导入偷偷塞进 Repair 或称为无损修复。
此处已定位入口缺口和可验证的修正方向;尚未实现并完成“无地址记录”维护路径的真实自动链路验收。
@@ -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,46 @@
# 工单 #2:用户实测失败后的修订记录
分支 `codex/temp-issue-2-icdb-recovery`。本轮修订不能视为现场验收通过;未合并、发布或关闭工单。
## 用户失败的实际原因
用户运行 `b26e2f2` 冻结包。真实日志位于程序旁的 `data` 目录。中心库存在有效的未释放会话检查点,应用进入文件系统恢复视图,因此管理按钮被禁用;旧界面没有清楚显示原因,禁用外观也像可用按钮。该次没有启动增删改操作。
ICDB 批次的首项 `1GPHY_8212` 在预检查报 `MAINTENANCE_TARGET_UNCONFIRMED`,原生 Repair 没有执行。旧检查硬性要求 `PCB/pcb.prj`,但该工程的 PCB 明确反向引用主 `1GPHY_8212.prj`。主 PRJ 指向 `database`;存在的 `PCB/template.prj` 不能当作活动工程猜测使用。后续八项被跳过。
## 修订
- 只有 PCB 唯一、精确反向引用主 PRJ 时,允许缺少辅助 `pcb.prj`。预检查、Repair 后重新打开、管理来源身份及库引用核对使用一致规则。`template.prj` 保持原样并参与资产哈希。
- 显示库会话阻止横幅、管理禁用原因、灰色禁用按钮及首项具体失败阶段。
- 集成校验跳过原生明确禁止调用、且已同步的动作;仍要求四项最终全部同步。必需动作被禁止或原生拒绝时继续判失败,不伪造通过。
- 识别原生 EDIF 中数字开头的精确标识符,例如 `&1GPHY_8212`;不放松设计内容比较。
- 私有桌面上的原生库编辑器若提示其他已确认缺少 PCB 的条目,只确认准确匹配的已知通知。当前目标、未知弹窗或身份不符的窗口不自动确认。
- 原生新增共享明确截止时间;父进程超时发出取消信号。阻塞调用返回后,以及所有日志和证据 I/O 完成、提交 OK 之前,重新检查监督进程、取消状态及期限,防止超时后迟到写入。
## 隔离原生证据及限制
证据根目录为 `diagnostics/issue2-user-feedback-20261103/`。
完整现场库副本保留原生地址和所有工程文件,共 38,954 个文件。原用户库始终不参与写入,完整恢复新增结束后 `source-final-recheck.json` 再次确认 25,214 个主要文件与试验前完全一致。
`d36b6bc` 冻结程序的实际维护按钮已在该副本完成完整备份、官方 Repair、数据库地址释放及同一 PCB 重新打开。随后原生要求选择历史 PCB 数据,应用返回 `PCB_VERSION_CHOICE_REQUIRED`,没有显示修复完成。
用户选择最后手动保存版本(2026/9/24 15:15)后,在确切所属的隔离会话中继续。SynchCES 和 LoadCES 成功,但原生 BackAnnotate 仍报已验证工程不允许执行。未保存、未达到 READY,失败 PCB 已正常关闭。这段人工续接不算无人值守自动修复通过。
空隔离库中的重新导入及工程身份核对通过,但自动校验因目标缺少 PartsDB 分区失败,不能算完整校验通过。完整依赖库中的首次同名替换完成原生移除后,新增被其他条目缺少 PCB 的提示阻塞而超时;该部分失败的检查点及完整旧库备份保留在 `diagnostics/full-update-events/`,没有自动重放。
完整隔离库中 IP101GR 的旧数据库地址通过官方 Repair 释放,证据为 `dependency-ip101gr-native-only/result.json`。这只是依赖数据库的原生修复诊断,没有重新打开或 READY 验收。
修订后对缺失的 `1GPHY_8212` 显式执行恢复新增,启用自动校验;独立证据目录为 `diagnostics/full-recovery-events/`。结果为 `UPLOADED_VERIFIED`,`safe_to_continue=true`。已知的其他缺 PCB 条目提示被自动准确确认;新增后独立重读库、三种原生逻辑导出及主要资产比较通过。随后自动执行 ForwardAnnotate、SynchCES、LoadCES、BackAnnotate,四项最终均同步,保存、关闭和进程退出确认完成,权威 `IsVerifiedReuseBlock` 返回 `raw=1 / READY`。自动校验链路耗时 126.422 秒(不含完整备份和新增身份检查)。
最终结果为 `full-recovery-add-result.json`,完整检查点为 `diagnostics/full-recovery-events/management-03a9dbc537f84e0faaea2ad5a2a732c2/checkpoint.json`。此结果证明修订后**重新导入加校验**的恢复路径有效,不能替代直接 ICDB Repair 后仍被原生 BackAnnotate 拒绝的失败结论,也不把用户选择历史数据后的工程称为无损修复。
## 尚未满足的门槛
服务器会话失联经实际按钮触发、自动 Repair、重新打开、保存关闭及权威 READY 的完整链路仍需通过。历史数据选择及重新导入均可能改变恢复版本,不能宣称无损恢复。Windows 10 尚未验证;当前实机为 Windows 11 / Mentor EE7.9.5。
## 自动化验证
修订代码全量 `python -X utf8 -m pytest -q`:**1095 passed,171.09 秒**。保留一条已有 pywinauto STA COM 线程模式警告。`compileall`、`git diff --check` 通过。取消发生在日志证据 I/O 中的回归先复现错误提交,再验证修复;相关集中测试 108 项通过。独立审查已复核全部代码修订,最后一项取消时序 P2 已解决,没有剩余实质问题。
候选包按提交归档构建。最终冻结按钮冒烟结果及构建、压缩包校验记录分别保存在证据目录的 `final-frozen-buttons/result.json`、`build-result.json`、`package-result.json`;按钮冒烟只证明界面响应,不等于现场 ICDB 自动修复验收。
@@ -0,0 +1,46 @@
# 无地址 ICDB 维护及 PCB 版本选择
沿用 `codex/temp-issue-2-icdb-recovery` 临时分支。依据实际错误日志与公开资料修正入口,用户明确授权在需要时弹窗选择版本。应用自动备份仍取消,操作前保留手动备份提醒;未修改原用户库。
## 本次行为
- 明确发起 ICDB 维护时,不再因为没有 `sAddress.adr` 或协调检查点而跳过原生检查。
- 无地址时,所选 PCB 必须唯一反向引用主 PRJ,工程内数据库映射必须唯一。多数据库、共享地址、路径身份不符、原生进程/脚本占用及无法独占读取仍停止。
- 原生 Repair 成功并确认释放后,沿同一任务重新打开。若原生要求选择历史 PCB 版本,主应用显示实际候选时间和“最后手动保存 / 自动保存 / 取消”。不默认选择任一历史版本。
- 用户选择后,私有桌面代理重新核对窗口、进程、候选时间及单选状态,再确认恢复。选择过期、窗口变化或执行失败不重试确认。等待期间应用保持响应;取消停止当前项并保留原生现场。
- 最终仍要求集成校验、保存关闭、进程退出及权威 READY。使用了历史 PCB 版本时,即便校验通过,也记录 `RESTORED_REVIEW_REQUIRED`(已恢复,版本待核对),不标记为无损 Repair。
- 未提供交互入口的调用保留待选择结果,不自动选版本;普通 Verify 不获得修复后授权。
## 过程证据
无地址隔离工程 IP101GR 经实际应用维护按钮完成原生 Repair,地址为空且进程退出。之后严格的修复后授权通过读写确认,继续到 PCB 历史版本选择。证据为 `diagnostics/noaddr-ui/evidence/maintenance-c05e9c4b06b2/result.json`。
用户此前已选择最后手动保存版本(2026/9/24 23:06)。首次诊断续接沿用该选择,完成校验、保存关闭,`IsVerifiedReuseBlock` 返回 READY/raw=1;记录在 `diagnostics/icdb-addressless-20261103/authorized-last-manual/result.json`。该次还通过诊断操作确认了保存弹窗,不能记为完整自动链路通过,因此继续实现上述应用内选择流程。
后续应用内选择试验两次在原生修复前被其他脚本占用阻止。进一步日志显示来自另一工具的并行 `run_bridge.vbs` 测试;没有强制结束或忽略该进程。失败记录保留在 `source-choice-button/`、`source-choice-button-retry/`。
## 验证边界
集中回归覆盖无地址选目标、地址变化、共享/多个数据库、修复后授权、选择/取消、版本日期改变、重复确认、原生动作失败、错 PID/桌面、真实单选状态复读和历史恢复归类。独立代码审查无剩余实质问题。
最终全量测试、冻结构建及实际按钮结果统一记录在 `diagnostics/icdb-addressless-20261103/`。本文件不将历史版本恢复视为无损修复,也不将模拟测试或人工续接替代最终冻结链路结果。
## 最终冻结包结果
程序源码提交 `de952a6`。全量 **1135 passed,228.63 秒**,一条已有 pywinauto STA COM 线程模式警告;编译、diff 检查及独立审查通过。候选程序从该提交的不可变归档构建。
最终试验使用原有完整隔离副本。先由官方 Repair 做独立准备,释放旧地址且不打开 PCB;这只用于构造此前真实遇到的无地址状态,不作为验收。启动最终冻结程序前确认:**地址为空、协调阻止检查点不存在**。
随后通过应用真实维护按钮执行,没有替换原生适配器或直接调用分阶段校验:
1. 原生检查确认未占用,执行 Repair,记录本轮原生日志并确认退出/释放。
2. 同一工程重新打开,应用弹窗显示手动保存和自动保存日期均为 `2026/9/24 23:06`。
3. 在应用弹窗选择用户此前已批准的最后手动保存版本。私有桌面代理完成单选复读及原生确认。
4. 原有监督器自动处理保存 Reusable Block cell 提示,完成校验、保存、关闭及进程退出,无诊断脚本手动点击原生窗口。
5. 权威 `IsVerifiedReuseBlock` 返回 `READY / raw=1`。最终 `PASS / GREEN / safe_to_continue=true`,恢复结果为 `RESTORED_REVIEW_REQUIRED`。
证据:`frozen-choice-button-retry/result.json`、`version-choice.png`,以及
`diagnostics/choice-frozen-ui-retry/evidence/verify-7b0cd3fb8608/result.json`。
之前被其他任务脚本阻止的各次试验均保留,没有计入成功。用户授权关闭并行测试时,该测试已经自行退出,因此没有终止 Mentor 进程或外来测试进程。
该结果证明本机 Windows 11 / EE7.9.5 上 IP101GR 的无地址维护、应用内用户选择和后续完整链路可执行;恢复采用历史手动保存版本,不证明无损保留了该版本之后的修改。未据此合并发布或关闭工单。
+53
View File
@@ -0,0 +1,53 @@
# 自动备份检查与调整
按用户 2026-11-03 最新要求:取消应用操作前自动备份,改为弹窗提示手动备份。本要求覆盖早期计划中的“必须完整备份后执行”。仍在 `codex/temp-issue-2-icdb-recovery` 临时分支,未合并或发布。
## 检查结果与调整范围
| 操作 | 检查到的旧行为 | 当前调整 |
| --- | --- | --- |
| 新增 CBB | 每项复制整个中心库,即使没有旧同名工程 | 取消,记录只读内容基线 |
| 同名替换 | 每项复制整个中心库,再移除并导入 | 取消,保留逐项阶段及失败记录;失败时使用手动备份恢复 |
| 移除 | 每项复制整个中心库 | 取消,原生移除后重新读库确认缺失 |
| 普通校验 | 本地工程辅助备份,网络路径跳过 | 统一取消,记录 `manual_backup_policy` |
| ICDB 修复 | 应用复制完整工程,原生工具另外备份 | 取消应用复制,保留独占访问、原生自身备份及成功证据要求 |
| 从备份恢复 | 整库回退备份,再从中复制验证库;额外保留来源副本 | 去掉回退备份和重复来源副本,直接生成一份隔离验证库 |
| 读取、搜索、筛选 | 无自动备份 | 保持只读 |
## 仍需生成的数据
- 新增/替换的来源暂存及原生内容导出副本:防止原生工具直接改写用户提供的源工程。
- 恢复的隔离验证库:用于在安装前完成实际校验,会占用磁盘并花费复制时间,不能等同于未经修改的整库备份。
- 恢复安装时保留旧 Work:仅同卷目录改名,不复制数据,用于安装失败时还原目录交换。
- 工程库引用修正前的单个 PRJ 原文、日志、清单及检查点:属于轻量变更证据,不是工程或中心库备份。
- Mentor 原生 Repair 自身生成的备份:属于原生修复流程,应用没有绕过。
独立研究探针中显式创建的实验备份及现存历史备份未删除。桌面生产路径不再触发上述旧的自动工程/整库备份辅助函数。
## 用户交互和约束
管理操作沿用原确认窗口,增加“应用不会自动备份,请先手动备份中心库及相关工程”。普通校验、维护、恢复同样在启动前提示;每批一次,取消不启动后台任务。应用不检查也不声称用户已经创建了手动备份。
取消备份不会取消串行任务、库锁、数据库独占检查、目标变更检查、来源身份核对、重新读库验证或未完成任务检查点。替换仍是移除后重新导入,非原子操作;部分失败必须使用手动备份及检查点恢复,不自动重放。
直接 ICDB Repair 的现场完整验收缺口仍保留,本次备份策略调整不代表该故障已解决。
## 隔离原生验证
在既有独立实验库 `diagnostics/reimport-8212/native-add/fixture/mentor_lib.lmc` 通过正式管理引擎实测:
- 原生移除 `1GPHY_8212` 后复读确认缺失,结果 `REMOVED`,安全释放,耗时 39.391 秒。
- 随后原生重新导入同一独立来源,复读名称/分区、原生逻辑导出及主要资产身份确认通过,结果 `UPLOADED`,安全释放,耗时 101.359 秒。
- 两项操作均没有生成 `library-before` 整库备份,来源主要文件清单未变。测试未启用自动校验,不将上传成功解释为 READY。
证据:`diagnostics/manual-backup-20261103/native-cycle-result.json`、`native-cycle-accepted.json` 和 `diagnostics/mb-events/`。上述耗时包含原生启动、复读和内容检查,不能当作与旧版同环境对照的提速比例。
开始实测前发现上一版应用在完整隔离库 IP101GR 上保留了“继续以读写方式打开”提示。仅向已核对进程命令和私有桌面的该提示发送“否”,两个 PCB 进程正常退出;没有强杀、保存或删除原生地址。原失败证据与取消记录保留在 `previous-test-cancel.json`。随后通过正式释放检查解除小实验库旧阻止记录,未绕过库锁。
## 代码验证
最终全量 Python 回归:**1111 passed,192.49 秒**,一条已有 pywinauto STA COM 线程模式警告。集中回归 297 项通过;占用检查修订后相关 151 项通过。编译及 diff 检查通过,独立复审无剩余实质问题。
审查发现取消整库复制时一并丢失了全库数据库独占检查,已改为不复制数据的 `build_exclusive_library_manifest`:记录基线和写入前检查均同时持有所有 `.lmc` / `icdb.dat` 的独占读取句柄。回归覆盖主库、共享库、其他 CBB 数据库仍被共享读取句柄占用的情况,确认未进入原生写入。
候选包从提交归档构建。最终冻结程序手动备份提示及取消测试记录位于 `diagnostics/manual-backup-20261103/frozen-prompts/result.json`,构建和交付信息保存在同一证据目录。
+62 -16
View File
@@ -1,31 +1,77 @@
# Native CRUD integration and review follow-up
# 原生 CBB 增删改查接入与候选包验证
The shared native Add transport uses the proven private-desktop UIA executor, bounded field readback and exact native success message. It closes/reopens the library before comparing exact catalog name/partition and engineering identity. Missing registration or mismatched native logical/drawing/physical proof cannot become an accepted upload. Production Add/Update are now enabled only with the exact pinned EE7.9.5 core and all three identity exporters, for ASCII target names in the proven DxDesigner / Logical-Physical scope. Every mutation still requires the prepared engine transaction and complete recovery snapshot.
程序源码提交:`b26e2f2f6232c22a94ee1269bd4449fe0fe06623`。
分支:`codex/temp-issue-2-icdb-recovery`。本地候选包,未合并、未发布、未关闭工单。
The review of 07a9c1e identified that route readiness alone did not authorize existing-library mutation. The follow-up makes public `add()` refuse before reading a source or launching a worker. Research callers must use `add_owned_fixture(..., probe_token=...)` against the fixed library created by the diagnostic workflow and matching probe-owner record. It requires the calling thread's live library lease, checks its lease ID against the checkpoint, owns the management mutex during submission, creates a fresh staged source copy and verified library snapshot, and binds the transaction nonce to target, name, partition, source identity and manifests.
## 已接入的操作
Before native activation the worker revalidates that evidence, exact current lease and live supervisor. It duplicates the supervisor's still-open exclusive sidecar handle and checks its final path, so JSON metadata alone cannot establish ownership. Source alignment is confined to the newly copied worker source. Existing probe CreateLibrary/readd guards remain intact. Removal success matching again excludes both carriage returns and newlines.
| 操作 | 原生入口与验收条件 |
| --- | --- |
| 读取 | `LibraryManager.Application.OpenLibrary`、`Partitions(7)`;核对库身份、分区和条目,正常关闭会话。 |
| 新增 CBB | `OnReusableBlocksEditor` → Logical-Physical → New;私有桌面 UIA 和有时限的控件消息提交完整 PRJ,确认成功提示后关闭重开库,再核对工程内容。重名拒绝覆盖。 |
| 用工程替换已选 CBB | 完整工程及中心库备份 → 原生移除 → 原生重新导入 → 重新读库和内容核对。失败保留恢复证据并停止后续写操作。 |
| 移除已选 | 安装脚本确认的 `CleanWGLib.exe <lmc> F4 <list>`,输入为 `REUSE_BLOCK`;先完整备份,要求明确 Removed 输出,再重新读库确认不存在。 |
Verification is mocked/file-only: the original focused suite passed 86 tests plus two close/reopen checks. Follow-up tests reject public bypass, unprepared activation, missing current-thread ownership, invalid nonce/token/lease, substituted original source, changed backup and expired supervisor, and exercise a valid leased fixture with unchanged original source bytes. No Mentor processes, builds or full suite were launched by this implementation agent; serialized native evidence and semantic-identity research remain coordinator-owned.
“用工程替换已选 CBB…(原生重新导入)”与已有“从备份恢复 CBB…”是不同操作。前者更新中心库注册条目,采用移除后重新导入,**不是原子替换**;后者沿用备份 Work 的副本验证与安装恢复流程。
The follow-up focused suite passed 99 tests. After restoring ordinary catalog queries for non-DxDesigner flow readback, the native boundary/field subset passed 47 tests (including four additional flow cases). `git diff --check` passed. The original ignored scratch report remains on disk but is removed from version control.
新增和替换默认继续自动校验,允许批次开始前取消。结果分别显示上传失败、上传成功但校验失败、上传并校验通过;取消自动校验时明确显示“已上传 / 未自动校验”。
A second review found ownership lifetime and reverse containment gaps. The fixture route now nests the already-proven caller lease around worker dispatch and retains that same exclusive handle/checkpoint on unsafe return or exception, including callers that supply no release callback. It also rejects a fixture nested anywhere inside the original source tree before staging. Three new failure cases were observed before the fix; the final native-boundary/field subset passed 51 tests, including normal release and uploader-handle denial after uncertain release. No native processes were launched.
## 支持范围与保护
The subsequent `mentor795-native-content-v1` contract requires pinned native hierarchy/flat ASCII, CSV/property tables and schematic EDIF exports on disposable copies, plus exact raw physical/primary assets. Only the three observed ASCII metadata headers, CSV `System_Date` field and root EDIF `status/written/timestamp` node are normalized. All project library references must resolve to an approved library before their values can be normalized. Unknown primary files, layout data, drawing coordinates, properties and EDIF userData remain part of the comparison. Unsupported exports fail closed; this is not a claim of arbitrary unexported CES equivalence.
- 已验证本机 Mentor EE7.9.5、DxDesigner、Logical-Physical、ASCII CBB 名称。原生核心组件和三种内容导出程序均核对固定 SHA-256;接口或版本不符时禁用并显示原因。
- 所有写操作使用串行任务、共享互斥和上传工具兼容的库锁;暂存来源、完整备份、目标身份、事务随机标识、监督进程及实际独占句柄必须相互匹配。
- 不直接修改 LMC 二进制,不依赖独立上传工具安装目录,不退回前台鼠标。遇到中心库升级或流程选择提示拒绝自动迁移。
- 原生导入会改写 ICDB 存储字节。内容身份采用官方 ASCII、CSV 和 EDIF 原理图导出,加上 Layout、约束及其他主要资产的 SHA-256。只规范化已实测的报告时间和路径字段;未知工程文件继续参与比较。
- 原生复制可能留下不正确的 PCB 库相对引用。仅在本任务导入、会话释放及库锁持有得到确认后校正已导入副本,再复读目录与内容。原始来源不改写。
- 导出副本所有权随库检查点持久保存;超时、重启、地址记录仍存在或进程、独占访问无法确认时,不能解除库锁或接续维护。
- 完整来源和预计目标路径达到 260 个 UTF-16 单元时,在原生写入前拒绝;同名替换在移除旧条目前检查。保留所有文件,提示缩短操作数据或目标库路径,不宣称已实现原生长路径支持。
- 本轮已确认的原生复制失败即时记录。只正常确认本任务进程的已验证错误对话框;未知提示不自动点击,会话释放不明确时保留阻止状态。
The real management engine now captures a source baseline before any removal. Native Add requires a prepared transaction binding the verified full backup, staged source, baseline proof, exact target/name/partition, supervisor and exclusive lease. After normal native release, it corrects imported PRJ/PCB library references using the existing documented text helpers, reopens the exact native catalog and compares a target-only identity. Update remains remove plus Add; failures retain the recovery snapshot and checkpoint. The UI action is explicitly labeled “用工程替换已选 CBB…(原生重新导入)”; backup Work restoration is unchanged.
## 实际验证
Coordinator-native source/registered capture matched all three exports and primary assets after correcting the observed imported PCB reference; original source manifests were unchanged. Implementation verification remains file-only: 114 focused tests passed before the final bootstrap/lease refinement. `create_owned_fixture` and `run_owned_fixture_management` provide a token-bound empty-library/real-engine route for the coordinator's actual CRUD cycle. Production Add/Update remain disabled until that separate acceptance and promotion step.
环境:Windows 11,版本 `10.0.26200`;Mentor EE7.9.5。
The coordinator's native engine cycle subsequently passed empty-library creation, Add A, duplicate refusal, same-name replacement by B (with a different verified layout hash), removal with strict absence, and reimport from a complete backup. Every operation reported safe native release and both original source manifests stayed unchanged; evidence is under `diagnostics/issue2-native-crud-20261103/engine-e2e`.
### 原生完整管理引擎
Final safety review narrowed the additional iCDB runtime exclusions to known log directories, exact events files and the observed dated GUID log filenames. Unknown `cdbsvr` content remains primary, including unknown events/plog files, and a registered unknown-file change now requires recovery. Export capture binds its analysis copy to the existing library checkpoint before launch. That binding survives retention/restart and cannot be cleared by release or maintenance adoption until recorded processes/child handles have exited, known exporter/server processes are absent, copied addresses are absent and copied database files can be held exclusively. Missing/malformed ownership evidence remains blocked. The final focused safety/engine suite passed 167 tests; no native operations or full-suite run were performed by the implementation agent. Production promotion remains a separate reviewed change.
真实新建隔离库完成:新增 A、拒绝重复名称、替换为 B、备份后移除、将独立备份工程重新导入。各项会话均安全释放。B 的 Layout 哈希与 A 不同,并与来源 B 一致。原始来源主要文件清单未变。
After scoped review found both safety issues corrected, the separate capability-promotion change enabled the public prepared engine routes. The basis is the accepted native cycle in `engine-e2e/cycle-result.json` plus the matching integrated three-export/asset identity evidence. That cycle deliberately used `auto_verify=False`: it proves native registration/replacement/removal/reimport and content identity, not the separate default Verify result or frozen UI acceptance. Unsupported exporter versions, flows, partitions or export formats still fail closed. Replacement remains non-atomic Remove+Add with recovery evidence, and arbitrary unexported CES/version equivalence is not claimed.
证据:`diagnostics/issue2-native-crud-20261103/engine-e2e/cycle-result.json`。
The promotion focused suite passed 93 tests, including every required binary mismatch, unsupported flow/partition, engine identity/recovery and UI progress behavior. Native default description is blank; progress reads “正在核对来源工程内容”. Source input and backup Work restoration behavior are unchanged. Full-suite/build and fresh public frozen-UI acceptance remain coordinator-owned.
### 最终冻结程序公开界面
Frozen public Add exposed a confirmed legacy path limit: the staged tree contained a 264-character historical CES log path, versus a maximum of 253 in the successful engine cycle. Native output reported `Cannot copy iCDB base of Reusable Block project` and an owned “系统找不到指定的路径。” dialog. The coordinator reproduced Windows error 3 with legacy 32-bit `CopyFile` on that exact file; the same frozen executable, same target library and blank description then completed Add safely when only the operation data/staging root was shortened (`frozen-public-ui-shortpath-control/result.json`).
从应用真实按钮、来源文件选择器和确认清单执行,没有替换原生适配器或绕过能力检查。
The complete staged and projected target trees are now checked against the legacy 260-WCHAR path buffer before native identity capture or Update removal, and again before dialog submission. Unsupported paths produce an actionable shorter-data/target-root message; no source/log files are excluded or deleted. Native copy failure detection uses a bounded pre-submit log size/hash baseline and exact current block name, so old log errors do not fail later operations. The exact observed owned error dialog is recorded and acknowledged only through its known id-2 “确定” button; unknown prompts are recorded without confirmation. Normal child-first close and exact owner-release checks remain required. Confirmed errors now return promptly instead of waiting for the full operation timeout. Focused verification passed 142 tests, including unchanged source/history and no native Remove on long-path update rejection; final frozen acceptance remains coordinator-owned.
| 试验 | 结果 |
| --- | --- |
| 275 字符暂存路径 | `UPLOAD_FAILED`,明确 `NATIVE_PATH_TOO_LONG`,`safe_to_continue=true`;未启动内容导出或原生 Add。 |
| 正常路径新增 A | `UPLOADED`,重新读库与工程内容核对通过。 |
| 同名替换为 B | `UPLOADED`,实际 Layout 匹配 B 且不同于 A。 |
| 原生移除 | `REMOVED`,重新读库确认不存在。 |
| 最终退出与来源检查 | 原生进程已退出;两份来源的 153/147 个主要文件哈希及 541/506 个文件的大小、修改时间保持一致。 |
证据位于 `diagnostics/issue2-native-crud-20261103/`:
- `frozen-public-ui-path-block/result.json`:写入前长路径拒绝。
- `frozen-public-ui/result.json`:最终冻结程序完整按钮流程及截图。
- `final-source-baselines.json`、`final-acceptance.json`:来源和会话释放证据。
- `build-result.json`、`validation.json`、`package-result.json`:源码、测试、构建和包校验记录。
本轮 CRUD 原生及冻结界面试验均在批次开始前取消自动校验,**上传成功不等于 READY**。这些结果不能代替上传后完整 Verify/Save/Close 或现场 ICDB 失联修复验收。
### 实测发现并修正的长路径问题
初版冻结程序在 264 字符暂存文件路径下弹出“系统找不到指定的路径”,日志记录 `Cannot copy iCDB base of Reusable Block project`,旧逻辑只检查成功提示,直到超时才返回。该失败未计入通过。
对同一文件,旧式 32 位 Win32 CopyFile 复现错误码 3;保持同一冻结程序、测试库、完整来源和空描述,仅缩短暂存路径后,原生新增和内容核对通过。最终修订增加完整路径预检和本轮失败识别,并在新冻结包实测提前拒绝。没有删减长路径中的日志或其他文件来绕过问题。
保留原始失败、正常关闭及库锁重新核验记录:`frozen-public-ui-longpath-failed/`、`longpath-failure-release/`、`longpath-failure-catalog/`、`path-copy-probe/`、`frozen-public-ui-shortpath-control/`。
## 自动化验证与交付
- 全量 `python -m pytest -q`:**1071 passed**,90.98 秒,1 条已有 pywinauto COM 线程模式警告。
- `python -m compileall -q src tests`、`git diff --check`:通过。
- 独立整体代码审查及长路径修订复审:无未解决的实质问题。
- 从提交归档构建冻结程序,启动与退出冒烟测试通过;上述公开界面验收使用同一构建。
- 候选包:`dist/issue2-native-crud-20261103-b26e2f2.zip`,旁附 SHA-256;包内含使用说明及验证摘要。
尚未完成 Windows 10 实机验证,也未将本轮 CRUD 试验视作现场服务器会话失联修复通过。旧版库迁移、其他 Mentor 版本、非 Logical-Physical 分区及原生长路径支持不在已验证范围。原用户库不参与本轮写入试验。
@@ -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,29 @@
# ICDB 维护审查修正(候选)
替代 `8180a8a` 的诊断实现。该旧候选曾把完整校验当作诊断,且存在缺失证据后直接进入 Repair 的分支,不应继续用于原库。
## 行为
- READY 始终不进入维护或默认备份恢复队列,即使被勾选。混合选择只处理可见的、可用的非 READY 项;全部 READY 时没有可执行目标,不回退到处理 READY。
- 先取得上传工具兼容的库锁,验证检查点、工程身份、进程和数据库独占访问,再启动诊断。
- 独立的 `diagnostic_only` 模式只打开并确认目标,随后通过原生 `Close(False)` 关闭。不执行 Project Integration、保存、原生 LM Verify 菜单、工程库路径改写或 READY 校验。Mentor 启动本身仍可能生成运行日志/地址记录,因此不宣称整个原生过程绝对只读。
- 诊断拒绝配置中指向其他中心库的引用,包含缩进/制表符格式。不会为了检查而改写引用。
- 原生关闭助手最多调用一次。关闭返回后最多观察 30 秒的进程/地址释放;超时保留现场并停止。
- Repair 只接受本次独立证据目录中的结构化 `ICDB_REPAIR_REQUIRED` 记录,要求工程级范围、会话身份和精确匹配的数据库路径。修复前再次确认目标及释放状态。
- 删除通过 Python 函数名、模块名判断可信度的逻辑,以及吞掉断言/pytest 失败后直接修复的分支。缺少证据、通用数据库安全错误、其他工程或历史轮次证据均不能授权 Repair。
- 诊断通过在报告中单列“启动检查通过、未修复”,不冒充修复完成或 READY。只有修复后完整校验取得权威 GREEN/READY 才算修复验证通过;历史恢复仍需核对版本。
## 验证范围
- 最终从 `ef652f3` 导出的固定源码运行完整回归:`python -X utf8 -m pytest -q --tb=short`,**1,151 passed,375.48 秒**;仅既有 pywinauto STA 警告。
- 此前的专项覆盖包括库锁、证据缺失/其他工程/历史轮次、无集成保存、关闭失败、路径格式、READY 选择范围和延迟退出。最终源码副本与构建输入哈希已核对。
- `compileall` 与 `git diff --check` 通过。
- 独立审查发现并修正重复关闭和路径格式遗漏;冻结构建和启动结果另存于 `diagnostics/icdb-review-20261104/`。
- 冻结启动/退出检查返回 0;EXE 内 5 个变更模块与固定源码编译结果一致;ZIP CRC 校验通过。
- 最终候选:`dist/issue2-icdb-reviewed-ef652f3.zip`,50,871,172 字节;SHA-256:`f4565f1696caf620522d621bd8555817a6d7d5d6ed4193cf87f2b53758a5d8c7`。构建和测试证据对应代码提交 `ef652f3ada0b9b8422e49f2ebc5b18305204d8ab`。
## 保留的限制
本轮不在原库执行原生操作,未重新完成现场失联故障的端到端验收。仅有 `sAddress.adr`、历史版本选择提示或一般数据库错误不足以认定 ICDB 损坏;这些情况会停止并保留证据,不自动 Repair。若原生启动后会话未释放,也不会继续修复或处理下一项。
本候选不推送、不合并发布、不关闭工单。测试中的模拟边界用于验证队列和安全条件,不代替现场 Mentor 验收。
@@ -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 项及冻结原生流程的失败结论仍分别保留,不能把展示回放当作新增原生验收。
@@ -0,0 +1,12 @@
# 无地址 ICDB 维护与 PCB 版本选择
用户要求按已确认的入口分析修复,并明确允许需要时弹窗让用户选择。沿用临时分支,不恢复应用自动备份,不改原库。
- [x] 无地址记录的明确维护也进入原生 Repair;仅允许唯一数据库与 PCB/PRJ 反向引用绑定,保留全库独占检查。新增回归先失败,集中 250 项通过,独立审查通过。
- [x] 实际应用按钮在无地址 IP101GR 副本完成原生 Repair,随后需要 PCB 版本选择;沿用用户此前确认的手动保存版本,诊断续接已保存关闭并读取 READY。人工续接不算完整自动链路验收。
- [x] 在主应用显示候选时间和手动保存/自动保存/取消按钮。没有 UI 选择入口的调用保持待选择,不自动选版本;每个原生窗口只问一次,等待期间继续观察会话。
- [x] 原生动作仍由私有桌面代理执行,核对修复证明、进程、窗口和候选版本;先选择单选项并复读,再确认 OK;取消或窗口变化不确认恢复。
- [x] 用户选择后沿原校验链路继续,原生保存提示仍由已有监督器处理。最终 READY 保持原有门槛;使用历史 PCB 版本记录“已恢复,版本待核对”,不标记无损修复。
- [x] 测试 UI 取消、手动/自动选择、选择失效、重复弹窗、错 PID/桌面、原生失败和 READY 区分;独立审查、全量回归、冻结实际按钮验证并交付候选。1135 项通过;de952a6 冻结实际按钮达到 PASS/GREEN/READY,历史版本仍标记待核对。
采用独立版本选择控制器与 Qt 对话框,复用原生代理及现有进度信号;不引入前台鼠标或自动重导入。界面只要求选择已有候选版本,不替用户推断应采用哪个版本。
@@ -0,0 +1,36 @@
# Manual Backup Implementation Plan
**Goal:** 按用户最新要求取消应用操作前的自动备份,改为提示手动备份,减少整库复制和重复哈希耗时。
**Architecture:** 管理操作使用只读内容基线、暂存来源、原生身份核对和现有库锁。备份责任转为用户;应用不验证或声称手动备份已存在。恢复操作只创建用于隔离校验的库副本,不再额外复制完整回退库。原生 Repair 自身备份保持原生行为。
**Tech Stack:** Python 3.12 / PySide6 / Mentor EE7.9.5。
用户已明确指定取消自动备份并提示手动备份,本计划直接执行。沿用临时分支,不合并发布、不修改原用户库。保留既有 `review.diff`。
## 范围与检查结果
| 操作 | 旧行为 | 新行为 |
| --- | --- | --- |
| 新增、替换、移除 | 每项完整中心库备份 | 手动备份提示;只读基线、检查点及来源暂存 |
| 普通校验 | 本地 CBB 辅助备份,网络跳过 | 所有路径统一取消应用辅助备份 |
| ICDB Repair | 应用完整工程备份,加原生自身备份 | 取消应用复制,保留独占读取/身份检查及原生自身行为 |
| 从备份恢复 | 整库回退备份再复制验证库;额外来源副本 | 直接复制一次隔离验证库,来源直接暂存到验证工程 |
| 读取/搜索/筛选 | 无备份 | 保持只读 |
验证工程副本和来源暂存是任务输入,不能删除后直接改原始来源。恢复安装中的旧 Work 改名保留是目录交换保护,不复制数据,继续保留。历史证据与备份不清理。独立研究工具的显式备份不属于桌面自动操作。
## Tasks
- [ ] 管理:先增加不复制整库及基线变化阻止写入的回归;移除事务授权对备份目录的依赖,绑定基线清单,保留身份、监督进程、活跃库锁和检查点验证;更新对应测试。
- [ ] 校验/Repair/恢复:先写不调用自动备份、保持独占检查及单一验证库副本的回归;改调用路径和进度说明,测试取消/占用/来源及目标变化继续阻止操作。
- [ ] 界面:将手动备份提示加入管理、校验、维护、恢复执行确认;取消不启动任务,每批一次,不伪称备份已完成。移除自动备份承诺。
- [ ] 验证:集中测试、全量 Python 测试、编译与 diff 检查、独立代码审查;隔离原生移除验证不创建整库备份;新冻结包验证提示和取消反馈。更新验证记录,提交并构建候选。
## Review Focus
- 没有备份目录仍能通过真实管理事务校验;错库、过期锁、来源变化、基线记录篡改仍拒绝。
- 替换移除成功但新增失败必须保留部分失败检查点,明确使用用户手动备份恢复。
- 删除备份调用不能同时删掉数据库独占和取消检查。
- 恢复仍隔离验证,并保留来源/目标变更检查与失败安装回退。
- UI 取消确认无写入;逐项自动校验不重复弹窗;没有目标时不弹无意义提示。
@@ -0,0 +1,32 @@
# 原生 CBB 管理接入续作
沿用用户已批准的工单 #2 管理范围与临时分支。此次用户要求找到并尝试接入库的增删改查原生接口。
不直接修改 LMC 二进制,不采用前台鼠标,不强制结束持有数据库的原生进程;原用户库不参与写入试验。
## 已确认接口
- 查询:LibraryManager.Application.OpenLibrary → Partitions(7) → 名称、分区,核对库身份并正常退出。
- 新增:OnReusableBlocksEditor → 原生 Logical-Physical 页签 → New → 源 PRJ、名称、顶层块,提交原生对话框。字段使用有时限的窗口消息复读,提交后确认成功消息,再关闭重开目录。
- 移除:安装脚本确认的 CleanWGLib/F4/REUSE_BLOCK,必须完整备份且重新读库确认缺失。
- 同名替换:复用经过验证的移除与新增;它不是原子更新,删除后导入失败时保留恢复检查点并停止队列。与仅替换 Work 的“从备份恢复”明确区分。
## 接入步骤
1. 共享原生新增适配层,保留私有桌面、二进制版本、同库租约、监督进程、来源暂存及完整备份的验证。生产能力未通过时只有带隔离库所有权证据的研究入口可写。
2. 原生 ICDB 导入会重写存储。用安装版本锁定的 ASCII、CSV 和 EDIF 原理图导出建立内容指纹,并保留布局及其他工程资产的字节哈希。不能把注册成功或名称相同等同于工程内容一致。
3. 导出仅使用新建的完整工程副本。严格确认退出、有效输出与原生完成标记;仅规范化已经实际证明会变化的报告时间/路径字段。布局、坐标、连接、属性及未知工程文件变化一律阻止接受。
4. 新增后原生程序可能未正确重定位 PCB 配置的 CentralLibrary。仅在本任务注册成功、原生释放和租约持有时修正该已导入工程的库引用,再重新打开核对目录与内容。原始输入工程不改动。
5. 在实际新建隔离库运行新增、同名冲突、不同版本同名替换、备份后移除、从备份重新导入;逐项保存证据,验证源文件未变。随后才提升对应生产能力。
6. 运行相关回归、独立审查、全量测试与冻结包实际管理入口验证。缺少原生证据的能力继续禁用并准确说明原因。
## 已完成的内容指纹取证
`diagnostics/issue2-native-crud-20261103/` 保存真实导出对照:
- ASCII:层次与展开连接、组件、端口和属性,3,531 行;只差生成时间和数据库目录三行报告元数据。
- CSV:14 个表格文件;只差信息表的 System_Date 字段。
- EDIF `-schematic`:约 580 KB,包含坐标、图形、连线、旋转、文本位置及属性;只差根级 status/written/timestamp。
- 139 个主要工程资产一致;其余变化为 ICDB 数据文件、其运行时记录及两处 PCB CentralLibrary 引用。
以上为已验证格式的内容身份合同,不声称任意未知版本、任意外部工具私有元数据都可无差别转换。
导出格式、安装版本、必需文件或引用不符合时拒绝操作。
+16 -1
View File
@@ -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'),
+11
View File
@@ -27,6 +27,8 @@ def configure_qt_application(app):
}
for role, color in colors.items():
palette.setColor(role, QColor(color))
for role in (QPalette.ColorRole.WindowText, QPalette.ColorRole.Text, QPalette.ColorRole.ButtonText):
palette.setColor(QPalette.ColorGroup.Disabled, role, QColor('#858b94'))
app.setPalette(palette)
app.setStyleSheet(
'QWidget { color: #202124; }'
@@ -34,6 +36,7 @@ def configure_qt_application(app):
'background: #ffffff; color: #202124; selection-color: #202124; }'
'QHeaderView::section { background: #e9edf2; color: #202124; }'
'QPushButton, QToolButton { color: #202124; }'
'QPushButton:disabled, QToolButton:disabled { color: #858b94; background: #e3e6eb; }'
)
return app
@@ -47,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)
@@ -57,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)
+18 -21
View File
@@ -86,17 +86,18 @@ def _source_check(source, name, original):
def _align_library(project, pcb, library):
from .mentor_adapter import ensure_project_central_library, ensure_pcb_central_library
for path in (project, pcb.parent/'pcb.prj'):
from .mentor_adapter import ensure_project_central_library
from .maintenance_entry import maintenance_project_files
projects = maintenance_project_files(project, pcb)
for path in projects:
if not re.findall(r'^KEY CentralLibrary "([^"]*)"', _project_text(path), re.M):
raise ValueError('备份工程缺少 CentralLibrary 引用。')
def already_references(path):
return all((path.parent/value).resolve() == Path(library).resolve()
for value in re.findall(r'^KEY CentralLibrary "([^"]*)"', _project_text(path), re.M))
if not already_references(project):
ensure_project_central_library(project, library)
if not already_references(pcb.parent/'pcb.prj'):
ensure_pcb_central_library(pcb, library)
for path in projects:
if not already_references(path):
ensure_project_central_library(path, library)
def recover_from_backup(request, source, *, progress=None, verifier=None, idle_check=None):
@@ -127,7 +128,7 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
installed = False
record = {'operation': 'same_cbb_complete_project_restore', 'source': str(source),
'library': str(library), 'block': request.block_name, 'installed': False,
'validation_library': str(validation_dir/library.name)}
'validation_library': str(validation_dir/library.name), 'backup_policy': 'manual'}
def emit(stage, message, **details):
if progress:
progress({'stage': stage, 'block': request.block_name, 'message': message, **details})
@@ -164,22 +165,17 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
library_size = sum(info.st_size for info in _scan(library_root).values() if stat.S_ISREG(info.st_mode))
source_size = sum(info.st_size for info in _scan(source.parent).values() if stat.S_ISREG(info.st_mode))
same_drive = root.anchor.casefold() == validation_dir.anchor.casefold()
required = library_size * (2 if same_drive else 1) + source_size * 3
required = (library_size + source_size * 2) if same_drive else 0
if (shutil.disk_usage(root).free < required
or shutil.disk_usage(validation_base).free < library_size + source_size * 2):
raise ValueError('磁盘空间不足:需要容纳中心库回退副本和验证副本。')
or shutil.disk_usage(validation_base).free < library_size + source_size * 2
or shutil.disk_usage(library_root).free < source_size):
raise ValueError('磁盘空间不足:需要容纳隔离验证库和待安装工程。')
(root/'recovery-request.json').write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
emit('backup', '正在保留完整中心库副本…')
emit('prepare_source', '正在准备隔离验证库;应用不自动创建回退备份…')
library_scope = ManifestScope.library(request.block_name, library.name)
original_manifest = _copy_verified(library_root, root/'library-before', scope=library_scope,
progress=copy_progress('backup', '正在保留中心库副本:'))
(root/'library-before-manifest.json').write_text(json.dumps(original_manifest, indent=2), encoding='utf-8')
emit('prepare_source', '正在准备备份验证副本…')
source_manifest = _copy_verified(source.parent, root/'source-before',
progress=copy_progress('prepare_source', '正在保留备份工程副本:'))
(root/'source-before-manifest.json').write_text(json.dumps(source_manifest, indent=2), encoding='utf-8')
_copy_verified(root/'library-before', validation_dir, scope=library_scope,
original_manifest = _copy_verified(library_root, validation_dir, scope=library_scope,
progress=copy_progress('prepare_source', '正在准备验证库:'))
(root/'library-baseline-manifest.json').write_text(json.dumps(original_manifest, indent=2), encoding='utf-8')
staged_library = validation_dir/library.name
staged_work = staged_library.parent/'ReusableBlocksLP'/request.block_name/'Work'
# Both paths are newly created private copies; originals are retained.
@@ -187,8 +183,9 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
if not resolved_work.is_relative_to(validation_dir.resolve()):
raise ValueError('验证副本工程路径越界。')
shutil.rmtree(resolved_work)
_copy_verified(root/'source-before', staged_work,
source_manifest = _copy_verified(source.parent, staged_work,
progress=copy_progress('prepare_source', '正在准备备份验证工程:'))
(root/'source-manifest.json').write_text(json.dumps(source_manifest, indent=2), encoding='utf-8')
staged_project = staged_work/source.name
staged_pcb = staged_work/source_pcb.relative_to(source.parent)
_align_library(staged_project, staged_pcb, staged_library)
@@ -238,7 +235,7 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
if final.status == 'PASS' and (final.library_flag != 'GREEN' or not final.safe_to_continue):
final = replace(final, status='FAIL', stderr='目标工程恢复后的 Ready 状态未确认。')
if final.status != 'PASS':
final = replace(final, stderr=(final.stderr + '\n原工程和完整库副本已保留,请查看恢复记录。').strip())
final = replace(final, stderr=(final.stderr + '\n原 Work 已改名保留;应用未创建完整库备份,请查看恢复记录并使用手动备份。').strip())
return save(final)
except Exception as error:
return save(VerifyResult('FAIL' if installed else 'BLOCKED', stderr=str(error),
+5 -2
View File
@@ -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)
+82 -25
View File
@@ -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:
+8
View File
@@ -236,6 +236,14 @@ class DialogActionExecutor:
def perform(self, snapshot: WindowSnapshot, action: dict) -> ActionResult:
channels = tuple(action.get("channels", ()))
action_name = action.get("action")
if action_name == 'user_selected_pcb_version':
try:
from .pcb_restore_prompt import validate_action_window
if channels != ('win32_button_click',):
raise ValueError('PCB_VERSION_ACTION_CHANNEL_MISMATCH')
validate_action_window(snapshot, action)
except Exception as error:
return ActionResult(error_code='PCB_VERSION_CHOICE_REQUIRED', detail=str(error))
if action_name == 'post_repair_local_read_write':
try:
from .post_repair_consent import validate_action_window
+13 -7
View File
@@ -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 尚未退出'
+11 -2
View File
@@ -15,16 +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 == '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,
+19 -8
View File
@@ -41,6 +41,7 @@ def refresh_integration(pi, *, emit=lambda **event: None, settle_seconds=5, time
deadline = ActivityDeadline(timeout_seconds, clock=clock) if timeout_seconds is not None else None
in_flight = {}
executed = set()
protected_green = set()
action_history = []
green_entry = None
previous_state = None
@@ -65,6 +66,8 @@ def refresh_integration(pi, *, emit=lambda **event: None, settle_seconds=5, time
# NoCES=3 is recorded as unsupported, never claimed green.
if status not in (1, 2):
raise IntegrationError(f'{name}: unsupported status {status}')
if status != 2:
protected_green.discard(name)
for name in tuple(in_flight):
if state[name] == 2:
started, call_elapsed = in_flight.pop(name)
@@ -74,11 +77,14 @@ def refresh_integration(pi, *, emit=lambda **event: None, settle_seconds=5, time
# When all four lamps start green, mirror the manual refresh: one
# ForwardAnnotate, then only repair statuses that actually become Required.
# Non-green entry keeps the previously validated four-action route.
refreshed = ('ForwardAnnotation' in executed if green_entry
else len(executed) == len(ACTIONS))
checked = executed | protected_green
refreshed = ('ForwardAnnotation' in checked if green_entry
else len(checked) == len(ACTIONS))
if refreshed and not in_flight and all(status == 2 for status in state.values()):
emit(stage='integration_complete', statuses=state, actions=action_history,
policy='green_first_only' if green_entry else 'required_full_sequence')
policy='green_first_only' if green_entry else
'required_with_native_gates' if protected_green else 'required_full_sequence',
skipped_synchronized=sorted(protected_green))
return state
if deadline is not None and deadline.expired():
raise IntegrationError('Project Integration timeout')
@@ -87,14 +93,19 @@ def refresh_integration(pi, *, emit=lambda **event: None, settle_seconds=5, time
continue
action_started = False
for name, method in ACTIONS:
if state[name] == 2 and (name in executed or
if state[name] == 2 and (name in checked or
(green_entry and name != 'ForwardAnnotation')):
continue
allowed = bool(value(pi, 'Is' + name + 'Allowed'))
# A green item still has to receive one Verify refresh attempt.
# Mentor may report the capability as false for that item; this
# flag is a gate only for a genuinely Required (status=1) item.
if state[name] != 2 and not allowed:
# Restored, previously verified CBBs can forbid a synchronized
# action even while another action is Required. Do not invoke a
# native-prohibited method or misreport the skip as a performed call.
if state[name] == 2 and not allowed:
protected_green.add(name)
emit(stage='integration_action_skipped', action=method, initial_status=2,
reason='synchronized_native_action_disallowed')
continue
if not allowed:
emit(stage='integration_action_unavailable', action=method,
initial_status=state[name], reason='mentor_not_allowed')
raise IntegrationError(f'{name}: required but not allowed')
+70 -20
View File
@@ -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):
+301 -73
View File
@@ -1,7 +1,7 @@
"""User-requested native inspection of a project with an existing advertisement.
"""User-requested native inspection with or without an existing advertisement.
An advertisement is never deleted, quarantined or called stale by this module.
Exclusive access permits a backed-up official inspection, not ordinary Verify.
Exclusive access and exact project binding permit an official inspection.
"""
from contextlib import contextmanager, ExitStack
from dataclasses import asdict, replace
@@ -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,22 +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)})
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,
@@ -46,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)
@@ -65,7 +103,26 @@ def _scoped_addresses(request):
return addresses
def select_maintenance_target(request):
def maintenance_project_files(project, pcb):
"""A legacy linked PCB need not contain the auxiliary PCB/pcb.prj.
Its explicit ProjectFile must bind back to the main project. Never guess
template.prj (or another PRJ) as an alternative database repair target.
"""
from .backup_recovery import _project_text
project, pcb = Path(project), Path(pcb)
auxiliary = pcb.parent/'pcb.prj'
if auxiliary.is_file():
return project, auxiliary
if os.path.lexists(auxiliary):
raise ValueError(f'MAINTENANCE_TARGET_UNCONFIRMED: 工程配置不是文件:{auxiliary}')
references = re.findall(r'^KEY ProjectFile "([^"\r\n]+)"', _project_text(pcb), re.M)
if (len(references) != 1 or (pcb.parent/references[0]).resolve() != project.resolve()):
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED: 缺少辅助 pcb.prj,且 PCB 的 ProjectFile 未唯一指向当前主工程')
return (project,)
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
@@ -73,9 +130,10 @@ 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 (project, pcb.parent/'pcb.prj'):
for candidate in maintenance_project_files(project, pcb):
if not candidate.is_file():
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED: 缺少工程配置')
text = _project_text(candidate)
@@ -93,7 +151,16 @@ 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.
references = re.findall(r'^KEY ProjectFile "([^"\r\n]+)"', _project_text(pcb), re.M)
if len(references) != 1 or (pcb.parent/references[0]).resolve() != project.resolve():
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED: PCB 的 ProjectFile 未唯一指向所选主工程')
if len(candidates) != 1:
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED: 无地址记录且存在多个工程数据库,不能推测修复目标')
return candidates[0], project, pcb, addresses
if len(addresses) != 1:
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED: 需要唯一工程地址记录;共享或多个数据库不能推测修复')
matches = [target for target in candidates
@@ -104,49 +171,180 @@ 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()),
'addresses': baseline,
'engineering_references': {str(p.resolve()): hash_file(p)
for p in (project, pcb, pcb.parent/'pcb.prj')}}
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):
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
@@ -154,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
@@ -166,56 +365,85 @@ 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
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
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:
json.dump({'intent': 'explicit_maintenance', 'target': asdict(target),
'maintenance_context': context}, stream, default=str, ensure_ascii=False)
emit('native_repair_start', detail='先完整备份工程与地址记录,再由官方工具检查/修复')
# Repeat immediately before dispatch; worker repeats after complete
# backup and before launching its native process as well.
with maintenance_target_guard(request, context): pass
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, 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,
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 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", "原生维护未确认修复")}',
@@ -223,4 +451,4 @@ def run_existing_address_maintenance(request, *, verify, progress=None):
except Exception as error:
return save(VerifyResult('BLOCKED' if recovery is None else 'FAIL', stderr=str(error),
safe_to_continue=False, recovery_attempts=(recovery,) if recovery else (),
error_category='ICDB_MAINTENANCE_BLOCKED'))
error_category='ICDB_MAINTENANCE_BLOCKED', error_stage=record['stage']))
+13 -11
View File
@@ -7,7 +7,8 @@ import re
from uuid import uuid4
from .library_lock import LibraryLock, LibraryBusy
from .scoped_manifest import ManifestScope, build_manifest, copy_verified, hash_file, scan_tree
from .scoped_manifest import (ManifestScope, build_manifest, build_exclusive_library_manifest,
copy_verified, hash_file, scan_tree)
@dataclass(frozen=True)
@@ -103,7 +104,8 @@ def source_project(source, top_level_block=''):
pcb = reference(source, 'PCBDesignPath')
if not pcb.is_file() or reference(pcb, 'ProjectFile') != source:
raise ValueError('PCB 未引用所选来源工程。')
for path in (source, pcb.parent/'pcb.prj'):
from .maintenance_entry import maintenance_project_files
for path in maintenance_project_files(source, pcb):
if not path.is_file():
raise ValueError('工程缺少 PCB 工程配置。')
# Healthy Expedition PCB projects can use Layout/LayoutDB.lyt without
@@ -178,14 +180,14 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
history.append({'stage': stage, 'time': datetime.now(timezone.utc).isoformat(), **details})
if report:
_write_json(report, {**asdict(request), 'stage': stage, 'status': 'RUNNING',
'safe_to_continue': False, 'history': history})
'safe_to_continue': False, 'history': history, 'backup_policy': 'manual'})
if progress:
progress({'stage': stage, 'block': request.name, 'operation': request.operation, **details})
def finish(status, detail='', safe=True):
result = ManagementResult(request.operation, request.library, request.name, request.partition,
request.source, request.auto_verify, 'complete', status, safe, detail, report)
if report:
_write_json(report, {**asdict(result), 'history': history})
_write_json(report, {**asdict(result), 'history': history, 'backup_policy': 'manual'})
return result
from .com_runtime import initialize_com, uninitialize_com
initialized = initialize_com()
@@ -201,7 +203,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
raise ValueError('中心库必须为现有 LMC 文件。')
evidence = Path(request.evidence_dir).resolve()
if evidence.is_relative_to(library_root) or library_root.is_relative_to(evidence):
raise ValueError('操作记录与备份必须位于目标中心库之外,且不能包含目标库。')
raise ValueError('操作记录与暂存目录必须位于目标中心库之外,且不能包含目标库。')
capability = adapter.capabilities().get(request.operation, Capability(False, '未验证的原生接口'))
if not capability.supported:
return finish('UNSUPPORTED', capability.reason)
@@ -257,9 +259,9 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
# Native/project owners must be idle before snapshot or mutation.
idle_check(library, target_project, target_pcb)
scope = ManifestScope.library(request.name, library.name)
checkpoint('backup')
original = copy_verified(library_root, root/'library-before', scope=scope, progress=progress)
_write_json(root/'library-before-manifest.json', original)
checkpoint('baseline')
original = build_exclusive_library_manifest(library_root, scope=scope, progress=progress)
_write_json(root/'library-baseline-manifest.json', original)
staged = request
identity = None
if source:
@@ -278,8 +280,8 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
if not owner_safe or proof.identity is None:
return finish('UPLOAD_FAILED', proof.detail, owner_safe)
identity = proof.identity
if build_manifest(library_root, scope=scope) != original:
raise OSError('备份后中心库内容变化,停止写入。')
if build_exclusive_library_manifest(library_root, scope=scope, progress=progress) != original:
raise OSError('内容基线记录后中心库发生变化,停止写入。')
if request.operation in ('remove', 'update'):
checkpoint('native_remove')
mutated = True; owner_safe = False
@@ -298,7 +300,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
removed = True
checkpoint('removed')
if request.operation == 'remove':
return finish('REMOVED', '已备份并由原生操作移除,重新读取目录确认不存在。')
return finish('REMOVED', '已由原生操作移除,重新读取目录确认不存在;应用未创建备份。')
checkpoint('native_add')
mutated = True; owner_safe = False
native = adapter.add(staged, root/'add')
@@ -1,4 +1,4 @@
"""Prepared Add authority bound to the engine checkpoint, snapshot and live lease."""
"""Prepared Add authority bound to the engine checkpoint, baseline and live lease."""
import json
import os
from pathlib import Path
@@ -6,7 +6,7 @@ import threading
from uuid import uuid4
from .management import _write_json, engineering_identity
from .scoped_manifest import build_manifest, ManifestScope
from .scoped_manifest import build_manifest
def _read(path):
@@ -62,18 +62,16 @@ def prepare_transaction(request, root, expected_identity, *, mentor_home, fixtur
if (checkpoint.get('status') != 'RUNNING' or checkpoint.get('stage') != 'prepare_identity'
or Path(checkpoint['library']).resolve() != library
or checkpoint['name'] != request.name or checkpoint['partition'] != request.partition
or not {'backup', 'stage_source'}.issubset(stages)):
raise ValueError('Native Add requires the engine backup/staging checkpoint.')
backup = _read(root/'library-before-manifest.json')
if build_manifest(root/'library-before', scope=ManifestScope.library(request.name, library.name)) != backup:
raise ValueError('Management backup has not been verified.')
or not {'baseline', 'stage_source'}.issubset(stages)):
raise ValueError('Native Add requires the engine baseline/staging checkpoint.')
library_baseline = _read(root/'library-baseline-manifest.json')
baseline = _read(root/'source-identity/identity.json')
if baseline.get('safe_to_continue') is not True or baseline.get('identity') != expected_identity:
raise ValueError('Native source identity evidence is missing or changed.')
record = {**current_lease(library), 'nonce': uuid4().hex, 'library': str(library),
'name': request.name, 'partition': request.partition, 'top_level_block': request.top_level_block,
'source_name': source.name, 'source_identity': engineering_identity(source),
'source_manifest': build_manifest(source.parent), 'backup_manifest': backup,
'source_manifest': build_manifest(source.parent), 'library_baseline': library_baseline,
'expected_identity': expected_identity, 'fixture': fixture}
_authorize(record, mentor_home)
_write_json(root/'native-add-prepared.json', record)
@@ -105,11 +103,10 @@ def validate_transaction(job, root, *, check_source=True):
_authorize(record, job['mentor_home'])
baseline = _read(root/'source-identity/identity.json')
if (baseline.get('safe_to_continue') is not True or baseline.get('identity') != record['expected_identity']
or build_manifest(root/'library-before', scope=ManifestScope.library(record['name'], library.name))
!= record['backup_manifest']
or _read(root/'library-baseline-manifest.json') != record['library_baseline']
or check_source and (build_manifest(source.parent) != record['source_manifest']
or engineering_identity(source) != record['source_identity'])):
raise ValueError('Native Add baseline, backup or staged source proof changed.')
raise ValueError('Native Add library baseline or staged source proof changed.')
process = win32api.OpenProcess(win32con.PROCESS_DUP_HANDLE, False, record['supervisor_pid'])
duplicate = None
try:
+83 -54
View File
@@ -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,40 +605,25 @@ 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)}')
# Do not recursively snapshot a live CBB over SMB immediately before
# launching Mentor. The backup is evidence only; on Win10 a timed-out
# robocopy can retain network handles/oplocks and make Verify nondeterministic.
# 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 '')
if mapped_drive and mapped_remote_root:
from .network_path import ensure_mapped_drive_visible
mapping = ensure_mapped_drive_visible(mapped_drive, mapped_remote_root)
emit(stage='mapped_drive_context', **mapping)
emit(stage='backup', block=job['block_name'])
if is_network_backed_path(block_root, mapped_drive=mapped_drive):
backup = {'status': 'SKIPPED',
'detail': '网络盘 CBB 跳过递归备份,避免 robocopy 与 Mentor 竞争 SMB 文件锁'}
emit(stage='backup_skipped', reason='network_source', source=str(block_root))
else:
backup_budget = backup_timeout_seconds(block_root)
emit(stage='backup_budget', timeout_seconds=backup_budget)
backup = best_effort_backup(block_root, root/'backup'/block_root.name,
timeout_seconds=backup_budget, emit=emit)
emit(stage='backup_done', status=backup.get('status'), detail=backup.get('detail'))
# Backup is evidence only, never a prerequisite for launching PCB. Volatile
# database/log directories are intentionally excluded to avoid file locks.
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))
emit(stage='backup_skipped', reason='manual_backup_policy', source=str(block_root),
detail='应用不自动备份;请在操作前手动备份。')
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,
@@ -703,15 +677,28 @@ def execute_job(job, emit):
launcher_process = None
completed = False
identity_verified = False
diagnostic_close_attempted = False
helper = None
app = doc = pi = None
try:
ensure_pcb_central_library(
job['pcb'],
job['lmc_file'],
evidence_dir=Path(root) / 'diagnostics',
emit=emit,
)
if job.get('diagnostic_only'):
if job.get('native_lm_verify') or job.get('post_repair_consent'):
raise ValueError('DIAGNOSTIC_MODE_INVALID: 诊断不能执行原生校验菜单或恢复确认')
from .backup_recovery import _project_text
from .maintenance_entry import maintenance_project_files
library = Path(job['lmc_file']).resolve()
for config in maintenance_project_files(job['project'], job['pcb']):
for match in _CENTRAL_LIBRARY_KEY.finditer(_project_text(config)):
reference = match[2]
if not reference or (config.parent/reference).resolve() != library:
raise ValueError(f'DIAGNOSTIC_LIBRARY_MISMATCH: {config}: {reference}')
else:
ensure_pcb_central_library(
job['pcb'],
job['lmc_file'],
evidence_dir=Path(root) / 'diagnostics',
emit=emit,
)
emit(
stage='verify_mode',
mode=('library_manager_native' if bool(job.get('native_lm_verify', False))
@@ -775,6 +762,33 @@ def execute_job(job, emit):
error_reader=native_error,
)
identity_verified = True
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
diagnostic_close_attempted = True
closed = close_failed_document(job, emit=emit)
if closed.get('status') != 'CLOSED':
raise RuntimeError(f'DIAGNOSTIC_CLOSE_UNCONFIRMED: {closed}')
release_deadline = time.monotonic() + 30
while True:
released = cleanup_verify_processes(lm_pid, worker_pid, worker_parent_pid,
expected_pcb=job['pcb'], baseline_pids=pcb_before, emit=emit)
if (released and released.get('safe_to_continue')
and not unreleased_addresses(job['lmc_file'], job['project'], job['pcb'])):
break
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 启动检查通过;未执行集成或保存,已关闭工程。'}
# Do not acquire MGCPCBAutomationLicensing from this 64-bit Python
# worker. EE7.9 registers that automation class for the 32-bit host;
# the old, working path acquires the token inside the SysWOW64
@@ -803,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:
@@ -839,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)
@@ -860,6 +876,10 @@ def execute_job(job, emit):
pass
if helper is not None and helper.poll() is None:
emit(stage='save_helper_retained', helper_pid=helper.pid)
elif diagnostic_close_attempted:
# A timed-out close helper may still own an in-flight native Close.
# Observe release below, but never start a second close helper.
pass
elif not completed and identity_verified:
try:
from .failed_session import close_failed_document
@@ -918,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}
@@ -963,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
@@ -1421,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
@@ -9,6 +9,36 @@ _COPY_ERROR = b'Error! Cannot copy iCDB base of Reusable Block project.'
_LOG_LIMIT = 2*1024*1024
def missing_other_pcb_notice(library, target, title, text, buttons):
"""Only the observed editor-open information about unrelated missing PCBs."""
from .management import validate_name
from .verify_runner import preflight_skip_reason
heading = ('The following Reusable Blocks do not contain PCB files and will not appear '
'in the list of available reusable blocks:')
if title != 'Library Manager' or len(text) > 131072 or len(buttons) != 1:
return None
button = buttons[0]
if (button.get('id') != 2 or button.get('class') != 'Button'
or button.get('text') not in ('OK', '确定') or button.get('enabled') is not True):
return None
lines = text.strip().splitlines()
if not lines or lines[0] != heading:
return None
names = []
for line in lines[1:]:
if not line.strip(): continue
if not line.startswith('\t'): return None
name = line[1:]
try: validate_name(name)
except ValueError: return None
if name.casefold() == str(target).casefold() or not preflight_skip_reason(library, name):
return None
names.append(name)
if not names or len(names) != len({name.casefold() for name in names}):
return None
return {'names': names, 'button': button['hwnd']}
def snapshot_add_log(library):
path = Path(library).parent/'LogFiles/ReuseBlockLogLO.txt'
try:
+155
View File
@@ -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.
@@ -129,7 +129,17 @@ def normalize_edif(data, top):
raise ValueError('Malformed EDIF header timestamp.')
datetime(*(int(v) for v in values))
design = one(root, b'design')
if one(design, b'cellRef')['items'][1] != top.encode('mbcs'):
top_bytes = top.encode('mbcs')
if re.fullmatch(rb'[A-Za-z][A-Za-z0-9_]*', top_bytes):
expected_identifier = top_bytes
elif re.fullmatch(rb'[0-9][A-Za-z0-9_]*', top_bytes):
# The installed exporter encodes digit-initial EDIF identifiers with
# '&' (observed cellRef &1GPHY_8212). Retain all report bytes; this is
# an exact identity check, not general name stripping or normalization.
expected_identifier = b'&' + top_bytes
else:
raise ValueError('Unsupported native EDIF RootBlock identifier representation.')
if one(design, b'cellRef')['items'][1] != expected_identifier:
raise ValueError('EDIF top design differs from the requested RootBlock.')
if (not any(n['items'] == [b'viewType', b'SCHEMATIC'] for n in nodes)
or any(not any(n['items'][0] == tag for n in nodes) for tag in (b'page', b'figure', b'pt'))):
@@ -163,8 +173,9 @@ def project_library(source):
"""Require one existing approved source library across every project ref."""
from .backup_recovery import _project_text
source, pcb, _ = source_project(source)
from .maintenance_entry import maintenance_project_files
libraries = set()
for path in (source, pcb.parent/'pcb.prj'):
for path in maintenance_project_files(source, pcb):
values = re.findall(r'^KEY CentralLibrary "([^"\r\n]+)"', _project_text(path), re.M)
if not values: raise ValueError('Project lacks CentralLibrary references.')
for value in values:
@@ -192,7 +203,8 @@ def asset_identity(source, expected_library):
expected_library = Path(expected_library)
if not expected_library.is_file(): raise ValueError('Approved CentralLibrary is missing.')
root = source.parent
projects = (source, pcb.parent/'pcb.prj')
from .maintenance_entry import maintenance_project_files
projects = maintenance_project_files(source, pcb)
databases = []
for project in projects:
values = re.findall(r'^KEY iCDBDir "([^"\r\n]+)"', _project_text(project), re.M)
+42 -4
View File
@@ -101,7 +101,7 @@ class NativeManagementAdapter:
'add': Capability(not add_reason and _PRODUCTION_ADD_VALIDATED, add_reason or
'已验证 EE7.9.5 原生导入及完整工程复读;仅 ASCII 名称、Logical-Physical 和 DxDesigner 库。'),
'update': Capability(not add_reason and _PRODUCTION_ADD_VALIDATED and _PRODUCTION_UPDATE_VALIDATED,
add_reason or '已验证同名原生替换:完整备份后移除并重新导入,失败时保留恢复证据。'),
add_reason or '已验证同名原生替换:移除并重新导入;操作前请手动备份。'),
}
def _worker(self, job, evidence):
@@ -161,17 +161,22 @@ class NativeManagementAdapter:
from .desktop_worker import DesktopWorker
request_path = evidence/'request.json'
desktop, timeout = job['desktop'], job['timeout_seconds']
deadline = time.monotonic() + timeout
add_job = job['operation'] in ('add', 'probe_create_add', 'probe_readd')
if add_job:
job = {**job, 'native_add_deadline': deadline}
_write_json(request_path, job)
command = ([sys.executable] if getattr(sys, 'frozen', False)
else [sys.executable, '-m', 'cbb_refresh_verify'])
worker = (self.worker_factory or DesktopWorker)(command + ['--management-worker', str(request_path)], desktop)
deadline = time.monotonic() + timeout
while worker.poll() is None and time.monotonic() < deadline:
time.sleep(.1)
if worker.poll() is None:
# DesktopWorker.close() requests a kill without a cancellation file.
# Keep this exact worker alive until its native call returns normally.
_retained_workers.append(worker)
if add_job:
(evidence/'cancel-native-add.signal').touch()
return {'success': False, 'safe_to_continue': False,
'detail': f'TIMEOUT: 原生调用尚未返回,保留私有桌面 {desktop},请检查 {evidence}'}
try:
@@ -278,12 +283,14 @@ class NativeManagementAdapter:
target, pcb, _ = source_project(projects[0], request.top_level_block)
_idle_check(request.library, target, pcb)
owner_safe = False
before_refs = {str(p): hash_file(p) for p in (target, pcb.parent/'pcb.prj')}
from .maintenance_entry import maintenance_project_files
project_files = maintenance_project_files(target, pcb)
before_refs = {str(p): hash_file(p) for p in project_files}
_align_library(target, pcb, request.library)
if project_library(target) != Path(request.library).resolve():
raise ValueError('Registered project references do not resolve to the exact target library.')
_write_json(evidence/'reference-alignment.json', {'before': before_refs,
'after': {str(p): hash_file(p) for p in (target, pcb.parent/'pcb.prj')}, 'library': job['library']})
'after': {str(p): hash_file(p) for p in project_files}, 'library': job['library']})
catalog = self.catalog(request.library, evidence/'reopen-aligned')
owner_safe = catalog.safe_to_continue
entries = [entry for entry in catalog.entries if entry.name == request.name and entry.partition == request.partition]
@@ -614,6 +621,15 @@ def _probe_add_dialog(app, job, desktop, owned_pids, root, *, library=None):
_close_probe_dialogs(desktop, owned_pids)
def _require_add_supervisor(job, root):
from .library_lock import _supervisor_alive
deadline = job.get('native_add_deadline')
if ((Path(root)/'cancel-native-add.signal').exists()
or deadline is not None and time.monotonic() >= deadline
or not _supervisor_alive(job['supervisor_pid'])):
raise RuntimeError('NATIVE_ADD_CANCELLED: 操作已超时、停止或监督进程退出,未提交新的导入。')
def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None):
"""Submit the proven Logical-Physical Add dialog on an owned library."""
import pythoncom, win32con, win32gui, win32process
@@ -649,7 +665,9 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
return hwnd
pythoncom.PumpWaitingMessages(); time.sleep(.1)
raise TimeoutError(f'原生窗口未出现:{title}')
_require_add_supervisor(job, root)
app.OnReusableBlocksEditor()
_require_add_supervisor(job, root)
editor = await_window('Reusable Blocks')
tabs = Desktop(backend='uia').window(handle=editor).descendants(control_type='TabItem')
physical = [tab for tab in tabs if tab.window_text() == 'Logical - Physical']
@@ -680,9 +698,11 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
ok = win32gui.GetDlgItem(dialog, 1083)
if not ok:
raise RuntimeError('原生新增确认按钮缺失。')
_require_add_supervisor(job, root)
log_baseline = snapshot_add_log(job['library'])
_write_json(root/'native-add-log-baseline.json', log_baseline)
observed_failures = {}
_require_add_supervisor(job, root)
win32gui.PostMessage(ok, win32con.BM_CLICK, 0, 0)
success = None
while time.monotonic() < deadline:
@@ -900,6 +920,7 @@ def _catalog_com(job, root):
stop = threading.Event()
refused = []
observed = []
acknowledged_notices = set()
owned_pids = set()
def observe_dialogs():
while not stop.wait(.1):
@@ -920,6 +941,23 @@ def _catalog_com(job, root):
cancel = win32gui.GetDlgItem(hwnd, 2)
if cancel:
win32gui.PostMessage(cancel, win32con.BM_CLICK, 0, 0)
elif (job['operation'] in ('add', 'probe_create_add', 'probe_readd')
and win32gui.GetClassName(hwnd) == '#32770'):
from .native_add_failures import missing_other_pcb_notice
controls = [{'hwnd': int(child), 'id': win32gui.GetDlgCtrlID(child),
'class': win32gui.GetClassName(child), 'text': win32gui.GetWindowText(child),
'enabled': bool(win32gui.IsWindowEnabled(child))} for child in children]
notice = missing_other_pcb_notice(job['library'], job.get('name'), title,
'\n'.join(c['text'] for c in controls if c['class'] == 'Static'),
[c for c in controls if c['class'] == 'Button'])
key = (int(hwnd), text)
if notice and key not in acknowledged_notices:
acknowledged_notices.add(key)
with (root/'native-information.jsonl').open('a', encoding='utf-8') as stream:
stream.write(json.dumps({'pid': pid, 'hwnd': int(hwnd), 'text': text,
'missing_names': notice['names'], 'action': 'acknowledge_unrelated_missing_pcb'},
ensure_ascii=False)+'\n')
win32gui.PostMessage(notice['button'], win32con.BM_CLICK, 0, 0)
except Exception:
continue
app = library = None
@@ -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'])
+32 -7
View File
@@ -1,4 +1,4 @@
"""Backed-up, single-attempt recovery through the installed native tool."""
"""Single-attempt recovery through the installed native tool."""
from dataclasses import dataclass
import hashlib
import json
@@ -48,6 +48,19 @@ def _hash(path):
return digest.hexdigest()
def check_repair_access(target):
"""Preserve the former pre-copy ownership checks without copying data."""
import win32con, win32file, pywintypes
from .scoped_manifest import scan_tree
scan_tree(target.project.parent) # Reject links before native traversal.
try:
handle = win32file.CreateFile(str(target.database/'icdb.dat'), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
except pywintypes.error as error:
raise OSError(f'REPAIR_DATABASE_IN_USE: 无法独占读取数据库:{error}') from error
handle.Close()
def backup_project(target, destination):
"""Keep every original file, holding icdb.dat exclusively during the copy."""
import win32con, win32file, pywintypes
@@ -130,7 +143,7 @@ def attempt_recovery(request, diagnosis, evidence_root, *, progress=None):
target = select_repair_target(request, diagnosis)
if progress:
progress({'stage': 'native_repair_start', 'block': request.block_name,
'detail': '正在备份并尝试原生数据库修复', 'project': str(target.project)})
'detail': '正在核对占用并尝试原生数据库修复;应用不自动备份', 'project': str(target.project)})
from .mentor_adapter import pcb_processes, _process_details
if pcb_processes() or _process_details('LibraryManager.exe'):
raise ValueError('REPAIR_DATABASE_IN_USE: 原生 PCB/Library Manager 会话尚未退出')
@@ -240,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)
@@ -251,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()
@@ -274,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:
+122 -11
View File
@@ -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, backup_project
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,21 +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:
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:
# 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')
backup_project(RepairTarget(project, database), root/'complete-backup')
emit(stage='complete_backup_verified', path=str(root/'complete-backup'))
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_AFTER_BACKUP')
if maintenance_context is not None:
with maintenance_target_guard(maintenance_request, maintenance_context): pass
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
@@ -335,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')
+8
View File
@@ -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
+61
View File
@@ -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()
@@ -0,0 +1,151 @@
"""Explicit user choice for the owned PCB's native historical-version prompt."""
from dataclasses import replace
import json
from pathlib import Path
from threading import Lock
import time
from .dialog_rules import pcb_version_choice
class RestoreChoice:
def __init__(self, block, library, candidates):
self.block, self.library = block, library
self.candidates = tuple(dict(c) for c in candidates)
self.decision = None
self._lock = Lock()
def choose(self, kind):
if kind != 'cancel' and not any(c['kind'] == kind and c['enabled'] for c in self.candidates):
raise ValueError('Unknown or disabled PCB restoration version')
with self._lock:
if self.decision is None:
self.decision = kind
def _candidate_key(candidates):
return tuple((c['kind'], c['control_id'], c['label'], c['date'], c['enabled']) for c in candidates)
def _choice(snapshot):
choice = pcb_version_choice(snapshot)
buttons = [c for c in snapshot.controls if c.class_name == 'Button']
if (choice is None or any(c.control_id not in (6212, 6213, 6206, 1, 2) for c in buttons)
or len([c for c in buttons if c.control_id == 1 and c.enabled and c.name == 'OK']) != 1):
raise ValueError('PCB_VERSION_PROMPT_CHANGED')
return choice
class RestoreController:
def __init__(self, job):
from .post_repair_consent import _validate_grant
self.job = job
self.grant = _validate_grant(job)
self.prompt = None
self.original = None
self.selection_sent = self.confirm_sent = self.failed = False
self.sent_at = 0.0
def handle(self, snapshot, snapshots, *, target_pid, launcher_pid, worker_pid, companion_pids, show, perform):
from . import post_repair_consent as consent
from .dialog_supervisor import DialogPollResult
from .management import _write_json
try:
choice = _choice(snapshot)
if sum(c['selected'] for c in choice['candidates']) > 1:
raise ValueError('PCB_VERSION_SELECTION_AMBIGUOUS')
if self.failed or snapshot.pid != target_pid or len(snapshots) != 1:
raise ValueError('PCB_VERSION_OWNER_OR_WINDOW_UNCONFIRMED')
if self.original is not None and (snapshot.hwnd != self.original.hwnd
or snapshot.pid != self.original.pid
or _candidate_key(choice['candidates']) != _candidate_key(self.prompt.candidates)):
raise ValueError('PCB_VERSION_CANDIDATES_CHANGED')
pre = json.loads((Path(self.job['root'])/'post-repair-prelaunch.json').read_text(encoding='utf-8'))
if (pre.get('nonce') != self.grant['nonce'] or pre.get('desktop') != self.job['desktop']
or pre.get('worker_pid') != worker_pid or pre.get('supervisor_pid') != self.job['supervisor_pid']
or pre.get('addresses') != []
or not all(consent._same(pre[key], self.grant[key]) for key in ('project', 'pcb', 'library'))):
raise ValueError('PCB_VERSION_PRELAUNCH_PROOF_INVALID')
consent._validate_current_processes(self.job, pre, target_pid, launcher_pid, worker_pid, companion_pids)
if self.prompt is None:
self.original = snapshot
self.prompt = RestoreChoice(self.job['block_name'], self.job['lmc_file'], choice['candidates'])
show(self.prompt)
if self.prompt.decision is None:
return DialogPollResult(activity=True, observed_snapshots=tuple(snapshots))
if self.prompt.decision == 'cancel':
raise ValueError('用户取消 PCB 版本选择;未确认恢复,保留原生现场。')
selected = next(c for c in choice['candidates'] if c['kind'] == self.prompt.decision)
if not selected['enabled']:
raise ValueError('PCB_VERSION_DISABLED')
if self.confirm_sent:
if time.monotonic()-self.sent_at < 2:
return DialogPollResult(activity=False, observed_snapshots=tuple(snapshots))
raise ValueError('PCB_VERSION_CONFIRMATION_NOT_COMPLETED')
if self.selection_sent and not selected['selected']:
if time.monotonic()-self.sent_at < 2:
return DialogPollResult(activity=False, observed_snapshots=tuple(snapshots))
raise ValueError('PCB_VERSION_SELECTION_NOT_CONFIRMED')
confirming = selected['selected'] and sum(c['selected'] for c in choice['candidates']) == 1
control = 1 if confirming else selected['control_id']
action = {'action': 'user_selected_pcb_version', 'channels': ['win32_button_click'],
'target': {'control_id': control}, 'desktop': self.job['desktop'], 'pid': target_pid,
'choice': selected['kind'], 'candidates': list(self.prompt.candidates)}
self.selection_sent = True
self.confirm_sent = confirming
self.sent_at = time.monotonic()
record = {'project': self.job['project'], 'pcb': self.job['pcb'], 'choice': selected['kind'],
'date': selected['date'], 'historical_restore': True, 'confirm_sent': confirming,
'snapshot': snapshot.to_record()}
_write_json(Path(self.job['root'])/'pcb-version-user-choice.json', record)
result = perform(snapshot, action, snapshot.phase)
if result.error_code or result.accepted_controls != (control,):
self.failed = True
return DialogPollResult(error_code=result.error_code or 'PCB_VERSION_ACTION_FAILED', detail=result.detail,
snapshot=snapshot, observed_snapshots=tuple(snapshots))
if confirming:
_write_json(Path(self.job['root'])/'pcb-version-restoration.json', record)
return DialogPollResult(activity=True, action_sent=True, snapshot=snapshot,
action=action['action'], channel=result.channel, accepted_controls=result.accepted_controls,
rule_id='explicit-user-pcb-version', observed_snapshots=tuple(snapshots))
except Exception as error:
self.failed = True
return DialogPollResult(error_code='PCB_VERSION_CHOICE_REQUIRED', detail=str(error),
snapshot=snapshot, observed_snapshots=tuple(snapshots))
def validate_action_window(snapshot, action):
"""Recheck the exact live window and radio selection on the private desktop."""
import win32gui, win32process
from .native_repair_ui import _current_desktop_name
from .dialog_models import ControlSnapshot
if (not str(action.get('desktop', '')).startswith('CbbVerify_')
or _current_desktop_name() != action.get('desktop') or snapshot.pid != action.get('pid')
or win32process.GetWindowThreadProcessId(snapshot.hwnd)[1] != snapshot.pid
or win32gui.GetWindowText(snapshot.hwnd) != snapshot.title
or win32gui.GetClassName(snapshot.hwnd) != snapshot.window_class
or not win32gui.IsWindowVisible(snapshot.hwnd)):
raise ValueError('PCB_VERSION_LIVE_WINDOW_MISMATCH')
children = []
win32gui.EnumChildWindows(snapshot.hwnd, lambda h, _: children.append(int(h)), None)
live = []
for h in children:
control_id = win32gui.GetDlgCtrlID(h) & 0xFFFF
checked = False
if control_id in (6213, 6206):
value = win32gui.SendMessageTimeout(h, 0x00F0, 0, 0, 2, 1000)
checked = (value[-1] if isinstance(value, tuple) else value) == 1
live.append(ControlSnapshot(h, control_id, win32gui.GetClassName(h), win32gui.GetWindowText(h),
enabled=bool(win32gui.IsWindowEnabled(h)), checked=checked))
choice = _choice(replace(snapshot, controls=tuple(live)))
if _candidate_key(choice['candidates']) != _candidate_key(action.get('candidates', [])):
raise ValueError('PCB_VERSION_LIVE_CANDIDATES_CHANGED')
selected = next((c for c in choice['candidates'] if c['kind'] == action.get('choice') and c['enabled']), None)
control_id = action.get('target', {}).get('control_id')
if selected is None or control_id not in (selected['control_id'], 1):
raise ValueError('PCB_VERSION_ACTION_MISMATCH')
if control_id == 1 and (not selected['selected'] or sum(c['selected'] for c in choice['candidates']) != 1):
raise ValueError('PCB_VERSION_LIVE_SELECTION_MISMATCH')
target = next(c for c in live if c.control_id == control_id)
if target.handle != next(c.handle for c in snapshot.controls if c.control_id == control_id):
raise ValueError('PCB_VERSION_CONTROL_CHANGED')
@@ -124,7 +124,8 @@ def prepare_launch(job, command):
if _current_desktop_name() != job['desktop']:
raise ValueError('POST_REPAIR_PRIVATE_DESKTOP_REQUIRED')
library, project, pcb = (Path(job[key]) for key in ('lmc_file', 'project', 'pcb'))
for path in (library, project, pcb, pcb.parent/'pcb.prj'):
from .maintenance_entry import maintenance_project_files
for path in (library, pcb, *maintenance_project_files(project, pcb)):
require_local_fixed(path)
if len(command) != 3 or not _same(command[1], pcb) or command[2] != '-ReusableCircuit':
raise ValueError('POST_REPAIR_LAUNCH_MISMATCH')
@@ -198,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
+40 -1
View File
@@ -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
@@ -227,6 +229,43 @@ def build_manifest(root, *, scope=None, exclude=None, progress=None, hash_functi
return _manifest(scope, files)
def build_exclusive_library_manifest(root, *, scope, progress=None):
"""Check every native database is idle while hashing, without making a copy."""
import win32con, win32file, pywintypes
root = Path(root)
entries = scan_tree(root) # Preserve full-library link and ownership checks.
with ExitStack() as stack:
handles = {}
for path, metadata in entries.items():
if stat.S_ISREG(metadata.st_mode) and (path.suffix.casefold() == '.lmc'
or path.name.casefold() == 'icdb.dat'):
try:
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
except pywintypes.error as error:
raise OSError(f'LIBRARY_DATABASE_IN_USE: 无法独占读取 {path}:{error}') from error
handles[path] = handle
stack.callback(handle.Close)
def digest(path):
if path not in handles:
return hash_file(path)
value = hashlib.sha256()
while True:
try:
_, data = win32file.ReadFile(handles[path], 1024 * 1024)
except pywintypes.error as error:
if error.winerror == 38: # ERROR_HANDLE_EOF
break
raise
if not data:
break
value.update(data)
return value.hexdigest()
return build_manifest(root, scope=scope, progress=progress, hash_function=digest)
def copy_verified(source, destination, *, scope=None, progress=None, hash_function=hash_file):
"""Copy the whole tree, validate all metadata, SHA256 only scoped primary files.
@@ -0,0 +1,5 @@
"""Shared wording for user-managed backups before write operations."""
MANUAL_BACKUP_NOTICE = (
'应用不会自动备份。请先手动备份中心库及相关工程,并确认备份可用于恢复。'
)
@@ -3,9 +3,10 @@ from pathlib import Path
from PySide6.QtCore import QObject, QThreadPool, Signal
from PySide6.QtWidgets import (QComboBox, QDialog, QFileDialog, QFormLayout,
QHBoxLayout, QLabel, QLineEdit, QPushButton)
QHBoxLayout, QLabel, QLineEdit, QPushButton, QMessageBox)
from .workers import ServiceWorker
from .backup_notice import MANUAL_BACKUP_NOTICE
class RecoverySignals(QObject):
@@ -37,7 +38,7 @@ class BackupRecoveryDialog(QDialog):
self.restore_button.clicked.connect(self._restore)
self.close_button = QPushButton('关闭')
self.close_button.clicked.connect(self.reject)
self.status_label = QLabel('使用所选备份版本恢复同名 CBB。先在库副本中验证,原工程与完整库副本会保留;需要额外磁盘空间。')
self.status_label = QLabel(MANUAL_BACKUP_NOTICE + ' 所选备份先在隔离库中验证;安装时旧 Work 仅改名保留。')
self.status_label.setWordWrap(True)
layout = QFormLayout(self)
layout.addRow('目标 CBB', self.block_combo)
@@ -77,6 +78,11 @@ class BackupRecoveryDialog(QDialog):
except Exception as error:
self.status_label.setText(str(error))
return
if QMessageBox.question(self, '确认从备份恢复',
f'{MANUAL_BACKUP_NOTICE}\n\n目标库:{request.lmc_file}\nCBB:{name}\n来源:{source}'
'\n\n将创建用于校验的隔离库副本,校验通过后替换目标工程。确认继续?',
QMessageBox.Yes | QMessageBox.No, QMessageBox.No) != QMessageBox.Yes:
return
self.busy = True
self._set_enabled(False)
self.status_label.setText('正在准备恢复…')
+419 -105
View File
@@ -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:
@@ -26,6 +35,7 @@ from cbb_refresh_verify.verify_runner import (VerifyRequest, preflight_skip_reas
class ProgressSignals(QObject):
event = Signal(object)
version_choice = Signal(object)
STATUS_LABELS = {
@@ -47,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()
@@ -64,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':
@@ -93,6 +114,8 @@ class MainWindow(QWidget):
self._global_icdb_run = False
self._icdb_completed = 0
self.signals = ProgressSignals(self); self.signals.event.connect(self._progress)
self.signals.version_choice.connect(self._show_version_choice)
self.version_dialog = None
self.lmc_edit = QLineEdit()
self.libspec_edit = QLineEdit(os.environ.get('CBB_LIBSPEC', 'EE7.9'))
self.dms_edit = QLineEdit(os.environ.get('CBB_DMS_LOGIN_CONFIG', ''))
@@ -113,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)
@@ -138,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 项;有勾选时仅处理其中可用项。未确认状态不等于损坏。')
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)
@@ -160,34 +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); layout.addRow(self.advanced_toggle); layout.addRow(self.advanced_panel)
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.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('')
@@ -195,32 +246,38 @@ 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))
widget.setToolTip(self.management_capabilities[operation].reason)
management_buttons.addWidget(widget)
management_layout.addLayout(management_buttons)
self.management_capability_label = QLabel('\n'.join(
f'{label}:{self.management_capabilities[op].reason}'
for op, label in (('add', '新增'), ('update', '同名更新'), ('remove', '移除'))
if not self.management_capabilities[op].supported))
self.management_capability_label = QLabel()
self.management_capability_label.setWordWrap(True)
management_layout.addWidget(self.management_capability_label)
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())
@@ -229,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 = {}
@@ -239,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:
@@ -250,16 +310,32 @@ 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()))
loaded = not self.busy and not self._management_unsafe and not self._maintenance_recovery_view and self.loaded_path == self.lmc_edit.text()
reasons = []
for operation, widget in (('add', self.add_button), ('update', self.update_button), ('remove', self.remove_button)):
widget.setEnabled(loaded and self.management_capabilities[operation].supported
and (operation == 'add' or bool(self.selected_records())))
reason = self._management_block_reason(operation)
widget.setEnabled(not reason)
widget.setToolTip(reason or self.management_capabilities[operation].reason)
if reason:
reasons.append(reason)
self.management_capability_label.setText('\n'.join(dict.fromkeys(reasons)))
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,
self.timeout_spin, self.advanced_toggle, self.advanced_panel,
self.search_edit, self.status_filter, self.select_visible_button, self.clear_selection_button):
@@ -268,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
@@ -292,17 +375,52 @@ 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._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:
return capability.reason
if not self.loaded_path or self.loaded_path != self.lmc_edit.text():
return '请先选择并读取中心库。'
if operation != 'add' and not self.selected_records():
return '替换和移除需要先勾选当前可见的 CBB。'
return ''
def manage_cbb(self, operation):
if (self.busy or self._management_unsafe or self._maintenance_recovery_view or self.loaded_path != self.lmc_edit.text()
or not self.management_capabilities[operation].supported):
reason = self._management_block_reason(operation)
if reason:
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
@@ -315,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('管理操作需要人工确认恢复/释放;已停止写入,未再次读取原生目录。')
@@ -364,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)
@@ -415,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()
@@ -437,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'}]
@@ -557,33 +719,114 @@ class MainWindow(QWidget):
return [record.name for record in self.selected_records()]
def verify_selected(self):
self._run(self._eligible_names(checked_only=True))
self._confirm_verify(self._eligible_names(checked_only=True))
def verify_all(self):
self._run(self._eligible_names())
self._confirm_verify(self._eligible_names())
def _confirm_verify(self, names):
from .backup_notice import MANUAL_BACKUP_NOTICE
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'
f'将校验 {len(names)} 个可见非 READY CBB 并保存结果。确认继续?',
QMessageBox.Yes | QMessageBox.No, QMessageBox.No) == QMessageBox.Yes:
self._run(names)
def repair_icdb_all(self):
if self.busy or not self.loaded_path: return
names = self._maintenance_names()
if not names: return
answer = QMessageBox.question(self, '非 READY ICDB 检查与修复',
answer = QMessageBox.question(self, 'ICDB 批量检查',
f'当前中心库:{self.loaded_path}\n\n'
f'将检查 {len(names)} 个可见非 READY CBB'
f'{"(仅勾选项)" if self.selected_records() else ""}。未确认状态不等于损坏。\n'
'无地址阻止时逐项校验;已有工程地址记录时先核对所有者和独占访问、完整备份,'
'再由官方工具确认未占用并检查/修复。不会删除地址文件。\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._maintenance_names()
names = self._eligible_names(checked_only=bool(self.selected_records()))
if not names:
return
self.backup_dialog = BackupRecoveryDialog(names, self._backup_request, self)
@@ -599,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._maintenance_names():
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)
@@ -639,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
eligible = set(self._eligible_names())
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)
@@ -658,26 +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))
flag_reader=read_library_flag_if_available,
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)
@@ -722,6 +973,11 @@ class MainWindow(QWidget):
self.cbb_table.item(row, 2).setToolTip(error or self.skip_reasons.get(name, ''))
if status == 'READY' and name not in self.skipped_names:
self.ready_names.add(name)
# A status transition invalidates a maintenance target;
# clear its old check so the repeatable diagnostic entry
# point does not become disabled merely because the user
# selected the row for the previous run.
self.cbb_table.item(row, 0).setCheckState(Qt.Unchecked)
self._mark_row_ready(row)
else:
for column in range(self.cbb_table.columnCount()):
@@ -745,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:
@@ -766,21 +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': '检查工程数据库与校验状态',
'native_repair_start': '准备完整备份与原生修复',
'complete_backup_verified': '完整备份已校验',
'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)
@@ -799,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:
@@ -815,38 +1079,80 @@ 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["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["repaired"]},恢复备份待复核 {counts["review_required"]},'
f'ICDB已修复/PCB版本待选 {counts["version_choice_required"]},'
f'修复未确认 {counts["repair_unconfirmed"]}。')
self.status_label.setText(status_text); self.output.append(text)
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', 'CHECKED', 'REPAIRED') and result.stderr), '')
if first_failure:
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()
def _show_version_choice(self, choice):
from .pcb_restore_dialog import PcbRestoreDialog
if not self.busy or self.stop.is_set():
choice.choose('cancel')
return
self.version_dialog = PcbRestoreDialog(choice, self)
self.status_label.setText(f'{choice.block}:等待选择 PCB 恢复版本。')
self.icdb_phase.setText(f'{choice.block} · 等待选择 PCB 恢复版本')
self.version_dialog.show()
def request_stop(self):
self.stop.set(); self.status_label.setText('已请求停止;当前 CBB 完成或超时后停止队列。'); self._update()
if self.version_dialog is not None:
self.version_dialog.reject()
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:
@@ -855,6 +1161,9 @@ class MainWindow(QWidget):
if self.logging_context: self.logging_context.logger.error('cbb_worker_failed %s', error)
def _finished(self):
if self.version_dialog is not None:
self.version_dialog.reject()
self.version_dialog = None
self.busy = False; self._update()
if self._reload_after_maintenance:
from PySide6.QtCore import QTimer
@@ -873,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()
+47 -16
View File
@@ -8,6 +8,7 @@ from PySide6.QtWidgets import (QCheckBox, QDialog, QFileDialog, QHBoxLayout, QLa
QMessageBox, QPushButton, QTableWidget, QTableWidgetItem, QTextEdit, QVBoxLayout)
from .workers import ServiceWorker
from .backup_notice import MANUAL_BACKUP_NOTICE
from ..management import run_management_batch, validate_name
RESULT_LABELS = {
@@ -18,10 +19,12 @@ RESULT_LABELS = {
}
STAGE_LABELS = {
'prepare_identity': '正在核对来源工程内容',
'catalog_before': '正在核对原生目录', 'backup': '正在备份完整中心库',
'stage_source': '正在复制并检查来源工程', 'native_remove': '正在原生移除',
'removed': '原条目已移除', 'native_add': '正在原生上传', 'uploaded': '上传身份已确认',
'verify': '正在校验上传结果', 'verified': '校验已返回', 'copy': '正在复制备份',
'catalog_before': '正在核对原生目录', 'baseline': '正在记录中心库内容基线',
'stage_source': '正在复制并检查来源工程', 'native_remove': '正在移除',
'removed': '原条目已移除', 'native_add': '正在上传', 'uploaded': '上传已确认',
'verify': '正在校验上传结果', 'verified': '校验已返回', 'copy': '正在准备来源副本',
'hash': '正在校验主要文件',
'release_check': '正在检查工程是否被占用',
}
@@ -32,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()
@@ -57,19 +66,29 @@ class ManagementDialog(QDialog):
self.auto_verify = QCheckBox('本批次上传后自动校验')
self.auto_verify.setChecked(self.template.auto_verify)
self.auto_verify.setVisible(self.operation != 'remove')
self.status_label = QLabel('先预览目标和来源;完整备份保存在目标库之外。更新会先移除再重新导入,失败时保留恢复证据。')
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)
@@ -127,12 +146,15 @@ class ManagementDialog(QDialog):
except ValueError as error:
self.status_label.setText(str(error)); return
preview = '\n'.join(f'{r.partition} / {r.name}' + (f' ← {r.source}' if r.source else '') for r in requests)
description = ('同名更新先备份,再原生移除并重新导入;导入失败需要人工恢复。' if self.operation == 'update'
else '移除前保留完整工程和中心库备份。' if self.operation == 'remove'
description = ('同名更新会原生移除并重新导入;导入失败需要使用手动备份恢复。' if self.operation == 'update'
else '将通过原生操作移除所列 CBB;恢复时需要使用手动备份。' if self.operation == 'remove'
else '新增同名冲突会拒绝覆盖,完整来源工程将先复制到暂存区。')
if self.recovery_from:
description = ('将用所选副本替换这些 CBB。操作会先移除原条目,再导入副本;'
'导入失败时需要用备份恢复。请确认副本版本。')
answer = QMessageBox.question(self, '确认管理操作',
f'{description}\n\n目标库:{self.template.library}\n{preview}\n\n'
f'完整备份与检查点:{self.template.evidence_dir}\n确认执行?', QMessageBox.Yes | QMessageBox.No,
f'{MANUAL_BACKUP_NOTICE}\n{description}\n\n目标库:{self.template.library}\n{preview}\n\n'
'确认继续执行?', QMessageBox.Yes | QMessageBox.No,
QMessageBox.No)
if answer != QMessageBox.Yes:
return
@@ -153,20 +175,29 @@ 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:
text += f' {event["hashed_files"]}/{event.get("total_files", "?")} · {event.get("hashed_bytes", 0)} 字节'
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):
@@ -0,0 +1,31 @@
"""Show the native version dates without preselecting a recovery version."""
from PySide6.QtWidgets import QMessageBox
class PcbRestoreDialog(QMessageBox):
def __init__(self, choice, parent=None):
super().__init__(parent)
self.choice = choice
self.setWindowTitle('选择 PCB 恢复版本')
self.setIcon(QMessageBox.Question)
candidates = {c['kind']: c for c in choice.candidates}
manual, auto = candidates['last_user_saved'], candidates['autosave']
self.setText(f'CBB:{choice.block}\n中心库:{choice.library}\n\n'
'原生程序检测到上次异常退出,需要选择 PCB 恢复版本。\n'
f'最后手动保存:{manual["date"]}\n自动保存:{auto["date"]}\n\n'
'选择历史版本可能丢失此版本之后的修改。选择后继续校验、保存和状态确认;恢复版本仍需核对。'
'\n取消将停止本项并保留原生现场,不自动选取版本。')
self.manual_button = self.addButton(f'最后手动保存({manual["date"]})', QMessageBox.ActionRole)
self.auto_button = self.addButton(f'自动保存({auto["date"]})', QMessageBox.ActionRole)
self.manual_button.setEnabled(manual['enabled'])
self.auto_button.setEnabled(auto['enabled'])
self.cancel_button = self.addButton(QMessageBox.Cancel)
self.setDefaultButton(self.cancel_button)
self.setEscapeButton(self.cancel_button)
self.buttonClicked.connect(self._chosen)
self.finished.connect(lambda _: choice.choose('cancel'))
self.setModal(True)
def _chosen(self, button):
self.choice.choose('last_user_saved' if button is self.manual_button else
'autosave' if button is self.auto_button else 'cancel')
+145 -51
View File
@@ -56,15 +56,16 @@ 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
@dataclass(frozen=True)
@@ -134,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'
@@ -156,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')
@@ -219,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):
@@ -269,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')):
@@ -474,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
@@ -498,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,
@@ -506,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):
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
@@ -516,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)
@@ -523,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))
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)
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):
@@ -580,7 +597,7 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
result = _run_verify_serialized(
replace(request, auto_repair=False, maintenance=False), progress=progress, flag_reader=flag_reader,
process_runner=process_runner, port_check=port_check,
dialog_supervisor_factory=dialog_supervisor_factory)
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt)
recovery['validation_evidence'] = str(result.evidence_path or '')
recovery['validation_passed'] = (result.status == 'PASS'
and result.library_flag == 'GREEN' and result.safe_to_continue)
@@ -623,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:
@@ -636,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):
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)
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')
@@ -667,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'
@@ -706,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):
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``.
@@ -738,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)
@@ -746,18 +789,7 @@ 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 = bool(str(request.libspec).strip() and str(request.dms_login_config).strip())
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:
executable = resolve_importer(request.mentor_bin)
@@ -789,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()
@@ -801,6 +832,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
return finish(VerifyResult('BLOCKED', stderr=ports_detail))
job = {'lmc_file': str(absolute_preserving_drive(request.lmc_file)), 'block_name': request.block_name,
'diagnostic_only': request.diagnostic_only,
'supervisor_pid': os.getpid(),
'project': str(project), 'pcb': str(pcb), 'root': str(root), 'timeout': request.timeout_seconds,
'mentor_bin': str(request.mentor_bin or ''),
@@ -853,6 +885,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
deadline = ActivityDeadline(request.timeout_seconds)
last_activity_key = None
phase = DialogPhase.PCB_STARTING
restore_controller = None
dialog_agent = None
latest_snapshots = ()
if dialog_supervisor_factory is None:
@@ -876,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)
@@ -950,6 +987,15 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
from .dialog_rules import archive_version_choice
choice_path = archive_version_choice(dialog_result.snapshot, root)
dialog_result = replace(dialog_result, detail=dialog_result.detail + f'\n版本候选与原生窗口证据:{choice_path}')
if (version_prompt is not None and consent is not None and dialog_agent is not None
and dialog_result.snapshot.hwnd in {int(h) for h in process.desktop.EnumDesktopWindows()}):
from .pcb_restore_prompt import RestoreController
if restore_controller is None:
restore_controller = RestoreController(job)
dialog_result = restore_controller.handle(dialog_result.snapshot,
dialog_result.observed_snapshots, target_pid=target_pid, launcher_pid=launcher_pid,
worker_pid=process.pid, companion_pids=tuple(process.companion_pids),
show=version_prompt, perform=dialog_supervisor.backend.perform)
# Normal progress stays in memory. Only actions/errors and the
# last failure snapshots are persisted, not every elapsed tick.
latest_snapshots = dialog_result.observed_snapshots
@@ -1012,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():
@@ -1027,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()
@@ -1034,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,
@@ -1053,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,
@@ -1090,7 +1172,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
win32event.ReleaseMutex(mutex)
mutex.Close()
if result.status == 'PASS':
if result.status == 'PASS' and not request.diagnostic_only:
timing.begin('library_flag')
bridge_records = []
def record_attempt(record):
@@ -1131,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)
@@ -1155,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 '')
@@ -1180,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' +
+1 -1
View File
@@ -69,7 +69,7 @@ def test_crashed_worker_cannot_pass_even_with_pass_file(tmp_path, monkeypatch, o
pytest.fail('A crashed writer must not become PASS via a pre-existing READY flag')
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):
+13 -5
View File
@@ -56,7 +56,8 @@ def test_restore_checks_source_in_library_copy_then_opens_actual_target(recovery
retained = list(original.parent.parent.glob('Work.before-restore-*'))
assert len(retained) == 1
assert (retained[0]/'database/icdb.dat').read_bytes() == b'damaged'
assert list(request.evidence_dir.rglob('library-before/target.lmc'))
assert not list(request.evidence_dir.rglob('library-before'))
assert not list(request.evidence_dir.rglob('source-before'))
def test_invalid_source_does_not_touch_target(recovery_files):
@@ -143,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)
@@ -208,14 +213,15 @@ def test_logs_and_unrelated_cbb_changes_after_snapshot_do_not_block_install(reco
assert len(calls) == 2
assert (original.parent/'database/icdb.dat').read_bytes() == b'healthy'
assert (other.parent/'database/icdb.dat').read_bytes() == b'unrelated update'
assert list(request.evidence_dir.rglob('source-before/session.log'))[0].read_bytes() == b'snapshot log'
staged = calls[0].lmc_file.parent/'ReusableBlocksLP/A/Work'
assert (staged/'session.log').read_bytes() == b'snapshot log'
@pytest.mark.parametrize('location,change', [
('source', 'edit'), ('source', 'delete'), ('source', 'add'),
('target', 'delete'), ('target', 'add'), ('cert', 'edit'), ('shared', 'edit'),
])
def test_primary_conflicts_preserve_target_and_complete_recovery_copies(recovery_files, location, change):
def test_primary_conflicts_preserve_target_and_validation_evidence(recovery_files, location, change):
from cbb_refresh_verify.backup_recovery import recover_from_backup
request, original, source = recovery_files
if location == 'source':
@@ -244,8 +250,10 @@ def test_primary_conflicts_preserve_target_and_complete_recovery_copies(recovery
assert len(calls) == 1
assert (original.parent/'database/icdb.dat').read_bytes() == b'damaged'
assert not list(original.parent.parent.glob('Work.before-restore-*'))
assert list(request.evidence_dir.rglob('library-before/target.lmc'))
assert list(request.evidence_dir.rglob('source-before/database/icdb.dat'))
assert list(request.evidence_dir.rglob('library-baseline-manifest.json'))
assert list(request.evidence_dir.rglob('source-manifest.json'))
assert calls[0][0].lmc_file.is_file()
assert not list(request.evidence_dir.rglob('library-before'))
def test_source_conflict_while_preparing_incoming_work_blocks_install(recovery_files, monkeypatch):
+7
View File
@@ -2,6 +2,13 @@ from pathlib import Path
from threading import Event
from cbb_refresh_verify.verify_runner import VerifyRequest, VerifyResult
import pytest
@pytest.fixture(autouse=True)
def accept_manual_backup_reminder(monkeypatch):
from PySide6.QtWidgets import QMessageBox
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
def test_backup_dialog_requires_a_project_and_passes_selected_target(qtbot, tmp_path):
+258
View File
@@ -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()
+23
View File
@@ -172,3 +172,26 @@ def test_authoritative_status_map_never_reuses_previous_scan_status(tmp_path, mo
assert first == {'A': 'PENDING'}
assert 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
+56
View File
@@ -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 == []
+20
View File
@@ -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
+11 -11
View File
@@ -200,14 +200,14 @@ def test_worker_attempts_normal_close_after_idle_integration_failure(tmp_path, m
assert not any(event['stage'] == 'save_start' for event in events)
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):
+194
View File
@@ -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
+6 -5
View File
@@ -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
+11 -10
View File
@@ -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
@@ -209,7 +208,9 @@ def test_real_windows_job_abort_preserves_native_like_child(tmp_path):
script.write_text(
'import subprocess, sys, time\nfrom pathlib import Path\n'
'child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"])\n'
f'Path({str(pid_path)!r}).write_text(str(child.pid))\n'
f'pid_file = Path({str(pid_path)!r})\n'
'pending = pid_file.with_suffix(".pending")\n'
'pending.write_text(str(child.pid)); pending.replace(pid_file)\n'
'time.sleep(30)\n', encoding='utf-8')
worker = DesktopWorker([sys.executable, str(script)], 'CbbSafetyTest_' + uuid.uuid4().hex[:8])
child_handle = None
+183
View File
@@ -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
+39
View File
@@ -290,6 +290,45 @@ def test_refresh_integration_skips_native_disabled_green_action():
assert pi.actions == []
@pytest.mark.parametrize('ces_allowed', [True, False])
def test_partial_sync_respects_protected_green_native_actions(ces_allowed):
class RestoredVerifiedBlock(GreenProjectIntegration):
IsForwardAnnotationAllowed = False
BackAnnotationStatus = 1
def ForwardAnnotate(self):
raise RuntimeError('Forward Annotation is not allowed on verified Reusable Blocks')
def BackAnnotate(self):
super().BackAnnotate()
self.BackAnnotationStatus = 2
return True
pi = RestoredVerifiedBlock()
pi.IsSynchCESAllowed = pi.IsLoadCESAllowed = ces_allowed
events = []
result = refresh_integration(pi, settle_seconds=0, emit=lambda **e: events.append(e))
assert set(result.values()) == {2}
assert pi.actions == (['SynchCES', 'LoadCES', 'BackAnnotate'] if ces_allowed else ['BackAnnotate'])
assert [e['action'] for e in events if e['stage'] == 'integration_action'] == pi.actions
def test_skipped_green_action_cannot_hide_a_later_required_native_gate():
class ChangedAfterCES(GreenProjectIntegration):
IsForwardAnnotationAllowed = False
BackAnnotationStatus = 1
def SynchCES(self):
super().SynchCES()
self.ForwardAnnotationStatus = 1
return True
pi = ChangedAfterCES()
with pytest.raises(IntegrationError, match='ForwardAnnotation: required but not allowed'):
refresh_integration(pi, settle_seconds=0)
assert pi.actions == ['SynchCES']
def test_refresh_integration_never_counts_rejected_green_action_as_completed():
class VerifiedProjectIntegration(GreenProjectIntegration):
def _blocked(self, action):
+68 -15
View File
@@ -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
+84
View File
@@ -0,0 +1,84 @@
"""Native occupancy must precede repair even when old addresses remain."""
import pytest
from test_maintenance_entry import case, no_native_launch, startup_failure, run_legacy_maintenance
from test_native_occupancy import output
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}}
@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
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 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 result.safe_to_continue is True
@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
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_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
calls = []
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)
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'])
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']
+207 -35
View File
@@ -19,6 +19,7 @@ def no_native_launch(monkeypatch):
monkeypatch.setattr(win32com.client, 'Dispatch', forbidden)
monkeypatch.setattr(win32com.client, 'DispatchEx', forbidden)
monkeypatch.setattr(desktop, 'DesktopWorker', forbidden)
monkeypatch.setattr('cbb_refresh_verify.verify_runner.runtime_fingerprint', lambda *_: {})
@pytest.fixture
@@ -38,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
@@ -46,19 +49,63 @@ def case(tmp_path, monkeypatch):
if owner: owner['handle'].Close()
def test_explicit_maintenance_enters_official_repair_once_without_lostsession_fabrication(case, monkeypatch):
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 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_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
if advertisement == 'absent':
address.unlink()
if pcb_config == 'legacy_template':
(project.parent/'PCB/pcb.prj').rename(project.parent/'PCB/template.prj')
calls = []
def repair(target, root, **kwargs):
calls.append('repair')
assert address.read_bytes() == b'old server address - preserved'
assert kwargs['maintenance_context']['addresses'][str(address.resolve())]['sha256']
# Native boundary fake simulates official removal of its address.
native_repair.backup_project(target, root/'complete-backup')
assert (root/'complete-backup/database/cdbsvr/sAddress.adr').read_bytes() == address.read_bytes()
address.unlink()
if advertisement == 'present':
assert address.read_bytes() == b'old server address - preserved'
assert kwargs['maintenance_context']['addresses'][str(address.resolve())]['sha256']
address.unlink() # Simulated native release, never a production cleanup.
else:
assert kwargs['maintenance_context']['addresses'] == {}
assert target.project == project
return complete_native_success(target)
monkeypatch.setattr(native_repair, 'run_native_repair', repair)
monkeypatch.setattr(native_repair, 'repair_release_state', lambda *a:
@@ -70,21 +117,121 @@ def test_explicit_maintenance_enters_official_repair_once_without_lostsession_fa
assert not req.maintenance and not req.auto_repair
assert req.lmc_file == request.lmc_file and req.block_name == request.block_name
return runner.VerifyResult('PASS', library_flag='GREEN')
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
result = runner.run_verify(request)
assert calls == ['repair', 'verify'] and result.status == 'PASS'
assert result.recovery_attempts[0]['validation_passed'] is True
patch_verification_after_fault(monkeypatch, runner, verify)
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']
def test_ordinary_verify_still_blocks_existing_address_without_repair(case, monkeypatch):
def test_addressless_target_binds_unique_project_and_rejects_new_address(case):
from cbb_refresh_verify.maintenance_entry import maintenance_target_guard
request, project, address = case
address.unlink()
with maintenance_target_guard(request) as checked:
context = checked['context']
assert checked['target'].project == project and context['addresses'] == {}
address.write_bytes(b'owner appeared after preflight')
with pytest.raises(ValueError, match='MAINTENANCE_SOURCE_CHANGED'):
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):
from cbb_refresh_verify.maintenance_entry import select_maintenance_target
request, project, address = case
address.unlink()
(project.parent/'PCB/IP101GR.pcb').write_text(reference)
with pytest.raises(ValueError, match='PCB.*ProjectFile'):
select_maintenance_target(request)
def test_addressless_multiple_project_databases_are_not_guessed(case):
from cbb_refresh_verify.maintenance_entry import select_maintenance_target
request, project, address = case
address.unlink()
(project.parent/'PCB/pcb.prj').write_text('KEY iCDBDir "database"\n')
database = project.parent/'PCB/database'; database.mkdir()
(database/'icdb.dat').write_bytes(b'another native database')
with pytest.raises(ValueError, match='多个工程数据库'):
select_maintenance_target(request)
@pytest.mark.parametrize('back_reference', ['', 'KEY ProjectFile "../other.prj"\n',
'KEY ProjectFile "../IP101GR.prj"\nKEY ProjectFile "../IP101GR.prj"\n'])
def test_legacy_maintenance_requires_unambiguous_pcb_back_reference(case, back_reference):
from cbb_refresh_verify.maintenance_entry import select_maintenance_target
request, project, _ = case
(project.parent/'PCB/pcb.prj').rename(project.parent/'PCB/template.prj')
(project.parent/'PCB/IP101GR.pcb').write_text(back_reference)
with pytest.raises(ValueError, match='MAINTENANCE_TARGET_UNCONFIRMED'):
select_maintenance_target(request)
def test_legacy_target_does_not_guess_template_for_physical_address(case):
from cbb_refresh_verify.maintenance_entry import select_maintenance_target
request, project, address = case
(project.parent/'PCB/pcb.prj').rename(project.parent/'PCB/template.prj')
address.unlink()
physical = project.parent/'PCB/database/cdbsvr/sAddress.adr'
physical.parent.mkdir(parents=True); physical.write_bytes(b'physical owner')
with pytest.raises(ValueError, match='SHARED_DATABASE_REPAIR_UNSUPPORTED'):
select_maintenance_target(request)
def test_optional_pcb_project_appearance_invalidates_maintenance_proof(case):
from cbb_refresh_verify.maintenance_entry import maintenance_target_guard
request, project, _ = case
config = project.parent/'PCB/pcb.prj'
config.rename(config.with_name('template.prj'))
with maintenance_target_guard(request) as proof:
before = proof['context']
config.write_text('KEY CentralLibrary "different.lmc"\n')
with pytest.raises(ValueError, match='MAINTENANCE_SOURCE_CHANGED'):
with maintenance_target_guard(request, before): pass
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'
@@ -112,8 +259,9 @@ 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:
if handle: handle.Close()
@@ -159,8 +307,8 @@ def test_nonrepair_outcomes_never_verify_or_count_success(case, monkeypatch, sta
monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **k: {
'status': status, 'release': {'safe_to_continue': False}, 'detail': 'native result'})
monkeypatch.setattr(native_repair, 'repair_release_state', lambda *a: {'safe_to_continue': False})
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: pytest.fail('unsafe or nonrepair outcome reopened'))
result = runner.run_verify(request)
patch_verification_after_fault(monkeypatch, runner, lambda *a, **k: pytest.fail('unsafe or nonrepair outcome reopened'))
result = run_legacy_maintenance(request)
assert result.status != 'PASS' and not result.safe_to_continue
assert result.recovery_attempts[0]['status'] == status
@@ -170,11 +318,11 @@ def test_native_success_cannot_bypass_remaining_address(case, monkeypatch):
from test_native_repair import complete_native_success
request, _, _ = case
monkeypatch.setattr(native_repair, 'run_native_repair', lambda target, *a, **k: complete_native_success(target))
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: pytest.fail('retained address reopened'))
patch_verification_after_fault(monkeypatch, runner, lambda *a, **k: pytest.fail('retained address reopened'))
# 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
@@ -191,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)
@@ -200,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
@@ -208,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']
@@ -248,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
@@ -264,8 +417,8 @@ def test_physical_release_alone_does_not_authorize_queue(case, monkeypatch, stat
return result
monkeypatch.setattr(native_repair, 'run_native_repair', repair)
monkeypatch.setattr(native_repair, 'repair_release_state', lambda req, target, result: result['release'])
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: pytest.fail('nonrepair outcome reopened'))
result = runner.run_verify(request)
patch_verification_after_fault(monkeypatch, runner, lambda *a, **k: pytest.fail('nonrepair outcome reopened'))
result = run_legacy_maintenance(request)
assert result.status != 'PASS'
assert result.safe_to_continue is expected_safe
assert result.recovery_attempts[0]['status'] == status
@@ -281,12 +434,31 @@ def test_successful_icdb_repair_then_version_choice_reports_partial_completion(c
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'])
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: runner.VerifyResult('FAIL',
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
def test_user_chosen_pcb_history_is_not_reported_as_lossless_repair(case, monkeypatch):
from cbb_refresh_verify import native_repair, verify_runner as runner
from test_native_repair import complete_native_success
request, project, address = case
address.unlink()
monkeypatch.setattr(native_repair, 'run_native_repair', lambda target, *a, **k: complete_native_success(target))
monkeypatch.setattr(native_repair, 'repair_release_state', lambda req, target, result: result['release'])
def verify(*a, **k):
root = request.evidence_dir/'verify'; root.mkdir(exist_ok=True)
(root/'pcb-version-restoration.json').write_text(json.dumps({'project': str(project),
'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 = 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()
+139
View File
@@ -0,0 +1,139 @@
from pathlib import Path
import pytest
from PySide6.QtCore import Qt
def test_ready_rows_never_enter_maintenance_even_when_unchecked(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window, MIXED
window = load_window(qtbot, tmp_path, monkeypatch, records=(MIXED[0],))
assert window._maintenance_names() == []
assert not window.icdb_repair_button.isEnabled()
assert not window.backup_restore_button.isEnabled()
window.select_visible_button.click()
assert window._maintenance_names() == []
def test_selected_ready_rows_are_ignored_in_mixed_maintenance(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
window = load_window(qtbot, tmp_path, monkeypatch)
window.select_visible_button.click()
assert window._maintenance_names() == ['Beta', 'Gamma', 'Delta']
window._apply_refreshed_records((('Beta', 'Gamma'), {'Beta': 'READY', 'Gamma': 'READY'}, {}, ''))
assert window._maintenance_names() == ['Delta']
assert window.icdb_repair_button.isEnabled()
def test_diagnostic_worker_closes_without_integration_save_or_config_edit(tmp_path, monkeypatch):
from test_verify_worker_stability import exercise_worker
from cbb_refresh_verify import mentor_adapter as adapter
job, events, execute = diagnostic_worker(tmp_path, monkeypatch)
job['diagnostic_only'] = True
def forbidden(*args, **kwargs):
pytest.fail('diagnosis attempted integration/save/config rewrite')
monkeypatch.setattr(adapter, 'ensure_pcb_central_library', forbidden)
monkeypatch.setattr('cbb_refresh_verify.integration.refresh_integration', forbidden)
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.launch_save_helper', forbidden)
closes = []
monkeypatch.setattr('cbb_refresh_verify.failed_session.close_failed_document',
lambda job, **kw: closes.append(job) or {'status': 'CLOSED'})
result = execute()
assert result['status'] == 'PASS'
assert len(closes) == 1
assert not any(e['stage'] in ('save_start', 'saved_and_closed') for e in events)
def test_diagnostic_close_failure_never_returns_healthy(tmp_path, monkeypatch):
from test_verify_worker_stability import exercise_worker
job, events, execute = diagnostic_worker(tmp_path, monkeypatch)
job['diagnostic_only'] = True
closes = []
monkeypatch.setattr('cbb_refresh_verify.failed_session.close_failed_document',
lambda *a, **kw: closes.append(a) or {'status': 'RETAINED'})
with pytest.raises(RuntimeError, match='DIAGNOSTIC_CLOSE_UNCONFIRMED'):
execute()
assert len(closes) == 1
@pytest.mark.parametrize('prefix', ['KEY CentralLibrary ', ' KEY CentralLibrary ', 'KEY\tCentralLibrary\t'])
def test_diagnosis_rejects_foreign_library_reference_before_native_launch(tmp_path, monkeypatch, prefix):
from test_verify_worker_stability import exercise_worker
from cbb_refresh_verify import mentor_adapter as adapter
job, events, execute = diagnostic_worker(tmp_path, monkeypatch)
job['diagnostic_only'] = True
project = Path(job['project'])
project.write_text(prefix + '"foreign.lmc"\n')
monkeypatch.setattr(adapter, 'launch_pcb_process', lambda *a: pytest.fail('foreign library opened'))
with pytest.raises(ValueError, match='DIAGNOSTIC_LIBRARY_MISMATCH'):
execute()
def diagnostic_worker(tmp_path, monkeypatch):
from test_verify_worker_stability import exercise_worker
job, events, execute = exercise_worker(tmp_path, monkeypatch)
(Path(job['pcb']).parent/'pcb.prj').write_text(
'KEY CentralLibrary "' + job['lmc_file'] + '"\n', encoding='utf-8')
return job, events, execute
def test_diagnostic_runner_skips_importer_and_ready_verification(tmp_path, monkeypatch):
import json
from test_verify_runner import fixture, request, PORTS_OK
from cbb_refresh_verify.verify_runner import run_verify
fixture(tmp_path)
captured = {}
class FinishedWorker:
desktop = None
returncode = 0
def __init__(self, command, name, **kwargs):
job = Path(command[-1])
captured.update(json.loads(job.read_text('utf-8')))
job.with_name('outcome.json').write_text('{"status":"PASS"}', encoding='utf-8')
def poll(self): return 0
def close(self): pass
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', FinishedWorker)
def forbidden(*a, **kw): pytest.fail('diagnosis must not run importer or query READY')
result = run_verify(request(tmp_path, diagnostic_only=True, auto_repair=False,
libspec='configured', dms_login_config='configured'), port_check=PORTS_OK,
flag_reader=forbidden, process_runner=forbidden)
assert result.status == 'PASS' and result.library_flag == 'UNKNOWN'
assert captured['diagnostic_only'] is True
def test_diagnostic_waits_for_normal_exit_after_close_returns(tmp_path, monkeypatch):
from cbb_refresh_verify import mentor_adapter as adapter
job, events, execute = diagnostic_worker(tmp_path, monkeypatch)
job['diagnostic_only'] = True
observations = []
def release(*a, **kw):
observations.append(True)
return {'safe_to_continue': len(observations) > 1}
monkeypatch.setattr(adapter, 'cleanup_verify_processes', release)
monkeypatch.setattr('cbb_refresh_verify.failed_session.close_failed_document',
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)
+185
View File
@@ -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'])
+38 -20
View File
@@ -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,29 +43,42 @@ 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 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):
from cbb_refresh_verify.ui.main_window import MainWindow
from cbb_refresh_verify.verify_runner import VerifyResult
window = MainWindow(data_root=tmp_path)
qtbot.addWidget(window)
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.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):
@@ -74,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.
@@ -86,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'
+42 -6
View File
@@ -82,17 +82,52 @@ def execute(request, adapter, **kwargs):
return run_management(request, adapter=adapter, idle_check=lambda *_: None, **kwargs)
def test_remove_backup_and_strict_absence(setup):
def test_remove_uses_baseline_without_automatic_library_backup(setup):
request, adapter, _ = setup
result = execute(request, adapter)
assert result.status == 'REMOVED' and result.safe_to_continue
assert (result.evidence_path.parent/'library-before/mentor.lmc').read_bytes() == b'library'
assert (result.evidence_path.parent/'library-before/ReusableBlocksLP/Block/Work/Block.prj').is_file()
assert not (result.evidence_path.parent/'library-before').exists()
assert (result.evidence_path.parent/'library-baseline-manifest.json').is_file()
assert '已备份' not in result.detail
record = json.loads(result.evidence_path.read_text(encoding='utf-8'))
assert record['operation'] == 'remove' and record['partition'] == 'Logical-Physical'
assert record['stage'] == 'complete'
@pytest.mark.parametrize('operation', ['add', 'update', 'remove'])
def test_management_never_copies_target_library(setup, monkeypatch, operation):
import cbb_refresh_verify.management as management
request, adapter, source = setup
real_copy = management.copy_verified
def copy(source_path, destination, **kwargs):
assert Path(source_path).resolve() != request.library.parent.resolve(), 'automatic whole-library backup'
return real_copy(source_path, destination, **kwargs)
monkeypatch.setattr(management, 'copy_verified', copy)
result = execute(replace(request, operation=operation, source=source if operation != 'remove' else None,
name='New' if operation == 'add' else 'Block', auto_verify=False), adapter)
assert result.status == ('REMOVED' if operation == 'remove' else 'UPLOADED')
@pytest.mark.parametrize('relative', ['mentor.lmc', 'SymbolLibs/shared/icdb.dat',
'ReusableBlocksLP/Other/Work/database/icdb.dat'])
def test_manual_backup_policy_still_rejects_external_shared_read_owner(setup, relative):
import win32con, win32file
request, adapter, _ = setup
path = request.library.parent/relative
path.parent.mkdir(parents=True, exist_ok=True)
if not path.exists():
path.write_bytes(b'owned database')
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, win32con.FILE_SHARE_READ, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
try:
result = execute(request, adapter)
assert result.status == 'BLOCKED'
assert not adapter.calls, 'An existing reader must block native writes even without address/process evidence'
assert not list(request.evidence_dir.rglob('library-before'))
finally:
handle.Close()
def test_add_conflict_cannot_overwrite(setup):
request, adapter, source = setup
result = execute(replace(request, operation='add', source=source), adapter)
@@ -123,7 +158,7 @@ def test_add_no_auto_verify_and_reimport_after_remove(setup):
assert result.status == 'UPLOADED'
def test_update_failed_readd_keeps_removed_checkpoint_and_recovery_snapshot(setup):
def test_update_failed_readd_keeps_removed_checkpoint_and_baseline(setup):
request, adapter, source = setup
adapter.fail_add = True
result = execute(replace(request, operation='update', source=source), adapter)
@@ -131,7 +166,8 @@ def test_update_failed_readd_keeps_removed_checkpoint_and_recovery_snapshot(setu
assert adapter.records == []
history = json.loads(result.evidence_path.read_text(encoding='utf-8'))['history']
assert 'removed' in [x['stage'] for x in history]
assert (result.evidence_path.parent/'library-before/mentor.lmc').is_file()
assert (result.evidence_path.parent/'library-baseline-manifest.json').is_file()
assert not (result.evidence_path.parent/'library-before').exists()
@pytest.mark.parametrize('operation', ['remove', 'add'])
@@ -311,7 +347,7 @@ def test_prepared_native_identity_is_required_after_exact_catalog(setup, matched
expected = {'policy': 'native-test', 'logical': 'same', 'physical': 'same'}
def prepare(staged, root, *, original_source):
assert original_source == source and staged.source != source
assert (root/'library-before/mentor.lmc').exists()
assert (root/'library-baseline-manifest.json').exists()
adapter.calls.append('prepare_identity')
return staged, IdentityOutcome(expected, True, 'baseline captured', root)
adapter.prepare_add_transaction = prepare
+6 -3
View File
@@ -25,7 +25,7 @@ def test_raw_dispatch_diagnostics_preserve_hresult_and_known_member_ids(tmp_path
def test_probe_records_dispatch_before_after_import_and_after_source_alignment(tmp_path, monkeypatch):
import cbb_refresh_verify.native_management as native
import sys
import sys, os
source = tmp_path/'source/Block.prj'
source.parent.mkdir()
source.write_text('KEY RootBlock "Block"\nKEY PCBDesignPath "PCB/Block.pcb"\n'
@@ -51,7 +51,7 @@ def test_probe_records_dispatch_before_after_import_and_after_source_alignment(t
raise AttributeError(name)
monkeypatch.setitem(sys.modules, 'pywinauto', Uia('pywinauto'))
job = {'operation': 'probe_create_add', 'source': str(source), 'library': str(library),
'name': 'Block', 'timeout_seconds': 0}
'name': 'Block', 'timeout_seconds': 0, 'supervisor_pid': os.getpid()}
with pytest.raises(RuntimeError, match='stop before native UI'):
native._probe_add_dialog_impl(App(), job, None, set(), root, library=SimpleNamespace(_oleobj_=Raw()))
records = [json.loads(line) for line in (root/'dispatch-diagnostics.jsonl').read_text(encoding='utf-8').splitlines()]
@@ -114,6 +114,8 @@ def test_probe_converts_desktop_pyhandle_before_uia_boundary(tmp_path, monkeypat
import cbb_refresh_verify.management as management
import cbb_refresh_verify.backup_recovery as recovery
source = tmp_path/'source/Block.prj'
source.parent.mkdir()
source.write_bytes(b'file-only UIA boundary fixture')
pcb = source.parent/'PCB/Block.pcb'
root = tmp_path/'native-add'; root.mkdir()
class Handle:
@@ -132,7 +134,8 @@ def test_probe_converts_desktop_pyhandle_before_uia_boundary(tmp_path, monkeypat
raise RuntimeError('integer UIA boundary reached')
monkeypatch.setitem(sys.modules, 'pywinauto', SimpleNamespace(Desktop=Desktop))
app = SimpleNamespace(OnReusableBlocksEditor=lambda: None)
job = {'operation': 'probe_create_add', 'source': str(source), 'name': 'Block',
import os
job = {'operation': 'probe_create_add', 'source': str(source), 'name': 'Block', 'supervisor_pid': os.getpid(),
'library': str(root/'fixture/mentor_lib.lmc'), 'timeout_seconds': 5}
with pytest.raises(RuntimeError, match='integer UIA boundary reached'):
native._probe_add_dialog_impl(app, job, desktop, {9}, root)
+6 -5
View File
@@ -42,8 +42,8 @@ def transaction(tmp_path, monkeypatch):
if job['operation'] == 'add':
if state.get('tamper') == 'nonce': job['transaction_nonce'] = 'foreign'
if state.get('tamper') == 'supervisor': job['supervisor_pid'] = -1
if state.get('tamper') == 'backup':
(evidence.parent/'library-before'/library.name).write_bytes(b'corrupted backup')
if state.get('tamper') == 'baseline':
(evidence.parent/'library-baseline-manifest.json').write_text('{}')
if state.get('tamper') == 'source':
(Path(job['source']).parent/'database/icdb.dat').write_bytes(b'changed staged input')
validate_transaction(job, evidence.parent)
@@ -110,13 +110,14 @@ def test_native_registered_but_asset_mismatch_retains_recovery(transaction, corr
assert result.status == 'RECOVERY_REQUIRED' and not result.safe_to_continue
def test_update_readd_failure_preserves_snapshot_and_removed_checkpoint(transaction):
def test_update_readd_failure_preserves_baseline_and_removed_checkpoint(transaction):
root, request, state = transaction
assert execute(root, request).status == 'UPLOADED'
state['fail_add'] = True
result = execute(root, replace(request, operation='update'))
assert result.status == 'RECOVERY_REQUIRED' and not result.safe_to_continue
assert (result.evidence_path.parent/'library-before/ReusableBlocksLP/Block/Work/Source.prj').exists()
assert (result.evidence_path.parent/'library-baseline-manifest.json').exists()
assert not (result.evidence_path.parent/'library-before').exists()
assert 'removed' in [entry['stage'] for entry in json.loads(result.evidence_path.read_text())['history']]
@@ -129,7 +130,7 @@ def test_fixture_grant_cannot_authorize_arbitrary_library(transaction, tmp_path)
assert other.read_bytes() == b'unchanged' and not state['calls']
@pytest.mark.parametrize('tamper', ['nonce', 'supervisor', 'backup', 'source'])
@pytest.mark.parametrize('tamper', ['nonce', 'supervisor', 'baseline', 'source'])
def test_worker_rejects_modified_management_authority_before_add(transaction, tamper):
root, request, state = transaction
state['tamper'] = tamper
+9 -1
View File
@@ -26,13 +26,21 @@ def test_layout_based_pcb_without_independent_icdb_directory_is_complete(healthy
assert engineering_identity(source)['top_level_block'] == 'IP101GR'
@pytest.mark.parametrize('missing', ['database/icdb.dat', 'PCB/Layout/LayoutDB.lyt', 'PCB/pcb.prj'])
@pytest.mark.parametrize('missing', ['database/icdb.dat', 'PCB/Layout/LayoutDB.lyt'])
def test_optional_pcb_icdb_does_not_relax_required_engineering_files(healthy_source, missing):
(healthy_source.parent/missing).unlink()
with pytest.raises(ValueError):
source_project(healthy_source)
def test_linked_legacy_pcb_uses_explicit_main_project_without_guessing_template(healthy_source):
(healthy_source.parent/'PCB/pcb.prj').rename(healthy_source.parent/'PCB/template.prj')
assert source_project(healthy_source)[0] == healthy_source
(healthy_source.parent/'PCB/IP101GR.pcb').write_text('KEY ProjectFile "../wrong.prj"\n')
with pytest.raises(ValueError, match='PCB'):
source_project(healthy_source)
def test_main_schematic_icdb_declaration_remains_required(healthy_source):
text = healthy_source.read_text(encoding='utf-8').replace('KEY iCDBDir ".\\database"\n', '')
healthy_source.write_text(text, encoding='utf-8')
+6 -5
View File
@@ -41,7 +41,7 @@ def test_management_dialog_preview_confirmation_and_result_status(qtbot, tmp_pat
qtbot.addWidget(dialog)
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: (confirmations.append(a[2]) or QMessageBox.No))
dialog.execute_button.click()
assert not calls and 'Block' in confirmations[0] and '完整' in confirmations[0]
assert not calls and 'Block' in confirmations[0] and '手动备份' in confirmations[0]
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
dialog.execute_button.click()
qtbot.waitUntil(lambda: not dialog.busy)
@@ -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:
+51
View File
@@ -0,0 +1,51 @@
from pathlib import Path
import pytest
from PySide6.QtWidgets import QMessageBox
@pytest.mark.parametrize('operation', ['add', 'update', 'remove'])
def test_management_prompts_for_manual_backup_and_cancel_starts_nothing(qtbot, tmp_path, monkeypatch, operation):
from cbb_refresh_verify.management import ManagementRequest
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
source = tmp_path/'Block.prj'; source.touch()
seen, calls = [], []
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: (seen.append(a[2]) or QMessageBox.No))
dialog = ManagementDialog([ManagementRequest(operation, tmp_path/'lib.lmc', 'Block', source=source)],
runner=lambda *a, **k: calls.append(a))
qtbot.addWidget(dialog)
dialog.execute_button.click()
assert not calls and not dialog.busy
assert len(seen) == 1 and '手动备份' in seen[0] and '不会自动备份' in seen[0]
assert '完整备份与检查点' not in seen[0]
@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
window = MainWindow(reader=lambda _: LibraryReadResult((CbbRecord('Block', 'LP'),)), data_root=tmp_path)
qtbot.addWidget(window)
window.lmc_edit.setText('library.lmc'); window.load_library()
qtbot.waitUntil(lambda: not window.busy)
window.select_visible_button.click()
seen, calls = [], []
monkeypatch.setattr(window, '_run', lambda *a, **k: calls.append(a))
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: (seen.append(a[2]) or QMessageBox.No))
getattr(window, action)()
assert not calls
assert len(seen) == 1 and '手动备份' in seen[0] and '不会自动备份' in seen[0]
def test_restore_prompts_for_manual_backup_before_starting_worker(qtbot, tmp_path, monkeypatch):
from cbb_refresh_verify.verify_runner import VerifyRequest, VerifyResult
from cbb_refresh_verify.ui.backup_recovery_dialog import BackupRecoveryDialog
calls, seen = [], []
source = tmp_path/'Block.prj'; source.touch()
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: (seen.append(a[2]) or QMessageBox.No))
dialog = BackupRecoveryDialog(['Block'], lambda n: VerifyRequest(tmp_path/'lib.lmc', n, tmp_path/'out'),
recoverer=lambda *a, **k: (calls.append(a) or VerifyResult('PASS')))
qtbot.addWidget(dialog)
dialog.source_edit.setText(str(source)); dialog.restore_button.click()
qtbot.waitUntil(lambda: not dialog.busy)
assert not calls
assert len(seen) == 1 and '手动备份' in seen[0] and '不会自动备份' in seen[0]
+85
View File
@@ -7,6 +7,91 @@ import pytest
ERROR = b'REUSE BLOCK: INFORMATION: Block\tError! Cannot copy iCDB base of Reusable Block project.\r\n'
@pytest.mark.parametrize('change', ['', 'target', 'pcb_present', 'question', 'extra_button', 'wrong_button', 'escape'])
def test_editor_missing_pcb_notice_is_only_for_unrelated_incomplete_entries(tmp_path, change):
from cbb_refresh_verify.native_add_failures import missing_other_pcb_notice
library = tmp_path/'lib.lmc'; library.touch()
work = tmp_path/'ReusableBlocksLP/Missing/Work'
(work/'PCB/Layout').mkdir(parents=True)
(work/'Missing.prj').write_text('KEY PCBDesignPath "PCB/Missing.pcb"\n')
text = ('The following Reusable Blocks do not contain PCB files and will not appear in the list of available reusable blocks:'
'\n\n\tMissing')
buttons = [{'hwnd':123, 'id':2, 'class':'Button', 'text':'确定', 'enabled':True}]
target = 'Missing' if change == 'target' else 'Current'
if change == 'pcb_present':
(work/'PCB/Missing.pcb').touch(); (work/'PCB/Layout/LayoutDB.lyt').touch()
if change == 'question': text += '\nOverwrite existing files?'
if change == 'extra_button': buttons.append({**buttons[0], 'hwnd':456})
if change == 'wrong_button': buttons[0]['text']='Yes'
if change == 'escape': text=text.replace('\tMissing', '\t../other')
result = missing_other_pcb_notice(library, target, 'Library Manager', text, buttons)
assert result == ({'names':['Missing'], 'button':123} if not change else None)
@pytest.mark.parametrize('reason', ['cancelled', 'supervisor_exited'])
def test_add_cannot_submit_after_timeout_or_supervisor_exit(tmp_path, monkeypatch, reason):
from cbb_refresh_verify.native_management import _require_add_supervisor
import cbb_refresh_verify.library_lock as locks
if reason == 'cancelled': (tmp_path/'cancel-native-add.signal').touch()
monkeypatch.setattr(locks, '_supervisor_alive', lambda _:reason != 'supervisor_exited')
with pytest.raises(RuntimeError, match='NATIVE_ADD_CANCELLED'):
_require_add_supervisor({'supervisor_pid':123}, tmp_path)
def test_add_timeout_publishes_cancellation_without_killing_native_owner(tmp_path, monkeypatch):
import cbb_refresh_verify.native_management as native
monkeypatch.setattr(native, '_retained_workers', [])
class Running:
def __init__(self, *args): pass
def poll(self): return None
def close(self): pytest.fail('live worker must not be killed')
adapter=native.NativeManagementAdapter(worker_factory=Running)
result=adapter._launch_worker({'operation':'add','desktop':'CbbManagement_test','timeout_seconds':0},tmp_path)
assert not result['safe_to_continue'] and (tmp_path/'cancel-native-add.signal').exists()
assert len(native._retained_workers)==1
def test_cancellation_during_log_evidence_prevents_native_submit(tmp_path, monkeypatch):
import os,sys
from types import SimpleNamespace
import win32gui,win32process
import cbb_refresh_verify.native_management as native
import cbb_refresh_verify.native_add_failures as failures
from test_management import project
source=project(tmp_path/'source',name='Block')
root=tmp_path/'native-add';root.mkdir()
library=root/'fixture/lib.lmc';library.parent.mkdir();library.touch()
for path in (source,source.parent/'PCB/pcb.prj'):
with path.open('a',encoding='utf-8') as stream:stream.write(f'KEY CentralLibrary "{library}"\n')
state={'new':False,'posted':[]}
tab=SimpleNamespace(window_text=lambda:'Logical - Physical',is_selected=lambda:True)
monkeypatch.setitem(sys.modules,'pywinauto',SimpleNamespace(Desktop=lambda **k:SimpleNamespace(
window=lambda **k:SimpleNamespace(descendants=lambda **k:[tab]))))
monkeypatch.setattr(win32process,'GetWindowThreadProcessId',lambda h:(1,99))
monkeypatch.setattr(win32gui,'IsWindowVisible',lambda h:True)
monkeypatch.setattr(win32gui,'IsWindowEnabled',lambda h:True)
monkeypatch.setattr(win32gui,'GetWindowText',lambda h:{100:'Reusable Blocks',200:'New Reusable Block'}[int(h)])
monkeypatch.setattr(win32gui,'GetDlgItem',lambda h,c:110 if h==100 else 210 if c==1083 else c+1000)
monkeypatch.setattr(win32gui,'GetClassName',lambda h:'Edit')
monkeypatch.setattr(native,'_set_probe_field',lambda *a:None)
def post(h,*args):
state['posted'].append(h)
if h==110:state['new']=True
monkeypatch.setattr(win32gui,'PostMessage',post)
original=native._write_json
def write(path,data):
original(path,data)
if path.name=='native-add-log-baseline.json':(root/'cancel-native-add.signal').touch()
monkeypatch.setattr(native,'_write_json',write)
monkeypatch.setattr(failures,'observe_add_failure',lambda *a:(_ for _ in ()).throw(RuntimeError('unsafe OK posted')))
desktop=SimpleNamespace(EnumDesktopWindows=lambda:[100,200] if state['new'] else [100])
job={'operation':'probe_create_add','source':str(source),'library':str(library),
'name':'Block','timeout_seconds':5,'supervisor_pid':os.getpid()}
with pytest.raises(RuntimeError,match='NATIVE_ADD_CANCELLED'):
native._probe_add_dialog_impl(SimpleNamespace(OnReusableBlocksEditor=lambda:None),job,desktop,{99},root)
assert state['posted']==[110]
def test_copy_failure_log_must_be_new_and_match_current_block(tmp_path):
from cbb_refresh_verify.native_add_failures import snapshot_add_log, fresh_add_failure
library = tmp_path/'lib.lmc'; library.touch()
+262
View File
@@ -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()
+29
View File
@@ -72,6 +72,24 @@ def test_assets_require_correct_library_references_and_unknown_bytes(project):
asset_identity(source, library)
def test_linked_legacy_identity_preserves_template_bytes_and_aligns_only_active_project(project, tmp_path):
from cbb_refresh_verify.native_engineering_identity import asset_identity, project_library
from cbb_refresh_verify.backup_recovery import _align_library
source, library = project
template = source.parent/'PCB/template.prj'
(source.parent/'PCB/pcb.prj').rename(template)
original = template.read_bytes()
before = asset_identity(source, library)
assert 'PCB/template.prj' in before['assets']
other = tmp_path/'other.lmc'; other.write_bytes(b'other library')
_align_library(source, next((source.parent/'PCB').glob('*.pcb')), other)
assert template.read_bytes() == original
assert project_library(source) == other
assert asset_identity(source, other) == before
template.write_bytes(original+b'unknown engineering change')
assert asset_identity(source, other) != before
@pytest.mark.parametrize('relative', ['database/cdbsvr/persistent.dat',
'database/cdbsvr/new-engineering/config.bin', 'database/cdbsvr/events/custom.dat',
'database/cdbsvr/plog/unknown-engineering.bin'])
@@ -199,3 +217,14 @@ def test_edif_only_normalizes_root_written_timestamp_preserving_geometry_and_pro
for bad in [first[:-1], first.replace(b'(edifVersion 2 0 0)', b'(edifVersion 1 0 0)'),
first.replace(b'(cellRef Top', b'(cellRef Other'), first.replace(b'(pt 1 2)', b'')]:
with pytest.raises(ValueError): normalize_edif(bad, 'Top')
def test_edif_binds_native_escaped_digit_initial_root_without_changing_design_bytes():
from cbb_refresh_verify.native_engineering_identity import normalize_edif
report = edif_report().replace(b'cell Top', b'cell &1GPHY_8212').replace(b'cellRef Top', b'cellRef &1GPHY_8212')
normalized = normalize_edif(report, '1GPHY_8212')
assert b'(cell &1GPHY_8212' in normalized and b'(cellRef &1GPHY_8212' in normalized
for wrong in ('1GPHY_8211', '&1GPHY_8212'):
with pytest.raises(ValueError): normalize_edif(report, wrong)
with pytest.raises(ValueError):
normalize_edif(report.replace(b'&1GPHY_8212', b'1GPHY_8212'), '1GPHY_8212')
+5 -5
View File
@@ -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()
+191
View File
@@ -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'
+41 -10
View File
@@ -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):
@@ -234,7 +236,7 @@ def test_retained_importer_blocks_repair_even_without_an_open_database_handle(tm
assert 'IMPORTER_RELEASE_UNCONFIRMED' in outcome['detail']
def test_repair_cancellation_during_backup_prevents_native_launch(tmp_path, monkeypatch):
def test_repair_cancellation_during_access_check_prevents_native_launch(tmp_path, monkeypatch):
from cbb_refresh_verify import native_repair_ui as ui, native_repair, mentor_adapter
request, record, target = target_fixture(tmp_path)
root = tmp_path/'worker'
@@ -251,15 +253,15 @@ def test_repair_cancellation_during_backup_prevents_native_launch(tmp_path, monk
monkeypatch.setattr(ui, '_repair_command', lambda *_: 32924)
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: [])
monkeypatch.setattr(mentor_adapter, '_process_details', lambda *_: [])
def backup(*a):
assert calls == ['watchdog'], 'Watch supervisor before the potentially long backup'
def check(*a):
assert calls == ['watchdog'], 'Watch supervisor before filesystem checks'
cancel.touch()
calls.append('backup')
monkeypatch.setattr(native_repair, 'backup_project', backup)
calls.append('check')
monkeypatch.setattr(native_repair, 'check_repair_access', check)
monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **kw: pytest.fail('Repair must not start'))
assert ui.repair_worker_main(job) == 1
outcome = json.loads((root/'repair-result.json').read_text('utf-8'))
assert 'REPAIR_CANCELLED_AFTER_BACKUP' in outcome['detail']
assert 'REPAIR_CANCELLED_BEFORE_LAUNCH' in outcome['detail']
def test_repair_worker_refuses_the_input_desktop_before_backup(tmp_path, monkeypatch):
@@ -425,6 +427,30 @@ def test_native_worker_preserves_success_and_historical_restore_distinction(tmp_
assert native_success_confirmed(target, result) is (scenario == 'success')
def test_repair_skips_application_backup_but_keeps_native_repair_backup(tmp_path, monkeypatch):
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'success')
monkeypatch.setattr('cbb_refresh_verify.native_repair.backup_project',
lambda *a: pytest.fail('application project backup must not run'))
assert ui.repair_worker_main(job) == 0
result = json.loads((root/'repair-result.json').read_text('utf-8'))
assert result['evidence']['native_backup'] is True
assert not (root/'complete-backup').exists()
def test_repair_without_application_backup_still_rejects_busy_database(tmp_path, monkeypatch):
import win32con, win32file
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'success')
database = Path(json.loads(job.read_text())['database'])/'icdb.dat'
handle = win32file.CreateFile(str(database), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
try:
monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **kw: pytest.fail('busy database launched'))
assert ui.repair_worker_main(job) == 1
assert 'REPAIR_DATABASE_IN_USE' in json.loads((root/'repair-result.json').read_text())['detail']
finally:
handle.Close()
def test_native_busy_project_on_load_never_invokes_repair(tmp_path, monkeypatch):
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'busy_before')
assert ui.repair_worker_main(job) == 1
@@ -487,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()
@@ -822,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
+43
View File
@@ -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()
+23
View File
@@ -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'])
+132
View File
@@ -0,0 +1,132 @@
from dataclasses import replace
import json
from pathlib import Path
from types import SimpleNamespace
import pytest
from test_pcb_version_choice import captured
from test_post_repair_consent import context, no_native_launch
@pytest.fixture
def session(context, monkeypatch):
from cbb_refresh_verify import post_repair_consent as consent
from cbb_refresh_verify.pcb_restore_prompt import RestoreController
_, _, proof, job = context
consent.prepare_launch(job, ['C:/Mentor/common/win32/bin/ExpeditionPCB.exe', job['pcb'], '-ReusableCircuit'])
monkeypatch.setattr(consent, '_validate_current_processes', lambda *a: None)
snapshot = captured()
controller = RestoreController(job)
prompts, calls = [], []
def perform(snap, payload, phase):
calls.append(payload)
return SimpleNamespace(accepted_controls=(payload['target']['control_id'],),
channel='win32_button_click', error_code='', detail='')
def poll(snap=snapshot, snapshots=None):
return controller.handle(snap, snapshots or (snap,), target_pid=snapshot.pid,
launcher_pid=10, worker_pid=__import__('os').getpid(), companion_pids=(),
show=prompts.append, perform=perform)
return controller, snapshot, prompts, calls, poll, job
def test_waits_for_user_once_and_rechecks_radio_before_confirm(session):
controller, snapshot, prompts, calls, poll, job = session
assert not poll().error_code
poll()
assert len(prompts) == 1 and not calls
prompts[0].choose('last_user_saved')
assert poll().action_sent and calls[-1]['target']['control_id'] == 6213
assert not poll().action_sent and len(calls) == 1
selected = replace(snapshot, controls=tuple(replace(c, checked=c.control_id == 6213,
selected=c.control_id == 6213) if c.control_id in (6213, 6206) else c for c in snapshot.controls))
assert poll(selected).action_sent and calls[-1]['target']['control_id'] == 1
assert not poll(selected).action_sent and len(calls) == 2
result = json.loads((Path(job['root'])/'pcb-version-restoration.json').read_text(encoding='utf-8'))
assert result['choice'] == 'last_user_saved' and result['date'] == '2026/9/24 23:06'
assert result['historical_restore'] and result['confirm_sent']
def test_cancel_never_selects_or_confirms_a_version(session):
_, _, prompts, calls, poll, _ = session
poll(); prompts[0].choose('cancel')
result = poll()
assert result.error_code == 'PCB_VERSION_CHOICE_REQUIRED'
assert '取消' in result.detail and not calls
@pytest.mark.parametrize('change', ['date', 'pid', 'window', 'extra'])
def test_changed_native_choice_invalidates_user_answer(session, change):
_, snapshot, prompts, calls, poll, _ = session
poll(); prompts[0].choose('last_user_saved')
changed = snapshot
if change == 'date':
changed = replace(snapshot, controls=tuple(replace(c, name=c.name.replace('23:06', '23:07'))
if c.control_id == 6213 else c for c in snapshot.controls))
if change == 'pid': changed = replace(snapshot, pid=snapshot.pid + 1)
if change == 'window': changed = replace(snapshot, hwnd=snapshot.hwnd + 1)
result = poll(changed, (changed, changed) if change == 'extra' else None)
assert result.error_code and not calls
def test_native_action_failure_never_retries_or_confirms(session):
controller, snapshot, prompts, calls, poll, _ = session
poll(); prompts[0].choose('last_user_saved')
def failed(*a):
return SimpleNamespace(accepted_controls=(), channel='', error_code='ACTION_CHANNEL_FAILED', detail='timeout')
result = controller.handle(snapshot, (snapshot,), target_pid=snapshot.pid, launcher_pid=10,
worker_pid=__import__('os').getpid(), companion_pids=(), show=prompts.append, perform=failed)
assert result.error_code == 'ACTION_CHANNEL_FAILED'
assert poll().error_code and not calls
def test_version_dialog_shows_dates_and_explicit_choices(qtbot):
from cbb_refresh_verify.pcb_restore_prompt import RestoreChoice
from cbb_refresh_verify.ui.pcb_restore_dialog import PcbRestoreDialog
from cbb_refresh_verify.dialog_rules import pcb_version_choice
choice = RestoreChoice('Block', 'library.lmc', pcb_version_choice(captured())['candidates'])
dialog = PcbRestoreDialog(choice)
qtbot.addWidget(dialog)
assert '2026/9/24 23:06' in dialog.text()
assert choice.decision is None
dialog.manual_button.click()
assert choice.decision == 'last_user_saved'
def test_closing_version_dialog_is_cancel_not_a_default_selection(qtbot):
from cbb_refresh_verify.pcb_restore_prompt import RestoreChoice
from cbb_refresh_verify.ui.pcb_restore_dialog import PcbRestoreDialog
from cbb_refresh_verify.dialog_rules import pcb_version_choice
choice = RestoreChoice('Block', 'library.lmc', pcb_version_choice(captured())['candidates'])
dialog = PcbRestoreDialog(choice)
qtbot.addWidget(dialog)
dialog.reject()
assert choice.decision == 'cancel'
@pytest.mark.parametrize('change', ['', 'desktop', 'pid', 'date', 'disabled', 'selection', 'channel'])
def test_private_agent_rechecks_live_version_before_confirmation(monkeypatch, change):
import win32gui, win32process
from cbb_refresh_verify.dialog_agent import DialogActionExecutor
from cbb_refresh_verify.dialog_rules import pcb_version_choice
snapshot = replace(captured(), controls=tuple(replace(c, checked=c.control_id == 6213,
selected=c.control_id == 6213) if c.control_id in (6213, 6206) else c for c in captured().controls))
controls = {c.handle: c for c in snapshot.controls if c.handle and c.class_name in ('Static', 'Button')}
monkeypatch.setattr('cbb_refresh_verify.native_repair_ui._current_desktop_name',
lambda: 'Default' if change == 'desktop' else 'CbbVerify_fixture')
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda h: (1, snapshot.pid + (change == 'pid')))
monkeypatch.setattr(win32gui, 'GetClassName', lambda h: snapshot.window_class if h == snapshot.hwnd else controls[h].class_name)
monkeypatch.setattr(win32gui, 'GetWindowText', lambda h: snapshot.title if h == snapshot.hwnd else
controls[h].name.replace('23:06', '23:07') if change == 'date' else controls[h].name)
monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda h: True)
monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda h: not (change == 'disabled' and controls[h].control_id == 6213))
monkeypatch.setattr(win32gui, 'GetDlgCtrlID', lambda h: controls[h].control_id)
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda h, callback, arg: [callback(c, arg) for c in controls])
monkeypatch.setattr(win32gui, 'SendMessageTimeout', lambda h, *a: int(controls[h].control_id == (6206 if change == 'selection' else 6213)))
calls = []
monkeypatch.setattr(win32gui, 'PostMessage', lambda *a: calls.append(a))
action = {'action': 'user_selected_pcb_version', 'channels': ['uia_invoke' if change == 'channel' else 'win32_button_click'],
'target': {'control_id': 1}, 'pid': snapshot.pid, 'desktop': 'CbbVerify_fixture',
'choice': 'last_user_saved', 'candidates': pcb_version_choice(snapshot)['candidates']}
result = DialogActionExecutor().perform(snapshot, action)
assert bool(result.accepted_controls) is (change == '')
assert len(calls) == (1 if change == '' else 0)
+6 -1
View File
@@ -95,9 +95,14 @@ def test_prelaunch_proof_blocks_without_launch(context, monkeypatch, obstacle):
if handle: handle.Close()
def test_exact_dialog_after_bound_prelaunch_is_allowed_only_once(context, monkeypatch):
@pytest.mark.parametrize('pcb_config', ['standard', 'legacy_template'])
def test_exact_dialog_after_bound_prelaunch_is_allowed_only_once(context, monkeypatch, pcb_config):
from cbb_refresh_verify import post_repair_consent as consent
_, _, proof, job = context
if pcb_config == 'legacy_template':
pcb = Path(job['pcb'])
(pcb.parent/'pcb.prj').rename(pcb.parent/'template.prj')
pcb.write_text('KEY ProjectFile "../'+Path(job['project']).name+'"\n')
command = ['C:/Mentor/common/win32/bin/ExpeditionPCB.exe', job['pcb'], '-ReusableCircuit']
consent.prepare_launch(job, command)
controller = consent.ConsentController(proof, job)
+242
View File
@@ -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 == []
+14 -4
View File
@@ -8,7 +8,8 @@ from cbb_refresh_verify.runtime_timing import parse_save_progress
@pytest.mark.parametrize('save_ok', [True, False])
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']
+8 -5
View File
@@ -25,6 +25,8 @@ def fake_reader(_): return LibraryReadResult((CbbRecord('CBB1','Reusable Blocks'
@pytest.fixture(autouse=True)
def isolate_authoritative_native_refresh(monkeypatch):
from PySide6.QtWidgets import QMessageBox
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
# Production refresh crosses the native Mentor boundary; these are UI tests.
monkeypatch.setattr('cbb_refresh_verify.ui.main_window.authoritative_status_map',
lambda names, *_: {name: 'READY' for name in names})
@@ -76,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):
@@ -95,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
@@ -357,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()
+1
View File
@@ -24,6 +24,7 @@ MIXED = (
def load_window(qtbot, tmp_path, monkeypatch, records=MIXED, **kwargs):
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
import cbb_refresh_verify.ui.main_window as ui
monkeypatch.setattr(ui, 'preflight_skip_reason',
lambda _, name: 'missing project' if name == 'Missing' else None)
+10 -10
View File
@@ -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
+9
View File
@@ -54,6 +54,15 @@ def test_missing_cert_cannot_block_saved_and_closed_worker(tmp_path, monkeypatch
assert any(e['stage'] == 'cert_diagnostics' and e['non_blocking'] for e in events)
def test_verify_does_not_create_automatic_project_backup(tmp_path, monkeypatch):
job, events, execute = exercise_worker(tmp_path, monkeypatch)
monkeypatch.setattr(adapter, 'best_effort_backup',
lambda *a, **kw: pytest.fail('automatic project backup must not run'))
assert execute()['status'] == 'PASS'
assert not (Path(job['root'])/'backup').exists()
assert any(e['stage'] == 'backup_skipped' and e['reason'] == 'manual_backup_policy' for e in events)
def test_cert_diagnostic_io_failure_is_nonblocking(tmp_path, monkeypatch):
from cbb_refresh_verify.mentor_adapter import collect_cert_evidence
original = Path.stat