Compare commits

..
Author SHA1 Message Date
阿白叔 9ac2f91dde fix: reject legacy copy paths and surface native Add failures 2026-11-03 12:51:35 +08:00
阿白叔 e915aaa865 feat: enable validated pinned native Add and replacement routes 2026-11-03 12:29:42 +08:00
阿白叔 f21781f170 fix: preserve unknown assets and retained export-copy ownership 2026-11-03 12:24:54 +08:00
阿白叔 55a82fdc5f feat: bind native CRUD to prepared engine identity transactions 2026-11-03 11:54:56 +08:00
阿白叔 89500cbb5f feat: require native EDIF geometry in engineering identity 2026-11-03 11:43:45 +08:00
阿白叔 63f3417f19 feat: capture gated native logical and physical identity evidence 2026-11-03 11:39:38 +08:00
阿白叔 ca84bce24f fix: retain uncertain fixture owners and reject source overlap 2026-11-03 11:27:34 +08:00
阿白叔 b97556dcc1 fix: require owned fixture authority for native Add research 2026-11-03 11:22:27 +08:00
阿白叔 07a9c1eaaf feat: integrate shared native Add worker behind identity gate 2026-11-03 11:11:36 +08:00
阿白叔 f8f2dd53aa docs: record actual maintenance button and user-selected recovery validation 2026-11-03 10:25:59 +08:00
阿白叔 2085ec770f docs: explain pending PCB recovery version decision 2026-11-03 09:55:24 +08:00
阿白叔 d76475a1d7 fix: report pending PCB recovery version without obscuring native repair 2026-11-03 09:54:01 +08:00
阿白叔 99a708b40c fix: distinguish UIA dialog chrome from native consent controls 2026-11-03 09:43:16 +08:00
阿白叔 9806ef8f66 docs: record local-only post-repair consent boundary 2026-11-03 09:37:52 +08:00
阿白叔 aa6684b588 fix: bound post-repair readwrite consent to proven local startup 2026-11-03 09:36:33 +08:00
阿白叔 5a758ee3b6 fix: separate maintenance release from safe queue continuation 2026-11-03 09:18:36 +08:00
阿白叔 b635432cff fix: scope maintenance addresses to selected project and shared stores 2026-11-03 09:16:13 +08:00
阿白叔 4cbca0b5a6 docs: explain explicit maintenance for existing ICDB addresses 2026-11-03 09:15:06 +08:00
阿白叔 e39dc63ded fix: admit explicit ICDB maintenance with preserved address evidence 2026-11-03 09:13:32 +08:00
阿白叔 4f741cd176 docs: record final issue 2 candidate evidence and acceptance gaps 2026-11-02 22:59:50 +08:00
阿白叔 122bafcc7a test: scope deletion safeguard to authorized runtime checkpoints 2026-11-02 22:56:30 +08:00
阿白叔 8e486c1097 fix: bound native edit messages and identify empty IE infrastructure 2026-11-02 22:44:50 +08:00
阿白叔 bb98fe66dd fix: normalize native editor handles before UIA calls 2026-11-02 22:36:23 +08:00
阿白叔 1f69480ed8 fix: preload UIA before native proxies and package timezone support 2026-11-02 22:32:32 +08:00
阿白叔 ffa7e84d43 fix: retain unknown startup windows and expose native dispatch errors 2026-11-02 22:19:59 +08:00
阿白叔 46c3e72364 fix: preserve mapped native paths and retain probe ownership guards 2026-11-02 21:48:40 +08:00
阿白叔 dd1fcea7e2 fix: accept layout-based PCB projects without optional icdb path 2026-11-02 21:19:57 +08:00
阿白叔 797a79c30e feat: add guarded native CBB management and recovery coordination 2026-11-02 21:13:24 +08:00
阿白叔 3415e010ff fix: preserve engineering identity in scoped runtime exclusions 2026-11-02 19:50:26 +08:00
阿白叔 29c154d2ca feat: scope recovery manifests while verifying complete backups 2026-11-02 19:32:07 +08:00
阿白叔 877e3b4c76 fix: wait for native repair project shell and ignore known input indicators 2026-11-02 19:12:12 +08:00
阿白叔 b90a9bbfab fix: allow explicit native repair owner process queries 2026-11-02 18:52:04 +08:00
阿白叔 747ce1add2 feat: scope CBB search selection and maintenance to visible non-READY rows 2026-11-02 18:47:25 +08:00
阿白叔 c823a4b92d fix: fail closed on busy or unconfirmed native repair evidence 2026-11-02 18:27:19 +08:00
阿白叔 aa760c2839 fix: classify ICDB repair outcomes and gate released recovery 2026-11-02 18:14:38 +08:00
阿白叔 44b808b8e2 docs: record approved issue 2 implementation plan 2026-11-02 17:52:50 +08:00
阿白叔 ec78dd722c fix: close owned PCB startup failures before ICDB recovery 2026-11-02 17:40:18 +08:00
阿白叔 39985f7cfd chore: release v0.2.3-beta.1 2026-10-29 09:54:10 +08:00
abaishu0730 ac9836a2d5 Merge pull request '增加 ICDB 全库维护与 CBB 备份恢复弹窗,完善会话安全处理' (#1) from codex/icdb-global-repair into main
Reviewed-on: #1
2026-10-28 20:57:02 +08:00
阿白叔 cdb8a6a28b feat: add ICDB maintenance and verified CBB backup recovery dialog 2026-10-28 19:43:07 +08:00
阿白叔 a851e47eca docs: record verified iCDB recovery trial and delivery scope 2026-10-27 18:15:00 +08:00
阿白叔 9cd4968a97 fix: enforce native repair ownership and cancellation boundaries 2026-10-27 18:08:14 +08:00
阿白叔 2490067b2d fix: prevent iCDB disconnects and recover failed projects 2026-10-27 17:51:53 +08:00
阿白叔 8a517d6f38 fix: diagnose iCDB lost sessions and stop unsafe verification 2026-10-27 16:38:51 +08:00
93 changed files with 14213 additions and 146 deletions

No files matched your search

+10 -5
View File
@@ -1,9 +1,14 @@
# CBB 中心库上传后校验工具 # CBB 中心库上传后校验工具
当前补丁:**[v0.2.2-beta.1](docs/releases/v0.2.2-beta.1.md)(Beta 预发布,待现场验收)**,替代 0.2.1。数据库所有权或关闭状态不确定时停止批次、保留现场;不自动移走地址文件、接管带锁设计或强杀 PCB 进程树。已修复真实试跑发现的已验证块重复 Forward Annotation 问题,以及工程文件编码、目录越界、互斥和依赖漏洞。详见 [本地验证与安全审查](docs/releases/2026-10-26-local-validation-and-audit.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)。下方日期记录描述历史版本,以本补丁说明为准。
本目录是独立的 CBB 中心库上传后校验工具,不属于 Part Replacement,也不负责 CBB 工程复制或中心库上传。 本目录是独立的 CBB 中心库上传后校验工具,不属于 Part Replacement,也不负责 CBB 工程复制或中心库上传。
针对 `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 入口时停止并要求人工处理。
## 功能边界 ## 功能边界
| 工具 | 处理对象 | 核心动作 | 结果 | | 工具 | 处理对象 | 核心动作 | 结果 |
@@ -135,8 +140,8 @@ python -m cbb_refresh_verify
- **不注入鼠标或键盘输入,不切换 Windows 桌面,不改写中心库源文件。** 生产路径在本次运行创建的私有桌面内启动中心库目录绑定的 ReusableCircuit PCB,随后用 COM 完成刷新、保存和关闭;只读状态桥在结束后确认 LMC 的 READY。Library Manager 菜单派发仅作为显式诊断路径保留。`tests/test_safety.py` 会在离线测试中阻止真实输入注入 API 重新进入生产代码。 - **不注入鼠标或键盘输入,不切换 Windows 桌面,不改写中心库源文件。** 生产路径在本次运行创建的私有桌面内启动中心库目录绑定的 ReusableCircuit PCB,随后用 COM 完成刷新、保存和关闭;只读状态桥在结束后确认 LMC 的 READY。Library Manager 菜单派发仅作为显式诊断路径保留。`tests/test_safety.py` 会在离线测试中阻止真实输入注入 API 重新进入生产代码。
- 所有自动化都跑在本进程创建的**私有 Windows 桌面**上:用户看不到窗口,光标不会被移动。 - 所有自动化都跑在本进程创建的**私有 Windows 桌面**上:用户看不到窗口,光标不会被移动。
- 弹窗只认领本次运行自己启动的进程,并在该进程的私有桌面内投递 `BM_CLICK`。数据库异常恢复提示默认选择“最后一次用户保存的数据库”;其他弹窗优先确认/继续/恢复,只有 Project Integration 进度窗(仅有 Cancel)保持不动。所有弹窗文本和实际控件 ID 都写入 `dialogs.jsonl`。 - 弹窗只认领本次运行的私有桌面/进程,依据已知规则投递 `BM_CLICK`。数据库恢复、会话失联和设计锁接管提示会阻断并保留现场;不会自动选择恢复或接管。未知弹窗也会阻断,Project Integration 进度窗保持观察。动作/错误弹窗和实际控件 ID 写入 `dialogs.jsonl`。
- 超时或失败时停止自动化客户端,保留可能仍在写库的原生会话并停止批次。监督器核对进程是否退出,记录 `process_exit_confirmed` 或 `process_retained`;无法确认释放时输出 `recovery-required.json`,不以强杀代替数据库安全关闭。 - 超时或失败时停止自动化客户端,保留可能仍在写库的原生会话并停止批次。内容检查超时也不再强杀整个进程树;监督器核对进程是否退出,记录 `process_exit_confirmed` 或 `process_retained`;无法确认释放时输出 `recovery-required.json`,不以强杀代替数据库安全关闭。已确认身份且原生调用返回的失败文档会通过 32 位助手执行 `Close(False)`,再确认进程和 iCDB 地址释放。
## 环境要求 ## 环境要求
@@ -163,7 +168,7 @@ Windows 版本判断以 Build 为准:`22000` 及以上归为 Win11,`10240–
## 批量策略 ## 批量策略
每个 CBB 独立执行并写入自己的 evidence 和结果行。缺少 PCB/PRJ、内容检查失败、刷新失败或超时只影响当前项,记录 `BLOCKED/FAIL/TIMEOUT` 后继续下一项;不会因为单项失败终止整批。只有点击“当前项完成后停止”(或执行器返回 `QUEUE_STOP`)才把后续项目标为 `SKIPPED`。 每个 CBB 独立执行并写入自己的 evidence 和结果行。可确认安全的单项失败允许继续;遇到 `ICDB_REPAIR_REQUIRED`、超时、原生会话释放未确认等情况,会停止整批并把后续项目标为 `SKIPPED`。点击“当前项完成后停止”或执行器返回 `QUEUE_STOP` 也会停止队列。
GUI 中状态为 `绿色 / Ready` 的条目不能勾选、也不会进入批量队列。 GUI 中状态为 `绿色 / Ready` 的条目不能勾选、也不会进入批量队列。
@@ -196,7 +201,7 @@ Mentor 桥耗时需在目标机器另行测量。
- `save.log`:`LICENSE_OK / SAVE_OK / IS_SAVED / POST_SAVE_SYNCHRONIZED / CLOSE_OK / QUIT_OK`; - `save.log`:`LICENSE_OK / SAVE_OK / IS_SAVED / POST_SAVE_SYNCHRONIZED / CLOSE_OK / QUIT_OK`;
- `result.json`:状态、中心库标志读取结果、阻断原因; - `result.json`:状态、中心库标志读取结果、阻断原因;
- `image-status-map.json`:按中心库路径隔离的本机动态 `image_id` 校准快照(当前格式 `schema_version=2`);旧版本或无版本缓存会自动忽略并重新校准,日志会记录当前样本、缓存样本、Ready 主 ID、未映射 ID 和逐项决策原因; - `image-status-map.json`:按中心库路径隔离的本机动态 `image_id` 校准快照(当前格式 `schema_version=2`);旧版本或无版本缓存会自动忽略并重新校准,日志会记录当前样本、缓存样本、Ready 主 ID、未映射 ID 和逐项决策原因;
- `backup/`:仅本地盘操作前的稳定文件副本;网络盘/UNC 跳过前置递归备份(`backup_skipped`);`database/LogFiles/tmp` 等易变目录和日志文件会排除,备份超时或失败不会阻断 PCB 校验。每个 CBB 结束后默认自动删除该目录,只保留 `events.jsonl`、`dialogs.jsonl`、`save.log` 和 `result.json` 等轻量证据。 - `backup/`:仅本地盘操作前的稳定文件副本;网络盘/UNC 跳过前置递归备份(`backup_skipped`);`database/LogFiles/tmp` 等易变目录和日志文件会排除,备份超时或失败不会阻断 PCB 校验。仅在成功且确认安全后清理该目录,失败时保留已有副本及日志;它不是完整数据库回滚备份。
超时采用无进展计时:界面和批量请求默认 600 秒无进展超时;它不是整个 CBB 的固定总时限,而是连续 600 秒没有可观察进展时才终止。PCB/COM 阶段切换、Project Integration 状态变化、保存标记变化和弹窗处理都会刷新计时器;重复的状态轮询不算进展。需要更快失败时仍可在界面将单项预算调低,但 30 秒只适合已确认 PCB 启动稳定的环境。 超时采用无进展计时:界面和批量请求默认 600 秒无进展超时;它不是整个 CBB 的固定总时限,而是连续 600 秒没有可观察进展时才终止。PCB/COM 阶段切换、Project Integration 状态变化、保存标记变化和弹窗处理都会刷新计时器;重复的状态轮询不算进展。需要更快失败时仍可在界面将单项预算调低,但 30 秒只适合已确认 PCB 启动稳定的环境。
+77
View File
@@ -0,0 +1,77 @@
# iCDB 原生手动修复与工程更新
适用:本机 Mentor EE7.9.5。菜单已从实际安装的原生程序资源核对;修复、失败诊断和修复后重新打开已在隔离工程实测。
## 先确定要处理的目标
以本轮原生日志的数据库路径为准。`ReusableBlocksLP/<CBB>/Work/database` 属于该工程;`SymbolLibs/__ReusableBlocksSymb` 属于中心库共享符号数据库。共享符号库不能靠修复无关的 CBB Work 工程替代。
操作前正常关闭使用相同库的 PCB、Library Manager、原理图/符号编辑客户端,核对原服务器会话已结束,保留包含数据库、原备份和日志的完整一致副本。以下写入先在副本上进行。
## 原生工程数据库 Repair
1. 启动本机的 iCDB Project Backup,并打开实际报错工程对应的 `.prj`。本机可用 PowerShell 命令形式如下,工程路径需替换为自己的隔离副本:
```powershell
& 'D:\Mentor\7.9.5EE\SDD_HOME\iCDB\win32\bin\iCDBProjectBackup.exe' -p 'F:\隔离副本\ReusableBlocksLP\IP101GR\Work\IP101GR.prj'
```
2. 核对窗口标题中的完整 PRJ 路径,确认它关联本轮日志中的数据库。
3. 选择 **Project → Repair**,阅读确认框后执行。原生工具会检查工程并尝试修复,事先创建当前状态备份。
4. 查看 **View → Output** 中的完整输出;必要时使用 **Backup → View operation log**。记录选择了哪份历史备份、是否恢复旧版本,以及是否明确报错。
5. 正常关闭原生修复工具,再打开原先失败的同一工程。检查原数据库错误是否消失,并执行下节同步/Verify。
前面的自动化测试调用的就是此原生 Repair 入口。手动操作可直接看到原生诊断和恢复选择,但不能保证对同样的损坏取得不同修复结果。
### 如何判断结果
| 原生结果 | 后续操作 |
| --- | --- |
| 原位检查/修复完成 | 再次打开同一目标,核对数据库加载、工程同步、保存和关闭 |
| 从某个历史备份恢复 | 核对备份日期、原理图、PCB 和约束内容版本,再决定是否使用;不能直接等同无损修复 |
| `Cannot repair the project - there is no backup of missing iCDB` | 停止反复重试;当前状态备份只保留损坏现场,寻找有效恢复源或厂商支持 |
| 仍有占用或原生操作未结束 | 先确认实际会话和操作状态,不通过强杀或删除地址/锁文件替代修复 |
文件头损坏且没有历史备份的本机实测已得到第三种结果。会话失联故障是否能够原位修复仍需按实际原生诊断单独验证。
## 能够正常打开后的手动工程更新
1. 打开当前工程的 PCB,进入 **Project Integration** 窗口。
2. 查看 Forward Annotation、CES/约束加载与同步、Back Annotation 状态。对原生允许且标记 Required 的动作逐项执行,每次执行后重新观察状态。
3. 确认所需项目达到同步状态,保存工程并正常关闭。
4. 在 Library Manager 中选中对应 Reusable Block,使用 **Verify**,再读取真实校验结果。工具中的权威状态检查可以进一步确认 `READY / raw=1`。
本机生产流程及实机日志已验证四项同步、保存、关闭和权威 Ready 状态。这些更新动作要求工程数据库能够加载;若一打开就报告 ICDB 数据库无法加载,应先处理修复/恢复。
## 检查与升级相关入口的实际用途
| 本机确认的入口 | 用途与验证边界 |
| --- | --- |
| iCDB Server Manager → Tools → Diagnostics → Check database | 数据库诊断;本轮只确认菜单存在,未在现场库执行。不能视为另一种已验证的修复方式 |
| iCDB Project Backup → Project → Create support package | 创建支持资料,供对应版本技术支持分析;本轮只确认菜单存在 |
| Library Manager → Tools → Update DxSystems Designer Cache | DxSystems Designer 缓存更新,不能据菜单名称推断它能恢复损坏的工程或共享符号数据库 |
| `conv2iCDBpi` | 本机内置帮助标明用于旧 CDB/CES 到 iCDB 的转换,`-updatepowers` 只更新已转换库的 POWER 属性;未验证为损坏库修复路线 |
| `SideFiles2iCDB` | 包装到 `sandboxfile.exe`,帮助标明从文件导入 pin package length 数据,要求已有 iCDB、snapshot、topblock;没有验证其具有通用重建能力 |
本次实际核对的 iCDB Project Backup 菜单中没有独立的“强制升级损坏数据库”入口。更新 Mentor 软件、安装补丁或正常格式迁移应根据工程创建版本、目标版本兼容说明及正式向导,在完整副本上操作;升级软件不能保证补回损坏或丢失的数据。
本机旧 CHM 帮助重定向到 InfoHub,但当前安装的完整 InfoHub 文档不齐全。上述菜单以实际二进制菜单资源为依据,转换工具用途以本机内置帮助字符串为依据;未确认的升级步骤没有作为可执行指令列出。
## 本仓库实机记录
- `docs/releases/2026-10-28-icdb-open-repair-reopen-validation.md`:实际报错 → 原生恢复 → 同一工程重新打开 PASS/READY。
- `docs/releases/2026-10-28-icdb-no-history-repair-validation.md`:没有历史备份时同类文件头损坏未能修复,保留原生 no-backup 错误文本。
若现场报错明确指向共享符号数据库,应继续核对该共享存储支持的原生恢复/重建入口和原始符号来源。目前没有已验证的共享库强制更新修复步骤。
## 工具中的“从备份恢复 CBB”弹窗
读取中心库后,点击数据库维护区的“从备份恢复 CBB…”,选择目标名称及独立备份中的同名工程 PRJ,再点击“恢复并校验”。备份必须包含完整工程目录,包括原理图 ICDB、PCB、布局数据库和相关工程文件;仅有 PRJ 或单个 `icdb.dat` 不够。
程序保留完整目标库副本,先在独立库副本中验证所选备份。验证通过后把原 Work 保留为 `Work.before-restore-*`,恢复完整 Work,再打开目标执行集成、保存、关闭和 Ready 检查。副本准备阶段会显示文件数量,运行时需等待原生操作完成再关闭弹窗。整个过程需要存放两个中心库副本及工程副本的额外磁盘空间。
恢复结果采用所选备份的工程版本。原工程、来源副本、库快照和原生日志都保留在恢复记录中。程序不会在失败后自动覆盖共享库回退,也不会把未确认结果标为成功。
此入口用于已有同名 CBB 的完整工程恢复,不删除库条目,不等同跨库原生重新导入。共享符号库自身损坏、备份引用外部工程或数据库、工程不完整、仍有活动会话时会停止;当前工程数据库需要位于完整 Work 目录中。
公开网络资料核对见 `docs/diagnostics/2026-10-28-icdb-web-recovery-research.md`,包含可读原文链接及适用范围。原生 Repair 的图文用户案例与上述菜单步骤一致;新的网络监听配置案例不能代替数据库修复。文件头损坏的无备份试验也不能代表原始会话失联故障必定不可原位修复。
@@ -0,0 +1,116 @@
# iCDB 旧服务器会话失联:分析、恢复步骤与分支改动
分支:`codex/icdb-lost-session-diagnostics`,基于 `a11eb3c`(`v0.2.2-beta.1`)。
## 错误的含义和影响范围
现场消息为:
```text
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.
Machine: [200091-CBB]
Session: [2026-10-24 08.22.29-10308]
```
原生 iCDB 检测到先前服务器会话的数据库状态需要检查/修复。这不是
“当前网络连接已经恢复就可以继续”的提示,也不能仅凭它认定端口被 Windows 保留。
`Machine` 和 `Session` 是故障记录中的原服务器、会话标识,不能当作当前进程 PID。
用户贴出的路径包含 `5:\5ymbolLibsReusableBlockssymb`,存在文字识别/转录歧义。
本机隔离样本确实存在 `SymbolLibs\__ReusableBlocksSymb\icdb.dat`:如果现场原文
指向这个结构,问题影响的是中心库共享符号数据库,而非单个 CBB 的
`ReusableBlocksLP\<CBB>\Work\database`。必须以现场原始日志为准,不能自动把
`5:` 改成 `S:`,或根据 CBB 名称推导修复目标。
异常关闭、原服务器/网络存储断开、写库期间复制工程、跨机器访问不一致的
路径,都可能涉及此类状态。现有消息不能区分这些原因,也不能证明
“校验失败一定导致损坏”;数据库异常本身同样会导致校验失败。共享符号库
出问题时,不同失败 CBB 可能只是访问了同一个有问题的数据库。
## 现场恢复步骤
1. 停止批量校验,核对 `200091-CBB` 和其他访问同一中心库的客户端。
正常关闭占用该目标的 Library Manager、PCB、原理图/符号编辑会话,并确认
原数据库服务器的实际状态;只看本机没有 PCB 或 TCP 探测失败不足以确认独占。
2. 在会话正常关闭后保留完整、一致的工程/中心库副本。共享库问题需包括
`.lmc`、相关 `SymbolLibs` 数据库、原有 `ProjectBackup`/数据库备份和日志。
工具日常的 `backup/` 排除了 `database` 等目录,网络操作还可能跳过备份,
因而不能把它当作这次修复所需的完整回滚副本。
3. 使用现场相同 Mentor 版本的 **iCDB Project Backup**,先核对打开的工程或
备份存储确实关联报错数据库,再执行 **Project → Repair**(错误提示称为
`Repair project`)。如果目标是共享符号库,而工具无法识别对应库/存储,
应由库管理员按该版本支持的库恢复流程处理,不能改选无关的 Work PRJ。
4. 保留原生工具的修复输出及 `Project Repair` 备份,确认修复结果。
不通过删除 `sAddress.adr`、锁文件、`icdb.dat`,也不通过强杀数据库服务器
来代替 Repair。如果原生修复失败,再依据原生日志选择一致备份恢复。
5. 正常重新打开原先失败的目标,先复测一个 CBB,检查本轮原生日志、
Project Integration、Save/Close 和进程释放,再以 `IsVerifiedReuseBlock`
返回 `READY/raw=1` 确认校验成功。之后再扩大批次。
本机已确认原生入口:
```text
%SDD_HOME%\iCDB\win32\bin\iCDBProjectBackup.exe
```
只读检查其命令行帮助显示 `-p <project file>`、`-ver`、`-h`;菜单资源确认存在
`Project → Repair`。没有查到公开的直接 Repair 命令行开关,因此本分支没有
编造 `-repair` 参数,也没有自动投递写库修复命令。曾在本机既有隔离样本上
打开原生管理界面进行入口检查,未执行 Repair;本机没有用户本次故障库,
未在 `200091-CBB` 或现场网络库上执行恢复。
## 代码修复
- 在内容检查输出、实时弹窗和本轮 `PCBLogFile.txt`、`ForwardAnnotation.txt`、
`MsgBoxResponse.log`、`PartPkg.log` 中识别完整的服务器会话失联消息。
- 分类为 `ICDB_REPAIR_REQUIRED`,保留原始错误和 `Machine/Path/Session`,
区分共享符号库、Work 工程数据库及不能确定的目标;写入
`diagnostics/icdb-recovery.json` 并在失败清单显示恢复说明。
- 该错误优先于通用打开失败、JobPrefs 错误及清理失败;即使内容检查同时
输出成功文字和退出码 0,也不能变成 PASS。标记 `safe_to_continue=False`,
后续条目标记 SKIPPED,沿用现有会话、证据、网络映射保留机制。
- 将当前日志与启动前检查点比较,支持追加、截断、等长/增长重写、UTF-16
及 UTF-8;恢复识别每次最多读取两个 128 KiB 片段。不能确认日志新旧时
保留原始失败,不据旧记录推荐本轮修复。重写后保留的同一历史会话不作为
新证据;可验证的追加则允许识别同一会话再次报错。
- 通用 `Could not run server` 不再直接推断端口保留并提示重启 WinNAT。
启动前独立端口绑定探测保留原逻辑。
## 验证和边界
原分支基线:`python -m pytest -q`,383 项通过。
新增回归包括原错误、共享库身份、内容检查停止队列、多行集成日志、
日志重写及历史错误隔离、编码、证据写入失败和监督器失败摘要。
诊断修复阶段验证(后续生命周期修复见下方链接):
- 全量 Python 测试 **417 项通过**,含 34 项新增回归;仍有基线已有的
一条 pywinauto STA COM 模式提示。
- 两组 PowerShell 测试、`python -m compileall -q src tests`、
`git diff --check` 通过。
- 只读解析仓库留存的真实 TUNER_R836_A 现场日志,正确提取到机器 `EDA03`、
`S:\ReusableBlocksLP\TUNER_R836_A\Work\database` 及会话
`2025-01-21 14.44.46-2323356`。该记录仅用于解析验证,不代表本次现场故障。
- 独立代码复查发现的集成日志遗漏、通用端口建议覆盖具体原因、历史日志
重写误判、不可读/超出窗口的基线问题,均补充回归并通过复核。
本分支修复自动化的错误识别、误导性建议和失败后的继续执行风险,
现在还会在目标明确、会话完全释放且完整备份成功时,自动调用同版本原生
Project → Repair,并只在原生诊断、Project Repair 备份、目标数据库关闭等
证据全部满足时重试一次校验。共享符号库路径没有 PRJ 入口时会明确阻断,
不会猜测或改修某个 CBB 的 Work 数据库。
这次在新复制的 IP101GR 工程上完成了真实隔离验证:Repair 菜单确认、完整
备份、原生 `dbcheck`/数据库日志、`Project Repair` ZIP 校验和数据库关闭均
成功;Repair worker 退出码为 0,随后才允许重试。该验证没有接触生产库。
仍然**没有修复现场受损数据库,也没有在 `200091-CBB` 上执行恢复**。
恢复识别仅覆盖已知日志末尾的有限窗口;错误出现在窗口外、相同历史会话
在重写时被原样重报、超出基线窗口的大日志发生重写、以及现场不同日志位置/格式,
仍需结合完整原生日志确认。这些不能确认新旧的情况不会自动提升为本轮修复诊断。
用户后续确认事故版本为 r4 或更早。失败强杀根因、正常关闭修复、自动 Repair
范围和 448 项最终回归详见
[失败生命周期与恢复验证](../releases/2026-10-27-icdb-failure-lifecycle-and-recovery.md)。
@@ -0,0 +1,47 @@
# ICDB 故障修复公开网络资料核对
检索日期:2026-10-28。目标是寻找原生会话失联、无备份恢复以及中心库共享符号数据库的可核实修复步骤。
## 能够读到原文的资料
1. **《Mentor XP如何修复文件》**,CSDN 用户经验文章:
https://blog.csdn.net/qq_53931654/article/details/147240707
已获取实际正文,内容为:打开 iCDB Project Backup、指定损坏文件路径、执行 Project → Repair,并有三张操作截图。该路线与本机 EE7.9.5 实际菜单及隔离实测一致。文章没有提供无健康恢复源时的通用强制修复办法,也没有验证共享 SymbolLibs 存储的修复入口。
2. **《Xpedition 2409 Designer 无法打开 icdb 连接》**,CSDN 用户经验文章:
https://blog.csdn.net/kkisscj/article/details/144323677
已获取实际正文。作者参考 VX2.8 的 icdb_admin 文档,将工作目录下 Server 配置中 Network/Address 设置为本机监听地址,解决其连接失败。这是 2409 版本的连接配置案例,不能直接当作 EE7.9.5 的数据库损坏或旧服务器会话失联修复方法,本轮未据此修改任何网络或数据库配置。
3. **Siemens Support Center 官方入口**:
https://support.sw.siemens.com/en-US/
本环境请求返回 HTTP 403,未读取到官方知识库文章。因此没有将检索摘要、第三方说法或猜测写成官方恢复结论。可以由具备相应产品支持权限的用户在此检索 iCDB administration、Project Backup Repair 和原始失联错误文本。
## 未找到能够验证的公开方案
本轮没有找到可核实的公开说明,能够保证在缺少有效恢复源时重建已经破坏的 icdb.dat,或直接修复 `SymbolLibs/__ReusableBlocksSymb` 的跨机器会话失联。检索无结果不能证明厂商没有内部恢复方式,只能说明当前没有依据提供相应可执行指令。
已排除 DLL 修复下载广告、AI 聚合回答,以及与原始故障不同的连接配置说明。没有根据这些结果操作现场库或删除数据库/锁文件。
## 对前面试验结论的必要限定
人为清零文件头得到的是 `old, unsupported format`。在无历史备份时,该特定试验原生 Repair 报告 `Cannot repair the project - there is no backup of missing iCDB`。
用户最初讨论的是 `The last server session on different server machine lost the connection to the database`。两者不是同一种故障,不能从文件头损坏试验推出“实际会话失联没有备份就一定修不好”。后者仍应在完整副本、实际占用已释放、目标身份明确的前提下尝试同版本原生 Repair,并根据修复后再次打开的结果判断。
## 当前可执行路线
对明确属于 Work/database 的工程数据库:正常结束实际写入会话 → 保留完整工程副本 → 用原生 iCDB Project Backup 打开对应 PRJ → Project/Repair → 查看 Output 是否原位修复、选择历史备份或明确失败 → 正常重新打开同一工程 → Project Integration/保存关闭/Verify。
若错误路径属于共享 SymbolLibs 数据库,本轮未找到已验证的 PRJ 替代入口。不能把任意 CBB 的 Work PRJ 指给它。需要针对该存储使用对应版本厂商支持的恢复/重建路线。
本机静态资源复核也显示 iCDBProjectBackup 的工程选择过滤器为 `Project file (*.prj)|*.prj||`,没有据此推断它可直接接受 LMC 或共享符号库目录。
已有 r4 现场日志中还保留一条具体工程失联记录,路径为 `S:\ReusableBlocksLP\TUNER_R836_A\Work\database`、原服务器 `EDA03`。这是旧日志,不能自动等同于当前 `200091-CBB` 故障,但说明现场历史中也存在工程数据库故障,需要逐条按原生 Path 区分。
网络检索原始页面及正文摘录保存在 `diagnostics/icdb-web-research-20261028`;未随源码发布第三方完整网页。
@@ -0,0 +1,99 @@
# r4 失败后 iCDB 断库:根因修复与受控恢复
分支:`codex/icdb-lost-session-diagnostics`。用户确认现场事故使用 r4 或更早版本。
## 工具侧根因
在 r4(`11a2b2e`)中,单项校验失败和监督器超时都会进入强制进程树清理:
- `DesktopWorker` 设置 `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`,`kill()` 调用
`TerminateJobObject`,回退路径是 `taskkill /T /F`。
- `cleanup_verify_processes()` 对目标 PCB 执行同样的强制进程树终止。
- `prepare_icdb_address()` 会在 TCP 探测失败后移走地址文件。连通性失败
不能证明服务器已安全退出;移走地址也不能修复数据库中未完成的会话状态。
这条失败收尾路径能连带杀死 PCB 启动的 iCDB 服务器,打断数据库事务或关闭过程,
留下 dirty session。下次由其他机器打开时,iCDB 拒绝继续并要求 Repair,
与用户描述的“未校验成功后才出现失联消息”吻合。现有代码足以确认该缺陷,
但没有 200091-CBB 本次完整进程/数据库日志,不能确定具体中断的是哪次事务。
`a11eb3c` 已修掉主要 PCB 强杀路径;继续检查发现内容检查超时仍保留
`taskkill /T /F`,以及失败文档只保留在隐藏桌面、没有正常关闭尝试。
这些遗漏在本分支继续修复,不能让用户继续用 r4 的收尾逻辑测试。
## 本轮行为
- 内容检查超时保留 importer 及原生子进程,使用文件承接输出,防止父进程
退出造成管道阻塞/断管;记录 PID、命令和退出状态并停止后续队列。
- 校验超时/监督器丢失改为协作取消。阻塞中的原生调用先返回,再在操作边界
停止后续动作;不终止正在 Save 的助手。
- 原生调用返回且已确认身份的失败文档,由 x86 助手核对 PRJ 和 PCB 名称后
执行 `Close(False)`,释放引用后正常 Quit。若另一个文档仍活动则保留应用;
慢 Close 同样保留助手,不用强杀代替完成。
- 写入前和成功前同时核对 Work、PCB 及中心库
`SymbolLibs/__ReusableBlocksSymb` 的地址所有权。隐藏 Library Manager
在失败 PCB 正常关闭后也请求正常关闭;所有权未知时继续停止批次。
- 只读状态桥先关闭标准输入并等待 EOF 清理,避免正常退出也被立即终止。
## 自动 Repair 的范围
只有本轮明确的 `ICDB_REPAIR_REQUIRED`、完整会话身份、可映射到当前
Work/PCB PRJ 的数据库,才进入一次原生恢复尝试。TIMEOUT、未释放的
importer/PCB/Library Manager/助手、外部目标及路径歧义都不会启动 Repair。
恢复前通过 Windows 独占文件访问确认目标 `icdb.dat` 没有仍打开的客户端,
完整复制工程全部文件(包括数据库、锁、原备份、日志),逐项校验副本及
源文件集合。该副本与平日排除数据库的轻量 evidence 备份不同。
Repair worker 绑定监督进程和确切私有桌面。它从安装程序资源解析
`Project → Repair`,核对原生窗口中的完整 PRJ,只接受实际验证过的
Repair 确认文本。备份期间取消会阻止后续启动;原生 Repair 已经开始后,
超时或监督器丢失不会强制终止它。
恢复成功需要本次原生 PID 的诊断完成、数据库关闭、完整 `Project Repair`
ZIP、原生进程正常退出及地址释放。满足后只重试一次完整校验,仍以
`IsVerifiedReuseBlock READY/raw=1` 为最终成功条件。原错误、原 evidence
和恢复结果保存在 `recovery_attempts`,完整修复备份保留。
**共享符号库边界:** 本机同版本 Project Backup 直接打开符号数据库目录时,
明确拒绝并要求 `.prj`。因此对 `SymbolLibs/__ReusableBlocksSymb` 的已损坏
数据库,本分支会报告 `SHARED_DATABASE_REPAIR_UNSUPPORTED`,不会改修一个
不相关的 Work 工程,也不会删地址/锁或猜测私有 ABI。正常关闭和共享所有权
检查用于防止再制造这类问题;已有共享库损坏仍需匹配该库的原生恢复入口。
## 实际验证
以下写入均针对本轮新副本,未修复或改动现场 200091-CBB 数据:
- 真实 Windows 无害 importer/子进程试验:超时后均存活,后续队列停止。
- x86 cscript 测试:核对身份、失败关闭用 `Close(False)`、不保存错误结果、
另有活动文档时不 Quit、Save 返回后响应取消。
- 新 IP101GR 副本主动注入空闲时的同步失败:输出 `FAILURE_CLOSE_OK`、
`FAILURE_QUIT_OK`,随后确认 PCB 进程退出;失败结果保持 FAIL。
- 同一隔离库随后正常校验:PASS/GREEN,Save/Close/退出和
`READY (IsVerifiedReuseBlock, raw=1)` 均确认。
- 原生 Repair 模块真实执行:完整备份、Repair 确认、本 PID 的 dbcheck/
数据库关闭日志、Project Repair ZIP 校验齐全,最终 `REPAIRED`、退出码 0。
这验证了原生恢复链,不代表复现并恢复了现场同一个 dirty session。
- 完整自动恢复链:向隔离副本的首次校验注入合成失联错误,之后实际执行
正常关闭、完整备份和原生 Repair,再启动第二次真实校验,最终
PASS/GREEN、`safe_to_continue=True`。只启动两次校验 worker、一次 Repair;
原错误及 evidence 保留。没有故意破坏数据库,也没有恢复现场损坏库。
- PyInstaller 目录包构建和冻结 GUI 生命周期冒烟通过;直接使用生成的 EXE
在另一个独立工程副本上运行 Repair worker,最终 `REPAIRED`、退出码 0。
因此原生修复入口也已验证能在冻结包内工作。
- 原样本 21,011 个文件在上述试验前后 SHA-256 内容指纹一致。
- 最终 Python 全量回归 **448 项通过**(含前次 417 项基线);仍有基线已有的
一条 pywinauto STA COM 模式提示。两组 PowerShell 测试、编译和 Git 空白检查通过。
- 独立复查指出的未释放 importer 进入 Repair、备份期间取消、修复 worker
父进程丢失、共享 COM 应用退出等边界均已修正,并补充对应回归。
本地原始证据位于 `diagnostics/icdb-auto-recovery-20261027`,不随包发布。
## 分支试用包
本地 `CbbRefreshVerify-icdb-recovery-20261027.zip` 包含完整目录程序、试用说明、
本报告和逐文件 SHA-256 构建清单;压缩包旁另有 SHA-256 文件。源码构建提交为
`9cd4968`,版本号仍为 `0.2.2b1`,这是分支修复试用包,不是新正式版本。
解压整个目录后启动 `CbbRefreshVerify.exe`,必须保留 `_internal`。尚未部署到
200091-CBB,也未推送远端;现场已有共享库损坏仍受上述原生入口限制。
@@ -0,0 +1,47 @@
# CBB 完整工程备份恢复弹窗实机验证
分支:`codex/icdb-global-repair`。本轮新增“从备份恢复 CBB…”入口,弹窗仅包含目标 CBB、备份工程 PRJ、“恢复并校验”和“关闭”。
## 已验证的行为
现有同名 CBB 的完整工程备份先在独立中心库副本中验证;只有原生流程、权威 Ready 和会话释放全部通过,才保留原 Work 并恢复目标,再对目标实际打开、保存、关闭和读取状态。全程保留完整库回退副本、来源副本、原工程和日志。
## 真实损坏与恢复
测试材料位于 `diagnostics/icdb-backup-dialog-live-20261028`,只改动新建的隔离副本,CBB 为 `IP101GR`。
1. 从健康库复制目标,移除目标 Work 中的 `ProjectBackup`、`cdbback` 历史目录,清零 `Work/database/icdb.dat` 的前 64 字节。
2. 实际打开该目标,得到 `MENTOR_DATABASE_LOAD_FAILED`。原生日志明确为 `Database cannot be loaded ... Please use iCDB Project Backup 'Repair project' ... icdb.dat ... old, unsupported format`。正常关闭未加载工程的原生窗口后继续。
3. 在真实主窗口点击“从备份恢复 CBB…”,选择独立健康来源 `verify-library/ReusableBlocksLP/IP101GR/Work/IP101GR.prj`,再点击“恢复并校验”;没有替换 reader、recoverer 或 verifier。
4. 验证库位于 `C:\Users\ABS_Windows\.cbb-restore\b963898c4e91`。17:47:59 原生 COM 确认该副本工程身份;四项集成状态均为 InSynch。17:48:19 已确认原生退出,结果 `PASS / GREEN / READY (raw=1)`。
5. 保留旧工程为 `Work.before-restore-b963898c4e91`,安装验证过的完整 Work。
6. 17:50:54 原生 COM 确认重新打开的正是最初失败的目标路径。四项集成状态均为 InSynch,Save、IsSaved、Close、Quit 标记完整;17:51:24 确认退出。目标结果 `PASS / GREEN / READY (raw=1)`,`safe_to_continue=True`,原来的数据库加载错误消失。
`comparison.json` 的七项检查全部通过:真实打开失败、备份副本验证成功、相同目标重新打开、最终 Ready、损坏 Work 保留、原始源库未变、原生加载错误消失。原始源库 21,029 个文件的 SHA-256 对照一致。
主要证据:
- `open-before.json`、`open-before-PCBLogFile.txt`。
- `data/evidence/backup-restore-b963898c4e91/recovery-result.json`。
- `source-verify/verify-bec9008be868`、`target-verify/verify-22808a7f330a` 下的结果、事件和原生日志。
- `dialog-before.png`、`dialog-after.png`、`window-after.png`、`ui-state.json`、`comparison.json`。
## 停止条件和兼容修正
实际观察到“工程已打开保存、但最终仍为 PENDING”的失败情形,恢复流程在替换目标前停止;损坏目标字节保持原样。短路径复核取得 Ready 后,生产实现采用真正较短的用户目录,避免深层证据目录及 MSIX 对 AppData 的重定向。
原生 PCB 工程允许多个配置段具有 `CentralLibrary` 引用,所有需要变更的引用均对齐。语义已指向目标库的引用保留原字节及时间。绝对工程/数据库引用、目录链接、不完整来源、来源/目标内容变化、未释放会话均会阻止安装。原生目标操作保留映射盘/别名;文件快照和 Work 替换使用实际路径。
## 回归与交付
- `python -m pytest -q`:471 passed,1 个既有 pywinauto STA 提示。
- 16 项新增恢复和弹窗测试覆盖输入校验、来源失败、最终失败、来源保护、并行快照、junction 拒绝、目标别名、等价引用、界面响应及异常终态。
- PyInstaller 构建及冻结程序启动/退出 smoke 检查通过。
- `frozen-modules.json` 确认恢复模块、弹窗、主窗和 Mentor 适配模块的冻结代码与当前源代码一致。
- 程序:`dist-icdb-backup-dialog-20261028/CbbRefreshVerify-Background/CbbRefreshVerify.exe`。
复现脚本:`tools/validate_backup_recovery_dialog.py`,依次执行 `setup`、`open-before`、`restore`、`compare`。`setup` 仅创建全新的测试目录;再次试验前保留现有证据,并将脚本中的输出 `root` 改为另一个全新诊断目录。
## 范围
本功能恢复已有同名 CBB 的完整工程,依赖目标库中已有的依赖数据,不删除库条目,不等同原生跨库重新导入或共享符号库重建。测试复现的是数据库文件头损坏;没有复现原始不同服务器会话丢失的问题,不能据此承诺所有 ICDB 故障均可恢复。恢复内容采用用户选择的备份版本。
@@ -0,0 +1,46 @@
# 全库 ICDB 检查与修复按钮实机验证
日期:2026-10-28。分支:`codex/icdb-global-repair`。
## 行为与界面
独立“数据库维护”面板提供“全库 ICDB 检查与修复”按钮。确认框展示当前库、可用项目数、Ready 项数和缺文件跳过数,说明操作会重新校验并保存工程。队列包含 Ready 项,串行执行,显示当前检查/备份/原生修复阶段及已处理数量;可请求当前项结束后停止。
复用现有本轮失联证据、目标身份、独占访问、完整备份、原生 Repair 和单次重试约束。共享符号库自动修复仍不支持。Ready 项同样预检工程文件,缺少 Work/PRJ/PCB 时跳过。失败后清除本次无法确认的绿色状态。
结果分别报告校验通过、失败/受阻、队列未执行、原生修复完成、恢复旧备份待复核和修复未确认。额外 JSON 报告保留每项原始错误、恢复尝试和证据路径。
## 实机按钮路径
使用 Windows 本机 Qt 界面,通过 QTest 点击实际按钮和实际确认框,未替换 reader/verifier,未注入合成失联错误。测试工具为 `tools/validate_icdb_button.py`。
输入是新复制的本地隔离库,包含一个实际可校验的 IP101GR(读取时 Ready)。按钮仍运行此项目,最终:
- `PASS`、`safe_to_continue=True`。
- `READY (IsVerifiedReuseBlock, raw=1)`。
- 四项集成状态 InSynch;Save/IsSaved/Close 成功,PCB 正常退出。
- 本轮正常校验不需要原生 Repair,恢复尝试数为 0。
- 测试源库 21,029 个文件逐项 SHA-256 比对一致。
原始证据:`diagnostics/icdb-button-live-20261028/outcome.json`、`data/evidence/verify-ebe807433b4f/result.json`、`data/reports/icdb-20261028-120446-f28be8.json`。`loaded.png`、`confirmation.png`、`finished.png` 是实际运行截图;`final-layout.png` 使用该次真实结果回放验证最后的两行摘要布局。
## 真实损坏试验及修复边界
`tools/probe_icdb_corruption.py` 在另一个新隔离工程副本中将 `database/icdb.dat` 前 64 字节清零,然后直接调用生产原生修复 worker。完整备份、原生 Repair 备份均保留。该试验直接验证原生修复 worker,不代表按钮已经复现现场跨机器失联故障的自动恢复链。
原生工具在本机从工程内的 `2026-09-18 10.44.14 - consDefUpgr.zip` 恢复数据库,输出 dbrestore DONE 和 Diagnostic FINISH。程序识别这属于已有备份恢复,返回 `RESTORED_REVIEW_REQUIRED`,正常关闭空闲原生窗口并确认进程退出,未将其提升为 `REPAIRED`,未自动重试校验。恢复版本和工程内容仍需复核,不能据此宣称无损修复。
原始证据:`diagnostics/icdb-corruption-probe-20261028-r2/damage.json`、`repair/repair-result.json`、`repair/complete-backup/backup-manifest.json`。原生测试 PID 29096 已退出;前次保留 PID 18452 也已核对空闲状态并请求正常关闭。
## 验证与试用程序
- 全量 Python 回归 455 项通过;一条既有 pywinauto STA COM 提示。最终摘要布局另跑 21 项界面回归通过。
- 独立代码审查提出 Ready 缺文件预检遗漏,已补充先失败后通过的回归并修正。
- 首次回归与实机校验并发,12 项被真实全局互斥锁拦住;实机结束后完整重跑得到上述 455 项通过,未改弱互斥保护。
- PyInstaller 目录程序位于 `dist-icdb-button-20261028/CbbRefreshVerify-Background/CbbRefreshVerify.exe`。已核对冻结包内四个变更模块与最终源码语义一致。
- 最终冻结程序启动冒烟完成,记录 `gui_smoke_window_created` 和 `application_clean_shutdown exit_code=0`;日志在 `diagnostics/icdb-button-live-20261028/frozen-smoke-final/logs/application.log`。
- 未部署或修改现场库。实机正常路径仅覆盖这个隔离库中的一个有效 CBB;共享符号库原生修复入口尚未支持。
## 后续实际打开对照验证
用户要求确认修复前工程实际报错、修复后再次打开。后续已在新隔离库完成:原生打开报告 ICDB 数据库格式不支持,原生恢复后同一工程重新打开并达到 PASS/READY raw=1。恢复使用旧备份,仍保留内容版本复核要求;没有复现现场跨机器失联报错。完整范围和前后证据见 `2026-10-28-icdb-open-repair-reopen-validation.md`。
@@ -0,0 +1,41 @@
# ICDB 无历史备份修复试验
日期:2026-10-28。分支:`codex/icdb-global-repair`。
## 实机结论
针对本次清零 `icdb.dat` 前 64 字节产生的文件头/格式损坏,没有可用历史备份时,EE7.9.5 原生 Repair 未能修复。此结论限于该故障类型,不应推断所有会话状态或一致性故障都必须使用历史备份。
原生 Project Backup 输出:
> The iCDB database is corrupted.
> There is no backup of iCDB.
> Repair project error [Cannot repair the project - there is no backup of missing iCDB].
> The project is probably in inconsistent state. Please restore the project from one of previous backups.
修复尝试前后数据库 SHA-256 相同:`b3a026b0bc9f695444220008527cbc3c5c2e53a7ce4eaf7bbccac297158b7e20`。本轮新建的 Project Repair ZIP 保存的是已经损坏的状态,不能充当损坏前的健康恢复源。原生输出也区分了“修复前状态备份”与缺失的有效 iCDB 备份。
## 测试范围与证据
使用新的隔离工程副本,复制时排除所有 ProjectBackup 和 cdbback 目录,只复制使用相对路径 `./backups` 的配置,启动前断言工程树内没有 ZIP 历史档案。完整损坏副本另行保留,再调用生产原生修复 worker,没有删除源工程的任何备份。
程序未取得修复成功证据,结果为 `UNCONFIRMED`,没有自动重新校验。读取原生 Output 面板确认明确的 no-backup 终止错误、窗口空闲且地址释放后,正常关闭测试进程 PID 18092。
原始证据目录:`diagnostics/icdb-no-history-probe-20261028`。
- `damage.json`:破坏方式和无历史备份测试标记。
- `native-output.json`:从原生 RichEdit Output 控件读取的完整错误文本。
- `probe-result.json`:结果及修复前后字节一致的 SHA-256 证据。
- `repair/complete-backup`:完整损坏状态保留副本。
可复现命令(需先设置 `PYTHONPATH=src`):
`python tools/probe_icdb_corruption.py --without-history --output icdb-no-history-probe-20261028`
输出目录必须新建,已有目录会拒绝覆盖。
## 没有历史备份时的处理
首先正常关闭写入方并完整保留当前损坏工程,在副本上使用匹配版本的原生工具检查。仅会话状态或部分一致性问题是否能够原位修复,应按实际诊断分别验证。
当原生工具像本次一样明确报告缺少有效恢复源,应寻找服务器快照、文件历史版本、其他机器的完整工程副本或厂商支持的恢复方式。若没有任何有效恢复源且原生修复失败,只能评估数据恢复或由仍完整的设计资料重建,不能承诺恢复全部原始内容。
@@ -0,0 +1,61 @@
# ICDB 实际打开报错、修复与再次打开对照验证
日期:2026-10-28。分支:`codex/icdb-global-repair`。环境:Windows 11,Mentor EE7.9.5。
## 结论
在新的本地隔离库中,实际打开 IP101GR 工程确认原生 ICDB 数据库加载失败;调用原生 Repair 后,再次打开同一工程,数据库报错消失,完整校验、保存、关闭和权威 Ready 确认均成功。本次补齐了前次试验缺少的修复前打开失败与修复后再次打开对照。
本次错误由清零隔离副本 `Work/database/icdb.dat` 前 64 字节产生,实际原生错误为数据库格式不支持。没有复现现场的 `last server session on different server machine lost the connection` 错误,不能将两种故障混为一谈。
## 修复前实际打开
使用生产 ReusableCircuit PCB 打开与校验流程,设置 `auto_repair=False`,没有注入合成错误或替换原生结果。工程为:
`diagnostics/icdb-open-repair-reopen-20261028/library/ReusableBlocksLP/IP101GR/Work/IP101GR.prj`
2026-10-28 13:49:14,PCB 原生弹窗报告:
> Problem encountered while opening one of the database files. See PCBLogFile.txt for details. Loading of the job has failed.
原生 PCBLogFile.txt 明确报告并指出被破坏的确切路径:
> Database cannot be loaded and the server cannot be started, the project will not be opened. Please use iCDB Project Backup 'Repair project' functionality to fix this issue. (Database [...]\Work\database\icdb.dat in old, unsupported format)
结果为 `FAIL / MENTOR_DATABASE_LOAD_FAILED`,未进入自动修复。原生失败会话经核对启动命令、空工程窗口和数据库地址释放后,请求正常关闭;没有强杀原生进程或删除地址文件。
证据目录 `diagnostics/icdb-open-repair-reopen-20261028` 中保留:
- `open-before.json` 与 `open-before-PCBLogFile.txt`。
- `open-before/verify-95ae0baa92f3/dialogs.jsonl` 中的原生弹窗及控件文本。
- `open-before/verify-95ae0baa92f3/diagnostics` 中的原生日志副本。
## 原生修复
先保留完整一致工程备份,再对同一 `IP101GR.prj` 和同一 `Work/database` 调用生产原生修复 worker。原生工具从工程内 `2026-09-18 10.44.14 - consDefUpgr.zip` 恢复数据库,完成 dbrestore 和 Diagnostic FINISH,并正常退出。
生产修复结果仍为 `RESTORED_REVIEW_REQUIRED`。本次依据用户明确要求,在隔离副本上手动继续再次打开验证;没有放宽旧备份恢复后的生产自动重试限制,也不宣称无损修复。
证据:`repair/repair-result.json`、`repair/repair-events.jsonl`、`repair/complete-backup/backup-manifest.json`、`repair-summary.json`。
## 修复后再次打开
再次使用生产校验流程和相同工程路径,保持 `auto_repair=False`。
- 13:54:45,原生 COM 确认工程身份:相同 `IP101GR.prj` 和 `IP101GR.pcb`;四项集成状态均为 InSynch。
- 保存、IsSaved、保存后同步检查、Close 和 Quit 均完成。
- 13:55:19,确认 PCB 进程退出;数据库地址释放。
- 最终 `PASS`、`safe_to_continue=True`、`READY (IsVerifiedReuseBlock, raw=1)`。
- 修复后的本轮 PCBLogFile.txt 不再出现修复前的 `Database cannot be loaded` 错误。
证据:`open-after.json`、`open-after-PCBLogFile.txt`、`open-after/verify-6b9874897377/events.jsonl`、`open-after/verify-6b9874897377/save.log`。
## 对照检查与可复现步骤
`comparison.json` 的七项检查全部为 true:同一工程、同一数据库、修复前原生 ICDB 报错成立、修复后工程身份匹配、原错误消失、完整校验通过、源工程数据库 SHA-256 不变。
测试脚本:`tools/validate_icdb_open_repair_reopen.py`。设置 `PYTHONPATH=src` 后,按顺序执行 `setup`、`open-before`、`repair`、`open-after`、`compare`。每一步需检查上一步的真实原生日志;失败打开留下的空闲原生窗口应核对目标后正常关闭,不能强杀或删锁。
本次按阶段直接调用生产原生修复 worker,未通过新按钮自动触发格式损坏修复。当前按钮的自动 Repair 仍以受支持的本轮失联诊断为入口。本次证明的是原生恢复确实消除了这个实际打开时的 ICDB 格式损坏报错;已有备份恢复后的工程内容版本仍需复核。
后续又用不含历史备份的副本测试相同文件头损坏,原生工具明确报告没有可用 iCDB 备份,无法修复,数据库字节未变。见 `2026-10-28-icdb-no-history-repair-validation.md`。
@@ -0,0 +1,95 @@
# CBB 管理候选实现(Issue #2 Task 4)
本次在当前应用增加新增、同名更新和移除入口、逐项检查点、库外完整备份、
来源工程暂存和明确的结果状态。READY 条目可以勾选用于管理;原有校验和恢复
仍仅处理当前可见的非 READY 合格条目。
## 原生能力边界
移除路线来自 EE 7.9.5 随附 Tcl 的 `CleanWGLib <lmc> F4 <list>`,输入为
`REUSE_BLOCK\tLogical-Physical\t<name>`。协调端已在独立库副本完成真实移除
和原生目录缺失复读。运行时核对已验证的 LibraryManager、CleanWGLib、
LMCDLL70 和 LMCDocAddin70 文件 SHA256;仅允许匹配版本、DxDesigner 流程、
Logical-Physical 分区及 ASCII 名称。输出必须包含对应名称/分区的 Removed
消息且不含 Warning/Error,之后重新打开原生目录确认条目缺失。
新增和同名更新默认禁用,界面说明缺少哪项隔离验证。已发现原生新增对话框
不等于完成库注册;不能仅凭返回值或出现目录启用。通用引擎已实现新增冲突
拒绝、暂存来源、名称/分区/工程内容复读、可选自动校验,以及明确更新时的
原生移除后重新导入。更新必须同时有两个原生路线和同名端到端验证才可启用。
移除后重新导入失败会报告 `RECOVERY_REQUIRED`,停止队列,不自动回滚或重放。
## 操作与恢复证据
每项结果包含 operation、library、name、partition、source、auto_verify、stage、
status、safe_to_continue 和 evidence_path。`management/management-<id>/`
保存原子更新的 `checkpoint.json`、完整 `library-before`、主数据清单、来源
暂存副本、原生请求/输出和后续校验记录。结果区区分:
- `UPLOAD_FAILED`:上传失败;不能解释为已上传。
- `UPLOADED`:原生注册与工程身份已确认,本批次未自动校验。
- `UPLOADED_VERIFY_FAILED`:已上传,但自动校验没有达到 PASS/GREEN。
- `UPLOADED_VERIFIED`:已上传且自动校验达到 PASS/GREEN 并确认释放。
- `REMOVED`:原生移除且重新读取目录确认缺失。
- `RECOVERY_REQUIRED`:原生写入可能发生,或更新已移除但重新导入未完成;
保留完整库备份和所有中间状态,需要人工审查。
启动时显示未完成和释放不确定的检查点,不自动执行。存在同一库的未完成
检查点时,新的管理任务被阻止。先由管理员检查原生进程、目标目录和备份,
按现场恢复流程处理;确认恢复完毕后把已审查的操作证据目录移至独立归档位置,
再重新读取库。不要删除锁文件,不要强制结束持有数据库的原生程序。
## 并发和来源保护
管理、校验和备份恢复共享 `Local\CbbRefreshVerify795` 及原上传工具兼容的
`.<LMC stem>.cbb-upload.lock` 独占句柄。只有相同线程持有的相同库锁允许嵌套;
完整备份通过已经持有的句柄读取锁内容,不重新打开或删除独占锁。
管理任务不能确认原生所有者释放时,在本应用进程内保留该独占句柄,阻止旧上传
工具抢入;不会仅因自动化线程返回或超时而释放锁。
直接校验与备份恢复也保留释放不明确的锁。库旁保存
`.<stem>.cbb-upload.blocked.json`,本应用重启后拒绝写入和原生读取。
该记录在取得库锁后、原生调用前写入,正常确认释放才清除。只有精确保留文件名、
协议版本和所有权字段匹配的记录被归类为运行时元数据;完整副本仍保留其字节,
主数据比较忽略其生命周期变化。同名普通文件或损坏记录保持原样并阻止自动解除。
“检查会话释放并解除协调阻止”入口先确认管理工作进程已返回、相关原生进程
均已退出、库内不存在 sAddress.adr,且能同时以独占只读句柄打开所有 LMC、
icdb.dat 和 LayoutDB.lyt。全部通过才归档阻止记录并关闭本应用保留的句柄;
不会删除上传锁文件,也不把会话释放解释为数据恢复成功。
进程崩溃会使 Windows 释放其句柄;旧上传工具不认识新增阻止记录,因此本方案
不能保证本应用崩溃后旧上传工具仍被排除。崩溃后应先正常结束原生会话,并通过
上述释放检查和未完成任务审查,再使用本工具或旧上传工具继续写入。
备份与来源不能置于目标库内部,来源必须是完整且引用位于工程内的 PRJ/PCB。
来源工程根目录和目标库根目录也不能相互包含或相同,避免操作嵌套库时改变原始来源。
链接、外部数据库引用、源文件变化、备份失败和同名新增冲突均会阻止写入。
来源先完整复制;工程身份比较使用顶层块、原理图数据库和布局数据库内容指纹,
原生规范化若改变数据库字节则保守拒绝确认,需要进一步语义验证,不能声称等价。
原生管理在私有 Windows 桌面运行,不移动鼠标或占用前台输入。只操作当前
已识别原生进程。读取目录遇到旧库升级或 Select flow type 对话框时取消并报错,
绝不将升级作为只读读取的一部分。超时保留原生所有者和证据,不强杀数据库进程;
确认前不继续下一项,不启动最终 Verify。
通过网络盘租约选择的盘符路径在原生 OpenLibrary、CLI、暂存工程库引用和后续
Verify 中保持原样;规范化路径仅用于身份、包含关系和锁键比较。工作进程按原
租约的盘符/共享目录上下文确认映射,不把原生盘符路径改回 UNC。
## 独立新增诊断
`python tools/validate_native_management.py SOURCE.prj NEW_OUTPUT_DIRECTORY NAME`
只接受不存在的新目录,先完整复制来源,再由私有工作进程调用原生
`CreateLibrary(..., kFLOW_DX=1)` 创建固定的新库。随后使用已验证的
Reusable Blocks / UIA Logical - Physical 页签和 New 按钮、1103 对话框字段。
诊断会记录原生消息、关闭后的重新打开清单、工程内容比较和原始来源不变检查。
它不接收生产库参数,不存在跳过生产能力门禁的开关,也不自动修改能力门禁。
可加 `--replacement-source OTHER.prj` 在同一个新建隔离库中验证同名更新:
先备份完整旧库,再原生移除并检查缺失,然后重新导入替换工程。重新导入必须
匹配本次 CreateLibrary 记录的固定路径和随机所有权令牌,不能指向外部库。
监督进程先创建新的空 fixture 目录并持有库锁,原生工作进程核对准备令牌、
检查点协议和监督 PID 后才创建 LMC。初次创建、所有复读和替换阶段均按生产
操作的释放规则持锁;超时或释放异常保留独占句柄和重启阻止记录,必须重新
通过会话释放检查才能解除。
本阶段单元测试通过注入文件模拟的原生边界执行,不启动 Mentor、不操作实际库。
候选冻结包、最终 Windows 11 原生场景由协调端单独验收。Windows 10 和真实
现场失联样本仍未验证;文件头损坏与模拟故障不能替代这些验收。
@@ -0,0 +1,77 @@
# 工单 #2 候选包验收记录
分支:`codex/temp-issue-2-icdb-recovery`。本记录区分软件回归、隔离原生试验和现场验收;未合并、发布或关闭工单。
最终候选程序源码提交:`8e486c1`。新增和同名更新保持禁用;原生新增虽已成功注册并复读,但原理图数据库被原生工具重写,尚未证明内容等价。移除已在新建隔离库通过完整管理流程验证。
最终全量回归:`python -m pytest -q` 在 `122bafc` 上 **887 passed,1 个已有 pywinauto STA 模式警告,68.62 秒**。`122bafc` 只调整安全测试,`src` 和 `packaging` 的 Git 树与打包提交 `8e486c1` 完全一致。编译检查及 `git diff --check` 通过;整分支审查和后续修正复审均无未处理问题。
日志:`build/issue2-final-tests-122bafc.log`。安全测试明确保留工程文件、上传锁以及损坏/外来检查点,只有本工具拥有且验证通过的运行时检查点允许清理。
## 已实现范围
- ICDB 启动失败后,仅在任务进程、工程路径、私有桌面、空闲窗口及地址释放可确认时正常关闭 PCB;同时等待启动器退出。Repair 区分缺少健康备份、原生失败、占用、未知窗口和释放超时。最终重新打开、校验及 READY 状态共同决定修复成功。
- 名称/分区搜索和状态筛选使用已加载数据;隐藏条目清除勾选。READY 可以用于管理,不能进入默认校验、维护和恢复队列。受影响条目刷新后重新判断资格。
- 完整备份保留全部文件;版本化清单对主要工程文件和库依赖计算 SHA-256,复制时同时核对文件集合、大小和时间。日志及其他运行时变化不再等同于工程内容变化。
- 管理请求、逐项结果、完整旧库备份、检查点、来源暂存、共享锁和安全释放入口已集成。新增/更新未达到原生验收门槛时禁用。重启只展示未完成任务,不自动重放写操作。
## 原生证据与边界
| 场景 | 实际观察 | 限制 |
| --- | --- | --- |
| 最终冻结程序启动失败退出 | `8e486c1` 的 PCB 和启动器自动正常退出、无数据库地址;`startup-close.json` 为 CLOSED,safe_to_continue=true | 人工损坏副本,不是现场服务器失联 |
| 最终冻结程序 Repair 缺少健康备份 | `8e486c1` 返回 MISSING_HEALTHY_BACKUP,原生工具自动退出、地址为空、允许安全继续 | 验证明确失败和释放,不代表修复成功 |
| 官方原生移除 | 独立副本中 CleanWGLib/F4 返回 0,之后原生目录重新读取为空 | 旧库升级存在告警;生产读取遇到升级必须拒绝 |
| 隔离新增首次完整探测 | 新建库后打开编辑器失败,尚未提交新增;来源保持不变,保留失败证据及协调阻止记录 | 不启用新增或同名更新,不作为成功验收 |
| 最终移除适配器命令 | 实际捕获 `# Note: Removed REUSE_BLOCK 'IP101GR' from partition 'Logical-Physical'.`,释放确认成功,来源清单未变 | 随后的旧库复读拒绝 Select flow type;不能宣称该库完整自动移除验收通过 |
| 新建隔离库完整移除 | 管理引擎完成原生读取、完整旧库备份、原生删除、重新读取确认缺失;最终 REMOVED,safe_to_continue=true | 仅代表此安装版本、库流程和 Logical-Physical 分区 |
| 新建隔离库原生新增 | 收到成功消息,正常关闭、重新打开仍有正确名称/分区,原始来源不变;布局哈希一致 | 原理图数据库哈希改变,identity_matches=false;新增/更新不启用,未执行同名更新和重新导入恢复验收 |
原始证据位于 `diagnostics/issue2-frozen-20261102/`、
`diagnostics/issue2-management-native-20261102/` 和
`C:/Users/ABS_Windows/.cbb-management-e2e-20261102-a/`。
首次新增失败后,仅向已确认的隔离 Library Manager 主窗口发送正常 WM_CLOSE;
随后进程查询为空,没有强制终止数据库所有者。
第二次新增探测的 `dispatch-diagnostics.jsonl` 在加载 pywinauto 前记录方法
DISPID 17/26/6,加载后全部返回 `CO_E_OBJNOTCONNECTED`(-2147220995)。
这证明失效发生在 UI 自动化依赖初始化边界,尚未提交新增;来源未变。
第二次隔离会话同样正常关闭。移除适配器及旧库拒绝证据保存在
`diagnostics/issue2-remove-adapter-20261102/`;旧库拒绝流程后出现的
“Unable to determine flow type”通知由协调端确认后正常退出,不能记为无人值守释放通过。
`ffa7e84` 冻结包的 GUI 冒烟通过,但真实批处理在启动 Mentor 前报
`No module named 'win32timezone'`。此包不能作为最终可用包交付;必须补齐打包依赖并重建验证。
`1f69480` 补齐依赖后运行了真实 PCB 流程;`8e486c1` 又收紧了隐藏基础设施窗口的精确识别条件,最终冻结测试自动通过退出分支。
最终证据:
- `diagnostics/issue2-frozen-20261102/full-8e486c1-startup/evidence/verify-97173dae8a21/startup-close.json`
- `diagnostics/issue2-frozen-20261102/full-8e486c1-nohistory/repair-result.json`
- `diagnostics/issue2-management-final-20261102/probe-result.json`
- `diagnostics/issue2-management-final-20261102/full-remove-result.json`
- 移除前完整旧库保留在 `C:/Users/ABS_Windows/.cbb-management-e2e-20261102-e/full-remove/management-e90d69ad7f624fb18f5401119b96856d/library-before/`。
冻结启动失败试验的批处理退出码为 2,因为输入是损坏工程;通过项是自动安全退出,而不是工程校验成功。缺少健康备份的 Repair 同样是已验证的明确失败分支。
## 仍需现场验收
工单附件只有日志,没有现场 `1GPHY_8211` 故障工程及其必要共享库的一致副本。
因此现场服务器会话失联尚未复现,也没有完成该现场故障经应用实际维护按钮触发的完整自动链路验收。
必须取得副本、记录来源/工程身份/主要文件哈希,在隔离环境记录失败、退出、Repair 调用、重新打开、保存关闭和 READY 查询的完整证据,并核对来源未改变。
复制后不能复现时应记录“未复现”,不能用数据库文件头损坏试验替代。
Windows 10 尚未验证。现有原生试验环境为 Windows 11 / Mentor EE 7.9.5。
历史备份恢复保持“已恢复,版本待核对”,不宣称无损修复。
## 候选包
`dist/issue2-repair-candidate-877e3b4.zip` 保留独立修复候选包及构建清单。
完整候选程序位于 `dist/issue2-full-candidate-8e486c1/`,由 `git archive 8e486c1` 的不可变源码构建。构建与 GUI 冒烟通过,真实冻结原生证据见上。
分发压缩包:`dist/issue2-full-candidate-8e486c1.zip`。解压后运行 `CbbRefreshVerify-Background/CbbRefreshVerify.exe`;包根目录保留构建清单、本文及关键验证证据。
`dist/issue2-full-candidate/` 和 `dist/issue2-full-candidate-1f69480/` 是被后续修正取代的中间试验构建,不作为交付包。
## 后续验收顺序
1. 取得现场故障工程及必要共享库一致副本,优先完成实际维护按钮触发的完整自动链路验收。
2. 针对原生导入会重写 ICDB 的行为,使用经过验证的 Mentor 语义读取/导出建立工程内容等价证据;不能只放松哈希检查。之后才能启用新增,并验证重复冲突、同名更新、部分失败及备份重新导入。
3. 在 Windows 10 / EE 7.9.5 重跑冻结关键路径,并在具备网络测试环境时验证真实断网、取消和恢复场景。现有模拟测试不能替代这些环境验收。
@@ -0,0 +1,182 @@
# Issue #2: release the PCB launched by a failed database open
Branch: `codex/temp-issue-2-icdb-recovery`.
## Field failure
The issue attachment records an iCDB lost-server-session error while opening
`1GPHY_8211`. The supervisor declined the database log viewer and cancelled the
worker. Because document identity had not been established, the existing
document-close helper was never called. PCB and its launcher remained alive;
the subsequent Repair attempt returned `REPAIR_DATABASE_IN_USE` and the other
380 queued entries were skipped. There is no evidence of native Repair actually
running on that field database.
## Change
The worker now has a separate startup-failure close path. It requires a current
iCDB diagnosis or a database-load-failure dialog belonging to this PCB during
startup. It checks the private desktop, excludes pre-existing process IDs, and
matches the complete PCB path and ReusableCircuit argument. Only an enabled
empty PCB main window, without modal dialogs, MDI documents or database address
records, receives a cooperative `WM_CLOSE`. A requested close is not treated as
success until process exit is observed. Ambiguous or busy sessions are retained.
The supervisor allows up to 40 seconds for fatal-error cleanup so that the
worker's 20-second startup-close window can complete before recovery begins.
The existing repair preconditions, backups and success checks remain in force.
Each attempt writes `startup-close.json` and close-request/result events.
## Verification
Regression tests cover the missing pre-identity cleanup route, real observed
empty-window titles, exact path matching, pre-existing processes, another
desktop, live address records, modal and MDI windows, disabled windows, unrelated
failure records and a close request that does not result in exit.
Delayed dialog/address release and delayed process exit are also covered.
Validation: `python -m pytest -q` — 491 passed, one existing pywinauto COM-mode
warning; `python -m compileall -q src tests` and `git diff --check` passed.
A new isolated local library was created with the existing
`tools/validate_icdb_open_repair_reopen.py` tool, output
`diagnostics/issue2-startup-20261102`. No production library was changed.
The test damages only the new copy's database header; it does not reproduce the
field server-session-loss condition.
The real Mentor opening run produced `MENTOR_DATABASE_LOAD_FAILED`, then:
- `startup_close_requested` for the launched PCB PID 6532;
- `startup_close_result: CLOSED`;
- worker and supervisor both recorded `process_exit_confirmed`, with no
remaining PCB processes.
The subsequent separate native Repair run was able to start and completed as
`RESTORED_REVIEW_REQUIRED`, using the fixture's historical backup. This proves
the failed-open session no longer blocks the next repair operation in this
fixture. It does not prove automatic recovery of the field database or establish
that an older backup contains the desired design revision.
The separate `open-after` run on the same restored fixture completed native
integration, Save/IsSaved/Close/Quit, confirmed process release and returned
`PASS`, `safe_to_continue=True`, `READY (IsVerifiedReuseBlock, raw=1)`.
The `compare` phase passed all seven checks, including absence of the original
opening error and unchanged source-fixture database SHA-256. Its
`server_session_loss_reproduced` field is explicitly `false`.
Reproduction commands (set `PYTHONPATH=src`; setup requires a new output name):
```powershell
python tools/validate_icdb_open_repair_reopen.py setup --output issue2-startup-20261102
python tools/validate_icdb_open_repair_reopen.py open-before --output issue2-startup-20261102
python tools/validate_icdb_open_repair_reopen.py repair --output issue2-startup-20261102
python tools/validate_icdb_open_repair_reopen.py open-after --output issue2-startup-20261102
python tools/validate_icdb_open_repair_reopen.py compare --output issue2-startup-20261102
```
The stages are deliberately separate: the test fixture has a format-corruption
error and historical-backup recovery, not the field lost-session auto-repair
trigger. The test does not change production handling of old-backup recovery.
READY filtering, hash-scope changes and CBB CRUD are outside this focused fix.
## Approved Task 1 follow-up: lifecycle and repair outcomes
The empty-PCB close path now receives the launcher process handle and waits for
its normal exit after PCB exits. It checks database addresses again during that
wait, so a late address record prevents a false `CLOSED` result. The startup
record includes PCB, launcher and address release state. A connected COM server
with no active document emits `pcb_document_wait`; it remains in startup and
continues reading the current native failure rather than implying identity.
Native Repair reads bounded Output text and records only the text appended after
this run's Repair invocation as operation evidence. Database logs are restricted
to the current native PID and start time. Output, native log copies, the complete
backup, native result and attempt record remain available under `native-repair`.
Detailed native evidence is preserved separately from its directory path.
The result distinguishes `MISSING_HEALTHY_BACKUP`, `NATIVE_REPAIR_FAILED`,
`DATABASE_BUSY`, `UNKNOWN_DIALOG`, and `TIMEOUT_UNRELEASED`. A failed tool receives
cooperative close only after a terminal native error, an enabled exact-project
main window, no other windows/prompts and no target database address. The worker
then waits for normal process exit. Unknown/custom prompts and incomplete native
operations receive no close action. A failure classification can coexist with
unreleased state; that state always stops the queue. Terminal `DATABASE_BUSY`
errors also retain the native tool without close, reopen or queue continuation.
Unreadable, absent, hung or truncated initial Output waits within the deadline
and retains the tool without requesting Repair; a readable empty string is a
valid invocation baseline. A busy-project message in
this fresh native process's initial loading Output prevents Repair invocation
entirely; it is not hidden by the later invocation baseline.
Before reopening or continuing, the parent independently checks relevant PCB,
Library Manager, Repair, importer and close-helper processes, all known project/
PCB/shared-library addresses, and exclusive read access to every existing known
database. Process-observation errors and exclusive-access failures block reuse.
Only a conclusively failed, released, independently revalidated project-local
target may allow the next CBB. Shared or unknown scope, busy owners, timeouts,
unknown prompts and historical restores stop for review.
Before accepting native success, the parent validates native process identity
and true exit, exact project/database, empty address state, confirmed backup/
repair evidence and absence of restore/failure/unknown-prompt contradictions.
Missing or wrong-typed fields fail closed. Independent process, address and
database-handle probes remain additional requirements.
Native `REPAIRED` is retained as `native_status`; summaries count a repair only
after the same request reopens, completes Verify and returns authoritative
`PASS/GREEN` with confirmed release. A failed reopen becomes
`REPAIR_VALIDATION_FAILED`; incomplete or contradictory native success/release
becomes `UNCONFIRMED` and prevents reopening.
Historical restoration remains `RESTORED_REVIEW_REQUIRED`. The original error,
stage and evidence references, a `pre-repair-result.json` snapshot, native
evidence and validation evidence remain attached even if the retry raises.
`tests/fixtures/issue2-lost-session-sanitized.json` contains selected fields from
the actual issue attachment, with paths, machine and process identities
sanitized. Replay asserts `PCB_STARTING`, the selected PRJ/database, normal PCB
and launcher release before native Repair, and exactly one automatic repair and
one reopen even if the opening error repeats. Separate replays cover the actual
2026-10-28 missing-backup Output, delayed exits/addresses, unknown custom prompts,
successful native repair and historical restoration. These are nonnative tests.
The attachment contains logs only. No matching `1GPHY_8211` faulty project was
found in the sibling `Skyworth_CBB_Lib` collection. This host runs Windows 11;
Windows 10 behavior and recovery of the real field database remain unverified.
The coordinator's prepared `diagnostics/issue2-frozen-20261102` fixture damages a
copied database header; it does not reproduce field lost-server-session loss.
Candidate packaging and frozen/native tests remain coordinator work after review.
Task 1 checks: full suite once, 532 passed with the existing pywinauto COM warning;
after the final initial-busy gate regression, the related final suite passed all
234 tests. Compileall and `git diff --check` passed. The coordinator will run
candidate/frozen validation against the final implementation.
Task 1 review fix round: 259 related tests passed (17.86s); compileall and
`git diff --check` passed. These checks include busy retention, real readback
failure branches, 30 malformed-success variants at both release and reopen/
counting boundaries, and a complete actual worker-result replay control.
Runtime fix round 2 adds `iCDBProjectBackup.exe` and `ReuseBlockImporter.exe` to
the process helper's fixed query whitelist. Without these entries, the real
parent release probe rejected its own required queries and always denied safe
release. New tests keep the release validator and process helper real and stub
only WMI: no owners permits release, either native owner prevents it, and
arbitrary query names remain rejected. Focused validation: 172 passed. Candidate
`c823a4b` must be rebuilt with this correction before frozen/native validation;
field recovery remains unverified.
Runtime fix round 3 uses the actual frozen-worker window capture. A single Afx
shell titled exactly `iCDB Project Backup` now waits, before invocation only,
for the exact project title within the existing deadline. Two owned-process
input-indicator classes (`UAC_InputIndicatorOverlayWnd`, `UAC Input Indicator`)
are ignored only with empty titles. Wrong/duplicate target windows, ambiguous
shells, named/lookalike auxiliary windows, unknown prompts, missing Output and
busy verdicts still retain the tool without unsafe commands. The native loading
line `Checking if project is in use.` is excluded from busy evidence; the actual
ownership verdict continues to control the busy gate.
Sanitized recorded-shape replay includes real shell children, RichEdit Output
readback, startup-to-loaded transition and both input indicators before and
after load. Focused validation: 189 passed (12.40s); compile and scoped diff
checks passed. New source/frozen native validation and rebuilding the candidate
remain coordinator work; these replay results do not establish field recovery.
@@ -0,0 +1,251 @@
# Scoped recovery manifests and complete verified backups
Status: implemented; review finding P1 addressed with focused validation. Started on b90a9bb; paused at
the RED checkpoint for the coordinator's native startup-window repair fix and
resumed on 877e3b4. No native UI/process/live-library actions were performed by
this implementer. Original untracked review.diff was preserved and not staged.
## Result and scope
Complete backup trees are still copied and retained. SHA256 and semantic
before/after comparisons now cover only primary design/project/database/
constraint files and required central-library dependencies. Runtime changes
after a successful snapshot do not stop install. Primary content changes,
additions and deletions do stop install, with copies retained as evidence.
The validate-copy -> conflict checks -> retain original Work -> install ->
reopen/native verification flow is preserved. Source equality now runs after
incoming Work preparation, immediately before target equality, closing the old
late-source-change window. Source idle/address ownership is rechecked there as
well: excluding address bytes from semantic hashes does not bypass idle checks.
Initial implementation: 29c154d. The review correction is described below.
Durable documentation lives here; an ignored review copy remains at
.superpowers/sdd/2026-11-02-issue-2-management/task-3-report.md.
Scoped production files: backup_recovery.py and new scoped_manifest.py. Scoped
tests: test_backup_recovery.py and new test_scoped_manifest.py. No Verify public
types, Task 2 helpers/READY logic, native repair classifiers/process whitelist,
or library binary contents were changed.
## Exact classification rules
Project scope retains every unclassified file as primary. This includes PRJ,
PCB, DXP, icdb.dat, Layout databases, schematic/logic/symbol assets, CES/config,
unknown binary/engineering formats, and text files outside explicit excluded
categories. Rules are case-insensitive; manifests preserve relative path case.
Explicit semantic exclusions, still copied and metadata-validated:
- Runtime/history child directories **at a project workspace root**, its PCB
workspace root, a selected Work/Cert root, or the library root: log, logs,
temp, tmp, __pycache__, backup, backups, output, outputs, report, reports,
gerber, gerbers, odb++, Log Files, LogFiles, and Work.before-restore-*.
- ProjectBackup/backups only at those workspace roots. Other ProjectBackup
content remains conservative primary data.
- Known native runtime below database/cdbsvr and PCB/database/cdbsvr: log,
dbcheck and dbrestore subtrees. In shared library databases, those same
subtrees below SymbolLibs/<partition>/cdbsvr or <shared-root>/cdbsvr. Other
unknown files below cdbsvr remain primary; the directory is not dropped.
- File suffixes: .log, .tmp, .temp, .lck, .lock, .bak, .backup, .pdf.
- File names: sAddress.adr and editor files starting with ~$.
Directory exclusions are contextual rather than arbitrary ancestor matching.
ReusableBlocksLP/<selected-block>/Work and Cert are structural identity
components, never runtime labels. CBB names Logs, Temp, Backup, Output, Report,
Log Files, ProjectBackup and Work.before-restore-engineering remain valid and
their primary files are hashed in both semantic manifests and complete-copy
validation. Case variants have the same protection.
Shared dependency partitions and nested engineering folders keep their names:
SymbolLibs/temp/icdb.dat, SymbolLibs/Temp_a/device.sym,
SymbolLibs/Backup/device.sym, hdl/Logs/design.v and hdl/Backup/design.v are
primary. Runtime directory labels apply at the known roots above, not inside
arbitrary engineering/dependency hierarchies. File suffix/name exclusions are
applied to files, not to engineering directories with matching suffixes.
The uploader-compatible .<stem>.cbb-upload.lock falls under .lock, so it is
runtime and never primary. It is **not** silently removed from complete copies.
Central-library scope includes only target ReusableBlocksLP/<block>/Work and
Cert, root configuration files (the selected .lmc, other root config files),
and shared/configuration dependency directories outside ReusableBlocksLP. Known
examples include SymbolLibs/__ReusableBlocksSymb, CellDB and PartDB; new unknown
dependency directory names remain primary conservatively. Other root .lmc files,
other ReusableBlocksLP CBBs, target historical/non-Work/non-Cert trees and the
explicit runtime/generated categories above do not enter semantic equality.
Those unrelated files still enter the complete copy and its metadata checks.
Later semantic scans prune ignored/runtime/unrelated CBB directories before
entering them, so transient/unavailable runtime or unrelated trees cannot
interfere with the post-snapshot content check.
## Reusable API contract for Task 4
Import from cbb_refresh_verify.scoped_manifest:
```python
scope = ManifestScope.library(block_name, selected_lmc.name)
before = copy_verified(library_root, private_backup, scope=scope, progress=callback)
current = build_manifest(library_root, scope=scope, exclude=private_incoming)
if current != before:
# stop install; retain evidence
...
```
- `ManifestScope()` is project scope. `ManifestScope.library(block_name,
library_name)` requires nonempty single-component names; no path traversal.
- `build_manifest(root, *, scope=None, exclude=None, progress=None,
hash_function=hash_file)` returns a semantic manifest. `exclude` is an optional
private incoming subtree, **not** a copy exclusion. Hash injection is a test
hook; normal callers use the default.
- `copy_verified(source, destination, *, scope=None, progress=None,
hash_function=hash_file)` requires a fresh destination outside source. Copies
all files/directories, returns the same semantic schema, retains partial
destination on failure, and raises ValueError/OSError for unsafe/changed data.
- `scan_tree(root)` scans complete membership and refuses links/junctions and
special files. Its optional scope/exclude is used by semantic scans only;
complete copies always scan without filters.
- `hash_file(path)` streams SHA256 in 1 MiB chunks. Files are processed with up
to eight workers, retaining the existing concurrency bound.
- Progress callback accepts **one dict**, not the old private `(count,total)`
pair: `stage` (`copy` or `hash`), `hashed_files`, `hashed_bytes`, `total_files`,
plus `copied_files` for copy. Hash counts/bytes count unique primary snapshot
files/logical bytes, not aggregate disk IO. `total_files` counts all files for
copies and primary files for standalone manifest generation. Initial zero and
each 256/final-file event are emitted. Recovery keeps existing public progress
stage/message keys and adds `manifest_stage` and these counters.
Version 1 JSON-compatible output (relative paths are POSIX, no machine-specific
absolute paths or mtimes in equality):
```json
{
"version": 1,
"scope": {"kind": "library", "block_name": "A", "library_name": "target.lmc"},
"files": {
"ReusableBlocksLP/A/Work/A.prj": {
"size": 123, "sha256": "<sha256>", "scope": "target_work"
}
}
}
```
Entry scope labels are project, target_work, target_cert, library_config and
shared_dependency. Default project's descriptor uses empty block/library names.
Recovery persists both library-before-manifest.json and
source-before-manifest.json. The shape changed only for private backup helpers;
VerifyRequest/VerifyResult contracts are unchanged. There is no old-manifest
loader or destructive migration: existing historical evidence remains intact.
## Copy integrity and old strict equality compatibility
Copy validation remains strict for the **entire** snapshot: before/after source
file/directory membership, file type, size and nanosecond mtime must agree;
destination membership/type/size/mtime must match too. Primary regular source
files are SHA256 read before copy and again for validation; destination hashes
must match. All native icdb.dat and .lmc files retain exclusive read handles
during copying. For scoped primary native files, the expected digest is built
from the source ReadFile stream independently of destination SHA256. Identical
size/mtime destination corruption is therefore rejected, including locked DBs.
Unrelated native DBs are still locked/copied; their bytes are not SHA256 hashed.
The old final `_manifest(source) == complete_copy_record` was an all-file hash
comparison that rehashed every runtime and unrelated project file. It is
replaced by full-tree copy metadata validation and primary byte verification at
snapshot time. Later equality compares version/scope and primary relative
path/size/hash/scope only. Thus log-only additions/changes/deletions after a
successful copy are accepted, while primary keyset/content changes remain real
conflicts. No conflict tests were weakened or deleted; additional source,
target, Cert, shared dependency, late-source and active-address regressions were
added. Empty directory metadata is intentionally not part of semantic equality.
## RED/GREEN and verification evidence
The original full-suite evidence below belongs to initial commit 29c154d. The
P1 review correction has fresh focused validation, and has **not** rerun the
full suite; the coordinator requested focused tests only for this fix.
1. Initial RED, before production edits:
`python -m pytest tests/test_scoped_manifest.py tests/test_backup_recovery.py -q`
-> **29 failed, 26 passed in 7.89s**. Failures demonstrated missing versioned
manifest/schema/progress and post-snapshot runtime/unrelated tolerance.
Copy/conflict protections already present continued passing.
2. Initial GREEN -> **55 passed in 11.93s**.
3. Additional RED for semantic traversal of an unavailable ignored/unrelated
tree -> **1 failed, 36 passed in 2.79s**; fixed by pruning semantic scans.
4. Additional RED for source mutation during incoming Work preparation and
source address reappearance -> **2 failed, 20 deselected in 1.56s**; both had
incorrectly installed before the final-source-check changes.
5. Final focused:
`python -m pytest tests/test_scoped_manifest.py tests/test_backup_recovery.py tests/test_backup_recovery_dialog.py -q`
-> **64 passed in 9.93s**.
6. Coordinator was notified **before** the full suite and explicitly confirmed
no native owner/mutex and paused all native probes. Exactly one final suite:
`python -m pytest -q` -> **693 passed, 1 warning in 47.99s**. Warning:
pywinauto's existing "Revert to STA COM threading mode" warning in
test_library_reader.py::test_status_log_records_unseen_id_inference.
7. `git diff --check` passed. Review confirmed no unrelated/native-helper edits.
Coverage includes every primary category, unknown engineering formats,
runtime/history/generated exclusions with complete-copy retention, hash-path
scope, relocatability, source changed/deleted/added during copy/validation,
target changes/deletions/additions, Cert/shared-library conflicts, unrelated
CBB tolerance, copied corruption with preserved metadata, locked stream bytes,
source content changes with preserved metadata, complete copy membership and
nonprimary size consistency, idle/address rechecks, retained copies on failure,
and unchanged native reopen/retained-Work recovery behavior.
## Review correction: contextual runtime directory classification
Review found that the initial unconditional directory ancestor rules could
classify valid selected CBB names (Logs/Temp/Backup) or real SymbolLibs/temp
engineering partitions as runtime. That removed primary paths from both the
baseline manifest and later conflict comparison, and from copy byte checks.
The classifier now resolves the structural role first and only applies the
runtime directory rules at documented workspace/native DB locations. Semantic
directory traversal and complete-copy byte classification share that rule.
Complete tree copy/metadata validation remains unchanged. This also protects
nested engineering folders with names Logs/Backup, and avoids broad dropping
of unknown cdbsvr files.
Independent regressions cover Work and Cert under 11 colliding CBB names/case
variants, real SymbolLibs/temp and Temp_a partitions, arbitrary nested
engineering folders, source and destination corruption with unchanged size/
mtime, independent locked database destination corruption, and end-to-end
recovery conflicts that previously overwrote concurrent target/shared edits.
Known native Log Files, ProjectBackup/backups and DB server log/dbcheck/
dbrestore data remain semantically ignored and completely copied.
Review-fix RED:
`python -m pytest tests/test_scoped_manifest.py tests/test_backup_recovery.py -q --tb=short`
-> **47 failed, 74 passed in 18.41s**, before production changes. The failures
included silently accepted primary corruption and installs over concurrent
target/shared edits. Additional conservative-boundary regressions prevented
reintroducing the same bug through Log Files/ProjectBackup/retained-Work names
or broad cdbsvr directory exclusion.
Final review-fix focused GREEN:
`python -m pytest tests/test_scoped_manifest.py tests/test_backup_recovery.py tests/test_backup_recovery_dialog.py -q --tb=short`
-> **141 passed in 18.28s**. No native UI/process actions, live-library mutation,
or full-suite run was performed during this fix round.
## Limitations / follow-up boundary
- No real field lost-session reproduction, native GUI success reproduction, or
Windows 10 run was performed for this task; file-based tests do not substitute
for those required native/field validations.
- Task 4 must adapt complete-copy access to a live uploader lock **only when the
operation actually owns that coordination lock**. The current helper copies
readable locks and fails closed on unreadable/live exclusively owned files;
it does not delete locks or broadly drop engineering data.
- Native idle guards and later coordination locks remain necessary. Final
equality and filesystem rename are not one cross-process atomic transaction
against arbitrary noncooperating external writers.
- Nonprimary byte hashes are intentionally absent. Their copy integrity uses
complete membership and size/mtime checks, as specified; same-size,
timestamp-preserving nonprimary corruption is outside the semantic guarantee.
- All snapshots must be stable while copied, including runtime files. This
deliberately differs from post-snapshot semantic checks, which tolerate
runtime changes. Original and partial recovery evidence is retained on failure.
@@ -0,0 +1,122 @@
# 既存地址记录下的明确 ICDB 维护入口
2026-11-03 的现场报告显示,点击“非 READY ICDB 检查与修复”后,IP101GR 在
0.172 秒内返回 BLOCKED,没有启动官方 Repair。原先维护按钮和普通校验使用
相同请求;普通校验对任何 sAddress.adr 的阻止条件也挡住了明确维护入口。
随后保留的库协调检查点使重新读取与维护都无法继续。
本次为用户明确确认的维护增加独立入口。普通校验遇到地址记录仍停止,不依据
文件日期、TCP 不通或本机无 PCB 进程判断地址失效,不删除、移动或隔离地址。
没有地址阻止时,维护继续沿用原有校验及本轮失联后的自动修复流程。
存在地址记录时,明确维护需要唯一可确认的工程 PRJ/database 映射。共享符号库
地址、所选工程内多个地址、外部引用、歧义目标、不完整工程均会阻止执行。
其他独立 CBB 的 Work 数据库地址不纳入当前修复目标,原文件保持不变。工具检查相关
原生程序和保留工作进程,并同时独占读取库中的原生数据库文件;记录目标工程
引用指纹和地址字节哈希,检查期间及完整备份后重新核对。完整工程备份保留
原地址文件,再由官方 iCDB Project Backup 打开工程。只有其实际 Output 明确
报告 `Project is not in use. Full iCDB Project Backup's functionality is available.`,
且没有占用或未知窗口时才请求 Repair。
库旁已有协调检查点时,明确维护可以接续有效的同库记录,条件是原监督进程
已退出,或当前进程确实持有已闲置的保留锁。相关所有者和目标独占访问检查
必须先全部通过,再原样归档旧检查点并建立本次检查点;库 sidecar 和全局 mutex
期间始终持有。未知、损坏、其他库的记录或仍存活的外部监督进程不会被接管。
普通释放检查的地址要求没有放宽,上传锁文件不删除。
重启后有有效同库检查点时,界面仅按工程目录显示 UNKNOWN 状态,明确标注
“状态未确认,不代表损坏”。此视图不调用原生状态读取,只允许明确维护或严格
释放检查;普通校验、上传/更新/移除及备份恢复均禁用。安全完成维护后再重新
读取权威状态,保留当前搜索条件。
Repair、原生退出、地址消失和最终校验仍是不同的判据。只有完整原生修复证据、
所有者与地址释放及同一工程后验 PASS/GREEN 全部成立才计为修复通过。缺健康
备份、恢复旧版本、占用、超时或不完整证据不会提升为成功,也不会盲目重试。
协调端在保留旧地址字节的用户工程副本上观察到:官方工具报告数据库曾在服务器
运行时被复制、工程当前未使用,随后官方 Repair 自行清除副本地址并返回成功。
这证明了明确维护入口的必要性;原始用户库没有由本次开发或测试修改。实际按钮、
冻结包及最终全套回归的实际验收结果见下。
## 修复后的本地读写访问提示
实际副本验证发现,原理图 iCDB Repair 成功并清除地址后,PCB 仍可能显示上次
异常退出后的读写访问确认。这与选择恢复旧数据库不同。明确维护确认现在说明:
仅在本地固定磁盘、严格确认修复后,工具可对本次启动的这一完整提示确认一次。
该授权不能由普通 Verify 或通用对话框规则开启。维护代码先验证完整原生修复
证据,生成绑定原库、PRJ、PCB 的内部凭据。实际 PCB 启动前,重新确认地址缺失、
无其他原生所有者,并同时独占读取 LMC、相关 icdb.dat 和选中 LayoutDB.lyt,
在本次私有桌面生成短时有效的启动证据。出现提示时再核对当前 PCB 与启动器的
实际 PID、父子关系、安装路径和完整设计参数,以及其他所有者缺失。
只接受原始完整英文提示正文(仅忽略空白差异)、精确窗口类型/标题和唯一可用
Yes6/No7 按钮。专用代理在自己的私有桌面再次读取实际窗口和控件;先消耗授权,
再发送一次按钮消息。没有证据、提示变更、重复提示、额外弹窗或身份不符均停止,
不使用鼠标、前台输入或通用 Yes 回退。后续文档身份、保存关闭和 READY 判据不变。
路径必须经 GetDriveType 确认为 LOCAL_FIXED,且没有重解析点祖先。UNC、网络
映射盘、可移动盘和链接路径不自动确认。该检查不宣称具备跨主机分布式排他能力;
数据库只读句柄在交给官方 PCB 启动前释放,任意非协作外部写入者之间仍不存在
跨进程原子事务保证。普通校验及其他数据库恢复选择继续保持硬性阻断。
## PCB 恢复版本待用户决定
后续实际副本已完成 iCDB Repair 和一次本地读写确认,但 PCB 又要求在“最后
用户保存数据库”和“自动保存数据库”之间选择恢复版本。本次两项显示的日期
均为 `2026/9/24 23:06`;同日期不代表内容相同,工具没有自动选择任何版本。
这类结果单独标识为 `PCB_VERSION_CHOICE_REQUIRED`,展示候选日期,并在
`pcb-version-choice.json` 保存完整窗口和候选状态。维护摘要显示“ICDB 已修复 /
PCB 版本待选”,原生状态仍为 REPAIRED,但整项保持未完成、需人工决定,不能
计为 PASS/GREEN。工具也不会因为显示了某个默认选中项就认可该版本。
## 最终验证(2026-11-03)
程序源码提交 `d76475a`:全量 `python -m pytest -q` **969 passed,1 条已有
pywinauto STA 模式警告,107.69 秒**;编译、diff 检查和代码复审通过。
由不可变 `git archive d76475a` 构建的 EXE 通过 GUI 冒烟。
在第二份完整隔离库上,通过打包 EXE 的实际“非 READY ICDB 检查与修复”按钮
确认并运行 IP101GR:有效旧阻止记录接续、旧地址完整备份、官方 Repair 成功并
正常释放、一次受约束的读写确认均实际执行。之后准确停在原生 PCB 版本选择,
显示 `version_choice_required=1`、`repair_unconfirmed=0`、`repaired=0`。
这是维护入口和结果分类通过验收,不代表未经用户选版本就达到 READY。
原始证据:
- 用户最初 0.172 秒失败:`diagnostics/issue2-user-maintenance-20261103/user-reports/`。
- 冻结 EXE 实际按钮:`diagnostics/issue2-user-maintenance-20261103/actual-button-frozen-d76475a/outcome.json`。
- 原生版本选项:上述目录的 `data/evidence/verify-8fa461b6d6fe/pcb-version-choice.json`。
- 全量测试:`build/issue2-maintenance-final-tests-d76475a.log`。
### 用户明确选择最后手动保存版本后的副本验证
用户选择“用最后手动保存版本继续验证”,授权范围仅为隔离副本。诊断续跑使用
真实校验器、原生工作进程、对话框代理及权威状态读取;只为这次用户决定提供
版本动作:先点击 6213,重新观察其已选中且 6206 未选中,再确认 OK 1。
选择前保留完整工程副本;没有改变程序的默认版本选择规则。
工程成功打开并核对身份,但在原长路径下两次 Project Integration 均产生本轮
JobPrefsDB.jpf / local Cell Library 加载错误。原文件、临时目录及备份中的 JPF/CEL
可读且哈希一致,日志前缀与时间证明是本轮错误,不能断言二进制数据已损坏。
随后保持同一工程数据,通过临时本地 `T:` 短路径进行对照,完成原生 Integration、
保存关闭、进程释放及权威状态查询,结果为 **PASS / GREEN / READY
(IsVerifiedReuseBlock, raw=1),safe_to_continue=true**。所有原生进程退出后已移除
该临时盘符。此结果说明短路径试验可通过,尚不能证明确切路径长度限制或永久
解决原长路径下的 JobPrefs/Cell Library 兼容问题;产品没有自动增加短路径映射。
这是**用户指定历史版本后的恢复与验证**,不是无人值守或无损自动修复验收。
验证后的完整库副本保留在 `diagnostics/issue2-user-maintenance-20261103/frozen-library/`,
原用户库没有被替换。结果和选择证据分别位于:
- `user-authorized-last-saved-r2/user-selection-events.jsonl`(实际 6213 → 复读 → OK 1)。
- `user-authorized-last-saved-short-path/result.json`(最终 PASS/GREEN)。
- `short-path-trial.json`(临时盘符及正常退出后清理记录)。
- `source-unchanged-after-user-choice.json`(全部试验后原库 21,013 个主要文件清单仍一致,原地址字节哈希未变)。
以上相对路径均位于 `diagnostics/issue2-user-maintenance-20261103/`。
现场原工单其他工程、网络共享读写确认和 Windows 10 仍不能由此验收代替。
交付候选包为 `dist/issue2-maintenance-20261103-d76475a.zip`。不合并发布、不自动关闭工单。
+31
View File
@@ -0,0 +1,31 @@
# Native CRUD integration and review follow-up
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.
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.
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.
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.
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.
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.
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.
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.
+27
View File
@@ -0,0 +1,27 @@
# CBB Verify v0.2.3-beta.1
**Beta 预发布,供隔离副本和小范围现场验收使用。**
版本标识:`0.2.3b1`;Git 标签:`v0.2.3-beta.1`。
## 本版内容
- 增加“全库 ICDB 检查与修复”维护入口,包含 Ready 项、串行进度、结果统计和维护报告。
- 增加“从备份恢复 CBB…”弹窗:选择同名 CBB 的完整工程 `.prj` 备份,先在独立短路径副本中验证,再保留原 Work、恢复目标并重新打开校验。
- 恢复只有在原生打开、集成、保存关闭、进程释放和权威 `READY / raw=1` 全部满足时才报告成功;失败保留回退副本并清除旧绿色状态。
- 加强 ICDB 会话所有权、原生修复备份恢复状态、目录链接/外部路径检查和异常 worker 的安全处理。
- 补充真实损坏工程恢复记录、无历史备份边界说明、手动原生修复文档和自动化验证脚本。
## 验证记录
- `python -m pytest -q`:471 passed,1 条既有 pywinauto STA 提示。
- `tests/CBBRefresh.Core.Tests.ps1`:通过。
- `tests/ContentCheck.ExitCode.Tests.ps1`:通过。
- EE7.9.5 隔离实测:破坏 ICDB 文件头后实际打开失败;通过恢复弹窗恢复同名完整备份;同一目标重新打开达到 `PASS / GREEN / READY (raw=1)`。
- PyInstaller 构建和冻结程序 smoke 检查通过。
## 范围限制
恢复功能支持已有同名 CBB 的完整工程备份,不自动删除旧库条目,不实现跨库重导入或共享符号数据库重建。共享库损坏、外部路径引用、不完整备份和未释放原生会话会停止操作。恢复采用用户选择的备份版本,发布前请在隔离副本和现场版本上复核。
详细实机记录:[2026-10-28-cbb-backup-dialog-validation.md](2026-10-28-cbb-backup-dialog-validation.md)。
@@ -0,0 +1,42 @@
# iCDB failure lifecycle and recovery implementation plan
**Goal:** Prevent failed verification from aborting iCDB owners, close owned idle failed documents normally, and attempt native recovery only against a validated idle target with a complete backup.
**Context:** User confirmed the incident used r4 or earlier. r4 enables `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`, calls `TerminateJobObject` and `taskkill /T /F` on failures and native owners. a11eb3c removed those PCB paths, but content-check timeout still kills a process tree. Failed worker exceptions currently release COM references without requesting normal document closure.
**Architecture:** Keep native transactions alive through timeouts. Signal cooperative cancellation to the worker; let blocking native calls return before closing a document. A separate recovery module owns target checks, backup and the official GUI repair transaction; failed or ambiguous repair remains failed. Work and central-library database ownership are checked separately.
**Tech stack:** Python 3.12, Windows process handles/private desktops, x86 cscript and Mentor EE7.9.5 native tools. Continue on `codex/icdb-lost-session-diagnostics`.
## Task 1 — Retain native owners on content timeout
- [x] Add a regression that starts a harmless importer with a harmless child, times out, and checks both survive until normal exit or test cleanup.
- [x] Add a content-timeout batch regression proving the second item does not start.
- [x] Remove tree/client termination from `_run_process` timeout; retain/drain the process in a background observer, record PID/command/release in evidence, and return TIMEOUT with `safe_to_continue=False`.
- [x] Verify targeted tests and the existing content-check tests.
## Task 2 — Normal close of failed owned sessions
- [x] Add x86 cscript harness tests for failed Save and close-only operation, checking `Close(False)`, reference release and Quit, with failure status preserved and mismatched identity untouched.
- [x] Implement an identity-checked close helper and call it only after the worker has returned from its native call and released Python references. Retain busy helpers instead of terminating them.
- [x] Add cooperative cancellation at Python/VBS native-operation boundaries; a supervisor timeout/crash must not terminate a pending native Save.
- [x] Add targeted tests for cancel before Save, cancel after a pending call returns, supervisor loss and blocked native-call retention.
- [x] Check shared `SymbolLibs/__ReusableBlocksSymb` ownership as well as Work/PCB database ownership before writing and before declaring release.
- [x] Give the status reader an EOF shutdown grace period before any fallback termination.
## Task 3 — Attempt official native recovery
- [x] Probe native UI on new isolated copies only; record accepted project/database identity, exact command, backup creation and completion signals. Do not invent CLI Repair flags or manipulate native ownership metadata.
- [x] Add recovery-policy tests: reject foreign/unresolved targets, active clients, inconsistent backups and repeat repair; preserve the original error; at most one recovery attempt.
- [x] Implement the supported native repair route with a complete backup and exact target checks. If the installed native tool cannot accept a shared symbol database, retain that explicit blocked result instead of repairing an unrelated Work project.
- [x] Retry opening/verifying only after native success and confirmed release; authoritative READY remains the success criterion.
## Validation and delivery
- [x] Run full Python and PowerShell regressions, compilation and whitespace checks, plus independent code review.
- [x] Verify a successful native run and a controlled failed integration/close on an isolated library, and source fingerprints afterward.
- [x] Record precisely which recovery target types were actually exercised and any remaining field-only limitations; commit changes on the current branch.
## Execution evidence
Completed on 2026-10-27. See `docs/releases/2026-10-27-icdb-failure-lifecycle-and-recovery.md` for 448 passing Python regressions, PowerShell and x86 harness checks, real failed-session close, real native Repair, the synthetic-error/real-repair/real-retry chain, frozen EXE Repair validation, and trial-package scope. Shared symbol databases without a supported PRJ entry remain explicitly unsupported; no field database was repaired.
@@ -0,0 +1,55 @@
# 从健康 CBB 来源恢复的增量设计
状态:同名 CBB 完整工程备份恢复弹窗已实现,并通过真实损坏打开失败 → 弹窗恢复 → 同一目标重新打开 PASS/READY 的闭环验证。471 项回归通过;原生跨库重新导入替换闭环仍未验证。
实机记录:`docs/releases/2026-10-28-cbb-backup-dialog-validation.md`。
## 本轮确定的实现范围
采用简单弹窗:目标 CBB、完整备份工程 PRJ、“恢复并校验”和“关闭”。选择的工程名和顶层块必须与目标一致,必须保留完整 Work 数据,不能仅选择单个数据库文件。
后台先保存完整目标库快照及 SHA256 清单,复制来源工程,在另一份目标库副本中恢复来源并通过原生 PCB 打开、集成、保存、关闭及权威 Ready 检查。通过后再次检查来源/目标内容及会话释放状态,保留原 Work 为同级 `Work.before-restore-*`,安装已验证的工程副本,再实际打开目标校验。只有 PASS、GREEN 和已释放的结果视为成功。失败保留回退库、来源快照、旧 Work 和原生日志,不自动覆盖共享数据库回退。
验证副本放在用户目录 `.cbb-restore/<编号>`,记录其实际路径。避开深层日志目录及 MSIX 对 AppData 的长路径重定向;本机短路径原生复核已通过 Ready 检查。目标原生操作保留映射盘/别名,文件快照和 Work 替换使用实际路径。原本已指向目标库的等价相对引用不重写,保留工程字节和日期。
该功能恢复现有条目的工程数据;不删除库条目,不宣称已完成原生跨库重新导入或共享符号库重建。原生导入探测已在新建的隔离库通过“Reusable Blocks / New Reusable Block”从 PRJ 创建 IP101GR,但替换损坏条目和依赖完整性尚未形成完整验证闭环,因此本轮不开放自动先删后导入。
真实验证脚本:`tools/validate_backup_recovery_dialog.py`,分 setup、open-before、restore、compare 四阶段。测试目标移除历史备份并破坏数据库文件头,使用独立健康来源;restore 阶段点击实际主窗口按钮及弹窗“恢复并校验”,使用生产后端。
目标:原生 Repair 无法恢复时,允许选择其他目录或库中的健康 CBB 作为恢复来源,重建目标 CBB 的可用状态,并保留完整回退材料。
## 已确认的原生行为
安装自带 `SDD_HOME/lm/win32/lib/upc_utils.tcl` 提供以下依据:
- `runReuseBlockLoader` 使用 DMS 的 `com.mentor.dms.rbloader.jar` 执行 `copyout`,下载/恢复 CBB。
- `processReuseBlockChunk` 在下载 CBB 和相关 Cell 后调用 `runReuseBlockImporter ... move`,同步 CBB 在共享 iCDB 中的符号。
- `removeReuseBlocks` 经 CleanWGLib 处理 CBB 移除;注释明确说明 Cell 和 iCDB 符号也由原生清理处理。
- `ReuseBlockImporter` 因此不能仅凭名字被当成通用完整 CBB 备份导入程序。任意本地目录/压缩包的完整原生导入方式仍需验证。
## 两种故障分开处理
1. 单个 CBB 的 Work 数据库损坏、目标中心库及共享符号库可用:可验证恢复该 CBB,并通过原生流程重新建立元数据、Cell 和符号关联。
2. `SymbolLibs/__ReusableBlocksSymb` 等共享数据库损坏:在同一损坏目标中删除或导入 CBB 都可能因无法访问共享库失败。应先恢复共享库,或评估建立健康新库并迁移 CBB 及依赖;该迁移路线尚未实测。
不将删除日志、地址文件、锁文件或修改私有数据库会话字段作为恢复方法。
## 建议操作流程
1. 选择健康来源:完整工程/可导入的 CBB 包、来源库或受支持的 DMS 版本。核对 CBB 类型、名称、分区、软件版本、来源时间及符号/Cell/零件依赖;名称相同不证明内容等价。
2. 在来源副本上验证可以打开,保留原始来源不被校验保存修改。
3. 在隔离目标副本中验证原生导入/恢复路径。目标中心库必须可访问,错误类别和数据库路径必须明确。
4. 通过原生流程替换/移除旧条目并恢复健康 CBB,确认 .lmc 元数据、CBB 工程、Cell 和共享符号关联一致。先验证是否支持原生替换;不盲目采用先删后导入,也不假定导入具备原子回退。
5. 实际打开恢复的工程,完成集成、保存、关闭和权威 Verify 状态确认。失败保留原始工程、恢复来源、原生日志和完整备份;不将失败结果改为绿色。
## 对现有按钮的建议升级
维护入口展示原生修复结果;受阻项目可选择“从健康 CBB 恢复”。启动前显示来源与目标、覆盖范围和版本差异;结果区分别报告“原位修复”“从备份恢复”“重新导入恢复”“共享库阻断”和“未确认”。
程序可以负责来源核对、隔离验证、备份、原生操作编排和复核。若本机版本只能使用 GUI 导入,先提供原生窗口及操作指引;没有可靠的原生命令/界面路径之前,不声称支持自动重新导入。
## 后续验证门槛
- 确定一个完整、可打开的来源 CBB,并在独立副本上复现目标报错。
- 记录本机原生本地导入/跨库复制/受支持 DMS 恢复的确切入口、替换策略、冲突提示和日志。
- 对照恢复前后的实际工程打开结果与依赖完整性,包含导入失败、来源版本不匹配、目标共享库不可用的停止行为。
@@ -0,0 +1,24 @@
# ICDB Global Check and Repair Implementation Plan
**Goal:** Provide a separate full-library action that checks each available CBB and invokes the existing evidence-bound iCDB recovery when appropriate.
**Architecture:** Reuse the serial verification queue, including Ready rows, and the existing backup, ownership, native repair and retry safeguards. Confirm the full-library write scope before starting; stop on unconfirmed ownership and retain existing reports and evidence. Shared symbol database repair remains unsupported.
**Tech Stack:** Python 3.12, PySide6, pytest, Windows native Mentor tools.
1. Add UI tests for confirmation, Ready-row inclusion, skipped projects, busy state and cancellation.
2. Add the button and route the full set of eligible rows through the existing queue without changing ordinary Verify behavior.
3. Run focused and full regression tests. On a new isolated project copy, attempt a reproducible native session failure and run the repair; retain evidence and explicitly report whether actual corruption and recovery were demonstrated.
## Button design and acceptance (2026-10-28)
- [x] Put the action in a separate database maintenance panel with the supported scope beside it.
- [x] Confirmation displays the exact library, eligible count, Ready count and missing-project count, and explains that verification saves projects.
- [x] Show item progress and separate checking, backup and native repair phases; allow stopping after the current item.
- [x] Report verified items, native repairs, restored backups requiring review, unconfirmed repairs and unexecuted items separately. Save a JSON maintenance report with original error and repair evidence.
- [x] Detect native restoration from an existing backup without treating it as an automatic repair success or retrying verification. Close only after restoration/diagnostics complete, the native main window is idle and the database address has been released.
- [x] Exercise the actual Qt button on a fresh local library copy using the production reader and verifier, capture screenshots and check source fingerprints afterwards.
- [x] Repeat the real header-corruption/native-repair probe with a 180-second native deadline and verify the restoration-review result and normal process exit.
- [x] Run the full regression suite and record the supported scope and practical limits in a release validation note.
Results: `docs/releases/2026-10-28-icdb-maintenance-button-validation.md`. Actual button run PASS/READY raw=1 on IP101GR; all 21,029 source file hashes unchanged. Real header corruption led to native restoration of an older backup and RESTORED_REVIEW_REQUIRED, without automatic retry. Full regression: 455 passed. Final Windows EXE smoke: clean exit 0.
@@ -0,0 +1,104 @@
# Issue #2 implementation plan
Approved by user on 2026-11-02. Continue branch codex/temp-issue-2-icdb-recovery,
baseline ec78dd7 (491 tests). Do not merge, publish or close the issue. Preserve
untracked review.diff. Python 3.12, PySide6, Mentor EE7.9.5, private desktop by
default. No force termination of native database owners, deleting locks,
guessing native write interfaces, or editing LMC binary contents.
Each task uses regression tests, focused validation and a separate commit.
Real field lost-session reproduction and Windows 10 validation must be reported
as unverified when unavailable; header corruption is not a substitute.
## Task 1: ICDB failure lifecycle and repair outcomes
Extend the existing owned-empty-PCB close path to wait for its launcher as well.
Cover COM connected without a document, delayed dialogs/addresses/process exit.
Native Repair must report missing healthy backup, native repair failure, database
busy, unknown dialogs and timeout/unreleased distinctly using this run's native
logs and Output. Safely close an idle, conclusively failed native repair tool;
never act on unrecognized prompts or active native operations.
Preserve original error, original evidence and all repair evidence. Record release
state. Repair success in summaries means original native repair succeeded AND
same-project reopening, verification and authoritative GREEN succeeded. Historical
backup restoration remains RESTORED_REVIEW_REQUIRED. A conclusively failed repair
may continue independent CBB items only if all relevant processes and addresses
are released and scope is project-local; shared-library/unknown ownership stops.
Add sanitized replay of issue2 lost-session/open-failure events with asserted target,
stage and invocation order; one automatic repair maximum, no repeated PCB loop.
Maintain VerifyRequest/VerifyResult compatibility. Files primarily failed_session,
pcb_bridge, mentor_adapter, native_repair[_ui], verify_runner, icdb_maintenance and
their tests. Update release evidence. No native live operations without coordinator
agreement (only one native operation at a time). Coordinator builds candidate and
runs frozen tests after review. Field fault sample is not in the attachment (logs
only); do not claim field recovery.
## Task 2: Search, filtering, selection and non-READY maintenance
Implement local name/partition keyword search and filters: all, READY, non-READY,
PENDING, unknown/read errors, missing project. Non-READY includes unconfirmed states
without calling them corrupt. Show visible/READY/error counts; no Mentor rereads on
filtering. Management selection permits READY; verify/maintenance/default backup
recovery exclude READY. Operations target current visible checked rows; hiding a row
clears its checkbox. Provide select visible/clear selection. Maintenance entry,
confirmation, progress and report agree on non-READY target set. Existing verify-all
means visible eligible rows, maintenance defaults visible eligible rows with checked
subset if any. Refresh affected authoritative statuses after operations, retain search
and filter. No premature integration of CRUD; expose selected records for Task4.
Maintain CbbRecord compatibility and explicit status separate from action result.
Tests include mixed READY/PENDING/errors/missing, filtering after state transitions,
selection scope and 381/3000 row responsiveness. Files UI main_window, small focused
filter helper if useful, backup dialog and maintenance report + tests. Avoid unrelated
UI overhaul. Commit and report focused tests plus full suite once.
## Task 3: Scoped primary-file hashes and verified backups
Copy and retain complete backup trees. Restrict SHA256 and semantic before/after
comparison to primary project/design/database/constraint files and required library
dependencies: PRJ/PCB/DXP, icdb.dat, Layout, schematic/logic/symbol assets, CES/config,
target LMC and shared database dependencies. Explicitly exclude runtime logs/temp/
locks/address records, historical backups, PDF/generated output from content hashes;
address files still participate in idle checks. Treat unclassified engineering data
conservatively as primary rather than accidentally excluding it. For central-library
manifest, only target CBB Work/Cert plus active library configuration/shared library
dependency trees; do not hash unrelated CBB projects.
During copy validate tree membership and file size/mtime before/after; primary files
also source/destination SHA256, including locked database stream bytes. Logs changing
after successful snapshot must not invalidate subsequent semantic comparison, while
primary changes/additions/deletions must block install. Manifest is versioned and
contains relative paths, size, hash and scope; progress gives hashed files/bytes/stage.
Keep existing validate-copy -> target conflict check -> retain Work -> install ->
reopen verification. Preserve old backups and evidence on failure. Add tests for logs
only, all primary categories, changed/deleted sources, target concurrency, copied byte
corruption and preserved recovery copies. Files backup_recovery and new focused
manifest helper + tests. Reuse helper in management Task4 without changing old public
Verify contracts. Document explicit rules/compatibility, commit after tests.
## Task 4: Native CBB management and delivery
Integrate add, same-name update, remove in current application. Input complete PRJ/PCB
projects, no Packager/PDF/part replacement/rename/partition move. Add conflicts never
overwrite. Update matches existing name/partition and backs up complete old project
and library recovery snapshot. Remove backs up then uses verified Mentor native
operation; reread confirms absence. Never fake removal by deleting directories.
Add/update reread identity, default auto-verify optional per batch, distinguish upload
failed, uploaded-but-verification-failed, uploaded-and-verified. Preserve source files.
Use isolated native adapter: capability detection by installed version/interface plus
isolated validation. Prefer proven COM/command; verified private desktop controls only
fallback, never foreground input. Unsupported operations disabled with exact reason.
Use cbb-upload-795 as research only, no external runtime dependency. Native API research
comes from coordinator. No fabricated operation parameters. Snapshot/readback result
must correspond to actual library entry and source engineering identity.
Requests/results contain operation, library, CBB, partition, source, auto_verify,
stage/status, safe_to_continue and evidence path. Serialize all writes with existing
verification mutex and a library-level lock compatible with original uploader; apply
coordination to verify/recovery too. Stop when native release uncertain. Persist item
checkpoints and show unfinished tasks on restart, never replay automatically.
Provide safe preview/confirmation for destructive operations; backups outside target.
Test isolated add/conflict/update/remove/reimport, cancellation, timeout/network errors,
partial successes, no-op/lying native response, busy library, restart checkpoints.
Implement capabilities conservatively: if actual native operation cannot be proven,
its UI remains disabled with actionable explanation and validation gap is explicit.
Full Python/compile/diff checks, candidate frozen smoke, Windows11 native scenario;
Windows10 and real field sample explicitly unverified if inaccessible. Coordinator
provides final review and source/frozen deliverables without merging/publishing.
+2 -1
View File
@@ -13,11 +13,12 @@ a = Analysis(
if verify_probe_path.is_file() else [] if verify_probe_path.is_file() else []
), ),
datas=[(str(project_root / 'src' / 'cbb_refresh_verify' / 'save_verified_block.vbs'), 'cbb_refresh_verify'), datas=[(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.ico'), 'cbb_refresh_verify/assets'),
(str(assets_root / 'cbb_refresh_verify.png'), 'cbb_refresh_verify/assets'), (str(assets_root / 'cbb_refresh_verify.png'), 'cbb_refresh_verify/assets'),
(str(assets_root / 'cbb_refresh_verify.svg'), 'cbb_refresh_verify/assets'), (str(assets_root / 'cbb_refresh_verify.svg'), 'cbb_refresh_verify/assets'),
(str(assets_root / 'dialog_rules.v1.json'), 'cbb_refresh_verify/assets')], (str(assets_root / 'dialog_rules.v1.json'), 'cbb_refresh_verify/assets')],
hiddenimports=['win32com.client','win32com.client.dynamic','pythoncom','pywintypes','win32job','pywinauto','pywinauto.uia_defines','pywinauto.controls.uiawrapper','pywinauto.win32_element_info','cbb_refresh_verify.dialog_agent','cbb_refresh_verify.dialog_probe','cbb_refresh_verify.dialog_rules','cbb_refresh_verify.ui.main_window','dx_productivity.trial_task_center.logging_setup','dx_productivity.trial_task_center.errors','dx_productivity.trial_task_center.retention'], hiddenimports=['win32com.client','win32com.client.dynamic','pythoncom','pywintypes','win32timezone','win32job','pywinauto','pywinauto.uia_defines','pywinauto.controls.uiawrapper','pywinauto.win32_element_info','cbb_refresh_verify.dialog_agent','cbb_refresh_verify.dialog_probe','cbb_refresh_verify.dialog_rules','cbb_refresh_verify.ui.main_window','cbb_refresh_verify.ui.management_dialog','cbb_refresh_verify.management','cbb_refresh_verify.native_management','cbb_refresh_verify.library_lock','cbb_refresh_verify.content_check','cbb_refresh_verify.failed_session','cbb_refresh_verify.icdb_ownership','cbb_refresh_verify.native_repair','cbb_refresh_verify.native_repair_ui','dx_productivity.trial_task_center.logging_setup','dx_productivity.trial_task_center.errors','dx_productivity.trial_task_center.retention'],
excludes=['PySide6.QtDesigner','PySide6.QtMultimedia','PySide6.QtMultimediaWidgets','PySide6.QtOpenGL','PySide6.QtOpenGLWidgets','PySide6.QtPdf','PySide6.QtPdfWidgets','PySide6.QtQml','PySide6.QtQuick','PySide6.QtQuickWidgets','PySide6.QtWebChannel','PySide6.QtWebEngineCore','PySide6.QtWebEngineWidgets'], excludes=['PySide6.QtDesigner','PySide6.QtMultimedia','PySide6.QtMultimediaWidgets','PySide6.QtOpenGL','PySide6.QtOpenGLWidgets','PySide6.QtPdf','PySide6.QtPdfWidgets','PySide6.QtQml','PySide6.QtQuick','PySide6.QtQuickWidgets','PySide6.QtWebChannel','PySide6.QtWebEngineCore','PySide6.QtWebEngineWidgets'],
) )
excluded_qt_binaries = {'icudt78.dll','icuuc.dll','qpdf.dll','qt6pdf.dll','qt6qml.dll','qt6qmlmeta.dll','qt6qmlmodels.dll','qt6qmlworkerscript.dll','qt6quick.dll','qt6quickwidgets.dll'} excluded_qt_binaries = {'icudt78.dll','icuuc.dll','qpdf.dll','qt6pdf.dll','qt6qml.dll','qt6qmlmeta.dll','qt6qmlmodels.dll','qt6qmlworkerscript.dll','qt6quick.dll','qt6quickwidgets.dll'}
+1 -1
View File
@@ -3,7 +3,7 @@ requires = ["setuptools>=84.1.0"]
build-backend = "setuptools.build_meta" build-backend = "setuptools.build_meta"
[project] [project]
name = "cbb-refresh-verify" name = "cbb-refresh-verify"
version = "0.2.2b1" version = "0.2.3b1"
requires-python = ">=3.12,<3.13" requires-python = ">=3.12,<3.13"
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<0.7", "Pillow>=13.0.0,<14"] dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<0.7", "Pillow>=13.0.0,<14"]
+1 -1
View File
@@ -1 +1 @@
__version__ = "0.2.2b1" __version__ = "0.2.3b1"
+8
View File
@@ -46,6 +46,8 @@ def resolve_data_root(cli_value: Path | None) -> Path:
def main(argv: Sequence[str] | None = None) -> int: def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="CbbRefreshVerify") parser = argparse.ArgumentParser(prog="CbbRefreshVerify")
parser.add_argument('--verify-worker', type=Path, help=argparse.SUPPRESS) parser.add_argument('--verify-worker', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--repair-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('--dialog-agent', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS) parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--batch-lmc', type=Path, help=argparse.SUPPRESS) parser.add_argument('--batch-lmc', type=Path, help=argparse.SUPPRESS)
@@ -55,6 +57,12 @@ def main(argv: Sequence[str] | None = None) -> int:
parser.add_argument('--mentor-bin', default='', help=argparse.SUPPRESS) 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) 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) args = parser.parse_args(list(argv) if argv is not None else None)
if args.management_worker:
from .native_management import management_worker_main
return management_worker_main(args.management_worker)
if args.repair_worker:
from .native_repair_ui import repair_worker_main
return repair_worker_main(args.repair_worker)
if args.collect_failure_logs: if args.collect_failure_logs:
from .verify_diagnostics import failure_logs_main from .verify_diagnostics import failure_logs_main
return failure_logs_main(args.collect_failure_logs) return failure_logs_main(args.collect_failure_logs)
+254
View File
@@ -0,0 +1,254 @@
"""Restore a complete same-CBB Work backup, then reopen through native Verify.
This restores project data for an existing library entry. It is not a native
cross-library import and does not delete library records or shared symbols.
"""
from dataclasses import asdict, replace
import json
from pathlib import Path
import re
import shutil
import stat
from uuid import uuid4
from .verify_runner import VerifyResult, preflight
from .scoped_manifest import (ManifestScope, build_manifest, copy_verified,
hash_file as _hash, scan_tree as _scan)
def _manifest(root, *, scope=None, exclude=None, progress=None):
return build_manifest(root, scope=scope, exclude=exclude, progress=progress, hash_function=_hash)
def _copy_verified(source, destination, *, scope=None, progress=None):
return copy_verified(source, destination, scope=scope, progress=progress, hash_function=_hash)
def _paths(root):
return list(_scan(root))
def _idle_check(library, project, pcb):
from .mentor_adapter import pcb_processes, _process_details
from .icdb_ownership import unreleased_addresses
if pcb_processes() or any(_process_details(name) for name in (
'LibraryManager.exe', 'viewdraw.exe')):
raise ValueError('请先正常关闭 PCB、Library Manager 和原理图编辑器,再恢复备份。')
addresses = unreleased_addresses(library, project, pcb)
if addresses:
raise ValueError(f'数据库会话尚未释放,停止恢复:{addresses}')
def _project_text(path):
data = path.read_bytes()
if data.startswith((b'\xff\xfe', b'\xfe\xff')):
return data.decode('utf-16')
try:
return data.decode('utf-8-sig')
except UnicodeDecodeError:
return data.decode('mbcs')
def _source_check(source, name, original):
if not source.is_file() or source.suffix.casefold() != '.prj':
raise ValueError('请选择完整健康备份中的工程 .prj。')
_paths(source.parent)
text = _project_text(source)
roots = re.findall(r'^KEY RootBlock "([^"]+)"', text, re.M)
if (source.name.casefold() != original.name.casefold() or not roots
or any(root.casefold() != name.casefold() for root in roots)):
raise ValueError('当前仅支持同名 CBB 的完整工程备份,工程名和顶层块必须与目标一致。')
refs = re.findall(r'^KEY PCBDesignPath "([^"]+)"', text, re.M)
if len(refs) != 1:
raise ValueError('备份工程必须包含唯一的 PCBDesignPath。')
def require_relative(value):
if Path(value).drive or Path(value).root:
raise ValueError('备份工程、PCB 和数据库必须使用工程内的相对路径,不能指向原备份位置。')
require_relative(refs[0])
pcb = (source.parent / refs[0]).resolve()
if not pcb.is_relative_to(source.parent.resolve()):
raise ValueError('备份 PCB 引用越出工程目录。')
if not all(path.is_file() for path in (pcb, pcb.parent/'Layout/LayoutDB.lyt',
pcb.parent/'pcb.prj', source.parent/'database/icdb.dat')):
raise ValueError('备份不完整:需要原理图数据库、PCB、布局数据库和 PCB 工程文件。')
project_refs = re.findall(r'^KEY ProjectFile "([^"]+)"', _project_text(pcb), re.M)
for value in project_refs:
require_relative(value)
if len(project_refs) != 1 or (pcb.parent/project_refs[0]).resolve() != source.resolve():
raise ValueError('备份 PCB 必须引用所选工程,不能引用其他位置的工程。')
for project in (source, pcb.parent/'pcb.prj'):
data = _project_text(project)
for value in re.findall(r'^KEY iCDBDir "([^"]+)"', data, re.M):
require_relative(value)
if not (project.parent/value).resolve().is_relative_to(source.parent.resolve()):
raise ValueError('备份数据库引用越出工程目录。')
return pcb
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'):
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)
def recover_from_backup(request, source, *, progress=None, verifier=None, idle_check=None):
"""Validate in copies before changing Work; preserve all recovery evidence."""
import pythoncom, win32con, win32event
from .network_path import absolute_preserving_drive
from .verify_runner import run_verify, read_library_flag_if_available
verifier = verifier or run_verify
idle_check = idle_check or _idle_check
source = Path(source).resolve()
library = absolute_preserving_drive(request.lmc_file)
library_root = library.parent.resolve()
root = Path(request.evidence_dir).resolve() / ('backup-restore-' + uuid4().hex[:12])
# Packaged desktop apps can redirect AppData to a very deep MSIX path.
# Keep native EE7.9 files in a genuinely short, user-owned directory.
validation_base = Path.home() / '.cbb-restore'
validation_dir = validation_base.resolve() / root.name.removeprefix('backup-restore-')
if root.is_relative_to(library_root) or library_root.is_relative_to(root):
return VerifyResult('BLOCKED', stderr='恢复记录目录与目标中心库不能相互包含。')
if root.is_relative_to(source.parent):
return VerifyResult('BLOCKED', stderr='恢复记录目录不能位于备份工程内。')
if validation_dir.is_relative_to(library_root) or validation_dir.is_relative_to(source.parent):
return VerifyResult('BLOCKED', stderr='本机验证目录不能位于目标库或备份工程内。')
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = False
library_lock = None
release_confirmed = True
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)}
def emit(stage, message, **details):
if progress:
progress({'stage': stage, 'block': request.block_name, 'message': message, **details})
def copy_progress(stage, message):
def report(event):
details = {key: value for key, value in event.items() if key != 'stage'}
emit(stage, f'{message} {event["copied_files"]} / {event["total_files"]}',
manifest_stage=event['stage'], **details)
return report
def save(result):
record.update({'installed': installed, 'result': asdict(result)})
root.mkdir(parents=True, exist_ok=True)
report = root/'recovery-result.json'
report.write_text(json.dumps(record, ensure_ascii=False, default=str, indent=2), encoding='utf-8')
return replace(result, evidence_path=report)
from .com_runtime import initialize_com, uninitialize_com
initialized = initialize_com()
try:
acquired = win32event.WaitForSingleObject(mutex, 0) in (
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired:
return VerifyResult('BLOCKED', stderr='已有 CBB 任务运行,请等待结束。', safe_to_continue=False)
from .library_lock import LibraryLock
library_lock = LibraryLock(library, safe_to_release=lambda: release_confirmed)
library_lock.__enter__()
if source.is_relative_to(library_root):
raise ValueError('请选择目标中心库之外的独立备份工程。')
project, pcb = preflight(replace(request, lmc_file=library))
source_pcb = _source_check(source, request.block_name, project)
idle_check(library, project, pcb)
idle_check(library, source, source_pcb)
root.mkdir(parents=True, exist_ok=False)
validation_base.mkdir(parents=True, exist_ok=True)
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
if (shutil.disk_usage(root).free < required
or shutil.disk_usage(validation_base).free < library_size + source_size * 2):
raise ValueError('磁盘空间不足:需要容纳中心库回退副本和验证副本。')
(root/'recovery-request.json').write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
emit('backup', '正在保留完整中心库副本…')
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,
progress=copy_progress('prepare_source', '正在准备验证库:'))
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.
resolved_work = staged_work.resolve()
if not resolved_work.is_relative_to(validation_dir.resolve()):
raise ValueError('验证副本工程路径越界。')
shutil.rmtree(resolved_work)
_copy_verified(root/'source-before', staged_work,
progress=copy_progress('prepare_source', '正在准备备份验证工程:'))
staged_project = staged_work/source.name
staged_pcb = staged_work/source_pcb.relative_to(source.parent)
_align_library(staged_project, staged_pcb, staged_library)
_source_check(staged_project, request.block_name, project)
validation = replace(request, lmc_file=staged_library, evidence_dir=root/'source-verify',
auto_repair=False, libspec='', dms_login_config='', mapped_drive='', mapped_remote_root='',
native_lm_verify=False, interactive_input=False)
preflight(validation)
emit('validate_source', '正在副本中打开备份工程并执行原生校验…')
release_confirmed = False
source_result = verifier(validation, progress=progress, flag_reader=read_library_flag_if_available)
release_confirmed = source_result.safe_to_continue
record['source_validation'] = asdict(source_result)
if (source_result.status != 'PASS' or source_result.library_flag != 'GREEN'
or not source_result.safe_to_continue):
return save(replace(source_result, status='FAIL', stderr=
'备份校验未通过,目标未更改。\n' + (source_result.stderr or source_result.library_flag_detail)))
idle_check(library, project, pcb)
idle_check(staged_library, staged_project, staged_pcb)
token = root.name.removeprefix('backup-restore-')
work = project.parent.resolve()
incoming = work.with_name('Work.restore-' + token)
retained = work.with_name('Work.before-restore-' + token)
_copy_verified(staged_work, incoming,
progress=copy_progress('prepare_source', '正在准备恢复工程:'))
_align_library(incoming/source.name, incoming/source_pcb.relative_to(source.parent), library)
idle_check(library, source, source_pcb)
if _manifest(source.parent) != source_manifest:
raise ValueError('备份来源在验证期间发生变化,目标未更改。')
if _manifest(library_root, scope=library_scope, exclude=incoming.resolve()) != original_manifest:
raise ValueError('目标中心库在验证期间发生变化,停止恢复。')
emit('install', '备份已通过验证,正在保留原工程并恢复…')
work.rename(retained)
try:
incoming.rename(work)
except Exception:
retained.rename(work)
raise
installed = True
record['retained_work'] = str(retained)
emit('verify_target', '正在重新打开恢复后的目标工程并校验…')
release_confirmed = False
final = verifier(replace(request, lmc_file=library, evidence_dir=root/'target-verify',
auto_repair=False, native_lm_verify=False, interactive_input=False),
progress=progress, flag_reader=read_library_flag_if_available)
release_confirmed = final.safe_to_continue
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())
return save(final)
except Exception as error:
return save(VerifyResult('FAIL' if installed else 'BLOCKED', stderr=str(error),
safe_to_continue=False))
finally:
try:
if library_lock is not None:
library_lock.__exit__(None, None, None)
finally:
if acquired:
win32event.ReleaseMutex(mutex)
mutex.Close()
uninitialize_com(initialized)
@@ -0,0 +1,29 @@
Option Explicit
Dim app, doc, pi, licensing, token, closed, remaining
Set app = GetObject(, "MGCPCB.Application")
Set doc = app.ActiveDocument
If doc Is Nothing Then WScript.Quit 3
Set pi = doc.ProjectIntegration
If LCase(pi.ProjectFile) <> LCase(WScript.Arguments(0)) Then WScript.Quit 2
If LCase(doc.Name) <> LCase(WScript.Arguments(1)) Then WScript.Quit 2
Set pi = Nothing
WScript.Echo "FAILURE_IDENTITY_OK"
Set licensing = CreateObject("MGCPCBAutomationLicensing.Application")
token = licensing.GetToken(doc.Validate(0))
doc.Validate token
WScript.Echo "FAILURE_CLOSE_START"
closed = doc.Close(False)
If Not closed Then WScript.Quit 4
WScript.Echo "FAILURE_CLOSE_OK"
Set doc = Nothing
Set licensing = Nothing
Set remaining = app.ActiveDocument
If Not remaining Is Nothing Then
Set remaining = Nothing
WScript.Echo "FAILURE_APP_RETAINED"
WScript.Quit 5
End If
Set remaining = Nothing
app.Quit
WScript.Echo "FAILURE_QUIT_OK"
Set app = Nothing
+18
View File
@@ -0,0 +1,18 @@
"""Balanced COM initialization without tearing down an existing MTA caller."""
def initialize_com():
import pythoncom
try:
pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED)
except pythoncom.com_error as error:
if error.hresult != -2147417850: # RPC_E_CHANGED_MODE
raise
return False # Existing apartment is usable; no reference was added.
return True
def uninitialize_com(initialized):
if initialized:
import pythoncom
pythoncom.CoUninitialize()
+46
View File
@@ -0,0 +1,46 @@
"""Run the native importer without aborting database owners on timeout."""
import json
import os
from pathlib import Path
import subprocess
import tempfile
import threading
def run_content_check(command, timeout_seconds, cwd, *, evidence_root=None):
root = (Path(evidence_root) if evidence_root is not None else
Path(tempfile.mkdtemp(prefix='cbb-content-check-')))
root.mkdir(parents=True, exist_ok=True)
stdout_path, stderr_path = root/'content-check.stdout.log', root/'content-check.stderr.log'
record_path = root/'content-check-process.json'
with stdout_path.open('wb') as stdout, stderr_path.open('wb') as stderr:
process = subprocess.Popen(command, cwd=str(cwd), stdout=stdout, stderr=stderr,
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
record = {'pid': process.pid, 'command': list(command), 'cwd': str(cwd),
'stdout': str(stdout_path), 'stderr': str(stderr_path)}
def save_record(**fields):
try:
record_path.write_text(json.dumps({**record, **fields}, ensure_ascii=False, indent=2),
encoding='utf-8')
except OSError:
pass
save_record(status='RUNNING')
try:
process.wait(timeout=max(.1, float(timeout_seconds)))
except subprocess.TimeoutExpired:
# Never kill this client or its descendants. The importer can own the
# shared symbol database even though contents checking sounds read-only.
# Files avoid pipe backpressure/BrokenPipe if the supervisor exits.
save_record(status='RETAINED', safe_to_continue=False)
def observe_exit():
process.wait()
save_record(status='EXITED', returncode=process.returncode,
note='Importer exit alone does not prove native database release.')
threading.Thread(target=observe_exit, name='retained-content-check', daemon=True).start()
return (None, stdout_path.read_bytes().decode('utf-8', errors='replace'),
stderr_path.read_bytes().decode('utf-8', errors='replace') +
f'\nIMPORTER_RELEASE_UNCONFIRMED: pid={process.pid}; '
f'内容检查超时,保留原生操作并停止批次;进程记录:{record_path}', True)
save_record(status='EXITED', returncode=process.returncode)
return (process.returncode, stdout_path.read_bytes().decode('utf-8', errors='replace'),
stderr_path.read_bytes().decode('utf-8', errors='replace'), False)
+20 -3
View File
@@ -1,6 +1,7 @@
"""Launch automation on a private Windows desktop, never the input desktop.""" """Launch automation on a private Windows desktop, never the input desktop."""
import subprocess import subprocess
import os import os
from pathlib import Path
import threading import threading
import win32con import win32con
import win32event import win32event
@@ -21,7 +22,7 @@ def launch_save_helper(command, **kwargs):
return helper return helper
def start_supervisor_watchdog(supervisor_pid): def start_supervisor_watchdog(supervisor_pid, *, cancel_path=None):
"""A crashed supervisor must not leave unsupervised automation writing. """A crashed supervisor must not leave unsupervised automation writing.
Stop only this Python worker and its registered automation clients. Native Stop only this Python worker and its registered automation clients. Native
@@ -33,6 +34,11 @@ def start_supervisor_watchdog(supervisor_pid):
def watch(): def watch():
try: try:
win32event.WaitForSingleObject(parent, win32event.INFINITE) win32event.WaitForSingleObject(parent, win32event.INFINITE)
if cancel_path is not 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
with _automation_clients_lock: with _automation_clients_lock:
for helper in _automation_clients: for helper in _automation_clients:
try: try:
@@ -42,7 +48,8 @@ def start_supervisor_watchdog(supervisor_pid):
pass pass
finally: finally:
parent.Close() parent.Close()
os._exit(75) if cancel_path is None:
os._exit(75)
thread = threading.Thread(target=watch, name='supervisor-watchdog', daemon=True) thread = threading.Thread(target=watch, name='supervisor-watchdog', daemon=True)
thread.start() thread.start()
@@ -139,6 +146,16 @@ class DesktopWorker:
except Exception: except Exception:
pass pass
def bind_cancellation(self, path):
self.cancel_path = Path(path)
def request_stop(self):
if not hasattr(self, 'cancel_path'):
# Compatibility for diagnostic workers without the Verify protocol.
self.kill()
return
self.cancel_path.touch()
def wait(self, timeout=5): def wait(self, timeout=5):
if win32event.WaitForSingleObject(self.handle, int(timeout*1000)) != win32con.WAIT_OBJECT_0: if win32event.WaitForSingleObject(self.handle, int(timeout*1000)) != win32con.WAIT_OBJECT_0:
raise TimeoutError('Automation worker did not exit') raise TimeoutError('Automation worker did not exit')
@@ -148,7 +165,7 @@ class DesktopWorker:
# Releasing Python resources must not kill native database owners. # Releasing Python resources must not kill native database owners.
try: try:
if self.poll() is None: if self.poll() is None:
self.kill() self.request_stop()
except Exception: except Exception:
pass pass
for companion in self.companions: for companion in self.companions:
+8
View File
@@ -236,6 +236,14 @@ class DialogActionExecutor:
def perform(self, snapshot: WindowSnapshot, action: dict) -> ActionResult: def perform(self, snapshot: WindowSnapshot, action: dict) -> ActionResult:
channels = tuple(action.get("channels", ())) channels = tuple(action.get("channels", ()))
action_name = action.get("action") action_name = action.get("action")
if action_name == 'post_repair_local_read_write':
try:
from .post_repair_consent import validate_action_window
validate_action_window(snapshot, action)
if channels != ('win32_button_click',) or action.get('target') != {'control_id': 6}:
raise ValueError('POST_REPAIR_ACTION_MISMATCH')
except Exception as error:
return ActionResult(error_code='DATABASE_RECOVERY_REQUIRED', detail=str(error))
if action_name == "accept_license": if action_name == "accept_license":
target = self._license_target(snapshot) target = self._license_target(snapshot)
elif action_name == "restore_last_saved": elif action_name == "restore_last_saved":
+44
View File
@@ -4,6 +4,7 @@ from __future__ import annotations
from dataclasses import dataclass, fields, replace from dataclasses import dataclass, fields, replace
import json import json
import re
from pathlib import Path from pathlib import Path
import sys import sys
from typing import Any, Sequence from typing import Any, Sequence
@@ -185,6 +186,39 @@ def _decision(rule: DialogRule) -> RuleDecision:
) )
def pcb_version_choice(snapshot):
"""Describe the captured native choice; never select or approve a version."""
if (snapshot.title != 'Database Restoration' or snapshot.window_class != '#32770'
or snapshot.process_name.casefold() != 'expeditionpcb.exe' or snapshot.process_role != 'pcb'
or snapshot.phase != DialogPhase.PCB_STARTING):
return None
explanation = ('The system has detected this design abnormally terminated the last time it was used. '
'The user has to decide what database (if any) to associate with the design.')
if not any(c.control_id == 6208 and ' '.join(c.name.split()) == explanation for c in snapshot.controls):
return None
candidates = []
for identifier, kind, prefix in ((6213, 'last_user_saved', 'Load the last user saved database dated '),
(6206, 'autosave', 'Load the autosave database dated ')):
controls = [c for c in snapshot.controls if c.control_id == identifier and c.class_name == 'Button']
if len(controls) != 1: return None
control = controls[0]
match = re.fullmatch(re.escape(prefix) + r'(.+)\.', ' '.join(control.name.split()))
if not match: return None
candidates.append({'kind': kind, 'control_id': identifier, 'label': control.name,
'date': match.group(1), 'enabled': control.enabled,
'selected': control.selected or control.checked})
return {'candidates': candidates, 'automatic_selection': False}
def archive_version_choice(snapshot, root):
choice = pcb_version_choice(snapshot)
if choice is None: raise ValueError('Not the recognized native PCB version choice')
path = Path(root)/'pcb-version-choice.json'
path.write_text(json.dumps({**choice, 'snapshot': snapshot.to_record()},
ensure_ascii=False, indent=2), encoding='utf-8')
return path
def decide(snapshot: WindowSnapshot, rules: Sequence[DialogRule]) -> RuleDecision: def decide(snapshot: WindowSnapshot, rules: Sequence[DialogRule]) -> RuleDecision:
# Windows Text Services Framework language-bar window exposed by Mentor's # Windows Text Services Framework language-bar window exposed by Mentor's
# process is not a Mentor modal: it has no controls and must not abort a run. # process is not a Mentor modal: it has no controls and must not abort a run.
@@ -193,6 +227,16 @@ def decide(snapshot: WindowSnapshot, rules: Sequence[DialogRule]) -> RuleDecisio
and not snapshot.controls): and not snapshot.controls):
return RuleDecision(rule_id='ime-floating-language-bar', category='OBSERVE_PROGRESS') return RuleDecision(rule_id='ime-floating-language-bar', category='OBSERVE_PROGRESS')
combined = normalize_text(' '.join((snapshot.title, *snapshot.texts))) combined = normalize_text(' '.join((snapshot.title, *snapshot.texts)))
from .icdb_recovery import ERROR_CODE, parse_session_loss
if parse_session_loss(combined):
return RuleDecision(error_code=ERROR_CODE,
detail=' | '.join(snapshot.texts) or snapshot.title)
choice = pcb_version_choice(snapshot)
if choice is not None:
labels = {'last_user_saved': '最后用户保存', 'autosave': '自动保存'}
detail = ';'.join(f'{labels[c["kind"]]}:{c["date"]}' for c in choice['candidates'])
return RuleDecision(error_code='PCB_VERSION_CHOICE_REQUIRED',
detail=f'PCB需选择恢复版本,尚未校验通过。候选版本:{detail}。未自动选择或确认任何版本。')
# These prompts require knowledge of database ownership or a recovery # These prompts require knowledge of database ownership or a recovery
# choice. A generic Yes/restore rule cannot establish either fact. # choice. A generic Yes/restore rule cannot establish either fact.
if any(marker in combined for marker in ( if any(marker in combined for marker in (
@@ -351,6 +351,11 @@ def classify_dialog(snapshot: DialogSnapshot) -> DialogDecision:
joined = " ".join(snapshot.texts).casefold() joined = " ".join(snapshot.texts).casefold()
combined = f"{title} {joined}" combined = f"{title} {joined}"
from .icdb_recovery import ERROR_CODE, parse_session_loss
if parse_session_loss(combined):
return DialogDecision(error_code=ERROR_CODE,
detail=' | '.join(snapshot.texts) or snapshot.title)
if ("problem encountered while opening one of the database files" in combined if ("problem encountered while opening one of the database files" in combined
and "loading of the job has failed" in combined): and "loading of the job has failed" in combined):
return DialogDecision(action="decline_database_log", return DialogDecision(action="decline_database_log",
+172
View File
@@ -0,0 +1,172 @@
"""Close only an idle document whose native identity was already established."""
import json
import os
from pathlib import Path
import time
def _command_args(command):
import ctypes
from ctypes import wintypes
shell = ctypes.WinDLL('shell32', use_last_error=True)
kernel = ctypes.WinDLL('kernel32', use_last_error=True)
shell.CommandLineToArgvW.argtypes = [wintypes.LPCWSTR, ctypes.POINTER(ctypes.c_int)]
shell.CommandLineToArgvW.restype = ctypes.POINTER(wintypes.LPWSTR)
kernel.LocalFree.argtypes = [wintypes.HLOCAL]
kernel.LocalFree.restype = wintypes.HLOCAL
count = ctypes.c_int()
args = shell.CommandLineToArgvW(command, ctypes.byref(count))
if not args:
raise ctypes.WinError(ctypes.get_last_error())
try:
return list(args[:count.value])
finally:
kernel.LocalFree(ctypes.cast(args, wintypes.HLOCAL))
def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event: None,
timeout_seconds=20, launcher_process=None):
"""Normally close our empty PCB after a diagnosed database startup failure.
No COM attach: there is no document, and the global ROT can name another
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
from .mentor_adapter import _process_details
from .native_repair_ui import _current_desktop_name
from .icdb_ownership import unreleased_addresses
root = Path(job['root'])
result = {'status': 'RETAINED', 'pcb_pid': pcb_pid}
result['release'] = {'pcb_exited': False, 'launcher_exited': launcher_process is None,
'safe_to_continue': False}
if launcher_process is not None:
result['launcher_pid'] = launcher_process.pid
try:
diagnosed = False
diagnosis_path = root/'diagnostics/icdb-recovery.json'
if diagnosis_path.is_file():
diagnosis = json.loads(diagnosis_path.read_text('utf-8'))
diagnosed = diagnosis.get('error_code') == 'ICDB_REPAIR_REQUIRED'
dialogs_path = root/'dialogs.jsonl'
if not diagnosed and dialogs_path.is_file():
for line in dialogs_path.read_text('utf-8').splitlines():
try:
dialog = json.loads(line)
except ValueError:
continue
if (dialog.get('pid') == pcb_pid and dialog.get('phase') == 'PCB_STARTING'
and dialog.get('error_code') == 'MENTOR_DATABASE_LOAD_FAILED'):
diagnosed = True
if not diagnosed:
raise ValueError('STARTUP_FAILURE_UNCONFIRMED')
desktop = job.get('desktop', '')
if (job.get('interactive_input') or not desktop.startswith('CbbVerify_')
or _current_desktop_name() != desktop):
raise ValueError('STARTUP_DESKTOP_UNCONFIRMED')
if not pcb_pid or pcb_pid in baseline_pids:
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
expected = os.path.normcase(os.path.abspath(job['pcb']))
deadline = time.monotonic() + max(0, timeout_seconds)
sent = False
while True:
records = [r for r in _process_details('ExpeditionPCB.exe') if r[0] == pcb_pid]
if not records:
addresses = unreleased_addresses(job['lmc_file'], job['project'], job['pcb'])
launcher_exited = launcher_process is None or launcher_process.poll() is not None
result['release'] = {'pcb_exited': True, 'launcher_exited': launcher_exited,
'addresses': addresses,
'safe_to_continue': launcher_exited and not addresses}
if result['release']['safe_to_continue']:
result['status'] = 'CLOSED'
result.pop('detail', None)
break
result['detail'] = 'STARTUP_RELEASE_UNCONFIRMED: 等待启动器退出和数据库地址释放'
if time.monotonic() >= deadline:
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:
windows = []
def observe(hwnd, _):
if (win32process.GetWindowThreadProcessId(hwnd)[1] == pcb_pid
and win32gui.IsWindowVisible(hwnd)):
windows.append(hwnd)
win32gui.EnumWindows(observe, None)
main = [w for w in windows if win32gui.GetClassName(w).startswith('Afx:')
and win32gui.GetWindowText(w).strip() in (
'Expedition PCB', 'Expedition PCB - Reusable Block')
and win32gui.IsWindowEnabled(w)]
observed = [{'hwnd': w, 'class': win32gui.GetClassName(w),
'title': win32gui.GetWindowText(w), 'enabled': bool(win32gui.IsWindowEnabled(w))}
for w in windows]
benign = [w for w in observed if w['title'] == '' and w['class'] in (
'UAC_InputIndicatorOverlayWnd', 'UAC Input Indicator')]
for window in observed:
if window['class'] == 'Internet Explorer_Hidden' and window['title'] == '':
window['rect'] = list(win32gui.GetWindowRect(window['hwnd']))
window['children'] = []
win32gui.EnumChildWindows(window['hwnd'],
lambda hwnd, _: window['children'].append(int(hwnd)), None)
left, top, right, bottom = window['rect']
if left == right and top == bottom and not window['children']:
benign.append(window)
unknown = [w for w in observed if w['hwnd'] not in main and w not in benign]
result.update(owned_windows=observed, unknown_windows=unknown,
benign_auxiliary_windows=benign)
documents = []
def child(hwnd, _):
if (win32gui.GetClassName(hwnd) == 'MDIClient'
and win32gui.GetWindow(hwnd, win32con.GW_CHILD)):
documents.append(hwnd)
if len(main) == 1:
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:
win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0)
sent = True
emit(stage='startup_close_requested', pcb_pid=pcb_pid, hwnd=main[0])
# Observe exit even when the caller requested no extra wait.
continue
result['detail'] = 'STARTUP_IDLE_UNCONFIRMED: 等待空闲窗口和数据库释放'
if time.monotonic() >= deadline:
if sent:
result['detail'] = 'STARTUP_EXIT_UNCONFIRMED: 已请求正常关闭,但 PCB 尚未退出'
break
time.sleep(.2)
except Exception as error:
result['detail'] = str(error)
(root/'startup-close.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
emit(stage='startup_close_result', **result)
return result
def close_failed_document(job, *, emit=lambda **event: None, timeout_seconds=30):
from .desktop_worker import launch_save_helper
root = Path(job['root'])
log_path = root/'failure-close.log'
command = [str(Path(os.environ.get('WINDIR', r'C:\Windows'))/'SysWOW64/cscript.exe'),
'//nologo', str(Path(__file__).with_name('close_failed_block.vbs')),
job['project'], Path(job['pcb']).name]
with log_path.open('w', encoding='utf-8') as log:
process = launch_save_helper(command, stdout=log, stderr=log)
emit(stage='failure_close_started', helper_pid=process.pid)
deadline = time.monotonic()+max(.1, float(timeout_seconds))
while process.poll() is None and time.monotonic() < deadline:
time.sleep(.2)
# A slow native Close can still be flushing. Retain the helper as well as
# PCB/iCDB; never force it to abandon the native call at this deadline.
text = log_path.read_text('utf-8', errors='replace')
result = {'status': ('CLOSED' if process.poll() == 0 and
all(marker in text.splitlines() for marker in ('FAILURE_CLOSE_OK', 'FAILURE_QUIT_OK'))
else 'RETAINED' if process.poll() is None else 'UNCONFIRMED'),
'helper_pid': process.pid, 'returncode': process.poll(), 'log': str(log_path)}
(root/'failure-close.json').write_text(json.dumps(result, indent=2), encoding='utf-8')
emit(stage='failure_close_result', **result)
return result
@@ -0,0 +1,35 @@
"""Reports for the explicit visible non-READY maintenance action."""
from dataclasses import asdict
import json
def maintenance_counts(results):
attempts = [attempt for result in results for attempt in result.recovery_attempts]
repaired = sum(attempt.get('status') == 'REPAIRED'
and attempt.get('native_status') == 'REPAIRED'
and attempt.get('validation_passed') is True
and result.status == 'PASS' and result.library_flag == 'GREEN'
and result.safe_to_continue
for result in results for attempt in result.recovery_attempts)
review = sum(attempt.get('status') == 'RESTORED_REVIEW_REQUIRED' for attempt in attempts)
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)
return {'total': len(results), 'passed': sum(r.status == 'PASS' 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}
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',
'library': str(requests[0].lmc_file), 'includes_ready': False,
'target_names': [request.block_name for request in requests],
'shared_database_repair_supported': False,
'preflight_skipped': sorted(skipped_names), 'counts': maintenance_counts(results),
'results': [{'block': req.block_name, **asdict(result)}
for req, result in zip(requests, results)]}
path.write_text(json.dumps(record, ensure_ascii=False, default=str, indent=2), encoding='utf-8')
return path
+16
View File
@@ -0,0 +1,16 @@
"""Known native database owners touched by a CBB verification operation."""
from pathlib import Path
def database_directories(lmc_file, project, pcb):
return tuple(dict.fromkeys((
Path(project).parent/'database',
Path(pcb).parent/'database',
Path(lmc_file).parent/'SymbolLibs/__ReusableBlocksSymb',
)))
def unreleased_addresses(lmc_file, project, pcb):
return [str(path/'cdbsvr/sAddress.adr')
for path in database_directories(lmc_file, project, pcb)
if (path/'cdbsvr/sAddress.adr').exists()]
+144
View File
@@ -0,0 +1,144 @@
"""Recognize native iCDB recovery requests without changing database state."""
import hashlib
import ntpath
from pathlib import Path
import re
ERROR_CODE = 'ICDB_REPAIR_REQUIRED'
LOG_LIMIT = 128 * 1024
RECOVERY_ACTION = (
'停止批次并确认原服务器及其他客户端已正常关闭;保留完整一致副本后,'
"使用同版本 iCDB Project Backup 的 Repair project 检查并修复正确目标。"
'共享符号库问题需核对中心库,不能只修复单个 CBB 的 Work 工程。'
'不要删除 sAddress.adr/锁文件;修复后重新打开、校验并确认权威 READY。'
)
_SESSION_LOSS = re.compile(
r'\bthe\s+last\s+server\s+session\s+on\s+different\s+server\s+machine\s+'
r'lost\s+the\s+connection\s+to\s+the\s+database\b', re.IGNORECASE)
def parse_session_loss(text):
"""Keep the native target verbatim; never infer a local repair target."""
text = str(text or '')
match = _SESSION_LOSS.search(text)
if match is None:
return None
# A log may contain several sessions. Use the identity following this
# error, never an unrelated Machine/Path header earlier in the log.
message = text[match.start():]
next_error = _SESSION_LOSS.search(message, 1)
if next_error:
message = message[:next_error.start()]
record = {'error_code': ERROR_CODE, 'native_message': message,
'machine': '', 'database_path': '', 'session': '', 'scope': 'unknown'}
for native_key, key in (('machine', 'machine'), ('path', 'database_path'),
('session', 'session')):
field = re.search(
rf'\b{native_key}\s*:\s*(?:\[([^\]]*)\]|([^\r\n]*?)(?=\s+\b(?:machine|path|session)\s*:|[\r\n]|$))',
message, re.IGNORECASE)
if field:
record[key] = (field.group(1) if field.group(1) is not None else field.group(2)).strip()
parts = ntpath.normpath(record['database_path']).casefold().split('\\')
if 'symbollibs' in parts:
record['scope'] = 'central_library'
elif 'work' in parts and parts[-1] == 'database':
record['scope'] = 'project'
return record
def recovery_detail(record):
target = ('中心库共享符号数据库' if record['scope'] == 'central_library' else
'工程数据库' if record['scope'] == 'project' else '报错中指定的数据库')
return (
f"{ERROR_CODE}: {target}的上次服务器会话失联。\n"
f"{record['native_message']}\n"
f'{RECOVERY_ACTION}'
)
def snapshot_log(path):
"""Fingerprint a bounded tail before launch, including a missing log."""
try:
with Path(path).open('rb') as stream:
stream.seek(0, 2)
size = stream.tell()
stream.seek(max(0, size-LOG_LIMIT))
tail = stream.read(LOG_LIMIT)
losses = [_session_identity(record) for record in _session_losses(decode_log(tail))]
return {'size': size, 'tail_sha256': hashlib.sha256(tail).hexdigest(),
'truncated': size > LOG_LIMIT,
'session_losses': losses}
except FileNotFoundError:
return {'size': 0, 'tail_sha256': hashlib.sha256(b'').hexdigest()}
except OSError as error:
return {'error': str(error)}
def _read_log_delta(path, baseline):
"""Read new bytes, detecting truncate/rewrite as well as append.
Unknown baselines cannot prove freshness. At most two bounded tails are
read, even when a native log is large or located on a network share.
"""
if not baseline or 'error' in baseline:
return b'', False
old_size = int(baseline['size'])
try:
with Path(path).open('rb') as stream:
stream.seek(0, 2)
size = stream.tell()
offset = 0
appended = False
if size >= old_size:
stream.seek(max(0, old_size-LOG_LIMIT))
old_tail = stream.read(min(old_size, LOG_LIMIT))
if hashlib.sha256(old_tail).hexdigest() == baseline['tail_sha256']:
offset = old_size
appended = True
stream.seek(max(offset, size-LOG_LIMIT))
return stream.read(LOG_LIMIT), appended
except OSError:
return b'', False
def _session_losses(text):
matches = list(_SESSION_LOSS.finditer(text))
for index, match in enumerate(matches):
end = matches[index+1].start() if index+1 < len(matches) else len(text)
yield parse_session_loss(text[match.start():end])
def _session_identity(record):
return [record[key] for key in ('machine', 'database_path', 'session')]
def read_log_failure(path, baseline):
"""Return new log text and a recovery request with evidence of freshness.
A rewritten header does not prove that a retained old session failed
again. In that ambiguous case keep the generic failure; a verified append
can report even the same old session as a current native error.
"""
data, appended = _read_log_delta(path, baseline)
text = decode_log(data)
if not appended and baseline and baseline.get('truncated'):
# A rewrite may expose an old error outside our bounded baseline.
# Without positive append evidence its age cannot be established.
return text, None
historical = baseline.get('session_losses', []) if baseline else []
recovery = next((record for record in _session_losses(text)
if appended or _session_identity(record) not in historical), None)
return text, recovery
def decode_log(data):
if data.startswith((b'\xff\xfe', b'\xfe\xff')):
return data.decode('utf-16', errors='replace')
# Appended UTF-16 bytes and bounded tails no longer contain a BOM.
sample = data[:200]
if sample[1::2].count(0) > len(sample)//8:
return data.decode('utf-16-le', errors='replace')
if sample[::2].count(0) > len(sample)//8:
return data.decode('utf-16-be', errors='replace')
return data.decode('utf-8', errors='replace')
+388
View File
@@ -0,0 +1,388 @@
"""Uploader-compatible exclusive sidecar lease. Metadata never proves ownership."""
from datetime import datetime, timezone
from contextlib import contextmanager, ExitStack
import json
import re
import os
from pathlib import Path
import socket
import threading
from uuid import uuid4
_guard = threading.RLock()
_owners = {}
class LibraryBusy(OSError):
pass
def _key(path):
return str(Path(path).resolve()).casefold()
def blocker_path(library):
library = Path(library).resolve()
return library.with_name('.' + library.stem + '.cbb-upload.blocked.json')
def checkpoint_record(path):
"""Recognize only our reserved filename and complete versioned protocol."""
path = Path(path)
if not (path.name.endswith('.cbb-upload.blocked.json') or path.name.endswith('.cbb-upload.blocked.pending')):
return None
try:
import stat
if path.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
return None
record = json.loads(path.read_text(encoding='utf-8'))
library = Path(record['library'])
expected = '.' + library.stem + '.cbb-upload.blocked'
if (record.get('protocol') != 'cbb-refresh-verify-library-lease' or record.get('version') != 1
or not library.is_absolute() or library.suffix.casefold() != '.lmc'
or path.name not in (expected+'.json', expected+'.pending')
or not re.fullmatch('[0-9a-f]{32}', str(record.get('lease_id', '')))
or not isinstance(record.get('pid'), int) or record['pid'] <= 0
or record.get('status') not in ('OPERATION_IN_PROGRESS', 'OWNER_RELEASE_UNCONFIRMED')
or not isinstance(record.get('time'), str)):
return None
return record
except (OSError, ValueError, TypeError, KeyError):
return None
def has_blocker(library):
path = blocker_path(library)
if path.with_suffix('.pending').exists():
return True
if not path.exists():
return False
record = checkpoint_record(path)
# Complete snapshots retain every file, including their source lease
# checkpoint. Only a valid relocated snapshot record can be ignored.
return record is None or _key(record['library']) == _key(library)
def _persist_blocker(library, status='OWNER_RELEASE_UNCONFIRMED', *, lease_id):
path = blocker_path(library)
pending = path.with_suffix('.pending')
previous = checkpoint_record(path)
export_record = ({'export_analysis': previous['export_analysis']}
if previous and previous['lease_id'] == lease_id and 'export_analysis' in previous else {})
with pending.open('w', encoding='utf-8') as stream:
json.dump({**export_record, 'protocol': 'cbb-refresh-verify-library-lease', 'version': 1,
'lease_id': lease_id, 'library': str(library), 'status': status,
'pid': os.getpid(), 'time': datetime.now(timezone.utc).isoformat()}, stream)
stream.flush(); os.fsync(stream.fileno())
pending.replace(path)
class LibraryLock:
def __init__(self, library, *, safe_to_release=None):
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.maintenance_guard = None
self.maintenance_mutex = None
@classmethod
def for_maintenance(cls, library, archive, guard, *, safe_to_release=None):
lease = cls(library, safe_to_release=safe_to_release)
lease.maintenance_guard = guard
lease.maintenance_archive = Path(archive)
return lease
def __enter__(self):
if self.maintenance_guard is not None:
return _enter_maintenance(self)
import win32con, win32file
with _guard:
owner = _owners.get(self.key)
if owner:
if owner['thread'] != threading.get_ident() or owner['retained']:
raise LibraryBusy(f'中心库被其他任务占用:{self.path}')
owner['depth'] += 1
else:
if has_blocker(self.library):
raise LibraryBusy(f'中心库存在未解除的会话阻止记录,请先执行释放检查:{blocker_path(self.library)}')
try:
lease_id = uuid4().hex
handle = win32file.CreateFile(str(self.path),
win32con.GENERIC_READ | win32con.GENERIC_WRITE, 0, None,
win32con.OPEN_ALWAYS, win32con.FILE_ATTRIBUTE_NORMAL, None)
except Exception as error:
raise LibraryBusy(f'中心库已锁定或无法创建协调锁:{self.path}: {error}') from error
try:
data = (f'machine={socket.gethostname()}; pid={os.getpid()}; '
f'startedUtc={datetime.now(timezone.utc).isoformat()}; '
f'library={self.library}').encode('utf-8')
win32file.SetFilePointer(handle, 0, win32con.FILE_BEGIN)
win32file.SetEndOfFile(handle)
win32file.WriteFile(handle, data)
win32file.FlushFileBuffers(handle)
# Closing flushes the last-write timestamp on Windows. Set
# 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)
except Exception:
handle.Close()
raise
_owners[self.key] = {'thread': threading.get_ident(), 'depth': 1,
'handle': handle, 'retained': False, 'lease_id': lease_id}
self.entered = True
return self
def snapshot_bytes(self):
data = owned_snapshot(self.path)
if data is None:
raise LibraryBusy('当前线程不拥有此库协调锁')
return data
def retain(self):
with _guard:
if self.entered:
_owners[self.key]['retained'] = True
def __exit__(self, *_):
try:
self._exit_owned()
finally:
if self.maintenance_mutex is not None:
import win32event
win32event.ReleaseMutex(self.maintenance_mutex)
self.maintenance_mutex.Close()
self.maintenance_mutex = None
def _exit_owned(self):
with _guard:
if not self.entered:
return
owner = _owners[self.key]
checkpoint = checkpoint_record(blocker_path(self.library))
if checkpoint is not None and 'export_analysis' in checkpoint:
owner['retained'] = True
if self.safe_to_release is not None:
try:
safe = self.safe_to_release() is True
except Exception:
safe = False
if not safe:
# A supervisor can time out while its native child still
# owns the DB. Keep excluding the uploader until app exit.
owner['retained'] = True
owner['depth'] -= 1
self.entered = False
if owner['depth'] == 0 and not owner['retained']:
# This JSON is our durable operation checkpoint, not the
# uploader's .lock file. Clear only after proven normal release.
marker = blocker_path(self.library)
record = checkpoint_record(marker)
if marker.exists() and (record is None or record['lease_id'] != owner['lease_id']):
owner['retained'] = True
raise LibraryBusy('协调检查点被替换或损坏,保留冲突文件及库锁。')
try:
marker.unlink(missing_ok=True)
except OSError:
owner['retained'] = True
raise
owner['handle'].Close()
del _owners[self.key]
elif owner['retained']:
marker = blocker_path(self.library)
record = checkpoint_record(marker)
if marker.exists() and (record is None or record['lease_id'] != owner['lease_id']):
raise LibraryBusy('协调检查点被替换或损坏,保留冲突文件及库锁。')
_persist_blocker(self.library, lease_id=owner['lease_id'])
def _supervisor_alive(pid):
import pywintypes, win32api, win32con, win32event
try:
handle = win32api.OpenProcess(win32con.SYNCHRONIZE, False, int(pid))
except pywintypes.error as error:
if error.winerror == 87: return False
raise LibraryBusy('无法确认原监督进程退出') from error
try:
return win32event.WaitForSingleObject(handle, 0) != win32con.WAIT_OBJECT_0
finally:
handle.Close()
def _enter_maintenance(lease):
"""Transfer only a valid known lease, after project admission under lock."""
import win32con, win32event, win32file
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = False
handle = None
existing = None
try:
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired: raise LibraryBusy('已有 CBB 操作运行,维护不能接续')
with _guard:
marker = blocker_path(lease.library)
if marker.with_suffix('.pending').exists():
raise LibraryBusy('未完成检查点写入,不能自动接续')
old = marker.read_bytes() if marker.exists() else None
record = checkpoint_record(marker) if old is not None else None
if old is not None and (record is None or _key(record['library']) != _key(lease.library)):
raise LibraryBusy('维护拒绝未知、损坏或其他库的检查点')
existing = _owners.get(lease.key)
if existing:
if (not existing['retained'] or existing['depth'] != 0 or record is None
or record['pid'] != os.getpid() or record['lease_id'] != existing['lease_id']):
raise LibraryBusy('本进程库锁仍在使用或检查点身份不符')
handle = existing['handle']
else:
if record is not None 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)
# All target/process/address/exclusive-file checks finish BEFORE
# any old checkpoint replacement. Keep the exact sidecar open.
from .native_export_guard import prove_export_copies_released
with prove_export_copies_released(lease.library), lease.maintenance_guard() as proof:
if (marker.read_bytes() if marker.exists() else None) != old:
raise LibraryBusy('维护检查期间检查点变化')
if old is not None:
lease.maintenance_archive.mkdir(parents=True, exist_ok=False)
saved = lease.maintenance_archive/'previous-checkpoint.json'
with saved.open('xb') as stream:
stream.write(old); stream.flush(); os.fsync(stream.fileno())
if saved.read_bytes() != old: raise OSError('原检查点归档校验失败')
lease_id = uuid4().hex
_persist_blocker(lease.library, 'OPERATION_IN_PROGRESS', lease_id=lease_id)
_owners[lease.key] = {'thread': threading.get_ident(), 'depth': 1, 'handle': handle,
'retained': False, 'lease_id': lease_id}
lease.maintenance_proof = proof
lease.entered = True
lease.maintenance_mutex = mutex
return lease
except Exception:
if handle is not None and existing is None: handle.Close()
if acquired: win32event.ReleaseMutex(mutex)
mutex.Close()
raise
def owned_snapshot(path):
"""Read only a lease held by this thread, never reopen an exclusive file."""
import win32con, win32file
with _guard:
owner = _owners.get(_key(path))
if not owner or owner['thread'] != threading.get_ident() or owner['retained']:
return None
handle = owner['handle']
position = win32file.SetFilePointer(handle, 0, win32con.FILE_CURRENT)
try:
win32file.SetFilePointer(handle, 0, win32con.FILE_BEGIN)
size = win32file.GetFileSize(handle)
return win32file.ReadFile(handle, size)[1] if size else b''
finally:
win32file.SetFilePointer(handle, position, win32con.FILE_BEGIN)
@contextmanager
def _prove_library_released(library):
"""Hold all native database read handles during explicit lease release."""
import pythoncom, win32com.client, win32con, win32file
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
from .native_engineering_identity import _OWNER_NAMES
assert_retained_exports_idle()
if any(worker.poll() is None for worker in _retained_workers):
raise LibraryBusy('原生管理工作进程尚未返回,不能解除协调阻止。')
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}')
entries = scan_tree(Path(library).parent)
addresses = [str(path) for path in entries if path.name.casefold() == 'saddress.adr']
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'))]
if Path(library).resolve() not in native:
raise LibraryBusy('目标库身份缺失,不能解除协调阻止。')
with ExitStack() as stack:
export_copies = stack.enter_context(prove_export_copies_released(library))
for path in native:
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
stack.callback(handle.Close)
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):
"""Explicit user-requested release, after fresh owner/address/access proof.
The upload sidecar is never deleted. This acknowledges process release,
not the correctness of a partially changed library or its recovery state.
"""
import win32con, win32event, win32file
library = Path(library).resolve(strict=True)
evidence = Path(evidence_dir).resolve()
if evidence.is_relative_to(library.parent) or library.parent.is_relative_to(evidence):
raise ValueError('释放检查证据必须位于目标库之外。')
lease = LibraryLock(library)
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = False
external = None
try:
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired:
raise LibraryBusy('另一个 CBB 操作仍在运行。')
with _guard:
owner = _owners.get(lease.key)
if owner and (not owner['retained'] or owner['depth']):
raise LibraryBusy('本应用操作仍在使用库锁。')
if owner is None:
try:
external = win32file.CreateFile(str(lease.path),
win32con.GENERIC_READ | win32con.GENERIC_WRITE, 0, None,
win32con.OPEN_ALWAYS, win32con.FILE_ATTRIBUTE_NORMAL, None)
except Exception as error:
raise LibraryBusy('其他进程仍持有库锁,不能解除。') from error
with _prove_library_released(library) 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):
raise LibraryBusy('协调检查点格式不明或已损坏,保留原文件供人工审查。')
root = evidence/('release-' + uuid4().hex)
root.mkdir(parents=True, exist_ok=False)
record = {'library': str(library), 'status': 'RELEASE_CONFIRMED', **proof,
'data_recovery_confirmed': False, 'evidence_path': str(root/'release.json')}
(root/'release.json').write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
for index, checkpoint in enumerate(checkpoints):
if checkpoint.exists():
data = checkpoint.read_bytes()
archived = root/f'blocker-before-{index}.json'
archived.write_bytes(data)
if archived.read_bytes() != data:
raise OSError('阻止记录归档校验失败,保持库锁。')
checkpoint.unlink() # Checkpoint JSON only; never .lock.
if owner:
owner['handle'].Close()
del _owners[lease.key]
return record
finally:
if external is not None:
external.Close()
if acquired:
win32event.ReleaseMutex(mutex)
mutex.Close()
+226
View File
@@ -0,0 +1,226 @@
"""User-requested native inspection of a project with 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.
"""
from contextlib import contextmanager, ExitStack
from dataclasses import asdict, replace
import json
import os
from pathlib import Path, PureWindowsPath
import re
from uuid import uuid4
def assert_native_idle():
import win32com.client
from .native_management import _retained_workers
from .native_export_guard import assert_retained_exports_idle
from .native_engineering_identity import _OWNER_NAMES
assert_retained_exports_idle()
if any(worker.poll() is None for worker in _retained_workers):
raise ValueError('MAINTENANCE_OWNER_ACTIVE: 管理工作进程尚未返回')
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():
continue
name, command = str(item.Name).casefold(), str(item.CommandLine or '').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)})
if owners:
raise ValueError(f'MAINTENANCE_OWNER_ACTIVE: 请正常关闭原生程序/操作助手:{owners}')
def address_snapshot(paths):
from .scoped_manifest import hash_file
return {str(path.resolve()): {'sha256': hash_file(path), 'size': path.stat().st_size,
'mtime_ns': path.stat().st_mtime_ns}
for path in paths}
def _scoped_addresses(request):
from .scoped_manifest import scan_tree
root = Path(request.lmc_file).parent
addresses = []
for path in scan_tree(root):
if path.name.casefold() != 'saddress.adr':
continue
parts = tuple(part.casefold() for part in path.relative_to(root).parts)
independent = (len(parts) >= 6 and parts[0] == 'reusableblockslp'
and parts[1] != request.block_name.casefold() and parts[2] == 'work'
and parts[3:] in (('database', 'cdbsvr', 'saddress.adr'),
('pcb', 'database', 'cdbsvr', 'saddress.adr')))
if not independent:
# Current project and shared/unknown scopes remain visible to the
# selector; only exact independent other-CBB Work stores are omitted.
addresses.append(path)
return addresses
def select_maintenance_target(request):
from .verify_runner import preflight
from .backup_recovery import _project_text
from .native_repair import RepairTarget
from .scoped_manifest import scan_tree
if request.maintenance is not True:
raise ValueError('MAINTENANCE_INTENT_REQUIRED')
project, pcb = preflight(request)
scan_tree(project.parent)
candidates = []
for candidate in (project, pcb.parent/'pcb.prj'):
if not candidate.is_file():
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED: 缺少工程配置')
text = _project_text(candidate)
values = re.findall(r'^KEY iCDBDir "([^"]*)"', text, re.M)
if candidate != project and not re.search(r'^KEY iCDBDir\b', text, re.M):
continue
if (len(values) != 1 or not values[0] or PureWindowsPath(values[0]).drive
or PureWindowsPath(values[0]).root):
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED: iCDBDir 必须唯一且为工程内相对路径')
database = (candidate.parent/values[0]).resolve()
# The proven Project Backup route binds PRJ.parent/database; do not
# guess alternate stores or route shared data through another PRJ.
if database != (candidate.parent/'database').resolve() or not database.is_relative_to(project.parent.resolve()):
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED: 未验证的 PRJ 数据库映射')
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)
if len(addresses) != 1:
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED: 需要唯一工程地址记录;共享或多个数据库不能推测修复')
matches = [target for target in candidates
if (target.database/'cdbsvr/sAddress.adr').resolve() == addresses[0].resolve()]
if len(matches) != 1:
raise ValueError('SHARED_DATABASE_REPAIR_UNSUPPORTED: 地址记录不属于唯一匹配的工程数据库')
return matches[0], project, pcb, addresses
@contextmanager
def maintenance_target_guard(request, expected=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)
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')}}
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'))]
with ExitStack() as stack:
for path in files:
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)
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_existing_address_maintenance(request, *, verify, progress=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 .verify_runner import VerifyResult
root = Path(request.evidence_dir).resolve()/('maintenance-' + 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('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'}
report = root/'result.json'
owner_safe = False
recovery = None
def emit(stage, **values):
record['stage'] = stage
if progress: progress({'stage': stage, 'block': request.block_name, **values})
def save(result):
result = replace(result, evidence_path=report)
record['result'] = asdict(result)
report.write_text(json.dumps(record, ensure_ascii=False, default=str, indent=2), encoding='utf-8')
return result
try:
lease = LibraryLock.for_maintenance(request.lmc_file, root/'takeover',
lambda: maintenance_target_guard(request), safe_to_release=lambda: owner_safe)
with lease:
checked = lease.maintenance_proof
target, context = checked['target'], checked['context']
record['maintenance_context'] = context
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
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()
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)
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,)))
if recovery.get('status') == 'REPAIRED':
recovery['status'] = 'UNCONFIRMED'; owner_safe = False
return save(VerifyResult('FAIL', stderr=f'{recovery["status"]}: {recovery.get("detail", "原生维护未确认修复")}',
safe_to_continue=owner_safe, recovery_attempts=(recovery,), error_category='ICDB_MAINTENANCE_RESULT'))
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'))
+363
View File
@@ -0,0 +1,363 @@
"""Checkpointed CBB mutations with native evidence and no automatic replay."""
from dataclasses import asdict, dataclass, field, replace
from datetime import datetime, timezone
import json
from pathlib import Path, PureWindowsPath
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
@dataclass(frozen=True)
class Capability:
supported: bool
reason: str
@dataclass(frozen=True)
class ManagementRequest:
operation: str
library: Path
name: str
partition: str = 'Logical-Physical'
source: Path | None = None
auto_verify: bool = True
evidence_dir: Path = Path('management-evidence')
top_level_block: str = ''
timeout_seconds: float = 180
mapped_drive: str = ''
mapped_remote_root: str = ''
transaction_token: str = ''
@dataclass(frozen=True)
class CatalogEntry:
name: str
partition: str
engineering_identity: dict = field(default_factory=dict)
@dataclass(frozen=True)
class Catalog:
library: Path
flow: int
entries: tuple[CatalogEntry, ...]
safe_to_continue: bool = True
@dataclass(frozen=True)
class NativeOutcome:
success: bool
safe_to_continue: bool
detail: str
identity_matches: bool | None = None
evidence_path: Path | None = None
identity_proof: dict | None = None
@dataclass(frozen=True)
class ManagementResult:
operation: str
library: Path
name: str
partition: str
source: Path | None
auto_verify: bool
stage: str
status: str
safe_to_continue: bool
detail: str = ''
evidence_path: Path | None = None
def validate_name(value):
if (not value or value != value.strip() or value.endswith('.') or value in ('.', '..')
or any(ord(c) < 32 or c in '<>:"/\\|?*' for c in value)
or value.split('.')[0].upper() in {'CON', 'PRN', 'AUX', 'NUL',
*(f'COM{i}' for i in range(1, 10)), *(f'LPT{i}' for i in range(1, 10))}):
raise ValueError('CBB 名称/分区不是有效单一名称,禁止路径、控制字符或保留名称。')
def source_project(source, top_level_block=''):
"""Require complete PRJ/PCB and self-contained engineering references."""
from .backup_recovery import _project_text
source = Path(source).resolve(strict=True)
if source.suffix.casefold() != '.prj' or not source.is_file():
raise ValueError('请选择完整工程的 PRJ 文件。')
scan_tree(source.parent) # Reject reparse points, including file links.
text = _project_text(source)
roots = re.findall(r'^KEY RootBlock "([^"]+)"', text, re.M)
if len(roots) != 1 or top_level_block and roots[0] != top_level_block:
raise ValueError('工程顶层块不唯一或与输入不一致。')
validate_name(roots[0])
def reference(path, key):
values = re.findall(r'^KEY ' + re.escape(key) + r' "([^"]+)"', _project_text(path), re.M)
if len(values) != 1 or PureWindowsPath(values[0]).is_absolute() or PureWindowsPath(values[0]).drive:
raise ValueError(f'{key} 必须为唯一工程内相对引用。')
resolved = (path.parent/values[0]).resolve()
if not resolved.is_relative_to(source.parent):
raise ValueError(f'{key} 越出来源工程。')
return resolved
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'):
if not path.is_file():
raise ValueError('工程缺少 PCB 工程配置。')
# Healthy Expedition PCB projects can use Layout/LayoutDB.lyt without
# declaring an independent iCDBDir. The schematic DB stays mandatory;
# an explicitly declared PCB DB must still pass every reference check.
if path != source and not re.search(r'^KEY iCDBDir\b', _project_text(path), re.M):
continue
db = reference(path, 'iCDBDir')
if not (db/'icdb.dat').is_file():
raise ValueError('工程缺少原理图/PCB 数据库。')
if not (pcb.parent/'Layout/LayoutDB.lyt').is_file():
raise ValueError('工程缺少布局数据库。')
return source, pcb, roots[0]
def engineering_identity(source):
"""Compare actual registered engineering bytes, not a name-only acknowledgment.
Conservative until native normalization has an independently proven semantic
comparison: changed database bytes cannot be claimed to match the source.
"""
source, pcb, top = source_project(source)
from .backup_recovery import _project_text
db = re.findall(r'^KEY iCDBDir "([^"]+)"', _project_text(source), re.M)[0]
return {'top_level_block': top, 'schematic_sha256': hash_file(source.parent/db/'icdb.dat'),
'layout_sha256': hash_file(pcb.parent/'Layout/LayoutDB.lyt')}
def _write_json(path, value):
path = Path(path)
pending = path.with_suffix('.pending')
with pending.open('w', encoding='utf-8') as stream:
json.dump(value, stream, ensure_ascii=False, default=str, indent=2)
stream.flush()
import os
os.fsync(stream.fileno())
pending.replace(path)
def unfinished_operations(root):
results = []
for path in sorted(Path(root).glob('*/checkpoint.json')):
try:
record = json.loads(path.read_text(encoding='utf-8'))
if record.get('stage') != 'complete' or record.get('safe_to_continue') is False:
results.append({**record, 'evidence_path': str(path)})
except (OSError, ValueError):
results.append({'status': 'CHECKPOINT_UNREADABLE', 'evidence_path': str(path)})
return results
def run_management(request, *, adapter=None, verifier=None, idle_check=None, progress=None):
from .verify_runner import VerifyRequest, run_verify
from .backup_recovery import _idle_check
import win32con, win32event
import pythoncom
if adapter is None:
from .native_management import NativeManagementAdapter
adapter = NativeManagementAdapter()
verifier = verifier or run_verify
idle_check = idle_check or _idle_check
root = report = None
stage = 'preflight'
history = []
mutated = uploaded = removed = False
owner_safe = True
mutex = None
acquired = False
def checkpoint(next_stage, **details):
nonlocal stage
stage = next_stage
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})
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})
return result
from .com_runtime import initialize_com, uninitialize_com
initialized = initialize_com()
try:
if request.operation not in ('add', 'update', 'remove'):
raise ValueError('不支持的管理操作。')
validate_name(request.name); validate_name(request.partition)
from .network_path import absolute_preserving_drive
library = absolute_preserving_drive(request.library)
canonical_library = library.resolve(strict=True)
library_root = canonical_library.parent
if library.suffix.casefold() != '.lmc' or not library.is_file():
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('操作记录与备份必须位于目标中心库之外,且不能包含目标库。')
capability = adapter.capabilities().get(request.operation, Capability(False, '未验证的原生接口'))
if not capability.supported:
return finish('UNSUPPORTED', capability.reason)
for unfinished in unfinished_operations(evidence):
if unfinished.get('library') and Path(unfinished['library']).resolve() == canonical_library:
return finish('BLOCKED', f'存在未完成/需恢复任务,禁止自动重放:{unfinished["evidence_path"]}', False)
source = pcb = None
if request.operation in ('add', 'update'):
if request.source is None:
raise ValueError('新增/更新需要完整来源工程。')
source, pcb, top = source_project(request.source, request.top_level_block)
if (source.parent.is_relative_to(library_root) or library_root.is_relative_to(source.parent)
or evidence.is_relative_to(source.parent)
or source.parent.is_relative_to(evidence)):
raise ValueError('来源工程、目标库与操作证据必须使用独立目录。')
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired:
return finish('BLOCKED', '已有 CBB 校验/管理/恢复任务运行。', False)
if hasattr(adapter, 'bind_library_mapping'):
adapter.bind_library_mapping(request.mapped_drive, request.mapped_remote_root)
with LibraryLock(library, safe_to_release=lambda: owner_safe):
root = evidence/('management-' + uuid4().hex)
root.mkdir(parents=True, exist_ok=False)
report = root/'checkpoint.json'
work = library.parent/'ReusableBlocksLP'/request.name/'Work'
target_project, target_pcb = work/(request.name+'.prj'), work/'PCB/pcb.pcb'
if request.operation != 'add':
# Read actual engineering references when available; fallback
# paths still permit removal of catalog entries missing Work.
from .verify_runner import preflight
try:
target_project, target_pcb = preflight(VerifyRequest(library, request.name, root))
except ValueError:
pass
idle_check(library, target_project, target_pcb)
if source:
idle_check(library, source, pcb)
checkpoint('catalog_before')
owner_safe = False
before = adapter.catalog(library, root/'before')
owner_safe = before.safe_to_continue
if not owner_safe or Path(before.library).resolve() != canonical_library or before.flow != 1:
return finish('BLOCKED', '原生目录身份/流程或所有者释放未确认。仅支持已验证 DxDesigner 流程。', owner_safe)
same_name = [entry for entry in before.entries if entry.name.casefold() == request.name.casefold()]
matches = [entry for entry in same_name if entry.partition == request.partition and entry.name == request.name]
if request.operation == 'add' and same_name:
return finish('UPLOAD_FAILED', '同名 CBB 已存在;新增禁止覆盖,请使用明确的同名更新。')
if request.operation != 'add' and len(matches) != 1:
return finish('BLOCKED', '目标名称和分区必须与原生目录唯一匹配。')
if hasattr(adapter, 'preflight'):
adapter.preflight(request, before)
# 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)
staged = request
identity = None
if source:
checkpoint('stage_source')
source_manifest = copy_verified(source.parent, root/'source', progress=progress)
_write_json(root/'source-manifest.json', source_manifest)
staged = replace(request, source=root/'source'/source.name, top_level_block=top)
identity = engineering_identity(staged.source)
if build_manifest(source.parent) != source_manifest:
raise OSError('来源工程在暂存期间变化。')
if source and hasattr(adapter, 'prepare_add_transaction'):
checkpoint('prepare_identity')
owner_safe = False
staged, proof = adapter.prepare_add_transaction(staged, root, original_source=source)
owner_safe = proof.safe_to_continue
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 request.operation in ('remove', 'update'):
checkpoint('native_remove')
mutated = True; owner_safe = False
native = adapter.remove(request, root/'remove')
owner_safe = native.safe_to_continue
if not owner_safe or not native.success:
return finish('RECOVERY_REQUIRED', native.detail, False)
owner_safe = False
idle_check(library, target_project, target_pcb)
owner_safe = False
after = adapter.catalog(library, root/'after-remove')
owner_safe = after.safe_to_continue
if (not owner_safe or Path(after.library).resolve() != canonical_library or after.flow != 1
or any(e.name == request.name and e.partition == request.partition for e in after.entries)):
return finish('RECOVERY_REQUIRED', '原生移除后目录未确认目标缺失。', False)
removed = True
checkpoint('removed')
if request.operation == 'remove':
return finish('REMOVED', '已备份并由原生操作移除,重新读取目录确认不存在。')
checkpoint('native_add')
mutated = True; owner_safe = False
native = adapter.add(staged, root/'add')
owner_safe = native.safe_to_continue
if not owner_safe or not native.success:
return finish('RECOVERY_REQUIRED' if removed or not owner_safe else 'UPLOAD_FAILED',
native.detail, owner_safe and not removed)
owner_safe = False
idle_check(library, target_project, target_pcb)
after = adapter.catalog(library, root/'after-add')
owner_safe = after.safe_to_continue
matches = [entry for entry in after.entries if entry.name == request.name
and entry.partition == request.partition]
proof_matches = (native.identity_matches is True and native.identity_proof == identity
if hasattr(adapter, 'prepare_add_transaction') else
len(matches) == 1 and matches[0].engineering_identity == identity)
if (not owner_safe or Path(after.library).resolve() != canonical_library or after.flow != 1
or len(matches) != 1 or not proof_matches):
return finish('RECOVERY_REQUIRED', '原生新增后名称、分区或来源工程内容未确认一致。', False)
uploaded = True
checkpoint('uploaded')
if not request.auto_verify:
return finish('UPLOADED', '上传已确认;本批次未启用自动校验。')
# Adapter catalog cannot return until its exact native owner exits.
checkpoint('verify')
owner_safe = False
verified = verifier(VerifyRequest(library, request.name, root/'verify',
mapped_drive=request.mapped_drive, mapped_remote_root=request.mapped_remote_root), progress=progress)
owner_safe = verified.safe_to_continue
checkpoint('verified', verification=asdict(verified))
good = verified.status == 'PASS' and verified.library_flag == 'GREEN' and owner_safe
return finish('UPLOADED_VERIFIED' if good else 'UPLOADED_VERIFY_FAILED',
verified.stderr or verified.library_flag_detail, owner_safe)
except Exception as error:
if uploaded:
return finish('UPLOADED_VERIFY_FAILED', str(error), False)
status = 'RECOVERY_REQUIRED' if mutated else ('UPLOAD_FAILED' if request.operation in ('add', 'update') else 'BLOCKED')
# Bad input is never described as a native upload attempt.
if root is None and isinstance(error, ValueError):
status = 'BLOCKED'
return finish(status, str(error), not mutated and owner_safe and not isinstance(error, LibraryBusy))
finally:
if mutex is not None:
if acquired:
win32event.ReleaseMutex(mutex)
mutex.Close()
uninitialize_com(initialized)
def run_management_batch(requests, *, stop=None, progress=None, **kwargs):
results = []
for request in requests:
if stop is not None and stop.is_set():
break
result = run_management(request, progress=progress, **kwargs)
results.append(result)
if progress:
progress({'stage': result.status, 'block': result.name, 'detail': result.detail,
'evidence_path': str(result.evidence_path or '')})
if not result.safe_to_continue:
break
return results
@@ -0,0 +1,127 @@
"""Prepared Add authority bound to the engine checkpoint, snapshot and live lease."""
import json
import os
from pathlib import Path
import threading
from uuid import uuid4
from .management import _write_json, engineering_identity
from .scoped_manifest import build_manifest, ManifestScope
def _read(path):
return json.loads(Path(path).read_text(encoding='utf-8'))
def fixture_authority(root, library, token):
root = Path(root).resolve()
expected = root/'native-add/fixture/mentor_lib.lmc'
owner = _read(root/'probe-owner.json')
if (not token or owner.get('token') != token or not expected.is_file()
or Path(library).resolve() != expected.resolve()
or Path(owner.get('library', '')).resolve() != expected.resolve()):
raise ValueError('Management research requires the exact newly created owned fixture.')
return {'root': str(root), 'token': token}
def current_lease(library):
from .library_lock import LibraryLock, _guard, _owners, blocker_path, checkpoint_record
lease = LibraryLock(library)
with _guard:
owner = _owners.get(lease.key)
guard = checkpoint_record(blocker_path(library))
if (owner is None or owner['retained'] or owner['thread'] != threading.get_ident()
or guard is None or guard['pid'] != os.getpid()
or guard['status'] != 'OPERATION_IN_PROGRESS'
or owner['lease_id'] != guard['lease_id']
or Path(guard['library']).resolve() != Path(library).resolve()):
raise ValueError('Management transaction requires the current thread exact active library lease.')
return {'lease_id': owner['lease_id'], 'lease_handle': int(owner['handle']), 'supervisor_pid': os.getpid()}
def _authorize(record, mentor_home):
fixture = record.get('fixture')
if fixture is not None:
fixture_authority(fixture['root'], record['library'], fixture['token'])
else:
from .native_management import NativeManagementAdapter
capability = NativeManagementAdapter(mentor_home=mentor_home).capabilities()['add']
if not capability.supported: raise ValueError(capability.reason)
def prepare_transaction(request, root, expected_identity, *, mentor_home, fixture=None):
root = Path(root).resolve()
source = Path(request.source).resolve()
if source.parent != root/'source':
raise ValueError('Native Add accepts only the management engine staged source.')
library = Path(request.library).resolve()
if root.is_relative_to(library.parent) or library.parent.is_relative_to(root):
raise ValueError('Management transaction evidence overlaps the target library.')
checkpoint = _read(root/'checkpoint.json')
stages = {item['stage'] for item in checkpoint.get('history', [])}
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.')
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,
'expected_identity': expected_identity, 'fixture': fixture}
_authorize(record, mentor_home)
_write_json(root/'native-add-prepared.json', record)
return record['nonce']
def validate_transaction(job, root, *, check_source=True):
from .library_lock import blocker_path, checkpoint_record, _supervisor_alive
import win32api, win32con, win32file
root = Path(root).resolve()
record = _read(root/'native-add-prepared.json')
library = Path(job['library']).resolve()
source = root/'source'/record['source_name']
guard = checkpoint_record(blocker_path(library))
checkpoint = _read(root/'checkpoint.json')
if (not job.get('transaction_nonce') or job['transaction_nonce'] != record['nonce']
or Path(record['library']).resolve() != library
or any(job.get(key) != record[key] for key in ('name', 'partition', 'top_level_block', 'source_identity'))
or source.parent != root/'source' or source.resolve().parent != (root/'source').resolve()
or Path(job['source']).resolve() != source.resolve()
or guard is None or guard['lease_id'] != record['lease_id']
or guard['pid'] != record['supervisor_pid'] or guard['pid'] != job['supervisor_pid']
or guard['status'] != 'OPERATION_IN_PROGRESS'
or Path(guard['library']).resolve() != library or not _supervisor_alive(guard['pid'])
or checkpoint.get('status') != 'RUNNING' or checkpoint.get('stage') != 'native_add'
or Path(checkpoint['library']).resolve() != library
or checkpoint['name'] != record['name'] or checkpoint['partition'] != record['partition']):
raise ValueError('Native Add transaction authority is missing, stale or foreign.')
_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 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.')
process = win32api.OpenProcess(win32con.PROCESS_DUP_HANDLE, False, record['supervisor_pid'])
duplicate = None
try:
duplicate = win32api.DuplicateHandle(process, record['lease_handle'], win32api.GetCurrentProcess(),
0, False, win32con.DUPLICATE_SAME_ACCESS)
final_path = win32file.GetFinalPathNameByHandle(duplicate, 0)
if final_path.startswith('\\\\?\\UNC\\'): final_path = '\\\\'+final_path[8:]
elif final_path.startswith('\\\\?\\'): final_path = final_path[4:]
expected_lock = library.with_name('.'+library.stem+'.cbb-upload.lock')
if Path(final_path).resolve() != expected_lock.resolve():
raise ValueError('Native Add supervisor lease belongs to another library.')
finally:
if duplicate is not None: duplicate.Close()
process.Close()
return record
+115 -25
View File
@@ -101,7 +101,14 @@ def ensure_pcb_central_library(pcb_path, lmc_path, *, evidence_dir=None,
is copied into evidence before a replacement, so the change is auditable is copied into evidence before a replacement, so the change is auditable
and recoverable. and recoverable.
""" """
project = Path(pcb_path).parent / 'pcb.prj' return ensure_project_central_library(Path(pcb_path).parent/'pcb.prj', lmc_path,
evidence_dir=evidence_dir, emit=emit)
def ensure_project_central_library(project, lmc_path, *, evidence_dir=None,
emit=lambda **event: None):
"""Align one native project file while preserving its original encoding."""
project = Path(project)
target = str(lmc_path) target = str(lmc_path)
if not project.is_file() or not target: if not project.is_file() or not target:
return False return False
@@ -213,7 +220,10 @@ def _process_details(name):
queries = { queries = {
'ExpeditionPCB.exe': "SELECT ProcessId, ParentProcessId, ExecutablePath, CommandLine FROM Win32_Process WHERE Name='ExpeditionPCB.exe'", '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'", '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'", '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 queries:
raise ValueError(f'Unsupported process query: {name}') raise ValueError(f'Unsupported process query: {name}')
@@ -633,12 +643,13 @@ def execute_job(job, emit):
emit(stage='backup_done', status=backup.get('status'), detail=backup.get('detail')) emit(stage='backup_done', status=backup.get('status'), detail=backup.get('detail'))
# Backup is evidence only, never a prerequisite for launching PCB. Volatile # Backup is evidence only, never a prerequisite for launching PCB. Volatile
# database/log directories are intentionally excluded to avoid file locks. # database/log directories are intentionally excluded to avoid file locks.
icdb_address = prepare_icdb_address( from .icdb_ownership import database_directories, unreleased_addresses
Path(job['project']).parent / 'database', root, emit=emit) for database in database_directories(job['lmc_file'], job['project'], job['pcb']):
if icdb_address.get('status') != 'ABSENT': icdb_address = prepare_icdb_address(database, root, emit=emit)
raise RuntimeError( if icdb_address.get('status') != 'ABSENT':
'ICDB_SESSION_UNCONFIRMED: 数据库存在服务器地址记录,无法确认独占使用;' raise RuntimeError(
'已保留地址文件,请先检查原 PCB/iCDB 会话。' + str(icdb_address)) 'ICDB_SESSION_UNCONFIRMED: 数据库存在服务器地址记录,无法确认独占使用;'
'已保留地址文件,请先检查原 PCB/iCDB 会话。' + str(icdb_address))
from .verify_diagnostics import collect_preflight_diagnostics, collect_native_failure_logs from .verify_diagnostics import collect_preflight_diagnostics, collect_native_failure_logs
diagnostics = collect_preflight_diagnostics(job['pcb'], root) diagnostics = collect_preflight_diagnostics(job['pcb'], root)
emit(stage='preflight_diagnostics', non_blocking=True, emit(stage='preflight_diagnostics', non_blocking=True,
@@ -647,10 +658,8 @@ def execute_job(job, emit):
evidence=str(root/'diagnostics/preflight.json')) evidence=str(root/'diagnostics/preflight.json'))
cert_project = block_root/'Cert'/Path(job['project']).name cert_project = block_root/'Cert'/Path(job['project']).name
pcb_log = Path(job['pcb']).parent/'LogFiles'/'PCBLogFile.txt' pcb_log = Path(job['pcb']).parent/'LogFiles'/'PCBLogFile.txt'
try: from .icdb_recovery import snapshot_log
pcb_log_offset = pcb_log.stat().st_size pcb_log_offset = snapshot_log(pcb_log)
except OSError:
pcb_log_offset = 0
integration_log_dir = Path(job['pcb']).parent / 'LogFiles' integration_log_dir = Path(job['pcb']).parent / 'LogFiles'
integration_offsets = {} integration_offsets = {}
for name in ('ForwardAnnotation.txt', 'MsgBoxResponse.log', 'PartPkg.log'): for name in ('ForwardAnnotation.txt', 'MsgBoxResponse.log', 'PartPkg.log'):
@@ -664,6 +673,28 @@ def execute_job(job, emit):
} }
except OSError: except OSError:
integration_offsets[path] = {'size': 0, 'mtime_ns': None, 'digest': ''} integration_offsets[path] = {'size': 0, 'mtime_ns': None, 'digest': ''}
integration_offsets[path]['icdb_baseline'] = snapshot_log(path)
try:
(root/'diagnostics/startup-log-baseline.json').write_text(json.dumps({
'source': str(pcb_log), 'baseline': pcb_log_offset,
'integration_logs': {str(path): value['icdb_baseline']
for path, value in integration_offsets.items()},
}, ensure_ascii=False), encoding='utf-8')
except OSError as error:
emit(stage='startup_log_baseline_unavailable', detail=str(error))
def native_error():
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
return 'VERIFY_CANCELLED: 停止后续操作并正常关闭目标文档'
# Inspect every source before returning a generic server/packager
# failure: either can be a consequence of a lost library session.
startup = pcb_log_reports_missing_server(job['pcb'], offset=pcb_log_offset)
integration = pcb_log_reports_integration_error(job['pcb'], offsets=integration_offsets)
if 'ICDB_REPAIR_REQUIRED' in startup:
return startup
if 'ICDB_REPAIR_REQUIRED' in integration:
return integration
return startup or integration
emit(stage='pcb_baseline', pids=sorted(pcb_before)) emit(stage='pcb_baseline', pids=sorted(pcb_before))
lm_session = None lm_session = None
lm_pid = None lm_pid = None
@@ -671,6 +702,7 @@ def execute_job(job, emit):
worker_parent_pid = None worker_parent_pid = None
launcher_process = None launcher_process = None
completed = False completed = False
identity_verified = False
helper = None helper = None
app = doc = pi = None app = doc = pi = None
try: try:
@@ -704,6 +736,9 @@ def execute_job(job, emit):
emit(stage='lm_session_ready', lm_pid=lm_pid, block=job['block_name']) emit(stage='lm_session_ready', lm_pid=lm_pid, block=job['block_name'])
else: else:
command = build_pcb_launch_command(job['pcb'], job.get('mentor_bin')) command = build_pcb_launch_command(job['pcb'], job.get('mentor_bin'))
if job.get('post_repair_consent') is not None:
from .post_repair_consent import prepare_launch
prepare_launch(job, command)
emit(stage='pcb_launch', command=list(command), strategy='reusable_circuit_direct') emit(stage='pcb_launch', command=list(command), strategy='reusable_circuit_direct')
launcher_process = launch_pcb_process(command, Path(job['pcb']).parent) launcher_process = launch_pcb_process(command, Path(job['pcb']).parent)
worker_parent_pid = int(launcher_process.pid) worker_parent_pid = int(launcher_process.pid)
@@ -712,6 +747,8 @@ def execute_job(job, emit):
pcb_deadline = reset_verify_activity_deadline( pcb_deadline = reset_verify_activity_deadline(
0.0, time.monotonic(), timeout_seconds=pcb_startup_timeout_seconds(job['timeout'])) 0.0, time.monotonic(), timeout_seconds=pcb_startup_timeout_seconds(job['timeout']))
while time.monotonic() < pcb_deadline: while time.monotonic() < pcb_deadline:
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
raise RuntimeError('VERIFY_CANCELLED: PCB 启动期间收到停止请求')
records = _process_details('ExpeditionPCB.exe') records = _process_details('ExpeditionPCB.exe')
worker = select_reusable_circuit_worker( worker = select_reusable_circuit_worker(
records, records,
@@ -735,8 +772,9 @@ def execute_job(job, emit):
process_alive=lambda: any(candidate_pid in {lm_pid, worker_pid, worker_parent_pid} process_alive=lambda: any(candidate_pid in {lm_pid, worker_pid, worker_parent_pid}
for candidate_pid, _, _ in pcb_processes()), for candidate_pid, _, _ in pcb_processes()),
emit=emit, emit=emit,
error_reader=lambda: pcb_log_reports_missing_server(job['pcb'], offset=pcb_log_offset), error_reader=native_error,
) )
identity_verified = True
# Do not acquire MGCPCBAutomationLicensing from this 64-bit Python # Do not acquire MGCPCBAutomationLicensing from this 64-bit Python
# worker. EE7.9 registers that automation class for the 32-bit host; # worker. EE7.9 registers that automation class for the 32-bit host;
# the old, working path acquires the token inside the SysWOW64 # the old, working path acquires the token inside the SysWOW64
@@ -746,18 +784,21 @@ def execute_job(job, emit):
pi, pi,
emit=emit, emit=emit,
timeout_seconds=job['timeout'], timeout_seconds=job['timeout'],
error_reader=lambda: pcb_log_reports_integration_error(job['pcb'], offsets=integration_offsets), error_reader=native_error,
) )
# The x86 helper acquires its own COM references. Keeping these Python # The x86 helper acquires its own COM references. Keeping these Python
# references alive prevents the native PCB server from exiting cleanly. # references alive prevents the native PCB server from exiting cleanly.
pi = doc = app = None pi = doc = app = None
gc.collect() gc.collect()
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
raise RuntimeError('VERIFY_CANCELLED: 未开始保存')
emit(stage='save_start') emit(stage='save_start')
script = Path(__file__).with_name('save_verified_block.vbs') script = Path(__file__).with_name('save_verified_block.vbs')
cscript = Path(os.environ.get('WINDIR', r'C:\Windows'))/'SysWOW64'/'cscript.exe' cscript = Path(os.environ.get('WINDIR', r'C:\Windows'))/'SysWOW64'/'cscript.exe'
from .desktop_worker import launch_save_helper from .desktop_worker import launch_save_helper
with (root/'save.log').open('w', encoding='utf-8') as log: with (root/'save.log').open('w', encoding='utf-8') as log:
helper = launch_save_helper([str(cscript), '//nologo', str(script), job['project']], helper = launch_save_helper([str(cscript), '//nologo', str(script), job['project'],
Path(job['pcb']).name, str(job.get('cancel_signal') or '')],
stdout=log, stderr=log, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0)) stdout=log, stderr=log, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
emit(stage='save_helper', helper_pid=helper.pid) emit(stage='save_helper', helper_pid=helper.pid)
last_markers = () last_markers = ()
@@ -796,9 +837,9 @@ def execute_job(job, emit):
baseline_pids=pcb_before, emit=emit) baseline_pids=pcb_before, emit=emit)
if not released or not released.get('safe_to_continue'): if not released or not released.get('safe_to_continue'):
raise RuntimeError(f'PCB_RELEASE_UNCONFIRMED: 未确认 PCB 退出: {released}') raise RuntimeError(f'PCB_RELEASE_UNCONFIRMED: 未确认 PCB 退出: {released}')
address = Path(job['project']).parent / 'database/cdbsvr/sAddress.adr' addresses = unreleased_addresses(job['lmc_file'], job['project'], job['pcb'])
if address.exists(): if addresses:
raise RuntimeError(f'ICDB_RELEASE_UNCONFIRMED: PCB 已退出但数据库地址记录仍存在;保留文件并停止批次: {address}') raise RuntimeError(f'ICDB_RELEASE_UNCONFIRMED: PCB 已退出但数据库地址记录仍存在;保留文件并停止批次: {addresses}')
cert_pcb = block_root/'Cert'/Path(job['pcb']).relative_to(block_root/'Work') cert_pcb = block_root/'Cert'/Path(job['pcb']).relative_to(block_root/'Work')
cert_evidence = collect_cert_evidence(block_root, cert_project, cert_pcb) cert_evidence = collect_cert_evidence(block_root, cert_project, cert_pcb)
emit(stage='cert_diagnostics', **cert_evidence) emit(stage='cert_diagnostics', **cert_evidence)
@@ -818,8 +859,24 @@ def execute_job(job, emit):
# Diagnostic failure must not erase the native error or cleanup. # Diagnostic failure must not erase the native error or cleanup.
pass pass
if helper is not None and helper.poll() is None: if helper is not None and helper.poll() is None:
# Stop only the automation client, never a native database tree. emit(stage='save_helper_retained', helper_pid=helper.pid)
helper.terminate() elif not completed and identity_verified:
try:
from .failed_session import close_failed_document
failed_close = close_failed_document(job, emit=emit)
if failed_close.get('status') == 'CLOSED' and lm_session is not None:
lm_session.close()
except Exception as error:
emit(stage='failure_close_unconfirmed', detail=str(error))
elif not completed and worker_pid is not None:
try:
from .failed_session import close_failed_startup
failed_close = close_failed_startup(job, worker_pid, baseline_pids=pcb_before, emit=emit,
launcher_process=launcher_process)
if failed_close.get('status') == 'CLOSED' and lm_session is not None:
lm_session.close()
except Exception as error:
emit(stage='startup_close_unconfirmed', detail=str(error))
cleanup_verify_processes( cleanup_verify_processes(
lm_pid, lm_pid,
worker_pid, worker_pid,
@@ -906,7 +963,7 @@ def worker_main(request_path):
try: try:
if job.get('supervisor_pid'): if job.get('supervisor_pid'):
from .desktop_worker import start_supervisor_watchdog from .desktop_worker import start_supervisor_watchdog
start_supervisor_watchdog(job['supervisor_pid']) start_supervisor_watchdog(job['supervisor_pid'], cancel_path=job.get('cancel_signal'))
start_gate = Path(job.get('start_gate', '')) if job.get('start_gate') else None start_gate = Path(job.get('start_gate', '')) if job.get('start_gate') else None
if start_gate is not None: if start_gate is not None:
gate_deadline = time.monotonic() + 15 gate_deadline = time.monotonic() + 15
@@ -1040,17 +1097,27 @@ def icdb_ports_bindable(ports=(10000, 10050, 10100)):
def pcb_log_reports_missing_server(pcb_path, *, offset=0): def pcb_log_reports_missing_server(pcb_path, *, offset=0):
"""Detect the same failure from ExpeditionPCB's own log, as a second signal.""" """Detect startup failure from this run, preserving native recovery causes."""
from .icdb_recovery import (decode_log, parse_session_loss, read_log_failure,
recovery_detail)
log = Path(pcb_path).parent/'LogFiles'/'PCBLogFile.txt' log = Path(pcb_path).parent/'LogFiles'/'PCBLogFile.txt'
try: try:
with log.open('rb') as stream: if isinstance(offset, dict):
stream.seek(max(0, offset)) text, recovery = read_log_failure(log, offset)
text = stream.read().decode('utf-8', errors='replace') else:
# Retain the byte-offset interface for existing diagnostic callers.
with log.open('rb') as stream:
stream.seek(max(0, offset))
text = decode_log(stream.read())
recovery = parse_session_loss(text)
except Exception: except Exception:
return '' return ''
if recovery:
return recovery_detail(recovery)
for marker in ("could not bring it alive", 'Could not run server'): for marker in ("could not bring it alive", 'Could not run server'):
if marker.lower() in text.lower(): if marker.lower() in text.lower():
return RESERVED_PORT_MESSAGE return (f'DESIGN_SERVER_FAILED: {marker}。请检查本轮原生日志中的数据库/服务器原因;'
'此信息本身不能证明端口被系统保留。')
return '' return ''
@@ -1065,6 +1132,7 @@ _INTEGRATION_ERROR_LINE = re.compile(
def pcb_log_reports_integration_error(pcb_path, *, offsets=None): def pcb_log_reports_integration_error(pcb_path, *, offsets=None):
"""Read explicit Project Integration errors produced by this run.""" """Read explicit Project Integration errors produced by this run."""
from .icdb_recovery import parse_session_loss, read_log_failure, recovery_detail
log_dir = Path(pcb_path).parent / 'LogFiles' log_dir = Path(pcb_path).parent / 'LogFiles'
offsets = offsets or {} offsets = offsets or {}
details = [] details = []
@@ -1073,6 +1141,19 @@ def pcb_log_reports_integration_error(pcb_path, *, offsets=None):
try: try:
size = path.stat().st_size size = path.stat().st_size
baseline = offsets.get(path, offsets.get(str(path), 0)) baseline = offsets.get(path, offsets.get(str(path), 0))
has_icdb_baseline = isinstance(baseline, dict) and any(
key in baseline for key in ('icdb_baseline', 'tail_sha256', 'error'))
icdb_baseline = baseline.get('icdb_baseline', baseline) if isinstance(baseline, dict) else None
if icdb_baseline and 'tail_sha256' in icdb_baseline:
text, recovery = read_log_failure(path, icdb_baseline)
if recovery:
return recovery_detail(recovery)
if 'tail_sha256' in baseline:
# New bounded checkpoints can also be supplied directly.
details.extend(line.strip() for line in text.splitlines()
if _INTEGRATION_ERROR_LINE.search(line.strip())
and not parse_session_loss(line))
continue
if isinstance(baseline, dict): if isinstance(baseline, dict):
baseline_size = int(baseline.get('size', 0) or 0) baseline_size = int(baseline.get('size', 0) or 0)
baseline_mtime = baseline.get('mtime_ns') baseline_mtime = baseline.get('mtime_ns')
@@ -1103,8 +1184,17 @@ def pcb_log_reports_integration_error(pcb_path, *, offsets=None):
text = stream.read().decode('utf-8', errors='replace') text = stream.read().decode('utf-8', errors='replace')
except OSError: except OSError:
continue continue
# Legacy byte offsets/digests remain accepted by offline callers.
if not has_icdb_baseline:
recovery = parse_session_loss(text)
if recovery:
return recovery_detail(recovery)
for line in text.splitlines(): for line in text.splitlines():
cleaned = line.strip() cleaned = line.strip()
if has_icdb_baseline and parse_session_loss(cleaned):
# read_log_failure already rejected this retained old session.
# Do not let the generic ERROR filter promote it again.
continue
if _INTEGRATION_ERROR_LINE.search(cleaned) and cleaned not in details: if _INTEGRATION_ERROR_LINE.search(cleaned) and cleaned not in details:
details.append(cleaned) details.append(cleaned)
return ' | '.join(details[:8]) return ' | '.join(details[:8])
@@ -0,0 +1,110 @@
"""Observed native copy failure and conservative legacy Win32 path admission."""
import hashlib
import json
from pathlib import Path
import re
import time
_COPY_ERROR = b'Error! Cannot copy iCDB base of Reusable Block project.'
_LOG_LIMIT = 2*1024*1024
def snapshot_add_log(library):
path = Path(library).parent/'LogFiles/ReuseBlockLogLO.txt'
try:
data = b''
if path.exists():
with path.open('rb') as stream: data = stream.read(_LOG_LIMIT+1)
if len(data) > _LOG_LIMIT: raise ValueError('Native Add log exceeds the bounded observation limit.')
return {'path': str(path), 'size': len(data), 'sha256': hashlib.sha256(data).hexdigest()}
except (OSError, ValueError) as error:
return {'path': str(path), 'unavailable': str(error)}
def fresh_add_failure(baseline, name):
if 'unavailable' in baseline: return None
try:
with Path(baseline['path']).open('rb') as stream:
data = stream.read(_LOG_LIMIT+1)
offset = baseline['size']
if (len(data) > _LOG_LIMIT or len(data) < offset
or hashlib.sha256(data[:offset]).hexdigest() != baseline['sha256']):
return None
marker = re.compile(rb'REUSE BLOCK:\s*INFORMATION:\s*'+re.escape(name.encode('mbcs'))
+rb'\s+'+re.escape(_COPY_ERROR))
for line in data[offset:].splitlines():
if marker.search(line): return line.decode('mbcs')
except (OSError, UnicodeError):
pass
return None
def failure_ack_button(title, static_text, buttons):
if title != 'Library Manager' or static_text.strip() != '系统找不到指定的路径。' or len(buttons) != 1:
return None
button = buttons[0]
if (button.get('id') == 2 and button.get('class') == 'Button'
and button.get('text') == '确定' and button.get('enabled') is True):
return button['hwnd']
return None
def validate_native_copy_paths(source, library, name):
from .scoped_manifest import scan_tree
from .network_path import absolute_preserving_drive
source = absolute_preserving_drive(source)
target = absolute_preserving_drive(library).parent/'ReusableBlocksLP'/name/'Work'
paths = [source.parent, *scan_tree(source.parent)]
for path in paths:
relative = path.relative_to(source.parent)
for label, candidate in (('暂存来源', path), ('目标', target/relative)):
# Legacy CopyFile's 260-WCHAR buffer includes the terminating NUL.
length = len(str(candidate).encode('utf-16-le'))//2
if length >= 260:
raise ValueError(f'NATIVE_PATH_TOO_LONG: {label}路径为 {length} 个字符,已超过原生复制支持范围。'
f'请缩短操作数据/证据目录或目标库路径后重试;所有工程和日志文件均保留。路径:{candidate}')
def observe_add_failure(desktop, owned_pids, root, baseline, name, state):
"""Record owned modal evidence and acknowledge only the observed error box."""
import pythoncom, win32con, win32gui, win32process
from .management import _write_json
fresh_log = fresh_add_failure(baseline, name)
for handle in desktop.EnumDesktopWindows():
hwnd = int(handle)
if (win32process.GetWindowThreadProcessId(hwnd)[1] not in owned_pids
or not win32gui.IsWindowVisible(hwnd) or win32gui.GetClassName(hwnd) != '#32770'):
continue
title = win32gui.GetWindowText(hwnd)
if title in ('New Reusable Block', 'Reusable Blocks'): continue
children = []
win32gui.EnumChildWindows(hwnd, lambda child, _: children.append(int(child)), None)
controls = [{'hwnd': child, 'id': win32gui.GetDlgCtrlID(child), 'class': win32gui.GetClassName(child),
'text': win32gui.GetWindowText(child), 'enabled': bool(win32gui.IsWindowEnabled(child))}
for child in children]
static = '\n'.join(c['text'] for c in controls if c['class'] == 'Static')
buttons = [c for c in controls if c['class'] == 'Button']
record = {'hwnd': hwnd, 'title': title, 'controls': controls, 'fresh_log_failure': fresh_log}
key = json.dumps(record, ensure_ascii=False, sort_keys=True)
if key not in state.setdefault('observed', set()):
state['observed'].add(key)
with (Path(root)/'native-add-dialogs.jsonl').open('a', encoding='utf-8') as stream:
stream.write(json.dumps(record, ensure_ascii=False)+'\n')
button = failure_ack_button(title, static, buttons)
if button is not None and win32process.GetWindowThreadProcessId(button)[1] in owned_pids:
win32gui.PostMessage(button, win32con.BM_CLICK, 0, 0)
deadline = time.monotonic()+2
while win32gui.IsWindow(hwnd) and time.monotonic() < deadline:
pythoncom.PumpWaitingMessages(); time.sleep(.05)
record['acknowledged'] = not win32gui.IsWindow(hwnd)
_write_json(Path(root)/'native-add-output.json', {'success_message': None, 'failure': record})
raise RuntimeError('NATIVE_ADD_FAILED: '+static.strip()
+ (' '+fresh_log if fresh_log else '')
+ ('' if record['acknowledged'] else ';原生错误对话框尚未确认关闭。'))
if fresh_log:
first_seen = state.setdefault('failure_seen_at', time.monotonic())
# Allow the paired native error popup to appear for normal acknowledgement.
if time.monotonic()-first_seen >= 2:
_write_json(Path(root)/'native-add-output.json', {'success_message': None,
'failure': {'fresh_log_failure': fresh_log, 'acknowledged': False}})
raise RuntimeError('NATIVE_ADD_FAILED: '+fresh_log)
@@ -0,0 +1,416 @@
"""Pinned EE7.9.5 native logical exports plus conservative physical/assets proof.
This contract is not raw iCDB equivalence or a claim of exhaustive arbitrary CES
semantics. It compares the proven hierarchy/flat ASCII and CSV/property exports,
and preserves physical design and all other primary engineering assets exactly.
"""
from dataclasses import dataclass
import hashlib
from pathlib import Path
import re
import subprocess
import time
from .management import source_project, _write_json
from .scoped_manifest import ManifestScope, build_manifest, hash_file
POLICY = 'mentor795-native-content-v1'
COVERAGE = {'logical_connectivity_and_properties': 'native hierarchy/flat ASCII and CSV',
'physical_design_and_primary_assets': 'raw SHA256',
'schematic_graphical_geometry': 'native EDIF schematic', 'production_acceptance': True}
EXPORTER_PROOF = {
'icdb2ascii.exe': 'e37c87356eaf57c0b97e4183458bc8c5eb6eb0ac497cc7ad40dcd585d8cd213b',
'icdb2csv.exe': '22059f4a432e8eabf30a5326ebcbd463ed6fa6495af21d7aad5ab5d2f892f255',
'edifExporter.exe': '8b5f9682007da5b759e7b2f0fa9720f6771b2efb9a546636b270a58e1268a80e',
}
INF_HEADER = (b'Design Name\tSystem Name\tSystem Version\tSystem_Date\tCompany_Name\tDepartment_Name'
b'\tAddress\tAddress1\tCity\tState_Province\tCountry\tZip\tPhone\tPhone_Ext\tFax\tFax_Ext')
CSV_SUFFIXES = ('', '.esf', '.inf', '.npr', '.ppn', '.ppr', '.prm', '.prt', '.pth',
'.sht', '.spn', '.spr', '.sym', '.thn')
_retained_exports = []
_OWNER_NAMES = frozenset({'icdb2ascii.exe', 'icdb2csv.exe', 'edifexporter.exe', 'icdbnetserver.exe',
'icdbnetlauncher.exe', 'icdbservermanager.exe', 'icdbservermonitor.exe'})
@dataclass(frozen=True)
class IdentityOutcome:
identity: dict | None
safe_to_continue: bool
detail: str
evidence_path: Path
def _digest(data):
return hashlib.sha256(data).hexdigest()
def normalize_ascii(data, top):
"""Only the three observed, position-bound report metadata values vary."""
lines = data.splitlines(keepends=True)
prefixes = {0: b'iCDB Ascii Report Generation Date: ',
4: b'\t iCDB directory: ', 5: b'\t DATE: '}
if (len(lines) < 12 or lines[3].rstrip(b'\r\n') != b'\tReport Criteria:'
or any(not lines[i].startswith(prefix) or not lines[i][len(prefix):].strip()
for i, prefix in prefixes.items())):
raise ValueError('Incomplete or unknown native ASCII report header.')
header = b''.join(lines[:next((i for i, line in enumerate(lines) if line.startswith(b'Block ')), len(lines))])
required = (b'\t REPORT FORMAT: FREEFORM', b'\t MODE: HIER AND FLAT BLOCKS',
b'\t CONNECTION LISTS: ON', b'\t TEXT LISTS: ON')
if any(header.count(value) != 1 for value in required):
raise ValueError('Native ASCII export mode does not match the proven contract.')
top_bytes = top.encode('mbcs')
if (not any(line.rstrip(b'\r\n') == b'Block '+top_bytes+b' \tRoot' for line in lines)
or not any(line.startswith(b'Config ') for line in lines)):
raise ValueError('Native ASCII export lacks the exact root or flat configuration.')
for index, prefix in prefixes.items():
ending = b'\r\n' if lines[index].endswith(b'\r\n') else b'\n'
lines[index] = prefix+b'<REPORT_METADATA>'+ending
return b''.join(lines)
def normalize_inf(data):
lines = data.splitlines(keepends=True)
if len(lines) != 2 or lines[0].rstrip(b'\r\n') != INF_HEADER:
raise ValueError('Unknown native CSV information schema.')
values = lines[1].rstrip(b'\r\n').split(b'\t')
if len(values) != 16 or values[:3] != [b'identity', b'Design Capture', b'VB99.0']:
raise ValueError('Malformed native CSV information row.')
if not re.fullmatch(rb'\d{2}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}', values[3]):
raise ValueError('Unknown native CSV System_Date format.')
values[3] = b'<SYSTEM_DATE>'
ending = b'\r\n' if lines[1].endswith(b'\r\n') else b'\n'
return lines[0]+b'\t'.join(values)+ending
def normalize_edif(data, top):
"""Bounded structural parse; replace only root/status/written/timestamp."""
from datetime import datetime
if not data or len(data) > 64*1024*1024:
raise ValueError('EDIF report is empty or exceeds the supported parsing limit.')
token_pattern = re.compile(rb'\s+|[()]|"(?:[^"\\]|\\.)*"|[^\s()"]+')
stack, roots, nodes = [], [], []
position = 0
for match in token_pattern.finditer(data):
if match.start() != position: raise ValueError('Malformed EDIF token.')
position = match.end(); token = match.group()
if token.isspace(): continue
if token == b'(':
node = {'start': match.start(), 'items': []}
if stack: stack[-1]['items'].append(node)
else: roots.append(node)
nodes.append(node); stack.append(node)
if len(stack) > 256 or len(nodes) > 1000000:
raise ValueError('EDIF exceeds supported structural limits.')
elif token == b')':
if not stack: raise ValueError('Unbalanced EDIF report.')
node = stack.pop(); node['end'] = match.end()
if not node['items'] or not isinstance(node['items'][0], bytes):
raise ValueError('EDIF node has no keyword.')
else:
if not stack: raise ValueError('Unexpected EDIF content outside the root.')
stack[-1]['items'].append(token)
if position != len(data) or stack or len(roots) != 1 or roots[0]['items'][0] != b'edif':
raise ValueError('Unbalanced or unsupported EDIF root.')
def children(node, tag):
return [n for n in node['items'] if isinstance(n, dict) and n['items'][0] == tag]
def one(node, tag):
matches = children(node, tag)
if len(matches) != 1: raise ValueError(f'EDIF requires one {tag!r} node in the expected context.')
return matches[0]
root = roots[0]
if one(root, b'edifVersion')['items'] != [b'edifVersion', b'2', b'0', b'0']:
raise ValueError('Unsupported EDIF version.')
written = one(one(root, b'status'), b'written')
if one(written, b'program')['items'][1] != b'"DxDesigner Edif Exporter"':
raise ValueError('Unrecognized native EDIF exporter.')
stamp = one(written, b'timestamp')
values = stamp['items'][1:]
if len(values) != 6 or any(not isinstance(v, bytes) or not v.isdigit() for v in values):
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'):
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'))):
raise ValueError('EDIF schematic drawing is absent or unsupported.')
return data[:stamp['start']]+b'(timestamp <EXPORT_TIME>)'+data[stamp['end']:]
def csv_identity(root):
from .scoped_manifest import scan_tree
root = Path(root)
paths = {p.relative_to(root).as_posix(): p for p in scan_tree(root) if p.is_file()}
expected = {'work/identity'+suffix for suffix in CSV_SUFFIXES}
if paths.keys() != expected or any(not p.stat().st_size for p in paths.values()):
raise ValueError('Native CSV export is empty, incomplete or an unsupported snapshot.')
index = paths['work/identity'].read_bytes().splitlines()
expected_index = {b'file:identity'+suffix.encode('ascii') for suffix in CSV_SUFFIXES if suffix}
if len(index) != len(expected_index) or set(index) != expected_index:
raise ValueError('Native CSV index does not bind every exported table.')
return {name: _digest(normalize_inf(path.read_bytes()) if name.endswith('.inf') else path.read_bytes())
for name, path in sorted(paths.items())}
def _project_encoding(data):
if data.startswith((b'\xff\xfe', b'\xfe\xff')): return 'utf-16'
if data.startswith(b'\xef\xbb\xbf'): return 'utf-8-sig'
try: data.decode('utf-8'); return 'utf-8'
except UnicodeDecodeError: return 'mbcs'
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)
libraries = set()
for path in (source, pcb.parent/'pcb.prj'):
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:
target = (path.parent/value).resolve(strict=True)
if target.suffix.casefold() != '.lmc' or not target.is_file():
raise ValueError('CentralLibrary is not an existing LMC.')
libraries.add(target)
if len(libraries) != 1: raise ValueError('Project CentralLibrary references disagree.')
return libraries.pop()
def _normalized_project(path, expected_library):
data = path.read_bytes(); encoding = _project_encoding(data)
text = data.decode(encoding)
refs = re.findall(r'^KEY CentralLibrary "([^"\r\n]*)"', text, re.M)
if not refs or any((path.parent/value).resolve() != expected_library.resolve() for value in refs):
raise ValueError(f'CentralLibrary reference does not resolve to the approved library: {path}')
return re.sub(r'(?m)^(KEY CentralLibrary ")[^"\r\n]*(")',
r'\1<CENTRAL_LIBRARY>\2', text).encode(encoding)
def asset_identity(source, expected_library):
from .backup_recovery import _project_text
source, pcb, top = source_project(source)
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')
databases = []
for project in projects:
values = re.findall(r'^KEY iCDBDir "([^"\r\n]+)"', _project_text(project), re.M)
databases.extend((project.parent/value).resolve() for value in values)
main_database = databases[0]
runtime = [db/'cdbsvr' for db in databases]
files = build_manifest(root, scope=ManifestScope())['files']
assets = {}
for relative, record in files.items():
path = root/relative
known_runtime = False
for server_root in runtime:
if not path.is_relative_to(server_root): continue
parts = path.relative_to(server_root).parts
folded = tuple(p.casefold() for p in parts)
known_runtime = (len(parts) > 1 and folded[0] in ('log', 'dbcheck', 'dbrestore', 'dbupgrade', 'pimlog')
or folded in (('events', 'events.dat'), ('events', 'events.idx'))
or len(parts) == 2 and folded[0] == 'plog'
and re.fullmatch(r'\d{4}\.\d{2}\.\d{2}\.guid\.\d+\.txt', parts[1]) is not None)
break
if path == main_database/'icdb.dat' or known_runtime:
continue
if path in projects:
data = _normalized_project(path, expected_library)
assets[relative] = {'size': len(data), 'sha256': _digest(data)}
else:
assets[relative] = {'size': record['size'], 'sha256': record['sha256']}
return {'policy': POLICY, 'top_level_block': top,
'layout_sha256': hash_file(pcb.parent/'Layout/LayoutDB.lyt'), 'assets': assets}
def check_exporters(mentor_home):
for name, expected in EXPORTER_PROOF.items():
path = Path(mentor_home)/('wv/win32/bin' if name == 'edifExporter.exe' else 'iCDB/win32/bin')/name
if not path.is_file() or hash_file(path) != expected:
raise ValueError(f'Native identity exporter is not the proven EE7.9.5 binary: {path}')
def validate_export_output(kind, code, report, log):
text = Path(log).read_bytes().decode('mbcs', errors='strict')
if code != 0 or re.search(r'(?im)^\s*(?:#\s*)?(?:error|fatal)\b', text):
raise ValueError('Native identity exporter failed or reported an error.')
if kind == 'ascii':
if (not Path(report).is_file() or not Path(report).stat().st_size
or f'Report generation complete, report file is {report}' not in text):
raise ValueError('Native ASCII export lacks a complete nonempty report.')
elif kind == 'csv':
if 'iCDB to CSV complete' not in [line.strip() for line in text.splitlines()]:
raise ValueError('Native CSV export lacks its completion marker.')
csv_identity(report)
elif kind == 'edif':
if (not Path(report).is_file() or not Path(report).stat().st_size
or 'Done' not in [line.strip() for line in text.splitlines()]
or f'Dumping edif file {report} ...' not in text):
raise ValueError('Native EDIF export lacks a complete nonempty drawing report.')
else:
raise ValueError('Unsupported native export kind.')
def _process_snapshot():
import win32com.client
service = win32com.client.GetObject('winmgmts:')
try:
return [{'pid': int(p.ProcessId), 'parent': int(p.ParentProcessId or 0),
'name': str(p.Name), 'executable': str(p.ExecutablePath or '')}
for p in service.ExecQuery('SELECT ProcessId, ParentProcessId, Name, ExecutablePath FROM Win32_Process')]
finally:
service = None
def _database_released(project_root):
"""Exclusive reads plus absent addresses prove the copied native DBs idle."""
import win32file, win32con
from contextlib import ExitStack
root = Path(project_root)
if any(root.rglob('sAddress.adr')):
return False
with ExitStack() as stack:
for path in root.rglob('*'):
if path.is_file() and path.name.casefold() in ('icdb.dat', 'layoutdb.lyt'):
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, 0, None)
stack.callback(handle.Close)
return True
def _run_exports(project, root, mentor_home, timeout_seconds):
"""Observe exact exporter/descendant handles; never kill a database owner."""
import win32api, win32con, win32event, pywintypes
root = Path(root)
_write_json(root/'export-launch.json', {'started': False})
before = _process_snapshot()
if any(p['name'].casefold() in _OWNER_NAMES for p in before):
return {'success': False, 'safe_to_continue': False, 'detail': 'An existing iCDB owner prevents isolated identity export.'}
if not _database_released(project.parent):
return {'success': False, 'safe_to_continue': False, 'detail': 'Analysis copy has unreleased native addresses or DB handles.'}
from .backup_recovery import _project_text
_, _, top = source_project(project)
database = (project.parent/re.findall(r'^KEY iCDBDir "([^"\r\n]+)"', _project_text(project), re.M)[0]).resolve()
commands = [
('ascii', [str(Path(mentor_home)/'iCDB/win32/bin/icdb2ascii.exe'),
f'-project={project}', f'-file={root/"design.rpt"}', f'-clog={root/"ascii.log"}',
'-f', '-h', '-c', '-t', '-nostrip'], root/'design.rpt', root/'ascii.log'),
('csv', [str(Path(mentor_home)/'iCDB/win32/bin/icdb2csv.exe'),
f'-project={project}', '-snap=DxD', '-file=identity', f'-output={root/"tables"}',
f'-clog={root/"csv.log"}', '-properties', '-nostrip'], root/'tables', root/'csv.log'),
('edif', [str(Path(mentor_home)/'wv/win32/bin/edifExporter.exe'), '-schematic',
'-icdb', str(database), '-isnap', 'DxD', '-top', top, '-o', str(root/'design.edf')],
root/'design.edf', root/'edif-stdout.txt'),
]
for kind, command, report, log in commands:
process = None
handles = {}
released = False
record = {'command': command, 'kind': kind, 'success': False, 'safe_to_continue': False}
try:
deadline = time.monotonic()+float(timeout_seconds)
with (root/(kind+'-stdout.txt')).open('wb') as output:
_write_json(root/'export-launch.json', {'started': True})
process = subprocess.Popen(command, stdout=output, stderr=subprocess.STDOUT,
creationflags=subprocess.CREATE_NO_WINDOW)
record['pid'] = process.pid
descendants = {process.pid}
_write_json(root/(kind+'-process.json'), record)
while time.monotonic() < deadline:
snapshot = _process_snapshot()
changed = True
while changed:
previous = len(descendants)
descendants.update(p['pid'] for p in snapshot if p['parent'] in descendants)
changed = len(descendants) != previous
owners = [p for p in snapshot if p['pid'] in descendants or p['name'].casefold() in _OWNER_NAMES]
for owner in owners:
if owner['pid'] not in handles:
try: handles[owner['pid']] = win32api.OpenProcess(win32con.SYNCHRONIZE, False, owner['pid'])
except pywintypes.error as error:
if error.winerror != 87: raise
record['observed_pids'] = sorted(descendants | handles.keys())
if (process.poll() is not None and not owners
and all(win32event.WaitForSingleObject(h, 0) == win32con.WAIT_OBJECT_0 for h in handles.values())):
released = _database_released(project.parent)
if released: break
time.sleep(.1)
record.update(exit_code=process.poll(), safe_to_continue=released)
if not released:
record['detail'] = 'TIMEOUT: native export owner or copied database release remains unconfirmed.'
return record
validate_export_output(kind, process.returncode, report, log)
record.update(success=True, detail='Native export complete and owners released.')
except Exception as error:
record.update(detail=str(error), safe_to_continue=released)
return record
finally:
if process is not None and not released:
_retained_exports.append((process, handles))
else:
for handle in handles.values(): handle.Close()
_write_json(root/(kind+'-process.json'), record)
return {'success': True, 'safe_to_continue': True, 'detail': 'All three native exports completed and released.'}
def capture_identity(source, evidence_root, *, expected_library, owner_library, mentor_home,
timeout_seconds=180):
"""Capture on a fresh project copy while an existing transaction owns its library."""
from .backup_recovery import _align_library
from .library_lock import LibraryLock, owned_snapshot
from .scoped_manifest import copy_verified
from .native_export_guard import begin_export_analysis, finish_export_analysis
import win32event, win32con
source, pcb, top = source_project(source)
root = Path(evidence_root).absolute()
library = Path(owner_library)
lease = LibraryLock(library)
if owned_snapshot(lease.path) is None:
raise ValueError('Native identity capture requires a current-thread transaction library lease.')
if (root.resolve().is_relative_to(source.parent) or source.parent.is_relative_to(root.resolve())
or root.resolve().is_relative_to(library.parent.resolve())):
raise ValueError('Native identity evidence must be independent of source and library.')
check_exporters(mentor_home)
root.mkdir(parents=True, exist_ok=False)
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = False
owner_safe = True
outcome = IdentityOutcome(None, True, 'Identity capture did not start.', root)
try:
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired: raise RuntimeError('Another CBB operation owns the management mutex.')
with LibraryLock(library, safe_to_release=lambda: owner_safe):
assets = asset_identity(source, Path(expected_library))
original = copy_verified(source.parent, root/'project')
clone = root/'project'/source.name
_, clone_pcb, _ = source_project(clone)
_align_library(clone, clone_pcb, Path(expected_library))
if any((root/'project').rglob('sAddress.adr')):
raise ValueError('Analysis source contains an unresolved database address.')
export_token = begin_export_analysis(library, root, clone)
owner_safe = False
native = _run_exports(clone, root, mentor_home, timeout_seconds)
_write_json(root/'native-outcome.json', native)
if native.get('safe_to_continue') is True:
finish_export_analysis(library, export_token)
owner_safe = True
if not owner_safe or not native.get('success'):
outcome = IdentityOutcome(None, owner_safe, native.get('detail', 'Native export failed.'), root)
else:
ascii_bytes = normalize_ascii((root/'design.rpt').read_bytes(), top)
csv = csv_identity(root/'tables')
edif_bytes = normalize_edif((root/'design.edf').read_bytes(), top)
if build_manifest(source.parent) != original:
raise ValueError('Identity input changed while exporting its disposable copy.')
fingerprint = {**assets, 'coverage': COVERAGE, 'ascii_sha256': _digest(ascii_bytes),
'csv': csv, 'edif_sha256': _digest(edif_bytes)}
outcome = IdentityOutcome(fingerprint, True, 'Native logical exports and primary assets captured.', root)
except Exception as error:
outcome = IdentityOutcome(None, owner_safe, str(error), root)
finally:
if acquired: win32event.ReleaseMutex(mutex)
mutex.Close()
_write_json(root/'identity.json', {'identity': outcome.identity, 'safe_to_continue': outcome.safe_to_continue,
'detail': outcome.detail, 'policy': POLICY})
return outcome
@@ -0,0 +1,117 @@
"""Export-copy ownership bound to the existing per-library lease checkpoint."""
from contextlib import contextmanager, ExitStack
import json
from pathlib import Path
from uuid import uuid4
from .management import _write_json
def assert_retained_exports_idle():
import win32con, win32event
from .native_engineering_identity import _retained_exports
from .library_lock import LibraryBusy
for process, handles in _retained_exports:
if process.poll() is None or any(win32event.WaitForSingleObject(handle, 0) != win32con.WAIT_OBJECT_0
for handle in handles.values()):
raise LibraryBusy('Native identity exporter or descendant has not released.')
def begin_export_analysis(library, root, project):
from .library_lock import _guard, blocker_path, checkpoint_record, LibraryBusy
from .management_transaction import current_lease
library, root, project = Path(library).resolve(), Path(root).resolve(), Path(project).resolve()
owner = current_lease(library)
if (project.parent != root/'project' or not project.is_file()
or root.is_relative_to(library.parent) or library.parent.is_relative_to(root)):
raise LibraryBusy('Export-copy ownership paths are not independent and exact.')
record = {'protocol': 'cbb-native-export-analysis', 'version': 1, 'token': uuid4().hex,
'library': str(library), 'lease_id': owner['lease_id'], 'supervisor_pid': owner['supervisor_pid'],
'analysis_root': str(root), 'project': str(project)}
with _guard:
marker = blocker_path(library)
checkpoint = checkpoint_record(marker)
if (checkpoint is None or checkpoint['lease_id'] != owner['lease_id']
or 'export_analysis' in checkpoint):
raise LibraryBusy('A prior export analysis is unresolved or the lease changed.')
_write_json(root/'export-owner.json', record)
_write_json(marker, {**checkpoint, 'export_analysis': [record]})
return record['token']
@contextmanager
def prove_export_copies_released(library):
"""Fresh process and exclusive-copy proof, including after interpreter exit."""
import win32file, win32con, pywintypes
from .library_lock import blocker_path, checkpoint_record, _supervisor_alive, LibraryBusy
from .native_engineering_identity import _process_snapshot, _OWNER_NAMES
from .scoped_manifest import scan_tree
assert_retained_exports_idle()
library = Path(library).resolve()
marker = blocker_path(library)
checkpoint = checkpoint_record(marker)
if marker.exists() and checkpoint is None:
raise LibraryBusy('Invalid library checkpoint cannot release export ownership.')
if checkpoint is None or 'export_analysis' not in checkpoint:
yield []
return
records = checkpoint['export_analysis']
if not isinstance(records, list) or not records:
raise LibraryBusy('Invalid export-analysis ownership record.')
owners = [p for p in _process_snapshot() if p['name'].casefold() in _OWNER_NAMES]
if owners: raise LibraryBusy(f'Native identity owners remain active: {owners}')
copies = []
with ExitStack() as stack:
for record in records:
try:
root, project = Path(record['analysis_root']), Path(record['project'])
if (record.get('protocol') != 'cbb-native-export-analysis' or record.get('version') != 1
or not record.get('token') or record['lease_id'] != checkpoint['lease_id']
or record['supervisor_pid'] != checkpoint['pid']
or Path(record['library']).resolve() != library
or not root.is_absolute() or not project.is_absolute() or root.resolve() != root
or project.parent != root/'project' or not project.is_file()
or root.resolve().is_relative_to(library.parent)
or library.parent.is_relative_to(root.resolve())
or json.loads((root/'export-owner.json').read_text(encoding='utf-8')) != record):
raise ValueError('Export record does not match the exact library, lease and copy.')
processes = [root/(kind+'-process.json') for kind in ('ascii', 'csv', 'edif')
if (root/(kind+'-process.json')).exists()]
if not processes:
launch = json.loads((root/'export-launch.json').read_text(encoding='utf-8'))
if launch != {'started': False}:
raise ValueError('Export launch has no confirmed process record.')
for path in processes:
process = json.loads(path.read_text(encoding='utf-8'))
pids = process.get('observed_pids', []) + [process['pid']]
if any(not isinstance(pid, int) or pid <= 0 for pid in pids):
raise ValueError('Invalid export process identity.')
if any(_supervisor_alive(pid) for pid in pids):
raise LibraryBusy('A recorded export process or descendant remains alive.')
entries = scan_tree(root/'project')
if any(path.name.casefold() == 'saddress.adr' for path in entries):
raise LibraryBusy('The retained analysis copy still has a database address.')
databases = [path for path in entries if path.is_file()
and path.name.casefold() in ('icdb.dat', 'layoutdb.lyt')]
if not any(path.name.casefold() == 'icdb.dat' for path in databases):
raise ValueError('The recorded analysis database is missing.')
for path in databases:
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, 0, None)
stack.callback(handle.Close)
copies.append(str(root/'project'))
except (KeyError, TypeError, ValueError, OSError, pywintypes.error) as error:
raise LibraryBusy(f'Export analysis release is not proven: {error}') from error
yield copies
def finish_export_analysis(library, token):
from .library_lock import _guard, blocker_path, checkpoint_record, LibraryBusy
with _guard, prove_export_copies_released(library):
marker = blocker_path(library)
checkpoint = checkpoint_record(marker)
records = checkpoint.get('export_analysis', []) if checkpoint else []
if len(records) != 1 or records[0].get('token') != token:
raise LibraryBusy('Export ownership changed before confirmed cleanup.')
del checkpoint['export_analysis']
_write_json(marker, checkpoint)
File diff suppressed because it is too large. Load diff
+285
View File
@@ -0,0 +1,285 @@
"""Backed-up, single-attempt recovery through the installed native tool."""
from dataclasses import dataclass
import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import time
from uuid import uuid4
@dataclass(frozen=True)
class RepairTarget:
project: Path
database: Path
def select_repair_target(request, diagnosis):
from .verify_runner import preflight
if diagnosis.get('error_code') != 'ICDB_REPAIR_REQUIRED' or not diagnosis.get('session'):
raise ValueError('REPAIR_TARGET_UNCONFIRMED: 缺少原生失联会话信息')
if diagnosis.get('scope') == 'central_library':
raise ValueError('SHARED_DATABASE_REPAIR_UNSUPPORTED: 当前原生 Repair 入口要求 PRJ,不能改修无关的 Work 工程')
if diagnosis.get('scope') != 'project':
raise ValueError('REPAIR_TARGET_UNCONFIRMED: 数据库所有权范围未知')
project, pcb = preflight(request)
try:
reported = Path(diagnosis.get('database_path', '')).resolve(strict=True)
except OSError as error:
raise ValueError(f'REPAIR_TARGET_UNCONFIRMED: 报错数据库路径不可用:{error}') from error
for candidate in (project, pcb.parent/'pcb.prj'):
database = candidate.parent/'database'
if (candidate.is_file() and database.resolve() == reported
and reported.is_relative_to(project.parent.resolve())):
if not (reported/'icdb.dat').is_file():
raise ValueError('REPAIR_TARGET_UNCONFIRMED: 未找到目标 icdb.dat')
return RepairTarget(candidate.resolve(), reported)
raise ValueError('REPAIR_TARGET_UNCONFIRMED: 报错数据库不属于本次工程,未猜测或改写路径')
def _hash(path):
digest = hashlib.sha256()
with path.open('rb') as stream:
for chunk in iter(lambda: stream.read(1024*1024), b''):
digest.update(chunk)
return digest.hexdigest()
def backup_project(target, destination):
"""Keep every original file, holding icdb.dat exclusively during the copy."""
import win32con, win32file, pywintypes
source = target.project.parent.resolve()
destination = Path(destination).resolve()
if destination.is_relative_to(source) or source.is_relative_to(destination):
raise ValueError('REPAIR_BACKUP_INVALID: 备份与源工程不能相互包含')
paths = list(source.rglob('*'))
if any(path.is_symlink() or path.is_junction() for path in paths):
raise ValueError('REPAIR_BACKUP_INVALID: 工程包含目录链接,不能完整备份')
if (source/'backup-manifest.json').exists():
raise ValueError('REPAIR_BACKUP_INVALID: 原工程含同名备份清单')
database_file = target.database/'icdb.dat'
try:
handle = win32file.CreateFile(str(database_file), 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
try:
destination.mkdir(parents=True, exist_ok=False)
files = {}
for path in paths:
relative = path.relative_to(source)
copied = destination/relative
if path.is_dir():
copied.mkdir(parents=True, exist_ok=True)
continue
before = path.stat()
copied.parent.mkdir(parents=True, exist_ok=True)
if path == database_file:
with copied.open('wb') as stream:
while True:
try:
_, data = win32file.ReadFile(handle, 1024*1024)
except pywintypes.error as error:
if error.winerror == 38: # ERROR_HANDLE_EOF
break
raise
if not data:
break
stream.write(data)
os.utime(copied, ns=(before.st_atime_ns, before.st_mtime_ns))
digest = _hash(copied)
else:
digest = _hash(path)
shutil.copy2(path, copied)
if _hash(copied) != digest:
raise OSError(f'REPAIR_BACKUP_CHANGED: 文件副本校验失败:{path}')
after = path.stat()
if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
raise OSError(f'REPAIR_BACKUP_CHANGED: 备份期间源文件变化:{path}')
files[str(relative)] = {'size': before.st_size, 'sha256': digest}
if {path.relative_to(source) for path in source.rglob('*')} != {
path.relative_to(source) for path in paths}:
raise OSError('REPAIR_BACKUP_CHANGED: 备份期间工程文件集合变化')
record = {'complete': True, 'source': str(source), 'files': files}
(destination/'backup-manifest.json').write_text(json.dumps(record, ensure_ascii=False, indent=2),
encoding='utf-8')
return record
finally:
handle.Close()
def attempt_recovery(request, diagnosis, evidence_root, *, progress=None):
root = Path(evidence_root)/'native-repair'
root.mkdir(exist_ok=True)
marker = root/'attempt.json'
if marker.exists():
return {'status': 'BLOCKED', 'detail': 'REPAIR_ALREADY_ATTEMPTED', 'evidence': str(root)}
record = {'status': 'BLOCKED', 'evidence_path': str(root),
'release': {'safe_to_continue': False}}
try:
process_record = Path(evidence_root)/'content-check-process.json'
if process_record.is_file():
state = json.loads(process_record.read_text('utf-8')).get('status')
if state in {'RUNNING', 'RETAINED'}:
raise ValueError('IMPORTER_RELEASE_UNCONFIRMED: 内容检查客户端仍占有数据库,未尝试 Repair')
with marker.open('x', encoding='utf-8') as stream:
json.dump({'status': 'PREPARING', 'diagnosis': diagnosis}, stream, ensure_ascii=False)
target = select_repair_target(request, diagnosis)
if progress:
progress({'stage': 'native_repair_start', 'block': request.block_name,
'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 会话尚未退出')
for _pid, _exe, command, _parent in _process_details('cscript.exe'):
if str(target.project).casefold() in str(command).casefold():
raise ValueError('REPAIR_DATABASE_IN_USE: 目标的保存/关闭助手尚未退出')
callback = (lambda event: progress({'block': request.block_name, **event})) if progress else None
record = run_native_repair(target, root, mentor_bin=request.mentor_bin,
timeout_seconds=max(60, request.timeout_seconds), progress=callback)
native_status = record.get('status')
record['release'] = repair_release_state(request, target, record)
if native_status == 'REPAIRED' and record['release']['safe_to_continue'] is not True:
record.update(status='UNCONFIRMED', native_status=native_status,
detail='NATIVE_REPAIR_EVIDENCE_UNCONFIRMED: 原生成功或释放证据不完整')
record['evidence_path'] = str(root)
except Exception as error:
record['detail'] = str(error)
marker.write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
return record
def _native_identity_and_exit_confirmed(target, record):
if not isinstance(record, dict):
return False
release = record.get('release')
if (not isinstance(release, dict) or release.get('safe_to_continue') is not True
or release.get('native_exited') is not True
or not isinstance(release.get('addresses'), list) or release['addresses']
or type(record.get('native_pid')) is not int or record['native_pid'] <= 0
or not isinstance(record.get('unknown_dialogs', []), list)
or record.get('unknown_dialogs')):
return False
try:
for name, expected in (('project', target.project), ('database', target.database)):
path = record.get(name)
if (not isinstance(path, str) or not Path(path).is_absolute()
or Path(path).resolve(strict=True) != expected.resolve(strict=True)):
return False
except (OSError, ValueError):
return False
return True
def native_success_confirmed(target, record):
"""Validate the worker's complete, consistent success before any reopening."""
if not _native_identity_and_exit_confirmed(target, record) or record.get('status') != 'REPAIRED':
return False
evidence = record.get('evidence')
if (not isinstance(evidence, dict) or evidence.get('confirmed') is not True
or evidence.get('native_backup') is not True
or evidence.get('outcome') != 'UNCONFIRMED'
or evidence.get('failure_complete') is not False
or evidence.get('restore_complete') is not False
or evidence.get('restored_from_backup') != ''):
return False
fields = ('diagnostic_tail', 'database_tail', 'restore_tail', 'output_tail')
if any(not isinstance(evidence.get(field), str) for field in fields):
return False
if not evidence['diagnostic_tail'] or not evidence['database_tail']:
return False
from .native_repair_ui import classify_repair_evidence
return (classify_repair_evidence(*(evidence[field] for field in fields))['outcome'] == 'UNCONFIRMED'
and 'iCDB database restored from backup:' not in evidence['restore_tail'])
def repair_release_state(request, target, native_result):
"""Require normal exit, owner/address absence and exclusive database access."""
from .mentor_adapter import pcb_processes, _process_details
from .icdb_ownership import database_directories, unreleased_addresses
from .verify_runner import preflight
release = native_result.get('release') if isinstance(native_result, dict) else None
result = {**(release if isinstance(release, dict) else {}), 'safe_to_continue': False,
'database_exclusive': False}
try:
if (not _native_identity_and_exit_confirmed(target, native_result)
or (native_result.get('status') == 'REPAIRED'
and not native_success_confirmed(target, native_result))):
result['error'] = 'NATIVE_REPAIR_EVIDENCE_UNCONFIRMED'
return result
project, pcb = preflight(request)
owners = [int(r[0]) for r in pcb_processes()]
for name in ('LibraryManager.exe', 'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe'):
owners.extend(int(r[0]) for r in _process_details(name))
for pid, _exe, command, _parent in _process_details('cscript.exe'):
if (not command or str(project).casefold() in command.casefold()
or str(pcb).casefold() in command.casefold()):
owners.append(int(pid))
result.update(remaining_pids=sorted(set(owners)),
addresses=unreleased_addresses(request.lmc_file, project, pcb))
if (native_result.get('release', {}).get('safe_to_continue') is not True
or owners or result['addresses']):
return result
import win32con, win32file
files = [target.database/'icdb.dat']
files.extend(folder/'icdb.dat' for folder in database_directories(request.lmc_file, project, pcb)
if (folder/'icdb.dat').is_file())
result['exclusive_databases'] = []
for database_file in dict.fromkeys(files):
handle = win32file.CreateFile(str(database_file), win32con.GENERIC_READ,
0, None, win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
handle.Close()
result['exclusive_databases'].append(str(database_file))
result.update(database_exclusive=True, safe_to_continue=True)
except Exception as error:
result['error'] = str(error)
return result
def run_native_repair(target, root, *, mentor_bin='', timeout_seconds=300, progress=None,
maintenance_context=None):
"""Supervise the GUI on its own desktop; a repair timeout never kills it."""
from .desktop_worker import DesktopWorker
root = Path(root)
root.mkdir(parents=True, exist_ok=True)
job_path = root/'repair-request.json'
cancel = root/'cancel-repair.signal'
desktop = 'CbbRepair_'+uuid4().hex[:12]
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},
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
event_count = 0
try:
while worker.poll() is None and time.monotonic()<deadline:
event_file = root/'repair-events.jsonl'
if progress and event_file.is_file():
lines = event_file.read_text('utf-8').splitlines()
for line in lines[event_count:]:
try:
progress(json.loads(line))
except json.JSONDecodeError:
break
event_count += 1
time.sleep(.2)
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,
'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':
result['status'] = 'UNCONFIRMED'
return {**result, 'evidence_path': str(root)}
finally:
worker.close()
+341
View File
@@ -0,0 +1,341 @@
"""Drive the installed Project Backup Repair command on a private desktop."""
import ctypes
from ctypes import wintypes
import json
import ntpath
from pathlib import Path
import re
import shutil
import subprocess
import time
import zipfile
def confirmation_allowed(main_title, project, text):
title = main_title.removeprefix('iCDB Project Backup - ')
if ntpath.normcase(ntpath.normpath(title)) != ntpath.normcase(ntpath.normpath(str(project))):
return False
normalized = ' '.join(text.casefold().split())
return all(marker in normalized for marker in (
'the project content will be validated and repaired if necessary.',
'a project backup will be created before any action take place.',
'you will be able to revert all changes using that backup.'))
def repair_completed(diagnostic_text, database_text, *, native_backup):
combined = diagnostic_text+'\n'+database_text
if re.search(r'\bERROR\s*:|not repaired|repair.*failed', combined, re.IGNORECASE):
return False
return bool(native_backup and 'Diagnostic: FINISH' in diagnostic_text
and ('Diagnostic: Snapshot:' in diagnostic_text or 'Diagnostic: START' in diagnostic_text)
and 'iCDBProjectBackupRepair' in database_text and 'IC: Closing project' in database_text)
def classify_repair_evidence(diagnostic, database, restore, output):
"""Classify this invocation only; an error alone does not prove native idle."""
combined = '\n'.join((diagnostic, database, restore, output))
# This observed loading-progress line precedes the actual ownership verdict.
combined = re.sub(r'(?im)^\s*(?:\[[^\]\r\n]+\]\s*)?Checking if project is in use\.\s*$', '', combined)
terminal_error = bool(re.search(r'Repair project error\s*\[[^\r\n]+\]', output, re.I))
closed_error = ('Diagnostic: FINISH' in diagnostic and 'IC: Closing project' in database)
if re.search(r'project is in use|database.*(?:in use|busy)|other clients are connected', combined, re.I):
outcome = 'DATABASE_BUSY'
elif re.search(r'there is no backup of (?:missing )?iCDB|no (?:healthy|valid) backup', combined, re.I):
outcome = 'MISSING_HEALTHY_BACKUP'
elif re.search(r'\bERROR\s*:|not repaired|repair.*failed|Repair project error', combined, re.I):
outcome = 'NATIVE_REPAIR_FAILED'
else:
outcome = 'UNCONFIRMED'
return {'outcome': outcome, 'failure_complete': bool(
outcome != 'UNCONFIRMED' and (terminal_error or closed_error))}
def _current_desktop_name():
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
user32 = ctypes.WinDLL('user32', use_last_error=True)
kernel32.GetCurrentThreadId.restype = wintypes.DWORD
user32.GetThreadDesktop.argtypes = [wintypes.DWORD]
user32.GetThreadDesktop.restype = wintypes.HANDLE
user32.GetUserObjectInformationW.argtypes = [wintypes.HANDLE, ctypes.c_int,
wintypes.LPVOID, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)]
desktop = user32.GetThreadDesktop(kernel32.GetCurrentThreadId())
name = ctypes.create_unicode_buffer(512)
required = wintypes.DWORD()
if not user32.GetUserObjectInformationW(desktop, 2, name, ctypes.sizeof(name), ctypes.byref(required)):
raise ctypes.WinError(ctypes.get_last_error())
return name.value
def _repair_command(executable):
import win32api, win32gui, win32con
user32 = ctypes.WinDLL('user32')
user32.GetMenuStringW.argtypes = [wintypes.HMENU, wintypes.UINT, wintypes.LPWSTR,
ctypes.c_int, wintypes.UINT]
library = win32api.LoadLibraryEx(str(executable), 0, 2) # data resources only
commands = set()
def walk(menu, parents=()):
for index in range(win32gui.GetMenuItemCount(menu)):
value = ctypes.create_unicode_buffer(512)
user32.GetMenuStringW(menu, index, value, len(value), win32con.MF_BYPOSITION)
label = value.value.replace('&', '').split('\t')[0].strip().casefold()
sub = win32gui.GetSubMenu(menu, index)
if sub:
walk(sub, (*parents, label))
elif parents == ('project',) and label == 'repair':
commands.add(win32gui.GetMenuItemID(menu, index))
try:
for name in win32api.EnumResourceNames(library, 4):
menu = win32gui.LoadMenu(library, name)
try:
walk(menu)
finally:
win32gui.DestroyMenu(menu)
finally:
win32api.FreeLibrary(library)
if len(commands) != 1:
raise ValueError('NATIVE_REPAIR_UNSUPPORTED: 未唯一定位原生 Project/Repair 菜单')
return commands.pop()
def _windows(pid):
import win32gui, win32process
windows = []
def observe(hwnd, _):
if win32process.GetWindowThreadProcessId(hwnd)[1] != pid or not win32gui.IsWindowVisible(hwnd):
return
children = []
def child(handle, _):
if win32gui.IsWindowVisible(handle):
children.append({'hwnd': handle, 'text': win32gui.GetWindowText(handle),
'class': win32gui.GetClassName(handle), 'id': win32gui.GetDlgCtrlID(handle),
'enabled': bool(win32gui.IsWindowEnabled(handle))})
win32gui.EnumChildWindows(hwnd, child, None)
windows.append({'hwnd': hwnd, 'title': win32gui.GetWindowText(hwnd),
'class': win32gui.GetClassName(hwnd), 'enabled': bool(win32gui.IsWindowEnabled(hwnd)),
'children': children})
win32gui.EnumWindows(observe, None)
return windows
def _native_output(windows):
"""Read Output without UI activation; a hung control has a bounded deadline."""
user32 = ctypes.WinDLL('user32', use_last_error=True)
user32.SendMessageTimeoutW.argtypes = [wintypes.HWND, wintypes.UINT, wintypes.WPARAM,
wintypes.LPARAM, wintypes.UINT, wintypes.UINT, ctypes.POINTER(ctypes.c_size_t)]
user32.SendMessageTimeoutW.restype = wintypes.LPARAM
texts = []
for window in windows:
for child in window['children']:
if not child['class'].casefold().startswith('richedit'):
continue
buffer = ctypes.create_unicode_buffer(131072)
copied = ctypes.c_size_t()
if not user32.SendMessageTimeoutW(child['hwnd'], 0x000D, len(buffer),
ctypes.addressof(buffer), 0x0002, 200, ctypes.byref(copied)):
return None
if copied.value >= len(buffer)-1:
return None # A truncated prefix cannot establish the current operation.
texts.append(buffer.value)
return '\n'.join(texts) if texts else None
def _native_evidence(project, database, pid, started_ns, baseline, *, output_text=''):
"""Use only this native process's new diagnostic/close and backup evidence."""
log_paths = []
def read_logs(folder):
text = []
for path in (database/'cdbsvr'/folder).glob(f'*-{pid}/*.txt'):
if path.stat().st_mtime_ns >= started_ns:
log_paths.append(str(path))
text.append(path.read_bytes()[-256*1024:].decode('utf-8', errors='replace'))
return '\n'.join(text)
from .icdb_recovery import read_log_failure
backup_log = project.parent/'Log Files/ProjectBackupLog.txt'
text, _ = read_log_failure(backup_log, baseline)
matches = re.findall(r'Successfully created \[Project Repair\] backup \[([^\]]+)\]', text)
native_backup = False
for name in matches:
# Native default storage verified here; alternate storage needs its own
# target/backup validation and must not silently become success.
if Path(name).name != name:
continue
archive = project.parent/'ProjectBackup/backups'/name
if archive.is_file():
with zipfile.ZipFile(archive) as zipped:
native_backup = bool(zipped.namelist()) and zipped.testzip() is None
diagnostic, db_log = read_logs('dbcheck'), read_logs('log')
restore_log = read_logs('dbrestore')
restored = re.search(r'iCDB database restored from backup:\s*([^\r\n]+)', restore_log)
classification = classify_repair_evidence(diagnostic, db_log, restore_log, output_text)
valid = (classification['outcome'] == 'UNCONFIRMED' and not restored
and str(database).casefold() in db_log.casefold()
and repair_completed(diagnostic, db_log, native_backup=native_backup))
return {**classification, 'confirmed': bool(valid), 'native_backup': native_backup,
'output_tail': output_text[-8192:], 'log_paths': log_paths,
'backup_log_tail': text[-8192:],
'diagnostic_tail': diagnostic[-8192:], 'database_tail': db_log[-8192:],
'restored_from_backup': restored.group(1).strip() if restored else '',
'restore_complete': bool(restored and '[0] DONE' in restore_log
and 'Diagnostic: FINISH' in diagnostic),
'restore_tail': restore_log[-8192:]}
def repair_worker_main(job_path):
import win32con, win32gui
from .native_repair import RepairTarget, backup_project
from .mentor_paths import discover_sdd_home
from .icdb_recovery import snapshot_log
job = json.loads(Path(job_path).read_text('utf-8'))
root = Path(job['root'])
project, database = Path(job['project']), Path(job['database'])
result = {'status': 'BLOCKED', 'project': str(project), 'database': str(database),
'release': {'safe_to_continue': False}}
process = None
def emit(**event):
with (root/'repair-events.jsonl').open('a', encoding='utf-8') as stream:
stream.write(json.dumps(event, ensure_ascii=False)+'\n')
try:
if (not str(job.get('desktop', '')).startswith('CbbRepair_')
or _current_desktop_name() != job['desktop']):
raise ValueError('REPAIR_PRIVATE_DESKTOP_REQUIRED')
if not job.get('supervisor_pid'):
raise ValueError('REPAIR_SUPERVISOR_REQUIRED')
from .desktop_worker import start_supervisor_watchdog
start_supervisor_watchdog(job['supervisor_pid'], cancel_path=job['cancel_signal'])
if project.suffix.casefold() != '.prj' or database.resolve() != (project.parent/'database').resolve():
raise ValueError('REPAIR_TARGET_UNCONFIRMED')
home = discover_sdd_home(job.get('mentor_bin'))
if home is None:
raise ValueError('NATIVE_REPAIR_UNAVAILABLE: 未找到 Mentor 安装目录')
executable = home/'iCDB/win32/bin/iCDBProjectBackup.exe'
command_id = _repair_command(executable)
from .mentor_adapter import pcb_processes, _process_details
if 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:
from .maintenance_entry import maintenance_target_guard
from .verify_runner import VerifyRequest
maintenance_request = VerifyRequest(Path(maintenance_context['library']),
maintenance_context['block'], root, maintenance=True)
with maintenance_target_guard(maintenance_request, maintenance_context) as checked:
if (checked['target'].project.resolve() != project.resolve()
or checked['target'].database.resolve() != database.resolve()):
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED')
backup_project(RepairTarget(project, database), root/'complete-backup')
emit(stage='complete_backup_verified', path=str(root/'complete-backup'))
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
baseline = snapshot_log(project.parent/'Log Files/ProjectBackupLog.txt')
started_ns = time.time_ns()
process = subprocess.Popen([str(executable), '-p', str(project)], cwd=str(project.parent))
result['native_pid'] = process.pid
emit(stage='native_started', pid=process.pid, project=str(project))
deadline = time.monotonic()+max(1, float(job['timeout']))
invoked = confirmed = closing = False
evidence = None
output_baseline = None
output = ''
while process.poll() is None and time.monotonic()<deadline:
windows = [w for w in _windows(process.pid) if not (
w['title'] == '' and w['class'] in (
'UAC_InputIndicatorOverlayWnd', 'UAC Input Indicator'))]
mains = [w for w in windows if w['class'].startswith('Afx:')
and w['title'].casefold() == ('iCDB Project Backup - '+str(project)).casefold()]
main = mains[0] if len(mains) == 1 else None
# The native Afx shell appears before it loads the requested PRJ.
# Only a unique, exact generic shell before Repair may wait here;
# it never authorizes a command or masks another target/window.
shells = [w for w in windows if not invoked and w['class'].startswith('Afx:')
and w['title'] == 'iCDB Project Backup']
starting = shells[0] if len(shells) == 1 and not mains else None
dialogs = [w for w in windows if w['class'] == '#32770']
unknown = [w for w in windows if w is not main and w is not starting and w not in dialogs]
current_output = _native_output(windows)
busy_before_start = (not invoked and current_output is not None
and classify_repair_evidence('', '', '', current_output)['outcome'] == 'DATABASE_BUSY')
if busy_before_start:
output = current_output
result.update(status='DATABASE_BUSY', detail='原生工具加载工程时报告占用;未请求 Repair')
maintenance_ready = (maintenance_context is None or isinstance(current_output, str)
and 'Project is not in use. Full iCDB Project Backup\'s functionality is available.' in current_output)
if (not invoked and isinstance(current_output, str) and not busy_before_start and maintenance_ready
and main and not dialogs and not unknown and main['enabled']):
if Path(job['cancel_signal']).exists():
raise ValueError('REPAIR_CANCELLED_BEFORE_START')
output_baseline = current_output
win32gui.PostMessage(main['hwnd'], win32con.WM_COMMAND, command_id, 0)
invoked = True
emit(stage='native_repair_requested', command=command_id)
if dialogs or unknown:
known = [d for d in dialogs if invoked and not confirmed and main
and confirmation_allowed(main['title'], project,
'\n'.join(c['text'] for c in d['children']))]
if unknown or len(dialogs) != 1 or len(known) != 1:
result.update(status='UNKNOWN_DIALOG', unknown_dialogs=[*unknown, *dialogs],
detail='未知原生弹窗;未发送操作,保留原生工具')
# Capture evidence below before stopping supervision.
else:
dialog = known[0]
text = '\n'.join(c['text'] for c in dialog['children'])
if confirmation_allowed(main['title'], project, text):
if Path(job['cancel_signal']).exists():
raise ValueError('REPAIR_CANCELLED_BEFORE_CONFIRM')
button = next((c for c in dialog['children'] if c['class'] == 'Button'
and c['id'] == 1 and c['enabled']), None)
if button:
win32gui.PostMessage(button['hwnd'], win32con.BM_CLICK, 0, 0)
confirmed = True
emit(stage='native_repair_confirmed', text=text)
if (invoked and output_baseline is not None and current_output is not None
and current_output.startswith(output_baseline)):
output = current_output[len(output_baseline):]
evidence = _native_evidence(project, database, process.pid, started_ns, baseline,
output_text=output)
(root/'native-output.json').write_text(json.dumps({
'native_pid': process.pid, 'baseline': output_baseline, 'current': current_output,
'invocation_output': output}, ensure_ascii=False, indent=2), encoding='utf-8')
if result['status'] == 'UNKNOWN_DIALOG' or busy_before_start:
break
if confirmed and not closing and main and not dialogs and main['enabled']:
if (evidence['outcome'] != 'DATABASE_BUSY'
and not (database/'cdbsvr/sAddress.adr').exists() and (
evidence['failure_complete'] or evidence['confirmed'] or (evidence.get('restore_complete')
and evidence['native_backup']
and evidence['outcome'] == 'UNCONFIRMED'))):
win32gui.PostMessage(main['hwnd'], win32con.WM_CLOSE, 0, 0)
closing = True
emit(stage='native_repair_finished', **evidence)
time.sleep(.2)
if evidence:
result['evidence'] = evidence
for log_path in evidence['log_paths']:
source = Path(log_path)
destination = root/'native-logs'/source.relative_to(database/'cdbsvr')
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, destination)
addresses = [str(database/'cdbsvr/sAddress.adr')] if (database/'cdbsvr/sAddress.adr').exists() else []
result['release'] = {'native_exited': process.poll() is not None, 'addresses': addresses,
'safe_to_continue': process.poll() is not None and not addresses}
if result['status'] == 'UNKNOWN_DIALOG':
pass
elif evidence and evidence['outcome'] != 'UNCONFIRMED':
result.update(status=evidence['outcome'], detail='原生 Repair 失败;详见本次日志和 Output')
elif (closing and process.poll() == 0 and evidence and evidence.get('restore_complete')
and not (database/'cdbsvr/sAddress.adr').exists()):
result.update(status='RESTORED_REVIEW_REQUIRED', evidence=evidence,
detail='原生工具从已有备份恢复数据库;需核对恢复版本和工程内容,未自动重试校验')
elif (closing and process.poll() == 0 and evidence and evidence['confirmed']
and not (database/'cdbsvr/sAddress.adr').exists()):
result.update(status='REPAIRED', evidence=evidence)
else:
result.update(status='TIMEOUT_UNRELEASED' if process.poll() is None else 'UNCONFIRMED',
detail='原生 Repair 未取得完整成功/释放证据,未重试校验')
except Exception as error:
result.update(detail=str(error), status='RETAINED' if process and process.poll() is None else 'BLOCKED')
# 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')
return 0 if result['status'] == 'REPAIRED' else 1
+5
View File
@@ -103,6 +103,11 @@ def wait_for_target_document(job, app_provider, *, process_alive, emit=lambda **
try: try:
app = app_provider() app = app_provider()
document = app.ActiveDocument document = app.ActiveDocument
if not document:
observation = ('PCB_DOCUMENT_NOT_READY', 'COM 已连接,尚无目标文档')
if observation != last_observation:
emit(stage='pcb_document_wait', error_code=observation[0], detail=observation[1])
last_observation = observation
if document: if document:
try: try:
integration = require_document_identity(document, job) integration = require_document_identity(document, job)
@@ -0,0 +1,279 @@
"""One-use, local-only read/write consent after proven explicit native Repair.
No normal Verify or declarative rule can enable this path. Database recovery
choices other than the captured read/write question remain unsupported.
"""
from contextlib import ExitStack
from dataclasses import dataclass
import json
import os
from pathlib import Path
import stat
import time
from uuid import uuid4
PROMPT_TEXT = ("If an XDS or ExpeditionPCB is running on this design, it's likely that\n"
"your file system and/or network system was too slow to determine\n"
"which product the design is open in within the 15 second timeout\nperiod.\n\n"
"Otherwise, the design may not have been closed properly due to\n"
"the XDS or ExpeditionPCB crashing in the last session.\n\n"
"Before continuing, please confirm that no other users have the\ndesign open.\n\n"
"Continue to open the design with read/write access permission?")
def _drive_type(path):
import win32file
return win32file.GetDriveType(str(Path(path).anchor))
def require_local_fixed(path):
from .network_path import absolute_preserving_drive
path = absolute_preserving_drive(path)
if path.drive.startswith('\\') or _drive_type(path) != 3:
raise ValueError('LOCAL_FIXED_REQUIRED: 修复后读写确认仅支持本地固定磁盘;UNC/网络盘不自动授权')
for item in (path, *path.parents):
if item.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
raise ValueError('LOCAL_FIXED_REQUIRED: 不允许重解析点、目录链接或挂载路径')
return path
def _same(a, b):
return Path(a).resolve() == Path(b).resolve()
def _process_records():
import win32com.client
names = ('ExpeditionPCB.exe', 'LibraryManager.exe', 'viewdraw.exe', 'XDS.exe',
'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe', 'CleanWGLib.exe',
'cscript.exe', 'wscript.exe', 'python.exe', 'pythonw.exe', 'CbbRefreshVerify.exe')
service = win32com.client.GetObject('winmgmts:')
rows = service.ExecQuery('SELECT ProcessId, Name, ExecutablePath, CommandLine, ParentProcessId '
'FROM Win32_Process WHERE ' + ' OR '.join(f"Name='{n}'" for n in names))
records = []
for item in rows:
name, command = str(item.Name), str(item.CommandLine or '')
if name.casefold() in ('python.exe', 'pythonw.exe', 'cbbrefreshverify.exe') and command and not any(
flag in command for flag in ('--verify-worker', '--repair-worker', '--management-worker', '--dialog-agent')):
continue
records.append((int(item.ProcessId), name, str(item.ExecutablePath or ''), command, int(item.ParentProcessId or 0)))
return records
@dataclass(frozen=True)
class PostRepairProof:
library: str
project: str
pcb: str
block: str
repair_project: str
repair_database: str
repair_json: str
nonce: str
@classmethod
def create(cls, request, target, recovery):
from .native_repair import native_success_confirmed
from .verify_runner import preflight
if request.maintenance is not True or not native_success_confirmed(target, recovery):
raise ValueError('POST_REPAIR_PROOF_REQUIRED: 必须是明确维护且严格确认的原生修复')
if request.mapped_remote_root:
raise ValueError('LOCAL_FIXED_REQUIRED: 网络映射库不自动确认修复后的读写访问')
project, pcb = preflight(request)
for path in (request.lmc_file, project, pcb, target.database/'icdb.dat', pcb.parent/'Layout/LayoutDB.lyt'):
require_local_fixed(path)
return cls(str(request.lmc_file), str(project), str(pcb), request.block_name,
str(target.project), str(target.database), json.dumps(recovery, ensure_ascii=False, default=str), uuid4().hex)
def for_job(self, job):
if (job.get('interactive_input') or job.get('native_lm_verify')
or not str(job.get('desktop', '')).startswith('CbbVerify_')
or job['block_name'] != self.block
or not all(_same(job[key], value) for key, value in (
('lmc_file', self.library), ('project', self.project), ('pcb', self.pcb)))):
raise ValueError('POST_REPAIR_TARGET_MISMATCH')
return {'nonce': self.nonce, 'intent': 'explicit_maintenance_after_confirmed_repair',
'library': self.library, 'project': self.project, 'pcb': self.pcb, 'block': self.block,
'repair_project': self.repair_project, 'repair_database': self.repair_database,
'repair': json.loads(self.repair_json), 'desktop': job['desktop'], 'root': job['root']}
def _validate_grant(job):
from .native_repair import RepairTarget, native_success_confirmed
grant = job.get('post_repair_consent')
if (not isinstance(grant, dict) or grant.get('intent') != 'explicit_maintenance_after_confirmed_repair'
or not isinstance(grant.get('nonce'), str) or len(grant['nonce']) != 32
or job.get('interactive_input') or job.get('native_lm_verify') or job.get('mapped_remote_root')
or grant.get('desktop') != job.get('desktop') or not str(job.get('desktop', '')).startswith('CbbVerify_')
or not _same(grant['root'], job['root']) or grant.get('block') != job.get('block_name')
or not all(_same(grant[key], job[field]) for key, field in (
('library', 'lmc_file'), ('project', 'project'), ('pcb', 'pcb')))):
raise ValueError('POST_REPAIR_PROOF_INVALID')
target = RepairTarget(Path(grant['repair_project']), Path(grant['repair_database']))
if not native_success_confirmed(target, grant['repair']):
raise ValueError('POST_REPAIR_PROOF_INVALID: 原生成功证据不完整')
return grant
def prepare_launch(job, command):
"""Called on the private worker immediately before direct PCB launch."""
import win32file, win32con
from .icdb_ownership import database_directories, unreleased_addresses
from .management import _write_json
grant = _validate_grant(job)
from .native_repair_ui import _current_desktop_name
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'):
require_local_fixed(path)
if len(command) != 3 or not _same(command[1], pcb) or command[2] != '-ReusableCircuit':
raise ValueError('POST_REPAIR_LAUNCH_MISMATCH')
def require_idle():
# Self is an expected automation worker, never a native owner.
others = [r for r in _process_records() if r[0] not in (os.getpid(), int(job['supervisor_pid']))
and not (r[1].casefold() in ('python.exe', 'pythonw.exe', 'cbbrefreshverify.exe')
and '--dialog-agent' in r[3] and r[4] == int(job['supervisor_pid']))]
if others: raise ValueError('POST_REPAIR_FOREIGN_OWNER: 存在其他原生进程或助手')
require_idle()
if unreleased_addresses(library, project, pcb): raise ValueError('POST_REPAIR_ADDRESS_REMAINS')
files = [library, pcb.parent/'Layout/LayoutDB.lyt']
files.extend(folder/'icdb.dat' for folder in database_directories(library, project, pcb) if (folder/'icdb.dat').is_file())
with ExitStack() as stack:
for path in dict.fromkeys(files):
require_local_fixed(path)
try:
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
except Exception as error:
raise ValueError(f'POST_REPAIR_EXCLUSIVE_ACCESS_REQUIRED: {path}: {error}') from error
stack.callback(handle.Close)
if unreleased_addresses(library, project, pcb): raise ValueError('POST_REPAIR_ADDRESS_CHANGED')
require_idle()
_write_json(Path(job['root'])/'post-repair-prelaunch.json', {
'nonce': grant['nonce'], 'desktop': job['desktop'], 'project': str(project), 'pcb': str(pcb),
'library': str(library), 'worker_pid': os.getpid(), 'supervisor_pid': job['supervisor_pid'],
'command': list(command), 'exclusive_files': [str(path) for path in dict.fromkeys(files)],
'addresses': [], 'monotonic': time.monotonic()})
def exact_prompt(snapshot):
from .dialog_models import DialogPhase
if (snapshot.phase != DialogPhase.PCB_STARTING or snapshot.process_name.casefold() != 'expeditionpcb.exe'
or snapshot.process_role != 'pcb' or snapshot.window_class != '#32770' or snapshot.title != 'Expedition PCB'):
return False
controls = []
for control in snapshot.controls:
self_window = (control.handle == snapshot.hwnd and control.control_id == 0
and control.class_name == snapshot.window_class and control.name == snapshot.title
and control.control_type == 'Window' and control.patterns == ('Window',))
uia_chrome = (control.handle == 0 and control.control_id == 0
and control.class_name == '' and control.automation_id == ''
and not control.selected and not control.checked and (
control.control_type == 'TitleBar' and control.name == '' and control.patterns == ('Value',)
or control.control_type == 'Button' and not control.enabled
and control.name in ('关闭', 'Close') and control.patterns == ('Invoke',)))
if not self_window and not uia_chrome:
controls.append(control)
buttons = [c for c in controls if c.class_name == 'Button']
static = [c for c in controls if c.class_name == 'Static' and c.name.strip()]
return (len(buttons) == 2 and {c.control_id for c in buttons} == {6, 7}
and all(c.enabled for c in buttons) and len(static) == 1 and static[0].control_id == 65535
and ' '.join(static[0].name.split()) == ' '.join(PROMPT_TEXT.split())
and all(c.class_name == 'Button' or c.class_name == 'Static' and c.control_id in (20, 65535)
for c in controls))
def _validate_current_processes(job, prelaunch, target_pid, launcher_pid, worker_pid, companion_pids):
from .mentor_adapter import is_reusable_circuit_pcb
rows = _process_records()
by_pid = {r[0]: r for r in rows}
if target_pid not in by_pid or launcher_pid not in by_pid:
raise ValueError('POST_REPAIR_PROCESS_UNCONFIRMED')
target, launcher = by_pid[target_pid], by_pid[launcher_pid]
executable = Path(prelaunch['command'][0])
expected_worker = executable.parents[3]/'wg/win32/bin/ExpeditionPCB.exe'
if (not _same(launcher[2], executable) or not _same(target[2], expected_worker)
or launcher[4] != worker_pid or target[4] != launcher_pid
or not is_reusable_circuit_pcb(target[2], target[3], job['pcb'])
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')
class ConsentController:
def __init__(self, proof, job):
if not isinstance(proof, PostRepairProof): raise ValueError('POST_REPAIR_PROOF_REQUIRED')
self.grant = proof.for_job(job)
self.job = json.loads(json.dumps(job))
self.used = False
self.snapshot = None
self.sent_at = 0.0
def handle(self, snapshot, snapshots, *, target_pid, launcher_pid, worker_pid, companion_pids, perform):
from .dialog_supervisor import DialogPollResult
from .management import _write_json
try:
if not exact_prompt(snapshot) or snapshot.pid != target_pid:
raise ValueError('POST_REPAIR_PROMPT_MISMATCH')
if len(snapshots) != 1:
raise ValueError('POST_REPAIR_ADDITIONAL_DIALOG')
if self.used:
if (self.snapshot.hwnd == snapshot.hwnd and self.snapshot.signature == snapshot.signature
and time.monotonic() - self.sent_at < 2):
return DialogPollResult(activity=False, observed_snapshots=tuple(snapshots))
raise ValueError('POST_REPAIR_CONSENT_ALREADY_USED')
pre = json.loads((Path(self.job['root'])/'post-repair-prelaunch.json').read_text(encoding='utf-8'))
required = {Path(self.grant['library']).resolve(),
(Path(self.grant['pcb']).parent/'Layout/LayoutDB.lyt').resolve(),
(Path(self.grant['repair_database'])/'icdb.dat').resolve()}
if (pre.get('nonce') != self.grant['nonce'] or pre.get('desktop') != self.job['desktop']
or pre.get('worker_pid') != worker_pid or pre.get('addresses') != []
or pre.get('supervisor_pid') != self.job['supervisor_pid']
or not required.issubset({Path(p).resolve() for p in pre.get('exclusive_files', [])})
or not 0 <= time.monotonic() - pre.get('monotonic', 0) <= 180
or not all(_same(pre[key], self.grant[key]) for key in ('project', 'pcb', 'library'))):
raise ValueError('POST_REPAIR_PRELAUNCH_PROOF_INVALID')
for path in (self.grant['library'], self.grant['project'], self.grant['pcb']): require_local_fixed(path)
_validate_current_processes(self.job, pre, target_pid, launcher_pid, worker_pid, companion_pids)
payload = {'action': 'post_repair_local_read_write', 'channels': ['win32_button_click'],
'target': {'control_id': 6}, 'postcondition': 'window_gone',
'desktop': self.job['desktop'], 'pid': target_pid}
# Consume before messaging: failure/timeout cannot authorize another click.
self.used = True; self.snapshot = snapshot; self.sent_at = time.monotonic()
_write_json(Path(self.job['root'])/'post-repair-consent.json', {
'nonce': self.grant['nonce'], 'consumed': True, 'target_pid': target_pid,
'launcher_pid': launcher_pid, 'worker_pid': worker_pid, 'snapshot': snapshot.to_record()})
result = perform(snapshot, payload, snapshot.phase)
return DialogPollResult(activity=True, action_sent=bool(result.accepted_controls), snapshot=snapshot,
error_code=result.error_code, detail=result.detail, accepted_controls=result.accepted_controls,
action=payload['action'], channel=result.channel, rule_id='explicit-local-post-repair-consent',
observed_snapshots=tuple(snapshots))
except Exception as error:
return DialogPollResult(error_code='DATABASE_RECOVERY_REQUIRED', detail=str(error),
snapshot=snapshot, observed_snapshots=tuple(snapshots))
def validate_action_window(snapshot, action):
"""Final check on the agent's actual private desktop, immediately before Yes."""
import win32gui, win32process
from .native_repair_ui import _current_desktop_name
from .dialog_models import ControlSnapshot
if (not exact_prompt(snapshot) or snapshot.pid != action.get('pid')
or _current_desktop_name() != action.get('desktop')
or not str(action.get('desktop', '')).startswith('CbbVerify_')
or win32process.GetWindowThreadProcessId(snapshot.hwnd)[1] != snapshot.pid
or win32gui.GetClassName(snapshot.hwnd) != snapshot.window_class
or win32gui.GetWindowText(snapshot.hwnd) != snapshot.title or not win32gui.IsWindowVisible(snapshot.hwnd)):
raise ValueError('POST_REPAIR_LIVE_WINDOW_MISMATCH')
children = []
win32gui.EnumChildWindows(snapshot.hwnd, lambda hwnd, _: children.append(int(hwnd)), None)
live = tuple(ControlSnapshot(hwnd, win32gui.GetDlgCtrlID(hwnd) & 0xFFFF,
win32gui.GetClassName(hwnd), win32gui.GetWindowText(hwnd), enabled=bool(win32gui.IsWindowEnabled(hwnd)))
for hwnd in children)
from dataclasses import replace
if not exact_prompt(replace(snapshot, controls=live)):
raise ValueError('POST_REPAIR_LIVE_PROMPT_CHANGED')
yes = next(c for c in live if c.control_id == 6)
if yes.handle != next(c.handle for c in snapshot.controls if c.control_id == 6):
raise ValueError('POST_REPAIR_BUTTON_CHANGED')
@@ -5,8 +5,12 @@ Set app = GetObject(, "MGCPCB.Application")
Set doc = app.ActiveDocument Set doc = app.ActiveDocument
Set pi = doc.ProjectIntegration Set pi = doc.ProjectIntegration
If LCase(pi.ProjectFile) <> LCase(expected) Then WScript.Quit 2 If LCase(pi.ProjectFile) <> LCase(expected) Then WScript.Quit 2
If WScript.Arguments.Count > 1 Then
If LCase(doc.Name) <> LCase(WScript.Arguments(1)) Then WScript.Quit 2
End If
If pi.ForwardAnnotationStatus <> 2 Or pi.SynchCESStatus <> 2 Or pi.LoadCESStatus <> 2 Or pi.BackAnnotationStatus <> 2 Then WScript.Quit 3 If pi.ForwardAnnotationStatus <> 2 Or pi.SynchCESStatus <> 2 Or pi.LoadCESStatus <> 2 Or pi.BackAnnotationStatus <> 2 Then WScript.Quit 3
WScript.Echo "VALIDATE_START" WScript.Echo "VALIDATE_START"
CheckCancellation
measuredStart = Timer measuredStart = Timer
Set licensing = CreateObject("MGCPCBAutomationLicensing.Application") Set licensing = CreateObject("MGCPCBAutomationLicensing.Application")
token = licensing.GetToken(doc.Validate(0)) token = licensing.GetToken(doc.Validate(0))
@@ -14,11 +18,13 @@ doc.Validate token
LogElapsed "validate", measuredStart LogElapsed "validate", measuredStart
WScript.Echo "LICENSE_OK" WScript.Echo "LICENSE_OK"
WScript.Echo "SAVE_START" WScript.Echo "SAVE_START"
CheckCancellation
measuredStart = Timer measuredStart = Timer
operationOK = doc.Save() operationOK = doc.Save()
LogElapsed "save", measuredStart LogElapsed "save", measuredStart
If Not operationOK Then WScript.Quit 4 If Not operationOK Then WScript.Quit 4
WScript.Echo "SAVE_OK" WScript.Echo "SAVE_OK"
CheckCancellation
measuredStart = Timer measuredStart = Timer
operationOK = doc.IsSaved() operationOK = doc.IsSaved()
LogElapsed "is_saved", measuredStart LogElapsed "is_saved", measuredStart
@@ -40,6 +46,7 @@ If Not stable Then WScript.Quit 7
WScript.Echo "POST_SAVE_SYNCHRONIZED" WScript.Echo "POST_SAVE_SYNCHRONIZED"
If Not doc.IsSaved() Then WScript.Quit 8 If Not doc.IsSaved() Then WScript.Quit 8
WScript.Echo "CLOSE_START" WScript.Echo "CLOSE_START"
CheckCancellation
measuredStart = Timer measuredStart = Timer
operationOK = doc.Close(True) operationOK = doc.Close(True)
LogElapsed "close", measuredStart LogElapsed "close", measuredStart
@@ -54,6 +61,18 @@ LogElapsed "quit", measuredStart
WScript.Echo "QUIT_OK" WScript.Echo "QUIT_OK"
Set app = Nothing Set app = Nothing
Sub CheckCancellation()
Dim fso, cancelPath
If WScript.Arguments.Count < 3 Then Exit Sub
cancelPath = WScript.Arguments(2)
If Len(cancelPath) = 0 Then Exit Sub
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists(cancelPath) Then
WScript.Echo "VERIFY_CANCELLED"
WScript.Quit 9
End If
End Sub
Sub LogElapsed(phaseName, started) Sub LogElapsed(phaseName, started)
Dim elapsed Dim elapsed
elapsed = Timer - started elapsed = Timer - started
+326
View File
@@ -0,0 +1,326 @@
"""Complete, metadata-verified snapshots with scoped semantic SHA256 manifests.
Unknown engineering files are primary. Only explicit runtime, history and
generated categories are ignored by semantic comparisons; they are still copied
and their membership/size/mtime must remain stable throughout the snapshot.
"""
from concurrent.futures import ThreadPoolExecutor
from contextlib import ExitStack
from dataclasses import asdict, dataclass
import hashlib
import os
from pathlib import Path
import shutil
import stat
MANIFEST_VERSION = 1
_NONPRIMARY_DIRECTORIES = frozenset({
'log', 'logs', 'temp', 'tmp', '__pycache__', 'backup', 'backups',
'output', 'outputs', 'report', 'reports', 'gerber', 'gerbers', 'odb++',
'log files', 'logfiles',
})
_NONPRIMARY_SUFFIXES = frozenset({
'.log', '.tmp', '.temp', '.lck', '.lock', '.bak', '.backup', '.pdf',
})
def _root_runtime(directories):
"""Known runtime/history children of a library or project workspace root."""
return bool(directories and (
directories[0] in _NONPRIMARY_DIRECTORIES
or directories[0].startswith('work.before-restore-')
or directories[:2] == ('projectbackup', 'backups')))
def _native_runtime(directories, database_prefix):
runtime_prefix = database_prefix + ('cdbsvr',)
return (directories[:len(runtime_prefix)] == runtime_prefix
and len(directories) > len(runtime_prefix)
and directories[len(runtime_prefix)] in ('log', 'dbcheck', 'dbrestore'))
def _project_runtime(directories):
return (_root_runtime(directories)
or (directories[:1] == ('pcb',) and _root_runtime(directories[1:]))
or _native_runtime(directories, ('database',))
or _native_runtime(directories, ('pcb', 'database')))
@dataclass(frozen=True)
class ManifestScope:
"""Project root by default; library selects one CBB and shared dependencies."""
kind: str = 'project'
block_name: str = ''
library_name: str = ''
def __post_init__(self):
if self.kind not in ('project', 'library'):
raise ValueError('Unknown manifest scope')
if self.kind == 'library':
for value in (self.block_name, self.library_name):
if not value or value in ('.', '..') or any(c in value for c in '/\\:'):
raise ValueError('Library scope requires single-component block/library names')
@classmethod
def library(cls, block_name, library_name):
return cls('library', block_name, library_name)
def includes_directory(self, relative):
parts = tuple(part.casefold() for part in Path(relative).parts)
if self._runtime_path(parts, directory=True):
return False
if self.kind == 'project' or not parts or parts[0] != 'reusableblockslp':
return True
return ((len(parts) < 2 or parts[1] == self.block_name.casefold())
and (len(parts) < 3 or parts[2] in ('work', 'cert')))
def _runtime_path(self, parts, *, directory=False):
"""Recognize runtime locations only in their structural context.
Generic names such as ``Logs`` are runtime when they are a project-root
or selected Work/Cert child. The same name deeper in an engineering
partition (or in shared SymbolLibs data) remains primary.
"""
directories = parts if directory else parts[:-1]
if not directory and (Path(parts[-1]).suffix in _NONPRIMARY_SUFFIXES
or parts[-1] == 'saddress.adr' or parts[-1].startswith('~$')):
return True
if self.kind == 'project':
return _project_runtime(directories)
if directories[:1] == ('reusableblockslp',):
# Identity and Work/Cert role components never act as runtime names.
if (len(directories) >= 3 and directories[1] == self.block_name.casefold()
and directories[2] in ('work', 'cert')):
return _project_runtime(directories[3:])
return False
if _root_runtime(directories):
return True
# Shared dependency names/partitions are engineering data. Only native
# server runtime subtrees within known DB positions are excluded.
if directories[:1] == ('symbollibs',) and len(directories) >= 2:
return _native_runtime(directories, directories[:2])
return bool(directories and _native_runtime(directories, directories[:1]))
def classify(self, relative):
"""Return a semantic scope label or None; paths are relative to the root."""
parts = tuple(part.casefold() for part in Path(relative).parts)
if self._runtime_path(parts):
return None
if self.kind == 'project':
return 'project'
if parts[0] == 'reusableblockslp':
if len(parts) < 4 or parts[1] != self.block_name.casefold():
return None
return {'work': 'target_work', 'cert': 'target_cert'}.get(parts[2])
if len(parts) == 1:
if Path(parts[0]).suffix == '.lmc' and parts[0] != self.library_name.casefold():
return None
return 'library_config'
# Shared DB/config/dependency trees are conservative: new dependency
# directory names remain primary without adding them to an allowlist.
return 'shared_dependency'
def hash_file(path):
digest = hashlib.sha256()
with Path(path).open('rb') as stream:
for data in iter(lambda: stream.read(1024 * 1024), b''):
digest.update(data)
return digest.hexdigest()
def _coordination_checkpoint(path):
from .library_lock import checkpoint_record
return checkpoint_record(path) is not None
def scan_tree(root, *, scope=None, exclude=None):
"""Refuse links/special files; optionally prune trees outside semantic scope.
Copies always call this without a scope, validating complete membership.
Later semantic scans avoid entering runtime or unrelated CBB directories.
"""
root = Path(root)
if root.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
raise ValueError(f'不支持通过目录链接恢复:{root}')
entries = {}
folders = [root]
while folders:
with os.scandir(folders.pop()) as scanned:
for entry in scanned:
path = Path(entry.path)
if exclude is not None and path.is_relative_to(exclude):
continue
if scope is not None:
relative = path.relative_to(root)
if entry.is_dir(follow_symlinks=False):
if not scope.includes_directory(relative):
continue
elif scope.classify(relative) is None or _coordination_checkpoint(path):
continue
metadata = entry.stat(follow_symlinks=False)
if metadata.st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
raise ValueError(f'目录含文件或目录链接,停止恢复:{entry.path}')
if not (stat.S_ISDIR(metadata.st_mode) or stat.S_ISREG(metadata.st_mode)):
raise ValueError(f'不支持的特殊文件:{entry.path}')
entries[path] = metadata
if stat.S_ISDIR(metadata.st_mode):
folders.append(path)
return dict(sorted(entries.items()))
def _metadata_record(root, entries):
return {path.relative_to(root).as_posix():
('file', info.st_size, info.st_mtime_ns) if stat.S_ISREG(info.st_mode) else ('dir',)
for path, info in entries.items()}
def _manifest(scope, files):
return {'version': MANIFEST_VERSION, 'scope': asdict(scope), 'files': dict(sorted(files.items()))}
def _emit(progress, stage, hashed_files, hashed_bytes, **extra):
if progress:
progress({'stage': stage, 'hashed_files': hashed_files, 'hashed_bytes': hashed_bytes, **extra})
def build_manifest(root, *, scope=None, exclude=None, progress=None, hash_function=hash_file):
"""Hash primary files only. Excluded subtrees are for private incoming Work.
The returned dict is versioned, JSON-compatible and relocatable. Equality
compares primary path membership, size, hash and scope, never runtime mtimes.
"""
root = Path(root)
scope = scope or ManifestScope()
entries = scan_tree(root, scope=scope, exclude=exclude)
selected = {path: scope.classify(path.relative_to(root)) for path, info in entries.items()
if stat.S_ISREG(info.st_mode)}
selected = {path: label for path, label in selected.items() if label is not None}
def hashed(path):
digest = hash_function(path)
after = path.stat()
before = entries[path]
if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
raise OSError(f'计算哈希期间文件变化:{path}')
return path.relative_to(root).as_posix(), {
'size': before.st_size, 'sha256': digest, 'scope': selected[path]}
files = {}
hashed_bytes = 0
_emit(progress, 'hash', 0, 0, total_files=len(selected))
with ThreadPoolExecutor(max_workers=8) as pool:
for count, (relative, item) in enumerate(pool.map(hashed, selected), 1):
files[relative] = item
hashed_bytes += item['size']
if count % 256 == 0 or count == len(selected):
_emit(progress, 'hash', count, hashed_bytes, total_files=len(selected))
# Check primary membership and metadata again after every hash completed.
# Runtime files can change/add/disappear without a semantic conflict.
after = scan_tree(root, scope=scope, exclude=exclude)
before_primary = {p: entries[p] for p in selected}
after_primary = {p: info for p, info in after.items() if stat.S_ISREG(info.st_mode)
and (exclude is None or not p.is_relative_to(exclude))
and scope.classify(p.relative_to(root)) is not None}
if _metadata_record(root, before_primary) != _metadata_record(root, after_primary):
raise OSError(f'计算哈希期间主要文件变化:{root}')
return _manifest(scope, files)
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.
Native icdb.dat/LMC files are held with exclusive read handles for the copy.
Their expected SHA256 comes from the source read stream, independently of
hashing destination bytes. Failures retain the partial destination evidence.
Progress receives one dict with stage, hashed_files/bytes and copied_files.
"""
import win32con
import win32file
source, destination = Path(source), Path(destination)
scope = scope or ManifestScope()
if destination.resolve().is_relative_to(source.resolve()):
raise ValueError('复制目标不能位于源目录内。')
entries = scan_tree(source)
expected_metadata = _metadata_record(source, entries)
destination.mkdir(parents=True, exist_ok=False)
files = [path for path, info in entries.items() if stat.S_ISREG(info.st_mode)]
from .library_lock import owned_snapshot
# Resolve ownership on the operation thread, before parallel copy workers.
owned = {path: data for path in files
if path.name.endswith('.cbb-upload.lock')
and (data := owned_snapshot(path)) is not None}
record = {}
hashed_count = hashed_bytes = 0
_emit(progress, 'copy', 0, 0, copied_files=0, total_files=len(files))
with ExitStack() as stack:
locks = {}
for path in files:
if path.name.casefold() == 'icdb.dat' or path.suffix.casefold() == '.lmc':
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
stack.callback(handle.Close)
locks[path] = handle
for path, info in entries.items():
if stat.S_ISDIR(info.st_mode):
(destination/path.relative_to(source)).mkdir(parents=True, exist_ok=True)
def copy_file(path):
relative = path.relative_to(source)
copied = destination/relative
copied.parent.mkdir(parents=True, exist_ok=True)
label = None if _coordination_checkpoint(path) else scope.classify(relative)
digest = None
if path in owned:
copied.write_bytes(owned[path])
shutil.copystat(path, copied)
if label is not None:
digest = hashlib.sha256(owned[path]).hexdigest()
elif path in locks:
stream_hash = hashlib.sha256() if label is not None else None
with copied.open('wb') as stream:
while True:
_, data = win32file.ReadFile(locks[path], 1024 * 1024)
if not data:
break
if stream_hash is not None:
stream_hash.update(data)
stream.write(data)
shutil.copystat(path, copied)
if stream_hash is not None:
digest = stream_hash.hexdigest()
else:
if label is not None:
digest = hash_function(path)
shutil.copy2(path, copied)
before, after = entries[path], path.stat()
if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
raise OSError(f'复制期间文件变化:{path}')
return relative.as_posix(), digest, label
with ThreadPoolExecutor(max_workers=8) as pool:
for count, (relative, digest, label) in enumerate(pool.map(copy_file, files), 1):
if label is not None:
size = entries[source/relative].st_size
record[relative] = {'size': size, 'sha256': digest, 'scope': label}
hashed_count += 1
hashed_bytes += size
if count % 256 == 0 or count == len(files):
_emit(progress, 'copy', hashed_count, hashed_bytes,
copied_files=count, total_files=len(files))
def validate_bytes(relative):
item = record[relative]
path = source/relative
if path not in locks and hash_function(path) != item['sha256']:
raise OSError(f'复制期间主要文件内容变化:{path}')
if hash_function(destination/relative) != item['sha256']:
raise OSError(f'复制内容校验失败:{path}')
with ThreadPoolExecutor(max_workers=8) as pool:
list(pool.map(validate_bytes, record))
if _metadata_record(source, scan_tree(source)) != expected_metadata:
raise OSError(f'复制期间目录内容变化:{source}')
if _metadata_record(destination, scan_tree(destination)) != expected_metadata:
raise OSError(f'复制目标目录或文件元数据不一致:{destination}')
return _manifest(scope, record)
+9 -6
View File
@@ -315,15 +315,18 @@ class StatusBridgeServer:
except OSError: except OSError:
pass pass
if process.poll() is None: if process.poll() is None:
process.terminate()
try: try:
process.wait(timeout=2) process.wait(timeout=2)
except subprocess.TimeoutExpired: except subprocess.TimeoutExpired:
try: process.terminate()
process.kill()
except OSError:
pass
try: try:
process.wait(timeout=2) process.wait(timeout=2)
except subprocess.TimeoutExpired: except subprocess.TimeoutExpired:
pass try:
process.kill()
except OSError:
pass
try:
process.wait(timeout=2)
except subprocess.TimeoutExpired:
pass
@@ -0,0 +1,128 @@
"""Small, asynchronous entry point for recovery from a healthy CBB project."""
from pathlib import Path
from PySide6.QtCore import QObject, QThreadPool, Signal
from PySide6.QtWidgets import (QComboBox, QDialog, QFileDialog, QFormLayout,
QHBoxLayout, QLabel, QLineEdit, QPushButton)
from .workers import ServiceWorker
class RecoverySignals(QObject):
progress = Signal(object)
class BackupRecoveryDialog(QDialog):
started = Signal(str)
completed = Signal(str, object)
def __init__(self, names, request_factory, parent=None, *, recoverer=None):
super().__init__(parent)
self.setWindowTitle('从备份恢复 CBB')
self.resize(620, 230)
self.request_factory = request_factory
self.recoverer = recoverer
self.busy = False
self.pool = QThreadPool(self)
self.pool.setMaxThreadCount(1)
self.signals = RecoverySignals(self)
self.signals.progress.connect(self._progress)
self.block_combo = QComboBox()
self.block_combo.addItems(list(names))
self.source_edit = QLineEdit()
self.source_edit.setPlaceholderText('选择同名 CBB 完整备份中的工程 .prj')
self.browse_button = QPushButton('选择…')
self.browse_button.clicked.connect(self._browse)
self.restore_button = QPushButton('恢复并校验')
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.setWordWrap(True)
layout = QFormLayout(self)
layout.addRow('目标 CBB', self.block_combo)
source = QHBoxLayout()
source.addWidget(self.source_edit)
source.addWidget(self.browse_button)
layout.addRow('备份工程', source)
layout.addRow(self.status_label)
buttons = QHBoxLayout()
buttons.addStretch()
buttons.addWidget(self.restore_button)
buttons.addWidget(self.close_button)
layout.addRow(buttons)
def _browse(self):
path, _ = QFileDialog.getOpenFileName(self, '选择健康备份工程', '', '工程 (*.prj)')
if path:
self.source_edit.setText(path)
def _restore(self):
if self.busy:
return
source = Path(self.source_edit.text().strip())
if not source.is_file() or source.suffix.casefold() != '.prj':
self.status_label.setText('请选择有效的备份工程 .prj 文件。')
return
name = self.block_combo.currentText()
if not name:
self.status_label.setText('请选择目标 CBB。')
return
try:
request = self.request_factory(name)
recoverer = self.recoverer
if recoverer is None:
from cbb_refresh_verify.backup_recovery import recover_from_backup
recoverer = recover_from_backup
except Exception as error:
self.status_label.setText(str(error))
return
self.busy = True
self._set_enabled(False)
self.status_label.setText('正在准备恢复…')
self.started.emit(name)
self.worker = ServiceWorker(lambda: recoverer(
request, source, progress=self.signals.progress.emit))
self.worker.signals.succeeded.connect(lambda result: self._result(name, result))
self.worker.signals.failed.connect(lambda error: self._failed(name, error))
self.worker.signals.finished.connect(self._finished)
self.pool.start(self.worker)
def _set_enabled(self, enabled):
for widget in (self.block_combo, self.source_edit, self.browse_button,
self.restore_button, self.close_button):
widget.setEnabled(enabled)
def _progress(self, event):
if isinstance(event, dict):
message = event.get('message') or event.get('detail')
if message:
self.status_label.setText(str(message))
def _result(self, name, result):
if result.status == 'PASS':
message = '恢复完成,工程打开与校验通过。'
else:
message = f'恢复未通过:{result.stderr or result.stdout or result.status}'
if result.evidence_path:
message += f'\n记录:{result.evidence_path}'
self.status_label.setText(message)
self.completed.emit(name, result)
def _failed(self, name, error):
from cbb_refresh_verify.verify_runner import VerifyResult
self._result(name, VerifyResult('FAIL', stderr=f'恢复未完成:{error}', safe_to_continue=False))
def _finished(self):
self.busy = False
self._set_enabled(True)
def reject(self):
if not self.busy:
super().reject()
def closeEvent(self, event):
if self.busy:
event.ignore()
else:
super().closeEvent(event)
+502 -58
View File
@@ -3,12 +3,13 @@ from threading import Event
import os import os
import time import time
from collections import Counter from collections import Counter
from dataclasses import replace
from PySide6.QtCore import QObject, QThreadPool, Signal, Qt from PySide6.QtCore import QObject, QThreadPool, Signal, Qt
from PySide6.QtGui import QColor, QIcon from PySide6.QtGui import QColor, QIcon
from PySide6.QtWidgets import (QWidget, QLineEdit, QPushButton, QFormLayout, from PySide6.QtWidgets import (QWidget, QLineEdit, QPushButton, QFormLayout,
QTextEdit, QFileDialog, QHBoxLayout, QLabel, QSpinBox, QMessageBox, QToolButton, QTextEdit, QFileDialog, QHBoxLayout, QLabel, QSpinBox, QMessageBox, QToolButton,
QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox) QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox, QGroupBox, QVBoxLayout, QProgressBar, QComboBox)
from PySide6.QtWidgets import QStyle from PySide6.QtWidgets import QStyle
try: try:
from dx_productivity.trial_task_center.ui.workers import ServiceWorker from dx_productivity.trial_task_center.ui.workers import ServiceWorker
@@ -45,7 +46,8 @@ def application_icon_path():
class MainWindow(QWidget): class MainWindow(QWidget):
def __init__(self, reader=None, verifier=None, logging_context=None, data_root=None, def __init__(self, reader=None, verifier=None, logging_context=None, data_root=None,
authoritative_status=True, path_lease_factory=None): authoritative_status=True, path_lease_factory=None, status_refresher=None,
management_adapter=None):
super().__init__() super().__init__()
self.setWindowTitle('CBB 刷新校验') self.setWindowTitle('CBB 刷新校验')
icon_path = application_icon_path() icon_path = application_icon_path()
@@ -58,6 +60,12 @@ class MainWindow(QWidget):
self.library_lease = None self.library_lease = None
self.mentor_lmc_path = None self.mentor_lmc_path = None
self.data_root = Path(data_root or (logging_context.root if logging_context else Path(os.environ.get('LOCALAPPDATA', '.'))/'CbbRefreshVerify')) self.data_root = Path(data_root or (logging_context.root if logging_context else Path(os.environ.get('LOCALAPPDATA', '.'))/'CbbRefreshVerify'))
from cbb_refresh_verify.native_management import NativeManagementAdapter
self.management_adapter = management_adapter or NativeManagementAdapter()
self.management_capabilities = self.management_adapter.capabilities()
self._management_unsafe = False
self._maintenance_recovery_view = False
self._reload_after_maintenance = False
if reader is not None: if reader is not None:
self.reader = reader self.reader = reader
elif authoritative_status and os.environ.get('CBB_STATUS_BRIDGE_MODE', 'authoritative').casefold() != 'legacy': elif authoritative_status and os.environ.get('CBB_STATUS_BRIDGE_MODE', 'authoritative').casefold() != 'legacy':
@@ -78,7 +86,12 @@ class MainWindow(QWidget):
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1) self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1)
self.busy = False; self.loaded_path = None; self.stop = Event(); self.ready_names = set() self.busy = False; self.loaded_path = None; self.stop = Event(); self.ready_names = set()
self._row_by_name = {} self._row_by_name = {}
self._records_by_name = {}
self.status_refresher = status_refresher or (lambda names, path: authoritative_status_map(
names, path, self.data_root / 'status-refresh.jsonl'))
self.skipped_names = set(); self.skip_reasons = {} self.skipped_names = set(); self.skip_reasons = {}
self._global_icdb_run = False
self._icdb_completed = 0
self.signals = ProgressSignals(self); self.signals.event.connect(self._progress) self.signals = ProgressSignals(self); self.signals.event.connect(self._progress)
self.lmc_edit = QLineEdit() self.lmc_edit = QLineEdit()
self.libspec_edit = QLineEdit(os.environ.get('CBB_LIBSPEC', 'EE7.9')) self.libspec_edit = QLineEdit(os.environ.get('CBB_LIBSPEC', 'EE7.9'))
@@ -107,11 +120,28 @@ class MainWindow(QWidget):
self.cbb_table.setSelectionBehavior(QTableWidget.SelectRows) self.cbb_table.setSelectionBehavior(QTableWidget.SelectRows)
self.cbb_table.setMinimumHeight(150) self.cbb_table.setMinimumHeight(150)
self.cbb_table.itemChanged.connect(lambda _item: self._update()) self.cbb_table.itemChanged.connect(lambda _item: self._update())
self.search_edit = QLineEdit()
self.search_edit.setPlaceholderText('按 CBB 名称或分区搜索')
self.status_filter = QComboBox()
for label, key in (('全部', 'all'), ('READY', 'ready'), ('非 READY(含未确认)', 'non_ready'),
('PENDING', 'pending'), ('未知 / 读取异常', 'errors'), ('缺少工程', 'missing')):
self.status_filter.addItem(label, key)
self.counts_label = QLabel()
self.select_visible_button = QPushButton('选择可见项')
self.clear_selection_button = QPushButton('清空选择')
self.select_visible_button.clicked.connect(lambda: self._check_visible(Qt.Checked))
self.clear_selection_button.clicked.connect(lambda: self._check_visible(Qt.Unchecked))
self.search_edit.textChanged.connect(self._apply_filters)
self.status_filter.currentIndexChanged.connect(self._apply_filters)
self.timeout_spin = QSpinBox(); self.timeout_spin.setRange(30, 1800); self.timeout_spin.setValue(DEFAULT_TIMEOUT_SECONDS); self.timeout_spin.setSuffix(' 秒 / 无进展') self.timeout_spin = QSpinBox(); self.timeout_spin.setRange(30, 1800); self.timeout_spin.setValue(DEFAULT_TIMEOUT_SECONDS); self.timeout_spin.setSuffix(' 秒 / 无进展')
self.load_button = QPushButton('读取 CBB'); self.load_button.clicked.connect(self.load_library) self.load_button = QPushButton('读取 CBB'); self.load_button.clicked.connect(self.load_library)
self.browse_button = QPushButton('选择'); self.browse_button.clicked.connect(self.choose_library) 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.selected_batch_button = QPushButton('批量校验已选'); self.selected_batch_button.clicked.connect(self.verify_selected)
self.batch_button = QPushButton('批量校验全部 CBB'); self.batch_button.clicked.connect(self.verify_all) 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.backup_restore_button = QPushButton('从备份恢复 CBB…')
self.backup_restore_button.clicked.connect(self.restore_backup)
self.stop_button = QPushButton('当前项完成后停止'); self.stop_button.clicked.connect(self.request_stop) 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.logs_button = QPushButton('打开日志目录'); self.logs_button.clicked.connect(self.open_logs)
self.recovery_button = QPushButton('打开异常证据'); self.recovery_button.setEnabled(False) self.recovery_button = QPushButton('打开异常证据'); self.recovery_button.setEnabled(False)
@@ -120,6 +150,7 @@ class MainWindow(QWidget):
self.browse_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_DirOpenIcon)) self.browse_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_DirOpenIcon))
self.selected_batch_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_ArrowRight)) self.selected_batch_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_ArrowRight))
self.batch_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_MediaPlay)) self.batch_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_MediaPlay))
self.icdb_repair_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_BrowserReload))
self.stop_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_MediaStop)) self.stop_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_MediaStop))
self.logs_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_DirOpenIcon)) self.logs_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_DirOpenIcon))
self.recovery_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_MessageBoxWarning)) self.recovery_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_MessageBoxWarning))
@@ -128,6 +159,7 @@ class MainWindow(QWidget):
self.recovery_path = None self.recovery_path = None
self.status_label = QLabel('请选择并读取中心库。校验期间可以使用其他前台应用。') self.status_label = QLabel('请选择并读取中心库。校验期间可以使用其他前台应用。')
self.status_label.setWordWrap(True) self.status_label.setWordWrap(True)
self.status_label.setMinimumHeight(self.status_label.fontMetrics().lineSpacing()*2)
self.output = QTextEdit(); self.output.setReadOnly(True) self.output = QTextEdit(); self.output.setReadOnly(True)
# Integration emits repeated status snapshots. Keep the visible # Integration emits repeated status snapshots. Keep the visible
# diagnostic buffer bounded so a 3,000-CBB run cannot grow the GUI # diagnostic buffer bounded so a 3,000-CBB run cannot grow the GUI
@@ -136,24 +168,74 @@ class MainWindow(QWidget):
layout = QFormLayout(self) layout = QFormLayout(self)
row = QHBoxLayout(); row.addWidget(self.lmc_edit); row.addWidget(self.browse_button); row.addWidget(self.load_button) 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) layout.addRow('中心库 .lmc', row); layout.addRow(self.advanced_toggle); layout.addRow(self.advanced_panel)
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('CBB 清单(勾选后可批量)', self.cbb_table); layout.addRow('超时', self.timeout_spin)
layout.addRow(QLabel('逐个刷新:命令行启动 ReusableCircuit PCB → Project Integration → 保存并关闭,全程不切换桌面、不移动鼠标。' layout.addRow(QLabel('逐个刷新:命令行启动 ReusableCircuit PCB → Project Integration → 保存并关闭,全程不切换桌面、不移动鼠标。'
'填写 LibSpec 与 DMS 登录配置后,会先执行一次 ReuseBlockImporter 内容检查。')) '填写 LibSpec 与 DMS 登录配置后,会先执行一次 ReuseBlockImporter 内容检查。'))
controls = QHBoxLayout() controls = QHBoxLayout()
for widget in (self.selected_batch_button, self.batch_button, self.stop_button, self.logs_button): controls.addWidget(widget) for widget in (self.selected_batch_button, self.batch_button, self.stop_button, self.logs_button): controls.addWidget(widget)
layout.addRow(controls); layout.addRow(self.status_label); layout.addRow(self.output) layout.addRow(controls)
maintenance = QGroupBox('数据库维护')
maintenance_layout = QVBoxLayout(maintenance)
maintenance_row = QHBoxLayout()
maintenance_row.addWidget(self.icdb_repair_button)
description = QLabel('处理可见非 READY 项;有勾选时仅处理勾选中的可用项。未确认不等于损坏。\n确认工程数据库失联后先备份再修复;无法确认会话安全时停止。')
description.setWordWrap(True)
maintenance_row.addWidget(description, 1)
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('')
self.icdb_phase.setWordWrap(True)
self.icdb_phase.setVisible(False)
maintenance_layout.addWidget(self.icdb_progress)
maintenance_layout.addWidget(self.icdb_phase)
layout.addRow(maintenance)
management = QGroupBox('CBB 管理(可处理 READY 项)')
management_layout = QVBoxLayout(management)
management_buttons = QHBoxLayout()
self.add_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.setWordWrap(True)
management_layout.addWidget(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.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) layout.addRow(self.recovery_button)
self.lmc_edit.textChanged.connect(self._invalidate) self.lmc_edit.textChanged.connect(self._invalidate)
for field in (self.libspec_edit, self.dms_edit, self.mentor_bin_edit): for field in (self.libspec_edit, self.dms_edit, self.mentor_bin_edit):
field.textChanged.connect(lambda _text: self._update()) field.textChanged.connect(lambda _text: self._update())
self.native_lm_verify_check.toggled.connect(lambda _checked: self._update()) self.native_lm_verify_check.toggled.connect(lambda _checked: self._update())
self._show_unfinished_management()
self._update() self._update()
def _invalidate(self): def _invalidate(self):
if self.loaded_path is not None and self.lmc_edit.text() != self.loaded_path: if self.loaded_path is not None and self.lmc_edit.text() != self.loaded_path:
self._release_library_lease() self._release_library_lease()
self.loaded_path = None; self.mentor_lmc_path = None; self.cbb_table.setRowCount(0); self._row_by_name = {} self.loaded_path = None; self.mentor_lmc_path = None; self.cbb_table.setRowCount(0); self._row_by_name = {}
self._records_by_name = {}
self.ready_names = set(); self.skipped_names = set(); self.skip_reasons = {}; self._update() self.ready_names = set(); self.skipped_names = set(); self.skip_reasons = {}; self._update()
self._global_icdb_run = False
self.icdb_progress.hide(); self.icdb_phase.hide()
def _release_library_lease(self): def _release_library_lease(self):
lease, self.library_lease = self.library_lease, None lease, self.library_lease = self.library_lease, None
@@ -168,16 +250,155 @@ class MainWindow(QWidget):
def _update(self): def _update(self):
# The refresh flow needs only the library and a CBB; LibSpec/DMS config # The refresh flow needs only the library and a CBB; LibSpec/DMS config
# are optional and only enable the extra contents check. # are optional and only enable the extra contents check.
ready = not self.busy and self.loaded_path == self.lmc_edit.text() and self.cbb_table.rowCount() > 0 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 any(self.cbb_table.item(row, 0).text() not in self.ready_names self.batch_button.setEnabled(ready and not self._maintenance_recovery_view and bool(self._eligible_names()))
and self.cbb_table.item(row, 0).text() not in self.skipped_names self.selected_batch_button.setEnabled(ready and not self._maintenance_recovery_view and bool(self._eligible_names(checked_only=True)))
for row in range(self.cbb_table.rowCount()))) self.icdb_repair_button.setEnabled(ready and bool(self._maintenance_names()))
self.selected_batch_button.setEnabled(ready and bool(self._selected_names())) self.backup_restore_button.setEnabled(ready and not self._maintenance_recovery_view and bool(self._maintenance_names()))
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()
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())))
for widget in (self.lmc_edit, self.browse_button, self.load_button, self.cbb_table, 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.timeout_spin, self.advanced_toggle, self.advanced_panel,
self.search_edit, self.status_filter, self.select_visible_button, self.clear_selection_button):
widget.setEnabled(not self.busy) widget.setEnabled(not self.busy)
counts = self.visible_counts()
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.setEnabled(self.busy and self.loaded_path is not None and not self.stop.is_set())
def _show_unfinished_management(self):
from cbb_refresh_verify.management import unfinished_operations
unfinished = unfinished_operations(self.data_root/'management')
self.unfinished_label.setText(f'发现 {len(unfinished)} 项未完成或需恢复的管理任务;只显示记录,不自动重放。'
if unfinished else '')
for item in unfinished:
self.output.append(f'未完成:{item.get("name", "")} {item.get("status", "")} '
f'{item.get("stage", "")}\n{item["evidence_path"]}')
def check_library_release(self):
if self.busy or not self.lmc_edit.text().strip():
return
if QMessageBox.question(self, '检查原生会话释放',
'检查所有原生编辑器/管理进程、库内数据库地址记录及数据库独占可读性。'
'\n全部通过后归档阻止记录并释放本应用保留的库锁。'
'\n数据恢复结果和未完成管理任务仍需单独审查。继续?',
QMessageBox.Yes | QMessageBox.No, QMessageBox.No) != QMessageBox.Yes:
return
from cbb_refresh_verify.library_lock import release_retained_library
library = Path(self.mentor_lmc_path or self.lmc_edit.text().strip())
if library.is_dir():
library = select_library_file(library)
def completed(result):
self._management_unsafe = False
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)
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):
return
from cbb_refresh_verify.management import ManagementRequest
from .management_dialog import ManagementDialog
records = self.selected_records()
if operation != 'add' and not records:
return
def request(name, partition):
return ManagementRequest(operation, Path(self.mentor_lmc_path or self.loaded_path), 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', ''))
requests = ([request('', 'Logical-Physical')] if operation == 'add' else
[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._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 _management_completed(self, results):
self._management_results = results
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 any(not result.safe_to_continue for result in results):
self._management_unsafe = True
if self.library_lease:
self.library_lease.retain_for_recovery()
self.status_label.setText('管理操作需要人工确认恢复/释放;已停止写入,未再次读取原生目录。')
self._show_unfinished_management()
def _management_closed(self, *_):
from PySide6.QtCore import QTimer
self.busy = False; self._update()
if self._management_results and not self._management_unsafe:
# Whole catalog reload is necessary for inserted/deleted identities;
# existing local search/filter controls are intentionally retained.
QTimer.singleShot(0, self.load_library)
def visible_records(self):
"""Cached records in table order, restricted to the current local view."""
return tuple(record for name, record in self._records_by_name.items()
if not self.cbb_table.isRowHidden(self._row_by_name[name]))
def selected_records(self):
"""Visible checked management records, including READY/missing projects."""
return tuple(record for record in self.visible_records()
if self.cbb_table.item(self._row_by_name[record.name], 0).checkState() == Qt.Checked)
def visible_counts(self):
records = self.visible_records()
return {'visible': len(records), 'ready': sum(r.status == 'READY' for r in records),
'error': sum(r.status not in {'READY', 'PENDING'} or r.name in self.skipped_names
for r in records)}
def _eligible_names(self, *, checked_only=False):
records = self.selected_records() if checked_only else self.visible_records()
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()))
def _check_visible(self, state):
self.cbb_table.blockSignals(True)
try:
for record in self.visible_records():
self.cbb_table.item(self._row_by_name[record.name], 0).setCheckState(state)
finally:
self.cbb_table.blockSignals(False)
self._update()
def _apply_filters(self, *_):
keyword = self.search_edit.text().strip().casefold()
mode = self.status_filter.currentData()
self.cbb_table.blockSignals(True)
self.cbb_table.setUpdatesEnabled(False)
try:
for name, record in self._records_by_name.items():
matches = (not keyword or keyword in record.name.casefold()
or keyword in record.partition_name.casefold())
matches = matches and (mode == 'all'
or mode == 'ready' and record.status == 'READY'
or mode == 'non_ready' and record.status != 'READY'
or mode == 'pending' and record.status == 'PENDING'
or mode == 'errors' and record.status not in {'READY', 'PENDING'}
or mode == 'missing' and name in self.skipped_names)
row = self._row_by_name[name]
if not matches:
self.cbb_table.item(row, 0).setCheckState(Qt.Unchecked)
self.cbb_table.setRowHidden(row, not matches)
finally:
self.cbb_table.setUpdatesEnabled(True)
self.cbb_table.blockSignals(False)
self._update()
def choose_library(self): def choose_library(self):
path = QFileDialog.getOpenFileName(self, '选择中心库', '', 'LMC (*.lmc)')[0] path = QFileDialog.getOpenFileName(self, '选择中心库', '', 'LMC (*.lmc)')[0]
if path: self.lmc_edit.setText(path); self.load_library() if path: self.lmc_edit.setText(path); self.load_library()
@@ -192,8 +413,12 @@ class MainWindow(QWidget):
def load_library(self): def load_library(self):
if self.busy or not self.lmc_edit.text(): return if self.busy or not self.lmc_edit.text(): return
self._maintenance_recovery_view = False
self._global_icdb_run = False
self.icdb_progress.hide(); self.icdb_phase.hide()
self._release_library_lease() self._release_library_lease()
self.loaded_path = None; self.cbb_table.setRowCount(0); self._row_by_name = {}; self.ready_names = set() self.loaded_path = None; self.cbb_table.setRowCount(0); self._row_by_name = {}; self.ready_names = set()
self._records_by_name = {}
self.skipped_names = set(); self.skip_reasons = {} self.skipped_names = set(); self.skip_reasons = {}
path = self.lmc_edit.text() path = self.lmc_edit.text()
self.status_label.setText('正在读取中心库…') self.status_label.setText('正在读取中心库…')
@@ -212,7 +437,21 @@ class MainWindow(QWidget):
'library_path_lease display=%s mentor=%s drive=%s remote=%s created=%s', 'library_path_lease display=%s mentor=%s drive=%s remote=%s created=%s',
lease.display_path, mentor_path, lease.drive or '-', lease.display_path, mentor_path, lease.drive or '-',
lease.remote_root or '-', lease.created) lease.remote_root or '-', lease.created)
result = self.reader(mentor_path) 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)
if self.logging_context: if self.logging_context:
statuses = Counter(record.status for record in result.records) statuses = Counter(record.status for record in result.records)
unknown = [record.name for record in result.records if record.status in {'UNKNOWN', 'UNAVAILABLE'}] unknown = [record.name for record in result.records if record.status in {'UNKNOWN', 'UNAVAILABLE'}]
@@ -223,18 +462,17 @@ class MainWindow(QWidget):
skip_reasons = {} skip_reasons = {}
if not result.error: if not result.error:
for record in result.records: for record in result.records:
if record.status != 'READY': reason = preflight_skip_reason(mentor_path, record.name)
reason = preflight_skip_reason(mentor_path, record.name) if reason:
if reason: skip_reasons[record.name] = reason
skip_reasons[record.name] = reason return result, skip_reasons, lease, mentor_path, recovery_view
return result, skip_reasons, lease, mentor_path
except Exception: except Exception:
if 'lease' in locals(): if 'lease' in locals():
lease.close() lease.close()
raise raise
finally: pythoncom.CoUninitialize() finally: pythoncom.CoUninitialize()
def loaded(payload): def loaded(payload):
result, skip_reasons, lease, mentor_path = payload result, skip_reasons, lease, mentor_path, recovery_view = payload
if path != self.lmc_edit.text(): if path != self.lmc_edit.text():
lease.close() lease.close()
return return
@@ -242,12 +480,14 @@ class MainWindow(QWidget):
lease.close() lease.close()
self.status_label.setText(result.error); return self.status_label.setText(result.error); return
self.library_lease = lease self.library_lease = lease
self._maintenance_recovery_view = recovery_view
self.mentor_lmc_path = mentor_path self.mentor_lmc_path = mentor_path
self.loaded_path = path self.loaded_path = path
self.cbb_table.setRowCount(0) self.cbb_table.setRowCount(0)
self.ready_names = {r.name for r in result.records if r.status == 'READY'} self.ready_names = {r.name for r in result.records if r.status == 'READY' and r.name not in skip_reasons}
self.skip_reasons = dict(skip_reasons) self.skip_reasons = dict(skip_reasons)
self.skipped_names = set(skip_reasons) self.skipped_names = set(skip_reasons)
self._records_by_name = {record.name: record for record in result.records}
# Populating a large library emits itemChanged for every cell. # Populating a large library emits itemChanged for every cell.
# Block those signals and refresh controls once after the batch; # Block those signals and refresh controls once after the batch;
# otherwise _update() repeatedly scans the growing table (O(n^2)). # otherwise _update() repeatedly scans the growing table (O(n^2)).
@@ -258,23 +498,21 @@ class MainWindow(QWidget):
for row, record in enumerate(result.records): for row, record in enumerate(result.records):
self._row_by_name[record.name] = row self._row_by_name[record.name] = row
item = QTableWidgetItem(record.name) item = QTableWidgetItem(record.name)
if record.status == 'READY' or record.name in self.skipped_names: # Management selection includes READY and missing projects;
# Already green: nothing left to verify, so it cannot be queued. # operation queues independently enforce eligibility.
item.setFlags(item.flags() & ~Qt.ItemIsUserCheckable) item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
else:
item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
item.setCheckState(Qt.Unchecked) item.setCheckState(Qt.Unchecked)
self.cbb_table.setItem(row, 0, item) self.cbb_table.setItem(row, 0, item)
self.cbb_table.setItem(row, 1, QTableWidgetItem(record.partition_name)) self.cbb_table.setItem(row, 1, QTableWidgetItem(record.partition_name))
status_text = STATUS_LABELS.get(record.status, record.status) status_text = STATUS_LABELS.get(record.status, record.status)
if record.name in self.skipped_names: if record.name in self.skipped_names:
status_text = '跳过:缺少工程/PCB' status_text += ' · 缺少工程/PCB'
self.cbb_table.setItem(row, 2, QTableWidgetItem(status_text)) self.cbb_table.setItem(row, 2, QTableWidgetItem(status_text))
# Preflight touches each CBB's project and was previously run # Preflight touches each CBB's project and was previously run
# synchronously in this GUI callback, making large libraries # synchronously in this GUI callback, making large libraries
# appear frozen. The verify worker performs it when queued. # appear frozen. The verify worker performs it when queued.
self.cbb_table.setItem(row, 3, QTableWidgetItem('未检查')) self.cbb_table.setItem(row, 3, QTableWidgetItem('未检查'))
if record.status == 'READY': if record.status == 'READY' and record.name not in self.skipped_names:
self._mark_row_ready(row) self._mark_row_ready(row)
elif record.name in self.skipped_names: elif record.name in self.skipped_names:
self.cbb_table.item(row, 0).setToolTip(self.skip_reasons[record.name]) self.cbb_table.item(row, 0).setToolTip(self.skip_reasons[record.name])
@@ -299,6 +537,10 @@ class MainWindow(QWidget):
self.status_label.setText( self.status_label.setText(
f'已读取 {len(result.records)} 个 CBB,其中 Ready {ready_count} 个,' f'已读取 {len(result.records)} 个 CBB,其中 Ready {ready_count} 个,'
f'缺文件跳过 {len(self.skipped_names)} 个。{suffix}') f'缺文件跳过 {len(self.skipped_names)} 个。{suffix}')
if recovery_view:
self.status_label.setText('协调阻止恢复视图:仅按目录显示工程,状态未确认(UNKNOWN),不代表损坏。'
'仅可明确执行 ICDB 维护或释放检查,其他写入与原生状态读取已禁用。')
self._apply_filters()
self._start(read, loaded) self._start(read, loaded)
def _request(self, name): def _request(self, name):
@@ -312,77 +554,259 @@ class MainWindow(QWidget):
native_lm_verify=self.native_lm_verify_check.isChecked()) native_lm_verify=self.native_lm_verify_check.isChecked())
def _selected_names(self): def _selected_names(self):
names = [] return [record.name for record in self.selected_records()]
for row in range(self.cbb_table.rowCount()):
item = self.cbb_table.item(row, 0)
if item and item.checkState() == Qt.Checked and (item.flags() & Qt.ItemIsUserCheckable):
names.append(item.text())
return names
def verify_selected(self): def verify_selected(self):
self._run(self._selected_names()) self._run(self._eligible_names(checked_only=True))
def verify_all(self): def verify_all(self):
names = [self.cbb_table.item(row, 0).text() for row in range(self.cbb_table.rowCount())] self._run(self._eligible_names())
self._run([name for name in names if name not in self.ready_names and name not in self.skipped_names])
def _run(self, names): def repair_icdb_all(self):
if self.busy or not self.loaded_path: return if self.busy or not self.loaded_path: return
names = [name for name in names if name not in self.ready_names and name not in self.skipped_names] names = self._maintenance_names()
if not names: return
answer = QMessageBox.question(self, '非 READY 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)
if answer == QMessageBox.Yes:
self._run(names, maintenance=True)
def restore_backup(self):
if self.busy or not self.loaded_path or self._maintenance_recovery_view:
return
from .backup_recovery_dialog import BackupRecoveryDialog
names = self._maintenance_names()
if not names: if not names:
self.status_label.setText('没有需要校验的 CBB(全部已经是绿色 / Ready)。') return
self.backup_dialog = BackupRecoveryDialog(names, self._backup_request, self)
row = self.cbb_table.currentRow()
if row >= 0 and self.cbb_table.item(row, 0).text() in names:
self.backup_dialog.block_combo.setCurrentText(self.cbb_table.item(row, 0).text())
self.backup_dialog.started.connect(self._backup_started)
self.backup_dialog.completed.connect(self._backup_completed)
self.backup_dialog.finished.connect(lambda _code: self._backup_dialog_closed())
self.backup_dialog.setModal(True)
self.backup_dialog.show()
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():
raise ValueError('目标需为当前可见、可用的非 READY CBB;请重新选择。')
return self._request(name)
def _backup_started(self, name):
self.busy = True
self._global_icdb_run = False
self.ready_names.discard(name)
if name in self._records_by_name:
self._records_by_name[name] = replace(self._records_by_name[name], status='UNKNOWN')
row = self._row_by_name.get(name)
if row is not None:
self.cbb_table.item(row, 2).setText('恢复中 / 需确认')
self.cbb_table.item(row, 0).setFlags(
self.cbb_table.item(row, 0).flags() | Qt.ItemIsUserCheckable)
for column in range(self.cbb_table.columnCount()):
self.cbb_table.item(row, column).setBackground(QColor('#FFF8E1'))
self._update()
self.stop_button.setEnabled(False)
def _backup_completed(self, name, result):
if not result.safe_to_continue and self.library_lease is not None:
self.library_lease.retain_for_recovery()
row = self._row_by_name.get(name)
if row is not None and result.status != 'PASS':
self.cbb_table.item(row, 2).setText('未知 / 需确认')
self._progress({'block': name, 'stage': result.status, 'detail': result.stderr,
'evidence': str(result.evidence_path or '')})
if result.safe_to_continue:
self.busy = False
self.refresh_affected_records([name])
else:
self._defer_status_refresh([name])
def _backup_dialog_closed(self):
if not getattr(self, '_refreshing_records', False):
self._finished()
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())
names = [name for name in names if name in eligible]
if not names:
self.status_label.setText('当前可见选择中没有可校验的非 READY CBB。')
self._update() self._update()
return return
requests = [self._request(name) for name in names] requests = [replace(self._request(name), maintenance=maintenance) for name in names]
self._global_icdb_run = maintenance
self._icdb_completed = 0
self.icdb_progress.setVisible(maintenance)
self.icdb_phase.setVisible(maintenance)
if maintenance:
self.icdb_progress.setRange(0, len(requests))
self.icdb_progress.setValue(0)
self.icdb_progress.setFormat('已处理 %v / %m 个 CBB')
self.icdb_phase.setText('准备检查…')
self.stop.clear(); self.recovery_path = None; self.recovery_button.setEnabled(False) self.stop.clear(); self.recovery_path = None; self.recovery_button.setEnabled(False)
self.output.clear(); self.status_label.setText(f'正在校验:共 {len(names)} 个 CBB') self.output.clear(); self.status_label.setText(
f'正在非 READY ICDB 检查与修复:共 {len(names)} 个 CBB' if maintenance
else f'正在校验:共 {len(names)} 个 CBB')
def action(): def action():
from cbb_refresh_verify.verify_runner import read_library_flag_if_available, run_verify from cbb_refresh_verify.verify_runner import read_library_flag_if_available, run_verify
verifier = self.verifier or (lambda req: run_verify( verify = self.verifier or (lambda req: run_verify(
req, progress=lambda e: self.signals.event.emit(e), req, progress=lambda e: self.signals.event.emit(e),
flag_reader=read_library_flag_if_available)) flag_reader=read_library_flag_if_available))
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, 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, 'detail': result.stderr, 'evidence': str(result.evidence_path or '')}))
report = write_batch_report(requests, results, self.data_root/'reports') report = write_batch_report(requests, results, self.data_root/'reports')
return results, report 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
return results, report, affected, refresh
self._start(action, self._batch_done) self._start(action, self._batch_done)
def _read_affected_records(self, names):
"""Worker-only read; never derive library state from action outcomes."""
import pythoncom
pythoncom.CoInitialize()
try:
path = Path(self.mentor_lmc_path or self.loaded_path)
try:
statuses = self.status_refresher(tuple(names), path)
reasons = {name: reason for name in names
if (reason := preflight_skip_reason(path, name))}
return tuple(names), statuses, reasons, ''
except Exception as error:
return tuple(names), {}, None, str(error)
finally:
pythoncom.CoUninitialize()
def _apply_refreshed_records(self, payload):
names, statuses, reasons, error = payload
self.cbb_table.blockSignals(True)
try:
for name in names:
if name not in self._records_by_name:
continue
status = statuses.get(name, 'UNKNOWN')
if status not in STATUS_LABELS:
status = 'UNKNOWN'
self._records_by_name[name] = replace(self._records_by_name[name], status=status)
self.ready_names.discard(name)
if reasons is not None:
self.skip_reasons.pop(name, None)
if name in reasons:
self.skip_reasons[name] = reasons[name]
self.skipped_names = set(self.skip_reasons)
row = self._row_by_name[name]
text = STATUS_LABELS[status]
if name in self.skipped_names:
text += ' · 缺少工程/PCB'
self.cbb_table.item(row, 2).setText(text)
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)
self._mark_row_ready(row)
else:
for column in range(self.cbb_table.columnCount()):
self.cbb_table.item(row, column).setBackground(QColor('#FFF8E1'))
finally:
self.cbb_table.blockSignals(False)
if error:
self.output.append(f'状态复核未完成 / 需确认:{error}')
self._apply_filters()
return tuple(self._records_by_name[name] for name in names if name in self._records_by_name)
def _defer_status_refresh(self, names):
self._apply_refreshed_records((tuple(names), {}, None,
'会话或数据库安全未确认;暂缓原生状态复核,请确认释放后重新读取。'))
def refresh_affected_records(self, names, callback=None):
"""Start an affected-only authoritative refresh once native owners release.
Return True if scheduled, False if busy/unloaded/empty. Callback receives
tuple[CbbRecord, ...] on the GUI thread after applying refreshed statuses
(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:
return False
targets = tuple(dict.fromkeys(name for name in names if name in self._records_by_name))
if not targets:
return False
self._refreshing_records = True
def refreshed(payload):
records = self._apply_refreshed_records(payload)
self._refreshing_records = False
if callback:
callback(records)
self._start(lambda: self._read_affected_records(targets), refreshed)
return True
def _progress(self, event): def _progress(self, event):
line = f"{event.get('block', '')} | {event.get('stage', '')}" line = f"{event.get('block', '')} | {event.get('stage', '')}"
for key in ('detail', 'error', 'action', 'statuses', 'evidence'): for key in ('detail', 'error', 'action', 'statuses', 'evidence'):
if event.get(key): line += f' | {event[key]}' if event.get(key): line += f' | {event[key]}'
self.output.append(line) self.output.append(line)
block = event.get('block'); stage = event.get('stage') block = event.get('block'); stage = event.get('stage')
if self._global_icdb_run:
if stage in {'PASS', 'FAIL', 'BLOCKED', 'TIMEOUT', 'SKIPPED', 'QUEUE_STOP'}:
self._icdb_completed += 1
self.icdb_progress.setValue(self._icdb_completed)
phases = {'icdb_check_start': '检查工程数据库与校验状态',
'native_repair_start': '准备完整备份与原生修复',
'complete_backup_verified': '完整备份已校验',
'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'}:
row = self._row_by_name.get(block) row = self._row_by_name.get(block)
if row is not None: if row is not None:
if stage == 'PASS': detail = str(event.get('detail') or event.get('error') or '').strip()
self.cbb_table.item(row, 2).setText('绿色 / Ready') label = str(stage) if not detail else f'{stage}: {detail[:96]}'
self.cbb_table.item(row, 3).setText('PASS') self.cbb_table.item(row, 3).setText(label)
self.ready_names.add(block) self.cbb_table.item(row, 3).setToolTip(detail)
self._mark_row_ready(row)
else:
detail = str(event.get('detail') or event.get('error') or '').strip()
label = str(stage) if not detail else f'{stage}: {detail[:96]}'
self.cbb_table.item(row, 3).setText(label)
if detail:
self.cbb_table.item(row, 3).setToolTip(detail)
if self.logging_context: self.logging_context.logger.info('cbb_progress %s', line) if self.logging_context: self.logging_context.logger.info('cbb_progress %s', line)
def _mark_row_ready(self, row): def _mark_row_ready(self, row):
"""Make a verified row visibly complete and remove it from the queue.""" """Color authoritative READY rows while retaining management selection."""
name_item = self.cbb_table.item(row, 0) name_item = self.cbb_table.item(row, 0)
if name_item is None: if name_item is None:
return return
name_item.setCheckState(Qt.Unchecked) name_item.setFlags(name_item.flags() | Qt.ItemIsUserCheckable)
name_item.setFlags(name_item.flags() & ~Qt.ItemIsUserCheckable)
for column in range(self.cbb_table.columnCount()): for column in range(self.cbb_table.columnCount()):
cell = self.cbb_table.item(row, column) cell = self.cbb_table.item(row, column)
if cell is not None: if cell is not None:
cell.setBackground(QColor('#E8F5E9')) cell.setBackground(QColor('#E8F5E9'))
def _batch_done(self, outcome): def _batch_done(self, outcome):
results, report = 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)
if len(outcome) > 2:
_, _, affected, refresh = outcome
if refresh is None:
self._defer_status_refresh(affected)
else:
self._apply_refreshed_records(refresh)
if self.library_lease is not None and any(not result.safe_to_continue for result in results): if self.library_lease is not None and any(not result.safe_to_continue for result in results):
self.library_lease.retain_for_recovery() self.library_lease.retain_for_recovery()
for result in results: for result in results:
@@ -394,11 +818,27 @@ class MainWindow(QWidget):
failed = len(results)-passed-skipped failed = len(results)-passed-skipped
text = (f'已结束:成功 {passed},失败 {failed},预检跳过 {len(self.skipped_names)},' text = (f'已结束:成功 {passed},失败 {failed},预检跳过 {len(self.skipped_names)},'
f'队列未执行 {skipped}。\n完整日志:{report}\n仅失败日志:{failure_report_path(report)}') 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'
f'完整日志:{report}\n仅失败日志:{failure_report_path(report)}')
self.icdb_phase.setText('已停止,存在待处理项目' if failed or skipped else '已完成非 READY 检查')
if any(not result.safe_to_continue for result in results): if any(not result.safe_to_continue for result in results):
text += '\n未确认数据库或会话安全,已停止剩余校验。请查看恢复现场。' text += '\n未确认数据库或会话安全,已停止剩余校验。请查看恢复现场。'
self.status_label.setText(text); self.output.append(text) status_text = text
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)
self.summary = QMessageBox(self) self.summary = QMessageBox(self)
self.summary.setWindowTitle('CBB 校验结果'); self.summary.setText(text) self.summary.setWindowTitle('非 READY ICDB 检查与修复结果' if self._global_icdb_run else 'CBB 校验结果'); self.summary.setText(text)
self.summary.setIcon(QMessageBox.Warning if failed else QMessageBox.Information) self.summary.setIcon(QMessageBox.Warning if failed else QMessageBox.Information)
# Modeless notification: do not force activation or steal keyboard focus. # Modeless notification: do not force activation or steal keyboard focus.
from PySide6.QtCore import Qt from PySide6.QtCore import Qt
@@ -416,6 +856,10 @@ class MainWindow(QWidget):
def _finished(self): def _finished(self):
self.busy = False; self._update() self.busy = False; self._update()
if self._reload_after_maintenance:
from PySide6.QtCore import QTimer
self._reload_after_maintenance = False
QTimer.singleShot(0, self.load_library)
def open_logs(self): def open_logs(self):
self.data_root.mkdir(parents=True, exist_ok=True); os.startfile(str(self.data_root)) self.data_root.mkdir(parents=True, exist_ok=True); os.startfile(str(self.data_root))
@@ -0,0 +1,189 @@
"""Explicit preview and asynchronous, checkpointed CBB management batch."""
from dataclasses import replace
from pathlib import Path
from threading import Event
from PySide6.QtCore import QObject, QThreadPool, Signal, Qt
from PySide6.QtWidgets import (QCheckBox, QDialog, QFileDialog, QHBoxLayout, QLabel,
QMessageBox, QPushButton, QTableWidget, QTableWidgetItem, QTextEdit, QVBoxLayout)
from .workers import ServiceWorker
from ..management import run_management_batch, validate_name
RESULT_LABELS = {
'REMOVED': '已移除', 'UPLOADED': '已上传 / 未自动校验',
'UPLOADED_VERIFIED': '已上传且校验通过', 'UPLOADED_VERIFY_FAILED': '已上传但校验未通过',
'UPLOAD_FAILED': '上传失败', 'RECOVERY_REQUIRED': '需要人工恢复 / 队列已停止',
'BLOCKED': '操作被阻止', 'UNSUPPORTED': '当前环境不支持',
}
STAGE_LABELS = {
'prepare_identity': '正在核对来源工程内容',
'catalog_before': '正在核对原生目录', 'backup': '正在备份完整中心库',
'stage_source': '正在复制并检查来源工程', 'native_remove': '正在原生移除',
'removed': '原条目已移除', 'native_add': '正在原生上传', 'uploaded': '上传身份已确认',
'verify': '正在校验上传结果', 'verified': '校验已返回', 'copy': '正在复制备份',
}
class ManagementSignals(QObject):
progress = Signal(object)
class ManagementDialog(QDialog):
completed = Signal(object)
def __init__(self, requests, parent=None, *, adapter=None, runner=None):
super().__init__(parent)
self.templates = tuple(requests)
self.template = self.templates[0]
self.operation = self.template.operation
self.adapter = adapter
self.runner = runner or run_management_batch
self.busy = False
self.executed = False
self.stop = Event()
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1)
self.signals = ManagementSignals(self)
self.signals.progress.connect(self._progress)
self.setWindowTitle({'add': '新增 CBB', 'update': '同名更新 CBB', 'remove': '移除 CBB'}[self.operation])
self.resize(850, 450)
self.table = QTableWidget(0, 4)
self.table.setHorizontalHeaderLabels(['CBB 名称', '分区', '来源 PRJ(完整工程)', '顶层块(空白时读取工程)'])
self.table.horizontalHeader().setStretchLastSection(True)
self.table.setColumnWidth(2, 300)
self.sources_button = QPushButton('选择来源工程…')
self.sources_button.setVisible(self.operation != 'remove')
self.sources_button.clicked.connect(self._browse)
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.setWordWrap(True)
self.output = QTextEdit(); self.output.setReadOnly(True)
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(self.table)
layout.addWidget(self.sources_button); layout.addWidget(self.auto_verify)
layout.addWidget(self.status_label); layout.addWidget(self.output)
buttons = QHBoxLayout()
for widget in (self.execute_button, self.stop_button, self.close_button): buttons.addWidget(widget)
layout.addLayout(buttons)
for request in self.templates:
if request.name:
self._append(request)
def _append(self, request):
row = self.table.rowCount(); self.table.insertRow(row)
for column, value in enumerate((request.name, request.partition, str(request.source or ''), request.top_level_block)):
item = QTableWidgetItem(value)
if column == 1 or column == 0 and self.operation != 'add' or self.operation == 'remove':
item.setFlags(item.flags() & ~Qt.ItemIsEditable)
self.table.setItem(row, column, item)
def add_sources(self, sources):
if self.operation == 'add':
for source in sources:
source = Path(source)
self._append(replace(self.template, name=source.stem, source=source))
elif self.operation == 'update' and sources:
row = max(0, self.table.currentRow())
self.table.item(row, 2).setText(str(sources[0]))
def _browse(self):
if self.operation == 'add':
paths, _ = QFileDialog.getOpenFileNames(self, '选择完整来源工程', '', '工程 (*.prj)')
else:
path, _ = QFileDialog.getOpenFileName(self, '为当前行选择同名更新来源', '', '工程 (*.prj)')
paths = [path] if path else []
self.add_sources(paths)
def requests(self):
result = []
for row in range(self.table.rowCount()):
name, partition, source, top = (self.table.item(row, i).text().strip() for i in range(4))
result.append(replace(self.template, name=name, partition=partition,
source=Path(source) if source else None, top_level_block=top,
auto_verify=self.operation != 'remove' and self.auto_verify.isChecked()))
return result
def _execute(self):
if self.busy or self.executed:
return
requests = self.requests()
try:
if not requests:
raise ValueError('请先选择来源工程。')
for request in requests:
validate_name(request.name)
if request.operation != 'remove' and (request.source is None or not request.source.is_file()):
raise ValueError(f'{request.name}:请选择完整来源 PRJ。')
if len({(r.partition.casefold(), r.name.casefold()) for r in requests}) != len(requests):
raise ValueError('批次包含重复目标名称。')
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'
else '新增同名冲突会拒绝覆盖,完整来源工程将先复制到暂存区。')
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,
QMessageBox.No)
if answer != QMessageBox.Yes:
return
self.busy = True; self.executed = True
self._enabled(False)
self.worker = ServiceWorker(lambda: self.runner(requests, adapter=self.adapter, stop=self.stop,
progress=self.signals.progress.emit))
self.worker.signals.succeeded.connect(self._result)
self.worker.signals.failed.connect(self._failed)
self.worker.signals.finished.connect(self._finished)
self.pool.start(self.worker)
def _enabled(self, enabled):
for widget in (self.table, self.sources_button, self.auto_verify, self.close_button):
widget.setEnabled(enabled)
self.execute_button.setEnabled(enabled and not self.executed)
self.stop_button.setEnabled(not enabled)
def _progress(self, event):
stage = str(event.get('stage', ''))
text = f'{event.get("block", "")} {STAGE_LABELS.get(stage, RESULT_LABELS.get(stage, stage))}'
if 'copied_files' in event:
text += f' {event["copied_files"]}/{event.get("total_files", "?")}'
self.status_label.setText(text)
def _result(self, results):
lines = []
for result in results:
text = f'{result.name}:{RESULT_LABELS.get(result.status, result.status)} — {result.detail}'
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.completed.emit(results)
def _failed(self, error):
from ..management import ManagementResult
request = self.template
self._result([ManagementResult(request.operation, request.library, request.name, request.partition,
request.source, request.auto_verify, 'complete', 'RECOVERY_REQUIRED', False, str(error))])
def _finished(self):
self.busy = False; self._enabled(True)
def reject(self):
if not self.busy:
super().reject()
def closeEvent(self, event):
if self.busy:
self.stop.set(); event.ignore()
else:
super().closeEvent(event)
@@ -113,6 +113,8 @@ def collect_native_failure_logs(pcb_path, evidence_root, *, max_bytes=NATIVE_LOG
target = destination/(label+'-'+source.name) target = destination/(label+'-'+source.name)
target.write_bytes(data) target.write_bytes(data)
item.update(evidence=str(target), copied_bytes=len(data)) item.update(evidence=str(target), copied_bytes=len(data))
if label == 'pcb-logfiles' and source.name != 'ReusableBlock.txt':
_collect_icdb_recovery(source, evidence_root)
except FileNotFoundError: except FileNotFoundError:
item['exists'] = False item['exists'] = False
except OSError as error: except OSError as error:
@@ -120,6 +122,23 @@ def collect_native_failure_logs(pcb_path, evidence_root, *, max_bytes=NATIVE_LOG
return _write_record(destination.parent/'native-logs.json', record) return _write_record(destination.parent/'native-logs.json', record)
def _collect_icdb_recovery(source, evidence_root):
"""Only promote a native error whose log changed after this launch."""
from .icdb_recovery import read_log_failure
root = Path(evidence_root)/'diagnostics'
try:
baseline = json.loads((root/'startup-log-baseline.json').read_text('utf-8'))
checkpoint = (baseline['baseline'] if baseline['source'] == str(source) else
baseline.get('integration_logs', {}).get(str(source)))
if checkpoint is None:
return
_, recovery = read_log_failure(source, checkpoint)
if recovery:
_write_record(root/'icdb-recovery.json', {**recovery, 'source': str(source)})
except (OSError, ValueError, KeyError, TypeError):
pass # Unknown freshness must not replace the original failure.
def failure_logs_main(request_path): def failure_logs_main(request_path):
job = json.loads(Path(request_path).read_text(encoding='utf-8')) job = json.loads(Path(request_path).read_text(encoding='utf-8'))
+203 -38
View File
@@ -62,6 +62,9 @@ class VerifyRequest:
# it before launching Library Manager/PCB. # it before launching Library Manager/PCB.
mapped_drive: str = '' mapped_drive: str = ''
mapped_remote_root: str = '' mapped_remote_root: str = ''
auto_repair: bool = True
maintenance: bool = False
post_repair_proof: object | None = field(default=None, repr=False, compare=False)
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -80,6 +83,7 @@ class VerifyResult:
bridge_attempts: tuple[dict, ...] = () bridge_attempts: tuple[dict, ...] = ()
timings_seconds: dict[str, float] = field(default_factory=dict) timings_seconds: dict[str, float] = field(default_factory=dict)
incomplete_timing_phases: tuple[str, ...] = () incomplete_timing_phases: tuple[str, ...] = ()
recovery_attempts: tuple[dict, ...] = ()
def resolve_importer(mentor_bin: str | None = None) -> Path: def resolve_importer(mentor_bin: str | None = None) -> Path:
@@ -127,6 +131,9 @@ def classify_output(exit_code: int | None, output: str, *, timed_out: bool = Fal
"""Never invent success: PASS needs the success text and no error marker.""" """Never invent success: PASS needs the success text and no error marker."""
if timed_out: if timed_out:
return 'TIMEOUT' return 'TIMEOUT'
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): if exit_code == 0 and SUCCESS_TEXT.search(output) and not ERROR_TEXT.search(output):
return 'PASS' return 'PASS'
if ERROR_TEXT.search(output): if ERROR_TEXT.search(output):
@@ -182,7 +189,7 @@ def preflight_skip_reason(lmc_file, block_name):
return '' return ''
work = library.parent / 'ReusableBlocksLP' / str(block_name) / 'Work' work = library.parent / 'ReusableBlocksLP' / str(block_name) / 'Work'
if not work.is_dir(): if not work.is_dir():
return '' return f'{block_name}: 缺少 Work 工程目录'
request = VerifyRequest(library, str(block_name), library.parent / '.cbb-preflight-evidence') request = VerifyRequest(library, str(block_name), library.parent / '.cbb-preflight-evidence')
try: try:
preflight(request) preflight(request)
@@ -195,38 +202,18 @@ def preflight_skip_reason(lmc_file, block_name):
return '' return ''
def _run_process(command, timeout_seconds, cwd): def _run_process(command, timeout_seconds, cwd, *, evidence_root=None):
"""Run the importer, draining both pipes while it works (no pipe deadlock).""" from .content_check import run_content_check
process = subprocess.Popen(command, cwd=str(cwd), stdout=subprocess.PIPE, stderr=subprocess.PIPE, return run_content_check(command, timeout_seconds, cwd, evidence_root=evidence_root)
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
try:
stdout, stderr = process.communicate(timeout=timeout_seconds)
return process.returncode, stdout.decode('utf-8', errors='replace'), stderr.decode('utf-8', errors='replace'), False
except subprocess.TimeoutExpired:
# A timed-out importer may have spawned a child that still owns the
# pipes. Bound both tree termination and the final drain so a hung
# helper cannot turn a 30-second item timeout into an unbounded wait.
try:
subprocess.run([str(Path(os.environ.get('WINDIR', r'C:\Windows'))/'System32'/'taskkill.exe'), '/PID', str(process.pid), '/T', '/F'],
capture_output=True, timeout=5,
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
except (OSError, subprocess.TimeoutExpired):
pass
try:
process.kill()
except OSError:
pass
try:
stdout, stderr = process.communicate(timeout=5)
except subprocess.TimeoutExpired:
stdout, stderr = b'', b''
return None, stdout.decode('utf-8', errors='replace'), stderr.decode('utf-8', errors='replace'), True
def _stop_worker(process, *, timeout=5): def _stop_worker(process, *, timeout=5):
"""Stop automation clients; native database owners are preserved.""" """Stop automation clients; native database owners are preserved."""
try: try:
process.kill() if hasattr(process, 'request_stop'):
process.request_stop()
else:
process.kill()
except Exception: except Exception:
pass pass
try: try:
@@ -277,6 +264,11 @@ def read_library_flag_with_retry(reader, library, block_name, *, attempts=3,
def classify_failure_category(detail): def classify_failure_category(detail):
text = str(detail or '') text = str(detail or '')
lower = text.casefold() lower = text.casefold()
if 'pcb_version_choice_required' in lower:
return 'PCB_VERSION_CHOICE_REQUIRED'
from .icdb_recovery import ERROR_CODE, parse_session_loss
if ERROR_CODE.casefold() in lower or parse_session_loss(text):
return ERROR_CODE
if any(code in lower for code in ( if any(code in lower for code in (
'pcb_release_unconfirmed', 'icdb_release_unconfirmed', 'pcb_release_unconfirmed', 'icdb_release_unconfirmed',
'icdb_session_unconfirmed', 'pcb_session_active', 'database_recovery_required')): 'icdb_session_unconfirmed', 'pcb_session_active', 'database_recovery_required')):
@@ -518,22 +510,129 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
# Cover contents checking, native work and final state reads with one # Cover contents checking, native work and final state reads with one
# session-wide mutex. The worker-stage lock below is reentrant on Windows. # session-wide mutex. The worker-stage lock below is reentrant on Windows.
import win32event, win32con import win32event, win32con
from .com_runtime import initialize_com, uninitialize_com
initialized = initialize_com()
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795') mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = False acquired = False
library_lock = None
release_confirmed = True
try: try:
acquired = win32event.WaitForSingleObject(mutex, 0) in ( acquired = win32event.WaitForSingleObject(mutex, 0) in (
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED) win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired: if not acquired:
return VerifyResult('BLOCKED', stderr='已有 CBB 校验任务运行,请等待结束。', return VerifyResult('BLOCKED', stderr='已有 CBB 校验任务运行,请等待结束。',
safe_to_continue=False) safe_to_continue=False)
return _run_verify_serialized( 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 .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.__enter__()
except LibraryBusy as error:
return VerifyResult('BLOCKED', stderr=str(error), safe_to_continue=False)
release_confirmed = False
result = _run_verify_serialized(
request, progress=progress, flag_reader=flag_reader, request, progress=progress, flag_reader=flag_reader,
process_runner=process_runner, port_check=port_check, process_runner=process_runner, port_check=port_check,
dialog_supervisor_factory=dialog_supervisor_factory) dialog_supervisor_factory=dialog_supervisor_factory)
if (request.auto_repair and result.status not in {'TIMEOUT', 'BLOCKED'}
and result.error_category == 'ICDB_REPAIR_REQUIRED'
and result.evidence_path):
from .native_repair import attempt_recovery
try:
diagnosis = json.loads((result.evidence_path.parent/'diagnostics/icdb-recovery.json').read_text('utf-8'))
original = result
snapshot = original.evidence_path.with_name('pre-repair-result.json')
snapshot.write_text(json.dumps(asdict(original), ensure_ascii=False, default=str, indent=2),
encoding='utf-8')
recovery = attempt_recovery(request, diagnosis, result.evidence_path.parent, progress=progress)
recovery = {**recovery, 'original_error': original.stderr,
'original_evidence': str(original.evidence_path),
'original_result_snapshot': str(snapshot),
'original_stage': original.error_stage,
'native_status': recovery.get('native_status', recovery.get('status')),
'validation_passed': False}
if recovery.get('status') == 'REPAIRED':
from .native_repair import native_success_confirmed, select_repair_target
try:
confirmed = native_success_confirmed(select_repair_target(request, diagnosis), recovery)
except (ValueError, OSError):
confirmed = False
if not confirmed:
release = recovery.get('release')
recovery.update(status='UNCONFIRMED',
release={**(release if isinstance(release, dict) else {}), 'safe_to_continue': False},
detail='NATIVE_REPAIR_EVIDENCE_UNCONFIRMED: 原生成功记录不完整或矛盾,未重试校验')
if (recovery.get('status') == 'REPAIRED'
and recovery.get('release', {}).get('safe_to_continue') is True):
result = replace(original, recovery_attempts=(recovery,))
recovery['status'] = 'REPAIR_VALIDATION_FAILED'
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)
recovery['validation_evidence'] = str(result.evidence_path or '')
recovery['validation_passed'] = (result.status == 'PASS'
and result.library_flag == 'GREEN' and result.safe_to_continue)
if not recovery['validation_passed']:
recovery['status'] = 'REPAIR_VALIDATION_FAILED'
if result.status == 'PASS':
result = replace(result, status='FAIL',
stderr=(result.stderr+'\nREPAIR_VALIDATION_UNCONFIRMED: 未取得校验 GREEN').strip())
else:
recovery['status'] = 'REPAIRED'
else:
# A failed local database must not block unrelated CBBs once
# every owner is released. Re-check target ownership here so
# an incomplete repair record cannot authorize the queue.
safe = False
if (recovery.get('status') in {'MISSING_HEALTHY_BACKUP', 'NATIVE_REPAIR_FAILED'}
and recovery.get('evidence', {}).get('failure_complete') is True
and recovery.get('release', {}).get('safe_to_continue') is True):
from .native_repair import select_repair_target
try:
target = select_repair_target(request, diagnosis)
safe = (Path(recovery.get('project', '')).resolve() == target.project
and Path(recovery.get('database', '')).resolve() == target.database)
except (ValueError, OSError):
pass
result = replace(result, safe_to_continue=safe, stderr=(result.stderr + '\n'
+ str(recovery.get('status', 'REPAIR_UNCONFIRMED')) + ': '
+ str(recovery.get('detail', '原生 Repair 未完成恢复'))).strip())
result = replace(result, recovery_attempts=(recovery,))
result.evidence_path.write_text(json.dumps({'block_name': request.block_name, **asdict(result)},
ensure_ascii=False, default=str, indent=2), encoding='utf-8')
except Exception as error:
result = replace(result, status='FAIL' if result.status == 'PASS' else result.status,
safe_to_continue=False,
stderr=(result.stderr+f'\nREPAIR_UNCONFIRMED: {error}').strip())
if result.evidence_path:
try:
result.evidence_path.write_text(json.dumps({'block_name': request.block_name, **asdict(result)},
ensure_ascii=False, default=str, indent=2), encoding='utf-8')
except OSError:
pass # Keep the native/repair errors even if evidence storage fails.
release_confirmed = result.safe_to_continue
return result
finally: finally:
if acquired: try:
win32event.ReleaseMutex(mutex) if library_lock is not None:
mutex.Close() library_lock.__exit__(None, None, None)
finally:
if acquired:
win32event.ReleaseMutex(mutex)
mutex.Close()
uninitialize_com(initialized)
def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_runner=None, def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_runner=None,
@@ -554,6 +653,31 @@ def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_
pass pass
finally: finally:
timing.end('failure_diagnostics') timing.end('failure_diagnostics')
if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP'}:
from .icdb_recovery import ERROR_CODE, RECOVERY_ACTION, parse_session_loss, recovery_detail
recovery = parse_session_loss(result.stderr)
if recovery is None and result.evidence_path:
try:
saved = json.loads(result.evidence_path.with_name('diagnostics').joinpath(
'icdb-recovery.json').read_text('utf-8'))
recovery = parse_session_loss(saved.get('native_message', ''))
except (OSError, ValueError, AttributeError):
pass
if recovery or ERROR_CODE.casefold() in result.stderr.casefold():
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)
if recovery and result.evidence_path:
try:
record_path = result.evidence_path.parent/'diagnostics/icdb-recovery.json'
record_path.parent.mkdir(parents=True, exist_ok=True)
if not record_path.is_file():
record_path.write_text(json.dumps(recovery, ensure_ascii=False, indent=2),
encoding='utf-8')
except OSError:
pass
durations, unfinished = timing.snapshot() durations, unfinished = timing.snapshot()
result = replace(result, timings_seconds=durations, incomplete_timing_phases=unfinished, result = replace(result, timings_seconds=durations, incomplete_timing_phases=unfinished,
error_category=(result.error_category or classify_failure_category(result.stderr) error_category=(result.error_category or classify_failure_category(result.stderr)
@@ -599,7 +723,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
progress({'stage': 'runtime_fingerprint', 'block': request.block_name, progress({'stage': 'runtime_fingerprint', 'block': request.block_name,
**fingerprint}) **fingerprint})
result_path = root/'result.json' result_path = root/'result.json'
runner = process_runner or _run_process runner = process_runner or (lambda command, timeout, cwd:
_run_process(command, timeout, cwd, evidence_root=root))
def finish(result): def finish(result):
# Only reclaim auxiliary backups after confirmed success. Failed runs # Only reclaim auxiliary backups after confirmed success. Failed runs
@@ -621,6 +746,17 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
finally: finally:
timing.end('preflight') 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 = bool(str(request.libspec).strip() and str(request.dms_login_config).strip())
if content_check_enabled: if content_check_enabled:
try: try:
@@ -648,7 +784,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
# A contents failure or an unusable DMS must block before touching the PCB. # A contents failure or an unusable DMS must block before touching the PCB.
return finish(VerifyResult(status if status in ('FAIL', 'TIMEOUT') else 'BLOCKED', return finish(VerifyResult(status if status in ('FAIL', 'TIMEOUT') else 'BLOCKED',
stderr=combined.strip() or f'内容检查结果未知(退出码 {exit_code})', stderr=combined.strip() or f'内容检查结果未知(退出码 {exit_code})',
stdout=stdout, report_path=report, content_check_exit_code=exit_code)) stdout=stdout, report_path=report, content_check_exit_code=exit_code,
safe_to_continue=not timed_out))
if progress: if progress:
progress({'stage': 'content_check_done', 'block': request.block_name, 'status': 'PASS'}) progress({'stage': 'content_check_done', 'block': request.block_name, 'status': 'PASS'})
@@ -672,12 +809,21 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
'interactive_input': bool(request.interactive_input), 'interactive_input': bool(request.interactive_input),
'native_lm_verify': bool(request.native_lm_verify), 'native_lm_verify': bool(request.native_lm_verify),
'desktop': 'CbbVerify_' + uuid4().hex[:12], 'desktop': 'CbbVerify_' + uuid4().hex[:12],
'cancel_signal': str(root/'cancel-worker.signal'),
'start_gate': str(root/'start-worker.signal')} 'start_gate': str(root/'start-worker.signal')}
consent = None
if request.post_repair_proof is not None:
from .post_repair_consent import PostRepairProof, ConsentController, exact_prompt
if not isinstance(request.post_repair_proof, PostRepairProof):
return finish(VerifyResult('BLOCKED', stderr='POST_REPAIR_PROOF_REQUIRED', safe_to_continue=False))
job['post_repair_consent'] = request.post_repair_proof.for_job(job)
consent = ConsentController(request.post_repair_proof, job)
job_path = root/'request.json' job_path = root/'request.json'
job_path.write_text(json.dumps(job, ensure_ascii=False), encoding='utf-8') job_path.write_text(json.dumps(job, ensure_ascii=False), encoding='utf-8')
events = root/'events.jsonl' events = root/'events.jsonl'
offset = 0 offset = 0
target_pid = None target_pid = None
launcher_pid = None
lm_pid = None lm_pid = None
verify_invoked = False verify_invoked = False
invoke_returned = False invoke_returned = False
@@ -702,6 +848,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
worker_command(job_path), None, interactive_input=True) worker_command(job_path), None, interactive_input=True)
else: else:
process = DesktopWorker(worker_command(job_path), job['desktop']) process = DesktopWorker(worker_command(job_path), job['desktop'])
if hasattr(process, 'bind_cancellation'):
process.bind_cancellation(job['cancel_signal'])
deadline = ActivityDeadline(request.timeout_seconds) deadline = ActivityDeadline(request.timeout_seconds)
last_activity_key = None last_activity_key = None
phase = DialogPhase.PCB_STARTING phase = DialogPhase.PCB_STARTING
@@ -738,6 +886,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
break break
timing.record(event) timing.record(event)
if event.get('pcb_pid'): target_pid = event['pcb_pid'] 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('lm_pid'): lm_pid = event['lm_pid']
stage = event.get('stage') stage = event.get('stage')
if stage == 'verify_invoke': verify_invoked = True if stage == 'verify_invoke': verify_invoked = True
@@ -789,6 +938,18 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
dialog_result = dialog_supervisor.poll() dialog_result = dialog_supervisor.poll()
else: else:
dialog_result = dialog_supervisor.poll() dialog_result = dialog_supervisor.poll()
if (consent is not None and dialog_agent is not None
and dialog_result.error_code == 'DATABASE_RECOVERY_REQUIRED'
and dialog_result.snapshot is not None and exact_prompt(dialog_result.snapshot)):
consent_snapshot = dialog_result.snapshot
if consent_snapshot.hwnd in {int(h) for h in process.desktop.EnumDesktopWindows()}:
dialog_result = consent.handle(consent_snapshot, dialog_result.observed_snapshots,
target_pid=target_pid, launcher_pid=launcher_pid, worker_pid=process.pid,
companion_pids=tuple(process.companion_pids), perform=dialog_supervisor.backend.perform)
if dialog_result.error_code == 'PCB_VERSION_CHOICE_REQUIRED' and dialog_result.snapshot is not None:
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}')
# Normal progress stays in memory. Only actions/errors and the # Normal progress stays in memory. Only actions/errors and the
# last failure snapshots are persisted, not every elapsed tick. # last failure snapshots are persisted, not every elapsed tick.
latest_snapshots = dialog_result.observed_snapshots latest_snapshots = dialog_result.observed_snapshots
@@ -814,7 +975,10 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
if dialog_result.error_code: if dialog_result.error_code:
_write_failure_windows(root, latest_snapshots) _write_failure_windows(root, latest_snapshots)
_write_process_tree(root, process, target_pid) _write_process_tree(root, process, target_pid)
_stop_worker(process) # A failed database load has no document to close. Give the
# worker time to normally close its owned empty PCB before
# recovery checks for remaining native database clients.
_stop_worker(process, timeout=40)
return finish(VerifyResult( return finish(VerifyResult(
'FAIL', 'FAIL',
stderr=f'{dialog_result.error_code}: {dialog_result.detail}', stderr=f'{dialog_result.error_code}: {dialog_result.detail}',
@@ -886,10 +1050,11 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
except Exception as error: except Exception as error:
release_result = {'safe_to_continue': False, 'error': str(error)} release_result = {'safe_to_continue': False, 'error': str(error)}
try: try:
address = Path(project).parent / 'database/cdbsvr/sAddress.adr' from .icdb_ownership import unreleased_addresses
if address.exists(): addresses = unreleased_addresses(request.lmc_file, project, pcb)
if addresses:
release_result = {**(release_result or {}), 'safe_to_continue': False, release_result = {**(release_result or {}), 'safe_to_continue': False,
'icdb_address': str(address)} 'icdb_address': addresses[0], 'icdb_addresses': addresses}
except OSError as error: except OSError as error:
close_errors.append(str(error)) close_errors.append(str(error))
if close_errors: if close_errors:
@@ -0,0 +1,26 @@
{
"source": "Frozen b90a9bb native startup capture: no-history-repair/repair-result.json; HWNDs sanitized. Auxiliary classes/empty titles from coordinator's readback of the same owned native process.",
"startup_shell": {
"hwnd": 100,
"title": "iCDB Project Backup",
"class": "Afx:00400000:b:00010003:00000006:5F991B0D",
"enabled": true,
"children": [
{"hwnd": 401, "text": "", "class": "BCGPSlider:400000:8:10003:10", "id": -1, "enabled": true},
{"hwnd": 402, "text": "Output ", "class": "BCGPControlBar:400000:8:10003:10", "id": 313, "enabled": true},
{"hwnd": 403, "text": "", "class": "#32770", "id": 0, "enabled": true},
{"hwnd": 400, "text": "", "class": "RichEdit20A", "id": 1002, "enabled": true},
{"hwnd": 404, "text": "", "class": "BCGPStatusBar:400000:8:10003:10", "id": 59393, "enabled": true},
{"hwnd": 405, "text": "", "class": "BCGPDockBar:400000:8:10003:10", "id": 59419, "enabled": true},
{"hwnd": 406, "text": "Standard", "class": "BCGPToolBar:400000:8:10003:10", "id": 59392, "enabled": true},
{"hwnd": 407, "text": "Menu Bar", "class": "BCGPToolBar:400000:8:10003:10", "id": 59398, "enabled": true},
{"hwnd": 408, "text": "", "class": "#32770", "id": 59648, "enabled": true}
]
},
"auxiliary_windows": [
{"hwnd": 500, "title": "", "class": "UAC_InputIndicatorOverlayWnd", "enabled": true, "children": []},
{"hwnd": 501, "title": "", "class": "UAC Input Indicator", "enabled": true, "children": []}
],
"loaded_title_prefix": "iCDB Project Backup - ",
"loaded_output": "Checking if project is in use.\r\nProject is not in use. Full iCDB Project Backup's functionality is available.\r\n"
}
+30
View File
@@ -0,0 +1,30 @@
{
"source": "Issue 2 data.zip, verify-86f90ffba911; selected fields only; paths and process identities sanitized",
"limitations": "Logs only. No field database, executable fault reproduction or recovery claim.",
"block": "1GPHY_8211",
"diagnosis": {
"error_code": "ICDB_REPAIR_REQUIRED",
"scope": "project",
"machine": "FIELD-PC",
"session": "2026-10-20 14.03.54-18212",
"database_relative": "Work/database"
},
"native_error": "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. (Machine:[FIELD-PC] Path:[<library>/ReusableBlocksLP/1GPHY_8211/Work/database] session:[2026-10-20 14.03.54-18212])",
"observed_events": [
{"stage": "pcb_launch", "strategy": "reusable_circuit_direct"},
{"stage": "pcb_launcher_started", "launcher_pid": 11},
{"stage": "pcb_worker_started", "pcb_pid": 12, "binding": "commandline"},
{"stage": "native_failure_logs"},
{"stage": "process_retained", "safe_to_continue": false},
{"stage": "failed", "error": "VERIFY_CANCELLED: stop and normally close target document"}
],
"dialog": {
"pid": 12,
"phase": "PCB_STARTING",
"action": "acknowledge_fatal",
"error_code": "MENTOR_DATABASE_LOAD_FAILED",
"text": "Problem encountered while opening one of the database files. See PCBLogFile.txt for details. Loading of the job has failed. Do you wish to view the log file now?"
},
"original_result": {"status": "FAIL", "error_category": "ICDB_REPAIR_REQUIRED", "error_stage": "PCB_STARTING"},
"original_repair": {"status": "BLOCKED", "detail": "REPAIR_DATABASE_IN_USE"}
}
+183
View File
@@ -0,0 +1,183 @@
{
"hwnd": 100,
"pid": 20,
"process_name": "ExpeditionPCB.exe",
"process_role": "pcb",
"window_class": "#32770",
"title": "Database Restoration",
"phase": "PCB_STARTING",
"controls": [
{
"handle": 101,
"control_id": 65535,
"class_name": "Static",
"name": "",
"automation_id": "65535",
"control_type": "Image",
"enabled": true,
"selected": false,
"checked": false,
"patterns": []
},
{
"handle": 102,
"control_id": 6208,
"class_name": "Static",
"name": "The system has detected this design abnormally terminated the last time it was used. The user has to decide what database (if any) to associate with the design.",
"automation_id": "6208",
"control_type": "Text",
"enabled": true,
"selected": false,
"checked": false,
"patterns": []
},
{
"handle": 103,
"control_id": 6212,
"class_name": "Button",
"name": "Restore Database",
"automation_id": "6212",
"control_type": "Group",
"enabled": true,
"selected": false,
"checked": false,
"patterns": []
},
{
"handle": 104,
"control_id": 6213,
"class_name": "Button",
"name": "Load the last user saved database dated 2026/9/24 23:06.",
"automation_id": "6213",
"control_type": "RadioButton",
"enabled": true,
"selected": false,
"checked": false,
"patterns": [
"Invoke",
"SelectionItem"
]
},
{
"handle": 105,
"control_id": 6206,
"class_name": "Button",
"name": "Load the autosave database dated 2026/9/24 23:06.",
"automation_id": "6206",
"control_type": "RadioButton",
"enabled": true,
"selected": true,
"checked": true,
"patterns": [
"Invoke",
"SelectionItem"
]
},
{
"handle": 106,
"control_id": 6207,
"class_name": "Static",
"name": "This will restore the design to the last autosave state.",
"automation_id": "6207",
"control_type": "Text",
"enabled": true,
"selected": false,
"checked": false,
"patterns": []
},
{
"handle": 107,
"control_id": 6209,
"class_name": "Static",
"name": "This will restore the design to the data from the last user save.",
"automation_id": "6209",
"control_type": "Text",
"enabled": true,
"selected": false,
"checked": false,
"patterns": []
},
{
"handle": 108,
"control_id": 6210,
"class_name": "Static",
"name": "Autosaved changes will be lost.",
"automation_id": "6210",
"control_type": "Text",
"enabled": true,
"selected": false,
"checked": false,
"patterns": []
},
{
"handle": 109,
"control_id": 6211,
"class_name": "Static",
"name": "* Cancelling will load no design.",
"automation_id": "6211",
"control_type": "Text",
"enabled": true,
"selected": false,
"checked": false,
"patterns": []
},
{
"handle": 110,
"control_id": 1,
"class_name": "Button",
"name": "OK",
"automation_id": "1",
"control_type": "Button",
"enabled": true,
"selected": false,
"checked": false,
"patterns": [
"Invoke"
]
},
{
"handle": 111,
"control_id": 2,
"class_name": "Button",
"name": "Cancel",
"automation_id": "2",
"control_type": "Button",
"enabled": true,
"selected": false,
"checked": false,
"patterns": [
"Invoke"
]
},
{
"handle": 100,
"control_id": 0,
"class_name": "#32770",
"name": "Database Restoration",
"automation_id": "",
"control_type": "Window",
"enabled": true,
"selected": false,
"checked": false,
"patterns": [
"Window"
]
},
{
"handle": 0,
"control_id": 0,
"class_name": "",
"name": "",
"automation_id": "",
"control_type": "TitleBar",
"enabled": true,
"selected": false,
"checked": false,
"patterns": [
"Value"
]
}
],
"owner_hwnd": 90,
"diagnostics": []
}
+328
View File
@@ -0,0 +1,328 @@
import pytest
from pathlib import Path
from cbb_refresh_verify.verify_runner import VerifyRequest, VerifyResult
def project(work, name, data):
(work/'database').mkdir(parents=True)
(work/'database/icdb.dat').write_bytes(data)
(work/'PCB/Layout').mkdir(parents=True)
(work/'PCB/Layout/LayoutDB.lyt').write_bytes(data)
(work/'PCB'/f'{name}.pcb').write_text(f'SECTION Integration\nKEY ProjectFile "..\\{name}.prj"\nENDSECTION\n')
(work/'PCB/pcb.prj').write_text('SECTION Project\nKEY CentralLibrary "old.lmc"\nENDSECTION\n')
path = work/f'{name}.prj'
path.write_text(f'SECTION Board1\nKEY RootBlock "{name}"\nKEY PCBDesignPath "PCB\\{name}.pcb"\nENDSECTION\n'
'SECTION DesignInfo\nKEY CentralLibrary "old.lmc"\nENDSECTION\n'
'SECTION iCDB\nKEY iCDBDir ".\\database"\nENDSECTION\n')
return path
@pytest.fixture
def recovery_files(tmp_path, monkeypatch):
monkeypatch.setattr(Path, 'home', lambda: tmp_path/'profile')
library = tmp_path/'target/target.lmc'
original = project(library.parent/'ReusableBlocksLP/A/Work', 'A', b'damaged')
library.write_bytes(b'library')
source = project(tmp_path/'backup/Work', 'A', b'healthy')
return VerifyRequest(library, 'A', tmp_path/'evidence'), original, source
def test_restore_checks_source_in_library_copy_then_opens_actual_target(recovery_files):
from cbb_refresh_verify.backup_recovery import recover_from_backup
request, original, source = recovery_files
pcb_project = source.parent/'PCB/pcb.prj'
pcb_project.write_text(pcb_project.read_text() +
'SECTION SecondNativeConfiguration\nKEY CentralLibrary "old.lmc"\nENDSECTION\n')
before = source.read_bytes()
calls = []
def verify(req, **kwargs):
work = req.lmc_file.parent/'ReusableBlocksLP/A/Work'
assert (work/'database/icdb.dat').read_bytes() == b'healthy'
if calls:
assert req.lmc_file == request.lmc_file
else:
assert req.lmc_file != request.lmc_file
assert not req.lmc_file.is_relative_to(request.evidence_dir)
assert (original.parent/'database/icdb.dat').read_bytes() == b'damaged'
calls.append(req)
assert not req.auto_repair
return VerifyResult('PASS', library_flag='GREEN')
result = recover_from_backup(request, source, verifier=verify, idle_check=lambda *_: None)
assert result.status == 'PASS'
assert len(calls) == 2
assert source.read_bytes() == before
assert (original.parent/'database/icdb.dat').read_bytes() == b'healthy'
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'))
def test_invalid_source_does_not_touch_target(recovery_files):
from cbb_refresh_verify.backup_recovery import recover_from_backup
request, original, source = recovery_files
source.write_text(source.read_text().replace('RootBlock "A"', 'RootBlock "OTHER"'))
result = recover_from_backup(request, source, verifier=lambda *_: pytest.fail('must not verify'),
idle_check=lambda *_: None)
assert result.status == 'BLOCKED'
assert '同名' in result.stderr
assert (original.parent/'database/icdb.dat').read_bytes() == b'damaged'
def test_unusable_backup_never_replaces_target(recovery_files):
from cbb_refresh_verify.backup_recovery import recover_from_backup
request, original, source = recovery_files
result = recover_from_backup(request, source, verifier=lambda *a, **k:
VerifyResult('FAIL', stderr='ICDB cannot load'), idle_check=lambda *_: None)
assert result.status == 'FAIL'
assert '目标未更改' in result.stderr
assert not list(original.parent.parent.glob('Work.before-restore-*'))
assert (original.parent/'database/icdb.dat').read_bytes() == b'damaged'
def test_final_open_failure_preserves_original_and_does_not_report_pass(recovery_files):
from cbb_refresh_verify.backup_recovery import recover_from_backup
request, original, source = recovery_files
calls = []
def verify(req, **kwargs):
calls.append(req)
return (VerifyResult('PASS', library_flag='GREEN') if len(calls) == 1 else
VerifyResult('FAIL', stderr='共享符号库不可用', safe_to_continue=False))
result = recover_from_backup(request, source, verifier=verify, idle_check=lambda *_: None)
assert result.status == 'FAIL'
assert not result.safe_to_continue
assert '共享符号库不可用' in result.stderr
assert list(original.parent.parent.glob('Work.before-restore-*'))
def test_source_verify_must_confirm_green_and_release(recovery_files):
from cbb_refresh_verify.backup_recovery import recover_from_backup
request, original, source = recovery_files
result = recover_from_backup(request, source, verifier=lambda *a, **k:
VerifyResult('PASS', library_flag='UNKNOWN'), idle_check=lambda *_: None)
assert result.status != 'PASS'
assert (original.parent/'database/icdb.dat').read_bytes() == b'damaged'
def test_external_changes_during_validation_stop_install(recovery_files):
from cbb_refresh_verify.backup_recovery import recover_from_backup
request, original, source = recovery_files
def verify(*args, **kwargs):
(original.parent/'database/icdb.dat').write_bytes(b'another-user')
return VerifyResult('PASS', library_flag='GREEN')
result = recover_from_backup(request, source, verifier=verify, idle_check=lambda *_: None)
assert result.status != 'PASS'
assert '变化' in result.stderr
assert (original.parent/'database/icdb.dat').read_bytes() == b'another-user'
@pytest.mark.parametrize('field', ['ProjectFile', 'iCDBDir'])
def test_absolute_source_references_are_rejected_before_native_open(recovery_files, field):
from cbb_refresh_verify.backup_recovery import recover_from_backup
request, original, source = recovery_files
if field == 'ProjectFile':
path = source.parent/'PCB/A.pcb'
path.write_text(f'SECTION Integration\nKEY ProjectFile "{source}"\nENDSECTION\n')
else:
source.write_text(source.read_text().replace('".\\database"', f'"{source.parent / "database"}"'))
result = recover_from_backup(request, source, verifier=lambda *a, **k:
pytest.fail('must not launch native against source'), idle_check=lambda *_: None)
assert result.status == 'BLOCKED'
assert '相对' in result.stderr
assert (original.parent/'database/icdb.dat').read_bytes() == b'damaged'
def test_idle_guard_queries_supported_native_process_names(recovery_files, monkeypatch):
import win32com.client
from cbb_refresh_verify.backup_recovery import _idle_check
request, original, source = recovery_files
queries = []
class EmptyProcesses:
def ExecQuery(self, query):
queries.append(query)
return []
monkeypatch.setattr(win32com.client, 'GetObject', lambda _: EmptyProcesses())
_idle_check(request.lmc_file, original, original.parent/'PCB/A.pcb')
assert any("Name='viewdraw.exe'" in query for query in queries)
def test_copy_refuses_directory_junction_before_copying(tmp_path):
import subprocess
from cbb_refresh_verify.backup_recovery import _copy_verified
source = tmp_path/'source'; source.mkdir()
outside = tmp_path/'outside'; outside.mkdir()
(outside/'sentinel').write_bytes(b'do not copy or modify')
linked = source/'linked'
result = subprocess.run(['cmd', '/c', 'mklink', '/J', str(linked), str(outside)], capture_output=True)
assert result.returncode == 0
with pytest.raises(ValueError, match='链接'):
_copy_verified(source, tmp_path/'destination')
assert not (tmp_path/'destination').exists()
assert (outside/'sentinel').read_bytes() == b'do not copy or modify'
def test_target_native_verification_keeps_selected_library_alias(recovery_files):
import subprocess
from dataclasses import replace
from cbb_refresh_verify.backup_recovery import recover_from_backup
request, original, source = recovery_files
alias = request.lmc_file.parent.with_name('selected-library')
made = subprocess.run(['cmd', '/c', 'mklink', '/J', str(alias), str(request.lmc_file.parent)], capture_output=True)
assert made.returncode == 0
selected = alias/request.lmc_file.name
calls = []
def verify(req, **kwargs):
calls.append(req.lmc_file)
return VerifyResult('PASS', library_flag='GREEN')
result = recover_from_backup(replace(request, lmc_file=selected), source,
verifier=verify, idle_check=lambda *_: None)
assert result.status == 'PASS'
assert calls[-1] == selected
def test_equivalent_library_reference_preserves_native_project_bytes_and_date(recovery_files):
from cbb_refresh_verify.backup_recovery import _align_library
request, original, source = recovery_files
original.write_text(original.read_text().replace('old.lmc', '../../../target.lmc'))
before = original.read_bytes(), original.stat().st_mtime_ns
_align_library(original, original.parent/'PCB/A.pcb', request.lmc_file)
assert (original.read_bytes(), original.stat().st_mtime_ns) == before
def test_logs_and_unrelated_cbb_changes_after_snapshot_do_not_block_install(recovery_files):
from cbb_refresh_verify.backup_recovery import recover_from_backup
request, original, source = recovery_files
(source.parent/'session.log').write_bytes(b'snapshot log')
other = project(request.lmc_file.parent/'ReusableBlocksLP/B/Work', 'B', b'unrelated')
calls = []
def verify(req, **kwargs):
calls.append(req)
if len(calls) == 1:
(source.parent/'session.log').write_bytes(b'updated source log')
(original.parent/'new.log').write_bytes(b'new target log')
(other.parent/'database/icdb.dat').write_bytes(b'unrelated update')
return VerifyResult('PASS', library_flag='GREEN')
result = recover_from_backup(request, source, verifier=verify, idle_check=lambda *_: None)
assert result.status == 'PASS'
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'
@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):
from cbb_refresh_verify.backup_recovery import recover_from_backup
request, original, source = recovery_files
if location == 'source':
conflict = source.parent/'database/icdb.dat'
elif location == 'target':
conflict = original.parent/'PCB/Layout/LayoutDB.lyt'
elif location == 'cert':
conflict = original.parent.parent/'Cert/A.prj'
else:
conflict = request.lmc_file.parent/'SymbolLibs/__ReusableBlocksSymb/icdb.dat'
conflict.parent.mkdir(parents=True, exist_ok=True)
if location in ('cert', 'shared'):
conflict.write_bytes(b'before')
calls = []
def verify(*args, **kwargs):
calls.append(args)
if change == 'delete':
conflict.unlink()
elif change == 'add':
(conflict.parent/'new-engineering.bin').write_bytes(b'new')
else:
conflict.write_bytes(b'concurrent edit')
return VerifyResult('PASS', library_flag='GREEN')
result = recover_from_backup(request, source, verifier=verify, idle_check=lambda *_: None)
assert result.status == 'BLOCKED'
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'))
def test_source_conflict_while_preparing_incoming_work_blocks_install(recovery_files, monkeypatch):
from cbb_refresh_verify import backup_recovery as recovery
request, original, source = recovery_files
copy = recovery._copy_verified
def copy_then_change_source(src, dst, **kwargs):
result = copy(src, dst, **kwargs)
if dst.name.startswith('Work.restore-'):
(source.parent/'database/icdb.dat').write_bytes(b'late concurrent change')
return result
monkeypatch.setattr(recovery, '_copy_verified', copy_then_change_source)
result = recovery.recover_from_backup(request, source,
verifier=lambda *a, **k: VerifyResult('PASS', library_flag='GREEN'), idle_check=lambda *_: None)
assert result.status == 'BLOCKED'
assert (original.parent/'database/icdb.dat').read_bytes() == b'damaged'
def test_source_address_record_is_rechecked_after_validation(recovery_files):
from cbb_refresh_verify.backup_recovery import recover_from_backup
request, original, source = recovery_files
address = source.parent/'database/cdbsvr/sAddress.adr'
def idle(library, project, pcb):
if project == source and address.exists():
raise ValueError('Source database ownership is still active')
def verify(*args, **kwargs):
address.parent.mkdir(parents=True, exist_ok=True)
address.write_bytes(b'live owner')
return VerifyResult('PASS', library_flag='GREEN')
result = recover_from_backup(request, source, verifier=verify, idle_check=idle)
assert result.status == 'BLOCKED'
assert 'ownership' in result.stderr
assert address.read_bytes() == b'live owner'
assert (original.parent/'database/icdb.dat').read_bytes() == b'damaged'
@pytest.mark.parametrize('name', ['Logs', 'tEmP', 'bAcKuP', 'Output'])
@pytest.mark.parametrize('role', ['Work', 'Cert'])
def test_cbb_names_matching_runtime_labels_do_not_hide_target_conflicts(tmp_path, monkeypatch, name, role):
from cbb_refresh_verify.backup_recovery import recover_from_backup
monkeypatch.setattr(Path, 'home', lambda: tmp_path/'profile')
library = tmp_path/'target/target.lmc'
original = project(library.parent/f'ReusableBlocksLP/{name}/Work', name, b'damaged')
library.write_bytes(b'library')
source = project(tmp_path/'backup/Work', name, b'healthy')
request = VerifyRequest(library, name, tmp_path/'evidence')
conflict = original.parent.parent/role/'database/icdb.dat'
conflict.parent.mkdir(parents=True, exist_ok=True)
if role == 'Cert':
conflict.write_bytes(b'cert before')
calls = []
def verify(*args, **kwargs):
calls.append(args)
conflict.write_bytes(b'concurrent target edit')
return VerifyResult('PASS', library_flag='GREEN')
result = recover_from_backup(request, source, verifier=verify, idle_check=lambda *_: None)
assert result.status == 'BLOCKED'
assert len(calls) == 1
assert conflict.read_bytes() == b'concurrent target edit'
assert not list(original.parent.parent.glob('Work.before-restore-*'))
@pytest.mark.parametrize('relative', ['SymbolLibs/temp/icdb.dat', 'SymbolLibs/Temp_a/device.sym',
'SharedDependency/hdl/Logs/design.v'])
def test_shared_partition_engineering_conflicts_block_install(recovery_files, relative):
from cbb_refresh_verify.backup_recovery import recover_from_backup
request, original, source = recovery_files
conflict = request.lmc_file.parent/relative
conflict.parent.mkdir(parents=True, exist_ok=True)
conflict.write_bytes(b'shared before')
calls = []
def verify(*args, **kwargs):
calls.append(args)
conflict.write_bytes(b'concurrent shared edit')
return VerifyResult('PASS', library_flag='GREEN')
result = recover_from_backup(request, source, verifier=verify, idle_check=lambda *_: None)
assert result.status == 'BLOCKED'
assert len(calls) == 1
assert (original.parent/'database/icdb.dat').read_bytes() == b'damaged'
assert conflict.read_bytes() == b'concurrent shared edit'
+91
View File
@@ -0,0 +1,91 @@
from pathlib import Path
from threading import Event
from cbb_refresh_verify.verify_runner import VerifyRequest, VerifyResult
def test_backup_dialog_requires_a_project_and_passes_selected_target(qtbot, tmp_path):
from cbb_refresh_verify.ui.backup_recovery_dialog import BackupRecoveryDialog
calls = []
def recover(request, source, **kwargs):
calls.append((request.block_name, source))
return VerifyResult('PASS', stdout='restored')
dialog = BackupRecoveryDialog(('A', 'B'),
lambda name: VerifyRequest(tmp_path/'target.lmc', name, tmp_path/'evidence'),
recoverer=recover)
qtbot.addWidget(dialog)
dialog.restore_button.click()
assert not calls
assert '备份' in dialog.status_label.text()
source = tmp_path/'B.prj'; source.touch()
dialog.block_combo.setCurrentText('B')
dialog.source_edit.setText(str(source))
dialog.restore_button.click()
qtbot.waitUntil(lambda: not dialog.busy)
assert calls == [('B', source)]
assert '通过' in dialog.status_label.text()
def test_backup_dialog_keeps_ui_responsive_and_cannot_close_during_restore(qtbot, tmp_path):
from cbb_refresh_verify.ui.backup_recovery_dialog import BackupRecoveryDialog
entered, release = Event(), Event()
def recover(*args, **kwargs):
entered.set(); release.wait(3)
return VerifyResult('FAIL', stderr='共享符号库不可用', safe_to_continue=False)
dialog = BackupRecoveryDialog(('A',),
lambda name: VerifyRequest(tmp_path/'target.lmc', name, tmp_path/'evidence'),
recoverer=recover)
qtbot.addWidget(dialog)
source = tmp_path/'A.prj'; source.touch()
dialog.source_edit.setText(str(source)); dialog.show()
dialog.restore_button.click()
try:
qtbot.waitUntil(entered.is_set)
assert not dialog.close_button.isEnabled()
dialog.reject()
assert dialog.isVisible()
finally:
release.set()
qtbot.waitUntil(lambda: not dialog.busy)
assert '共享符号库不可用' in dialog.status_label.text()
assert dialog.close_button.isEnabled()
def test_main_window_opens_non_ready_dialog_and_failure_retains_ready_untargeted(qtbot, tmp_path):
from cbb_refresh_verify.ui.main_window import MainWindow
from cbb_refresh_verify.library_reader import CbbRecord, LibraryReadResult
window = MainWindow(reader=lambda _: LibraryReadResult((
CbbRecord('A', 'LP', status='READY'), CbbRecord('B', 'LP'))), data_root=tmp_path,
status_refresher=lambda names, _: {name: 'UNKNOWN' for name in names})
qtbot.addWidget(window)
window.lmc_edit.setText('lib.lmc'); window.load_library()
qtbot.waitUntil(lambda: not window.busy)
window.cbb_table.selectRow(0)
window.backup_restore_button.click()
dialog = window.backup_dialog
assert dialog.isVisible()
assert dialog.block_combo.currentText() == 'B'
dialog.started.emit('B')
assert window.busy
assert 'A' in window.ready_names
dialog.completed.emit('B', VerifyResult('FAIL', stderr='无法确认', safe_to_continue=False))
assert window.cbb_table.item(1, 2).text() == '未知 / 需确认'
dialog.reject()
qtbot.waitUntil(lambda: not window.busy)
def test_unhandled_worker_error_notifies_main_window_of_unsafe_result(qtbot, tmp_path):
from cbb_refresh_verify.ui.backup_recovery_dialog import BackupRecoveryDialog
def recover(*args, **kwargs):
raise OSError('磁盘写入失败')
dialog = BackupRecoveryDialog(('A',),
lambda name: VerifyRequest(tmp_path/'target.lmc', name, tmp_path/'evidence'), recoverer=recover)
qtbot.addWidget(dialog)
completed = []
dialog.completed.connect(lambda name, result: completed.append((name, result)))
source = tmp_path/'A.prj'; source.touch()
dialog.source_edit.setText(str(source)); dialog.restore_button.click()
qtbot.waitUntil(lambda: not dialog.busy)
assert len(completed) == 1
assert completed[0][0] == 'A'
assert not completed[0][1].safe_to_continue
+255
View File
@@ -0,0 +1,255 @@
import json
from pathlib import Path
import pytest
from cbb_refresh_verify import failed_session, mentor_adapter
def startup_fixture(tmp_path, monkeypatch):
import win32gui, win32process
from cbb_refresh_verify import native_repair_ui
job = {'root': str(tmp_path), 'pcb': str(tmp_path/'PCB/CBB.pcb'),
'project': str(tmp_path/'CBB.prj'), 'lmc_file': str(tmp_path/'lib.lmc'),
'desktop': 'CbbVerify_test'}
diagnostics = tmp_path/'diagnostics'
diagnostics.mkdir()
(diagnostics/'icdb-recovery.json').write_text(json.dumps({
'error_code': 'ICDB_REPAIR_REQUIRED', 'scope': 'project',
'database_path': str(tmp_path/'database'), 'session': 'lost-session'}))
records = [(12, r'C:\Mentor\wg\ExpeditionPCB.exe',
f'ExpeditionPCB.exe "{job["pcb"]}" -ReusableCircuit', 11)]
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: list(records))
monkeypatch.setattr(native_repair_ui, '_current_desktop_name', lambda: 'CbbVerify_test')
monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg: fn(100, arg))
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda *args: None)
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda _: (1, 12))
monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda _: True)
monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda _: True)
monkeypatch.setattr(win32gui, 'GetWindowText', lambda _: 'Expedition PCB')
monkeypatch.setattr(win32gui, 'GetClassName', lambda _: 'Afx:main')
messages = []
def post(hwnd, message, wparam, lparam):
messages.append((hwnd, message))
records.clear()
monkeypatch.setattr(win32gui, 'PostMessage', post)
return job, records, messages
@pytest.mark.parametrize('title', ['Expedition PCB', 'Expedition PCB - Reusable Block'])
def test_failed_startup_normally_closes_owned_empty_pcb(tmp_path, monkeypatch, title):
import win32con
import win32gui
job, records, messages = startup_fixture(tmp_path, monkeypatch)
monkeypatch.setattr(win32gui, 'GetWindowText', lambda _: title)
result = failed_session.close_failed_startup(job, 12, baseline_pids=(), timeout_seconds=0)
assert result['status'] == 'CLOSED'
assert not records
assert messages == [(100, win32con.WM_CLOSE)]
assert json.loads((tmp_path/'startup-close.json').read_text())['status'] == 'CLOSED'
@pytest.mark.parametrize('obstacle', ['baseline', 'wrong_path', 'path_prefix', 'desktop', 'address',
'dialog', 'document_title', 'mdi_document', 'disabled', 'no_diagnosis'])
def test_failed_startup_preserves_unconfirmed_or_busy_session(tmp_path, monkeypatch, obstacle):
import win32gui
from cbb_refresh_verify import native_repair_ui
job, records, messages = startup_fixture(tmp_path, monkeypatch)
baseline = ()
if obstacle == 'baseline': baseline = (12,)
if obstacle == 'wrong_path': records[0] = (12, records[0][1], 'other.pcb -ReusableCircuit', 11)
if obstacle == 'path_prefix':
records[0] = (12, records[0][1], f'pcb.exe "{job["pcb"]}.other" -ReusableCircuit', 11)
if obstacle == 'desktop': monkeypatch.setattr(native_repair_ui, '_current_desktop_name', lambda: 'Default')
if obstacle == 'address':
address = tmp_path/'database/cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True)
address.write_text('owner')
if obstacle == 'dialog': monkeypatch.setattr(win32gui, 'GetClassName', lambda _: '#32770')
if obstacle == 'document_title': monkeypatch.setattr(win32gui, 'GetWindowText', lambda _: 'CBB.pcb - Expedition PCB')
if obstacle == 'mdi_document':
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda hwnd, fn, arg: fn(101, arg))
monkeypatch.setattr(win32gui, 'GetClassName', lambda hwnd: 'MDIClient' if hwnd == 101 else 'Afx:main')
monkeypatch.setattr(win32gui, 'GetWindow', lambda *args: 102)
if obstacle == 'disabled': monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda _: False)
if obstacle == 'no_diagnosis': (tmp_path/'diagnostics/icdb-recovery.json').unlink()
result = failed_session.close_failed_startup(job, 12, baseline_pids=baseline, timeout_seconds=0)
assert result['status'] == 'RETAINED'
assert records
assert not messages
def test_requested_close_without_exit_is_not_reported_closed(tmp_path, monkeypatch):
import win32gui
job, records, messages = startup_fixture(tmp_path, monkeypatch)
monkeypatch.setattr(win32gui, 'PostMessage', lambda hwnd, message, *_: messages.append((hwnd, message)))
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
assert result['status'] == 'RETAINED'
assert 'STARTUP_EXIT_UNCONFIRMED' in result['detail']
assert len(messages) == 1
assert records
@pytest.mark.parametrize('obstacle', ['address', 'dialog', 'process'])
def test_startup_close_waits_for_native_state_transitions(tmp_path, monkeypatch, obstacle):
from types import SimpleNamespace
import win32gui
job, records, messages = startup_fixture(tmp_path, monkeypatch)
ticks = [0]
address = tmp_path/'database/cdbsvr/sAddress.adr'
if obstacle == 'address':
address.parent.mkdir(parents=True)
address.write_text('owner')
if obstacle == 'dialog':
monkeypatch.setattr(win32gui, 'GetClassName',
lambda _: '#32770' if ticks[0] == 0 else 'Afx:main')
if obstacle == 'process':
monkeypatch.setattr(win32gui, 'PostMessage',
lambda hwnd, message, *_: messages.append((hwnd, message)))
def advance(seconds):
ticks[0] += seconds
if obstacle == 'address' and address.exists(): address.unlink()
if obstacle == 'process' and messages: records.clear()
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
assert result['status'] == 'CLOSED'
assert len(messages) == 1
assert not records
def test_worker_closes_startup_failure_before_document_identity(tmp_path, monkeypatch):
from test_verify_worker_stability import exercise_worker
job, events, execute = exercise_worker(tmp_path, monkeypatch)
job['desktop'] = 'CbbVerify_test'
def fail_open(*args, **kwargs):
raise RuntimeError('VERIFY_CANCELLED: database open failed')
monkeypatch.setattr('cbb_refresh_verify.pcb_bridge.wait_for_target_document', fail_open)
# Native process/window behavior is covered above; here verify the worker
# actually reaches startup cleanup instead of requiring a loaded document.
def close(job, pid, **kwargs):
kwargs['emit'](stage='startup_close_result', status='CLOSED', pcb_pid=pid)
return {'status': 'CLOSED'}
monkeypatch.setattr(failed_session, 'close_failed_startup', close, raising=False)
with pytest.raises(RuntimeError, match='VERIFY_CANCELLED'):
execute()
assert any(e['stage'] == 'startup_close_result' and e['pcb_pid'] == 2 for e in events)
assert not any(e['stage'] == 'save_start' for e in events)
def test_failed_startup_accepts_current_owned_database_failure_dialog(tmp_path, monkeypatch):
job, records, messages = startup_fixture(tmp_path, monkeypatch)
(tmp_path/'diagnostics/icdb-recovery.json').unlink()
(tmp_path/'dialogs.jsonl').write_text(json.dumps({
'pid': 12, 'phase': 'PCB_STARTING', 'error_code': 'MENTOR_DATABASE_LOAD_FAILED'})+'\n')
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
assert result['status'] == 'CLOSED'
assert not records
@pytest.mark.parametrize('pid,phase', [(99, 'PCB_STARTING'), (12, 'SAVING')])
def test_failed_startup_rejects_unrelated_failure_dialog(tmp_path, monkeypatch, pid, phase):
job, records, messages = startup_fixture(tmp_path, monkeypatch)
(tmp_path/'diagnostics/icdb-recovery.json').unlink()
(tmp_path/'dialogs.jsonl').write_text(json.dumps({
'pid': pid, 'phase': phase, 'error_code': 'MENTOR_DATABASE_LOAD_FAILED'})+'\n')
assert failed_session.close_failed_startup(job, 12, timeout_seconds=0)['status'] == 'RETAINED'
assert not messages
@pytest.mark.parametrize('exits', [True, False])
def test_startup_close_waits_for_launcher_after_empty_pcb_exit(tmp_path, monkeypatch, exits):
from types import SimpleNamespace
job, records, messages = startup_fixture(tmp_path, monkeypatch)
ticks = [0.0]
launcher = SimpleNamespace(pid=11, poll=lambda: 0 if exits and ticks[0] >= .4 else None)
monkeypatch.setattr(failed_session, 'time', SimpleNamespace(
monotonic=lambda: ticks[0], sleep=lambda seconds: ticks.__setitem__(0, ticks[0]+seconds)))
result = failed_session.close_failed_startup(job, 12, launcher_process=launcher, timeout_seconds=1)
assert ticks[0] >= .4
assert result['status'] == ('CLOSED' if exits else 'RETAINED')
assert result['release']['launcher_exited'] is exits
assert result['release']['pcb_exited'] is True
assert len(messages) == 1
def test_startup_exit_does_not_hide_late_database_address(tmp_path, monkeypatch):
import win32gui
job, records, messages = startup_fixture(tmp_path, monkeypatch)
def close(*args):
records.clear()
address = tmp_path/'database/cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True)
address.write_text('still owned')
monkeypatch.setattr(win32gui, 'PostMessage', close)
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
assert result['status'] == 'RETAINED'
assert result['release']['addresses']
@pytest.mark.parametrize('window_class,title', [('CustomPrompt', 'Database action pending'),
('Afx:tool', ''), ('UAC_InputIndicatorOverlayWnd', 'Unknown prompt'), ('UAC Input Indicator', ' ')])
def test_enabled_empty_main_with_unaccounted_owned_window_is_never_closed(tmp_path, monkeypatch, window_class, title):
import win32gui
job, records, messages = startup_fixture(tmp_path, monkeypatch)
monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg: [fn(hwnd, arg) for hwnd in (100, 200)])
monkeypatch.setattr(win32gui, 'GetClassName', lambda hwnd: 'Afx:main' if hwnd == 100 else window_class)
monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: 'Expedition PCB' if hwnd == 100 else title)
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
assert result['status'] == 'RETAINED' and not result['release']['safe_to_continue']
assert messages == [] and records
assert result['unknown_windows'] == [{'hwnd': 200, 'class': window_class, 'title': title, 'enabled': True}]
assert json.loads((tmp_path/'startup-close.json').read_text(encoding='utf-8'))['unknown_windows'] == result['unknown_windows']
def test_empty_title_known_uac_windows_are_accounted_for_before_normal_close(tmp_path, monkeypatch):
import win32gui, win32con
job, records, messages = startup_fixture(tmp_path, monkeypatch)
classes = {100: 'Afx:main', 200: 'UAC_InputIndicatorOverlayWnd', 201: 'UAC Input Indicator'}
monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg: [fn(hwnd, arg) for hwnd in classes])
monkeypatch.setattr(win32gui, 'GetClassName', classes.__getitem__)
monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: 'Expedition PCB' if hwnd == 100 else '')
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
assert result['status'] == 'CLOSED' and messages == [(100, win32con.WM_CLOSE)]
assert result['unknown_windows'] == []
assert [entry['hwnd'] for entry in result['benign_auxiliary_windows']] == [200, 201]
def test_custom_prompt_must_disappear_before_main_close(tmp_path, monkeypatch):
from types import SimpleNamespace
import win32gui
job, records, messages = startup_fixture(tmp_path, monkeypatch)
ticks = [0.0]
monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg:
[fn(hwnd, arg) for hwnd in ((100, 200) if ticks[0] == 0 else (100,))])
monkeypatch.setattr(win32gui, 'GetClassName', lambda hwnd: 'Afx:main' if hwnd == 100 else 'CustomPrompt')
monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: 'Expedition PCB' if hwnd == 100 else 'Still processing')
monkeypatch.setattr(failed_session, 'time', SimpleNamespace(monotonic=lambda: ticks[0],
sleep=lambda seconds: ticks.__setitem__(0, ticks[0] + seconds)))
result = failed_session.close_failed_startup(job, 12, timeout_seconds=1)
assert result['status'] == 'CLOSED' and ticks[0] > 0
assert len(messages) == 1
@pytest.mark.parametrize('obstacle', ['', 'title', 'area', 'children', 'near_class'])
def test_only_exact_empty_zero_area_childless_ie_infrastructure_is_benign(tmp_path, monkeypatch, obstacle):
import win32gui, win32con
job, records, messages = startup_fixture(tmp_path, monkeypatch)
monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg: [fn(hwnd, arg) for hwnd in (100, 200)])
monkeypatch.setattr(win32gui, 'GetClassName', lambda hwnd: 'Afx:main' if hwnd == 100 else
'Internet Explorer_Hidden_other' if obstacle == 'near_class' else 'Internet Explorer_Hidden')
monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: 'Expedition PCB' if hwnd == 100 else
'Active prompt' if obstacle == 'title' else '')
monkeypatch.setattr(win32gui, 'GetWindowRect', lambda hwnd: (0, 0, 100, 50) if obstacle == 'area' else (0, 0, 0, 0))
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda hwnd, fn, arg:
fn(201, arg) if hwnd == 200 and obstacle == 'children' else None)
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
if obstacle:
assert result['status'] == 'RETAINED' and messages == []
assert result['unknown_windows'][0]['hwnd'] == 200
else:
assert result['status'] == 'CLOSED' and messages == [(100, win32con.WM_CLOSE)]
entry = result['benign_auxiliary_windows'][0]
assert entry['class'] == 'Internet Explorer_Hidden' and entry['rect'] == [0, 0, 0, 0]
assert entry['children'] == []
+306
View File
@@ -0,0 +1,306 @@
import json
import os
from pathlib import Path
import subprocess
import sys
import time
import pytest
from cbb_refresh_verify import verify_runner as runner
def test_content_timeout_preserves_importer_and_native_like_child(tmp_path):
import win32api, win32con, win32process
script = tmp_path/'importer.py'
pids = tmp_path/'pids.json'
script.write_text(
'import subprocess,sys,time,os,json\nfrom pathlib import Path\n'
'child=subprocess.Popen([sys.executable,"-c","import time;time.sleep(30)"],'
'stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)\n'
f'Path({str(pids)!r}).write_text(json.dumps([os.getpid(),child.pid]))\n'
'time.sleep(30)\n', encoding='utf-8')
handles = []
try:
result = runner._run_process([sys.executable, str(script)], 2, tmp_path)
assert result[3] is True
assert pids.is_file()
for pid in json.loads(pids.read_text()):
try:
handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION |
win32con.PROCESS_TERMINATE, False, pid)
except Exception:
pytest.fail(f'Timeout terminated database-related process {pid}')
handles.append(handle)
assert win32process.GetExitCodeProcess(handle) == 259
finally:
for handle in handles:
win32process.TerminateProcess(handle, 0)
handle.Close()
def test_content_timeout_stops_remaining_batch(tmp_path, monkeypatch):
from test_verify_runner import fixture, request
fixture(tmp_path)
monkeypatch.setattr(runner, 'resolve_importer', lambda *_: Path('ReuseBlockImporter.exe'))
calls = []
def timeout(*args):
calls.append(args)
return None, '', 'content check still running', True
req = request(tmp_path, libspec='EE', dms_login_config='login')
results = runner.run_batch([req, req], verifier=lambda item: runner.run_verify(item,
process_runner=timeout, port_check=lambda: pytest.fail('PCB must not start')))
assert len(calls) == 1
assert results[0].status == 'TIMEOUT'
assert results[0].safe_to_continue is False
assert results[1].status == 'SKIPPED'
@pytest.mark.parametrize('identity,close_ok,other_document,expected_code', [
(True, True, False, 0), (False, True, False, 2), (True, False, False, 4), (True, True, True, 5)])
def test_failed_document_close_uses_native_discard_and_rejects_wrong_identity(
tmp_path, identity, close_ok, other_document, expected_code):
source = Path('src/cbb_refresh_verify/close_failed_block.vbs').read_text('utf-8')
classes = r'''
Dim nativeClosed
nativeClosed = False
Class FakePi
Public ProjectFile
Private Sub Class_Initialize
ProjectFile = PROJECT_VALUE
End Sub
End Class
Class FakeDoc
Public Name
Private Sub Class_Initialize
Name = "CBB.pcb"
End Sub
Public Property Get ProjectIntegration
Set ProjectIntegration = New FakePi
End Property
Public Function Validate(value)
Validate = 17
End Function
Public Function Close(saveChanges)
If saveChanges Then WScript.Quit 90
WScript.Echo "NATIVE_DISCARD_CLOSE"
nativeClosed = CLOSE_RETURN
Close = CLOSE_RETURN
End Function
End Class
Class FakeApp
Public Property Get ActiveDocument
If nativeClosed And Not OTHER_DOCUMENT Then
Set ActiveDocument = Nothing
Else
Set ActiveDocument = New FakeDoc
End If
End Property
Public Sub Quit()
WScript.Echo "NATIVE_QUIT"
End Sub
End Class
Class FakeLic
Public Function GetToken(value)
GetToken = value
End Function
End Class
'''.replace('PROJECT_VALUE', 'WScript.Arguments(0)' if identity else '"OTHER.prj"')
classes = classes.replace('CLOSE_RETURN', str(close_ok))
classes = classes.replace('OTHER_DOCUMENT', str(other_document))
source = source.replace('Option Explicit', 'Option Explicit\n'+classes)
source = source.replace('GetObject(, "MGCPCB.Application")', 'New FakeApp')
source = source.replace('CreateObject("MGCPCBAutomationLicensing.Application")', 'New FakeLic')
harness = tmp_path/'close.vbs'
harness.write_text(source, encoding='ascii')
outcome = subprocess.run([str(Path(os.environ['WINDIR'])/'SysWOW64/cscript.exe'),
'//nologo', str(harness), 'expected.prj', 'CBB.pcb'], capture_output=True, text=True, timeout=10)
assert outcome.returncode == expected_code, outcome.stderr
assert ('NATIVE_DISCARD_CLOSE' in outcome.stdout) is identity
assert ('NATIVE_QUIT' in outcome.stdout) is (identity and close_ok and not other_document)
def test_cancel_after_native_save_returns_stops_later_native_operations(tmp_path):
source = Path('src/cbb_refresh_verify/save_verified_block.vbs').read_text('utf-8')
classes = r'''
Class FakePi
Public ProjectFile, ForwardAnnotationStatus, SynchCESStatus, LoadCESStatus, BackAnnotationStatus
Private Sub Class_Initialize
ProjectFile = WScript.Arguments(0)
ForwardAnnotationStatus = 2
SynchCESStatus = 2
LoadCESStatus = 2
BackAnnotationStatus = 2
End Sub
End Class
Class FakeDoc
Public Name
Private Sub Class_Initialize
Name = "CBB.pcb"
End Sub
Public Property Get ProjectIntegration
Set ProjectIntegration = New FakePi
End Property
Public Function Validate(token)
Validate = 17
End Function
Public Function Save()
Dim fso, flag
Set fso = CreateObject("Scripting.FileSystemObject")
Set flag = fso.CreateTextFile(WScript.Arguments(2), True)
flag.Close
WScript.Sleep 120
WScript.Echo "NATIVE_SAVE_RETURNED"
Save = True
End Function
Public Function IsSaved()
IsSaved = True
End Function
Public Function Close(saveChanges)
Close = True
End Function
End Class
Class FakeApp
Public Property Get ActiveDocument
Set ActiveDocument = New FakeDoc
End Property
Public Sub Quit()
End Sub
End Class
Class FakeLic
Public Function GetToken(value)
GetToken = value
End Function
End Class
'''
source = source.replace('Option Explicit', 'Option Explicit\n'+classes)
source = source.replace('GetObject(, "MGCPCB.Application")', 'New FakeApp')
source = source.replace('CreateObject("MGCPCBAutomationLicensing.Application")', 'New FakeLic')
harness = tmp_path/'save-cancel.vbs'
harness.write_text(source, encoding='ascii')
outcome = subprocess.run([str(Path(os.environ['WINDIR'])/'SysWOW64/cscript.exe'),
'//nologo', str(harness), 'expected.prj', 'CBB.pcb', str(tmp_path/'cancel.signal')],
capture_output=True, text=True, timeout=10)
assert 'NATIVE_SAVE_RETURNED' in outcome.stdout
assert outcome.returncode == 9, outcome.stderr
assert 'VERIFY_CANCELLED' in outcome.stdout
assert 'CLOSE_OK' not in outcome.stdout
def test_worker_attempts_normal_close_after_idle_integration_failure(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, integration_error='packaging rejected')
closes = []
monkeypatch.setattr('cbb_refresh_verify.failed_session.close_failed_document',
lambda value, **kwargs: closes.append(value) or {'status': 'CLOSED'})
with pytest.raises(RuntimeError, match='packaging rejected'):
execute()
assert closes == [job]
assert not any(event['stage'] == 'save_start' for event in events)
def test_stop_requests_cooperative_cancel_without_terminating_busy_client(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']
def test_status_server_close_allows_eof_cleanup_before_termination(tmp_path):
from cbb_refresh_verify.status_bridge import StatusBridgeServer
script = tmp_path/'reader.py'
marker = tmp_path/'released.txt'
script.write_text('import sys,time\nfrom pathlib import Path\n'
'for line in sys.stdin: pass\n'
'time.sleep(.1)\n'
f'Path({str(marker)!r}).write_text("native handles released")\n', encoding='utf-8')
server = StatusBridgeServer(script)
server.start()
time.sleep(.2)
server.close()
assert marker.is_file()
def test_shared_symbol_database_owner_blocks_content_check_and_pcb(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
assert address.read_bytes() == b'unknown native owner'
def test_shared_symbol_database_must_be_released_before_pass(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)
original = adapter.subprocess.Popen
def helper(*args, **kwargs):
address = Path(job['lmc_file']).parent/'SymbolLibs/__ReusableBlocksSymb/cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True)
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)
def test_cooperative_supervisor_loss_keeps_pending_save_helper_alive(tmp_path):
import win32api, win32con, win32process
supervisor = subprocess.Popen([sys.executable, '-c', 'import time;time.sleep(30)'])
script, ready, cancel = tmp_path/'worker.py', tmp_path/'ready.json', tmp_path/'cancel.signal'
script.write_text('import subprocess,sys,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})\n'
'helper=launch_save_helper([sys.executable,"-c","import time;time.sleep(30)"])\n'
f'Path({str(ready)!r}).write_text(json.dumps(helper.pid))\n'
'time.sleep(30)\n', encoding='utf-8')
worker = subprocess.Popen([sys.executable, str(script)])
handle = None
try:
deadline = time.monotonic()+5
while not ready.exists() and time.monotonic()<deadline:
time.sleep(.05)
assert ready.exists()
handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_TERMINATE,
False, json.loads(ready.read_text()))
supervisor.terminate()
supervisor.wait(3)
deadline = time.monotonic()+3
while not cancel.exists() and time.monotonic()<deadline:
time.sleep(.05)
assert cancel.exists()
assert worker.poll() is None
assert win32process.GetExitCodeProcess(handle) == 259
finally:
for process in (worker, supervisor):
if process.poll() is None: process.terminate()
process.wait(3)
if handle:
win32process.TerminateProcess(handle, 0)
handle.Close()
def test_idle_failed_native_verify_closes_its_library_manager_owner(tmp_path, monkeypatch):
from types import SimpleNamespace
from test_verify_worker_stability import exercise_worker
job, events, execute = exercise_worker(tmp_path, monkeypatch, integration_error='packaging rejected')
job['native_lm_verify'] = True
closed = []
monkeypatch.setattr('cbb_refresh_verify.library_manager_verify.launch_library_verify',
lambda *a, **kw: SimpleNamespace(process=SimpleNamespace(pid=11), close=lambda: closed.append(11)))
monkeypatch.setattr('cbb_refresh_verify.failed_session.close_failed_document',
lambda *a, **kw: {'status':'CLOSED'})
with pytest.raises(RuntimeError, match='packaging rejected'):
execute()
assert closed == [11]
+310
View File
@@ -0,0 +1,310 @@
import json
from pathlib import Path
import pytest
from cbb_refresh_verify import mentor_adapter as adapter
from cbb_refresh_verify import verify_runner as runner
ERROR = (
"The last server session on different server machine lost the connection\n"
"to the database. Please use iCDB Project Backup 'Repair project' functionality "
"to fix this issue. (Machine:[200091-CBB] Path:"
"[S:\\SymbolLibs\\__ReusableBlocksSymb] session:[2026-10-24 08.22.29-10308])"
)
def test_native_session_loss_has_priority_over_generic_load_and_cleanup_errors():
detail = 'DATABASE_LOAD_FAILED: Could not load Job Preferences DB\n' + ERROR
detail += '\nPCB_RELEASE_UNCONFIRMED'
assert runner.classify_failure_category(detail) == 'ICDB_REPAIR_REQUIRED'
def test_live_repair_dialog_blocks_without_clicking():
from test_dialog_rules import prompt, ASSETS
from cbb_refresh_verify.dialog_rules import decide, load_rules
from cbb_refresh_verify.dialog_supervisor import classify_dialog, DialogSnapshot, DialogControl
decision = decide(prompt(ERROR), load_rules(ASSETS/'dialog_rules.v1.json'))
legacy = classify_dialog(DialogSnapshot(1, 2, 'Expedition PCB', (
DialogControl(3, 1, 'Static', ERROR, True),)))
for item in (decision, legacy):
assert item.error_code == 'ICDB_REPAIR_REQUIRED'
assert not item.action
assert '200091-CBB' in item.detail
def test_startup_probe_reports_session_loss_instead_of_port_reset(tmp_path):
log = tmp_path/'LogFiles/PCBLogFile.txt'
log.parent.mkdir()
log.write_text(ERROR + '\nCould not run server', encoding='utf-8')
detail = adapter.pcb_log_reports_missing_server(tmp_path/'CBB.pcb')
assert 'ICDB_REPAIR_REQUIRED' in detail
assert '__ReusableBlocksSymb' in detail
assert 'Repair project' in detail
assert 'net stop winnat' not in detail
def test_generic_server_log_does_not_claim_port_reservation(tmp_path):
log = tmp_path/'LogFiles/PCBLogFile.txt'
log.parent.mkdir()
log.write_text('Could not run server', encoding='utf-8')
detail = adapter.pcb_log_reports_missing_server(tmp_path/'CBB.pcb')
assert 'DESIGN_SERVER_FAILED' in detail
assert 'WinError 10013' not in detail
assert 'net stop winnat' not in detail
@pytest.mark.parametrize('mode', ['append', 'shorter', 'same_size', 'longer'])
def test_current_run_probe_handles_appended_and_rewritten_logs(tmp_path, mode):
from cbb_refresh_verify.icdb_recovery import snapshot_log
log = tmp_path/'LogFiles/PCBLogFile.txt'
log.parent.mkdir()
old = 'old harmless text\n' if mode == 'longer' else 'x'*(len(ERROR.encode())+40)
if mode == 'same_size':
old = 'x'*len(ERROR.encode())
log.write_text(old, encoding='utf-8')
baseline = snapshot_log(log)
log.write_text(old+ERROR if mode == 'append' else ERROR, encoding='utf-8')
assert 'ICDB_REPAIR_REQUIRED' in adapter.pcb_log_reports_missing_server(
tmp_path/'CBB.pcb', offset=baseline)
def test_old_loss_record_does_not_fail_a_new_run(tmp_path):
from cbb_refresh_verify.icdb_recovery import snapshot_log
log = tmp_path/'LogFiles/PCBLogFile.txt'
log.parent.mkdir()
log.write_text(ERROR, encoding='utf-8')
baseline = snapshot_log(log)
assert adapter.pcb_log_reports_missing_server(tmp_path/'CBB.pcb', offset=baseline) == ''
with log.open('a', encoding='utf-8') as stream:
stream.write('\nNormal startup completed\n')
assert adapter.pcb_log_reports_missing_server(tmp_path/'CBB.pcb', offset=baseline) == ''
def test_rewritten_header_does_not_promote_retained_old_session_loss(tmp_path):
from cbb_refresh_verify.icdb_recovery import snapshot_log
log = tmp_path/'LogFiles/PCBLogFile.txt'
log.parent.mkdir()
log.write_text('old header\n'+ERROR, encoding='utf-8')
baseline = snapshot_log(log)
log.write_text('new header\n'+ERROR+'\nNormal startup\n', encoding='utf-8')
assert adapter.pcb_log_reports_missing_server(tmp_path/'CBB.pcb', offset=baseline) == ''
def test_repeated_old_session_loss_is_current_when_verifiably_appended(tmp_path):
from cbb_refresh_verify.icdb_recovery import snapshot_log
log = tmp_path/'LogFiles/PCBLogFile.txt'
log.parent.mkdir()
log.write_text(ERROR+'\n', encoding='utf-8')
baseline = snapshot_log(log)
with log.open('a', encoding='utf-8') as stream:
stream.write(ERROR)
assert 'ICDB_REPAIR_REQUIRED' in adapter.pcb_log_reports_missing_server(
tmp_path/'CBB.pcb', offset=baseline)
@pytest.mark.parametrize('name', ['MsgBoxResponse.log', 'ForwardAnnotation.txt', 'PartPkg.log'])
def test_integration_log_retains_multiline_loss_identity(tmp_path, name):
from cbb_refresh_verify.icdb_recovery import snapshot_log
log = tmp_path/'LogFiles'/name
log.parent.mkdir()
baseline = snapshot_log(log)
log.write_text(ERROR.replace(' (Machine:', '\nMachine:').replace(' Path:', '\nPath:')
.replace(' session:', '\nSession:'), encoding='utf-8')
detail = adapter.pcb_log_reports_integration_error(tmp_path/'CBB.pcb', offsets={log: baseline})
assert 'ICDB_REPAIR_REQUIRED' in detail
assert '200091-CBB' in detail
assert '__ReusableBlocksSymb' in detail
assert '2026-10-24 08.22.29-10308' in detail
@pytest.mark.parametrize('production_checkpoint', [False, True])
def test_integration_generic_filter_does_not_repromote_historical_repair(tmp_path, production_checkpoint):
import hashlib
from cbb_refresh_verify.icdb_recovery import snapshot_log
log = tmp_path/'LogFiles/MsgBoxResponse.log'
log.parent.mkdir()
old = 'old header\nERROR: '+ERROR.replace('\n', ' ')
log.write_text(old, encoding='utf-8')
baseline = snapshot_log(log)
if production_checkpoint:
raw = log.read_bytes()
baseline = {'size': len(raw), 'digest': hashlib.sha256(raw).hexdigest(),
'icdb_baseline': baseline}
log.write_text(old.replace('old header', 'new header')+'\nnormal startup', encoding='utf-8')
detail = adapter.pcb_log_reports_integration_error(tmp_path/'CBB.pcb', offsets={log: baseline})
assert 'ICDB_REPAIR_REQUIRED' not in detail
assert runner.classify_failure_category(detail) != 'ICDB_REPAIR_REQUIRED'
def test_unreadable_integration_baseline_never_falls_back_to_historical_log(tmp_path):
log = tmp_path/'LogFiles/MsgBoxResponse.log'
log.parent.mkdir()
log.write_text('ERROR: '+ERROR.replace('\n', ' '), encoding='utf-8')
baseline = {'size': 0, 'mtime_ns': None, 'digest': '',
'icdb_baseline': {'error': 'access denied'}}
detail = adapter.pcb_log_reports_integration_error(tmp_path/'CBB.pcb', offsets={log: baseline})
assert runner.classify_failure_category(detail) != 'ICDB_REPAIR_REQUIRED'
def test_rewrite_of_large_log_does_not_promote_error_outside_baseline_window(tmp_path):
from cbb_refresh_verify.icdb_recovery import LOG_LIMIT, snapshot_log
log = tmp_path/'LogFiles/PCBLogFile.txt'
log.parent.mkdir()
log.write_text(ERROR+'\n'+'normal\n'*LOG_LIMIT, encoding='utf-8')
baseline = snapshot_log(log)
log.write_text('changed header\n'+ERROR, encoding='utf-8')
assert adapter.pcb_log_reports_missing_server(tmp_path/'CBB.pcb', offset=baseline) == ''
def test_integration_session_loss_has_priority_over_generic_startup_error(tmp_path, monkeypatch):
from test_verify_worker_stability import exercise_worker
from cbb_refresh_verify.pcb_bridge import PcbBridgeError
job, events, execute = exercise_worker(tmp_path, monkeypatch)
def attach(job, provider, **kwargs):
logs = Path(job['pcb']).parent/'LogFiles'
logs.mkdir()
(logs/'PCBLogFile.txt').write_text('Could not run server', encoding='utf-8')
(logs/'MsgBoxResponse.log').write_text(ERROR, encoding='utf-8')
detail = kwargs['error_reader']()
assert 'ICDB_REPAIR_REQUIRED' in detail
assert 'net stop winnat' not in detail
raise PcbBridgeError('PCB_STARTUP_FAILED', detail)
monkeypatch.setattr('cbb_refresh_verify.pcb_bridge.wait_for_target_document', attach)
with pytest.raises(PcbBridgeError, match='ICDB_REPAIR_REQUIRED'):
execute()
assert not any(event['stage'] == 'save_start' for event in events)
def test_optional_baseline_evidence_write_failure_does_not_block_verify(tmp_path, monkeypatch):
from test_verify_worker_stability import exercise_worker
job, events, execute = exercise_worker(tmp_path, monkeypatch)
original = Path.write_text
def deny_baseline(path, *args, **kwargs):
if path.name == 'startup-log-baseline.json':
raise PermissionError('diagnostic evidence unavailable')
return original(path, *args, **kwargs)
monkeypatch.setattr(Path, 'write_text', deny_baseline)
assert execute()['status'] == 'PASS'
def test_recovery_record_preserves_identity_and_distinguishes_shared_library():
from cbb_refresh_verify.icdb_recovery import parse_session_loss
record = parse_session_loss(ERROR)
assert record['machine'] == '200091-CBB'
assert record['database_path'] == r'S:\SymbolLibs\__ReusableBlocksSymb'
assert record['session'] == '2026-10-24 08.22.29-10308'
assert record['scope'] == 'central_library'
assert parse_session_loss(ERROR.replace(r'S:\SymbolLibs\__ReusableBlocksSymb',
r'S:\ReusableBlocksLP\CBB\Work\database'))['scope'] == 'project'
assert parse_session_loss('Could not run server') is None
@pytest.mark.parametrize('encoding', ['utf-8', 'utf-16', 'utf-16-le'])
def test_new_utf16_or_utf8_log_errors_are_detected_after_append(tmp_path, encoding):
from cbb_refresh_verify.icdb_recovery import snapshot_log
log = tmp_path/'LogFiles/PCBLogFile.txt'
log.parent.mkdir()
log.write_bytes('old text\n'.encode(encoding))
baseline = snapshot_log(log)
with log.open('ab') as stream:
stream.write(ERROR.encode('utf-16-le' if encoding == 'utf-16' else encoding))
assert 'ICDB_REPAIR_REQUIRED' in adapter.pcb_log_reports_missing_server(
tmp_path/'CBB.pcb', offset=baseline)
@pytest.mark.parametrize('baseline_state', ['stale', 'absent', 'unreadable'])
def test_historical_log_evidence_never_creates_a_repair_recommendation(tmp_path, baseline_state):
from cbb_refresh_verify.icdb_recovery import snapshot_log
from cbb_refresh_verify.verify_diagnostics import collect_native_failure_logs
pcb = tmp_path/'Work/PCB/CBB.pcb'
log = pcb.parent/'LogFiles/PCBLogFile.txt'
log.parent.mkdir(parents=True)
log.write_text(ERROR, encoding='utf-8')
evidence = tmp_path/'evidence'
(evidence/'diagnostics').mkdir(parents=True)
if baseline_state != 'absent':
baseline = snapshot_log(log) if baseline_state == 'stale' else {'error': 'access denied'}
(evidence/'diagnostics/startup-log-baseline.json').write_text(json.dumps({
'source': str(log), 'baseline': baseline}), encoding='utf-8')
collect_native_failure_logs(pcb, evidence)
assert not (evidence/'diagnostics/icdb-recovery.json').exists()
def test_content_success_text_cannot_override_native_session_loss():
assert runner.classify_output(0, 'content checking completed successfully\n'+ERROR) == 'FAIL'
@pytest.mark.parametrize('name', ['PCBLogFile.txt', 'MsgBoxResponse.log', 'ForwardAnnotation.txt', 'PartPkg.log'])
def test_native_log_capture_generates_only_fresh_repair_evidence(tmp_path, name):
from cbb_refresh_verify.icdb_recovery import snapshot_log
from cbb_refresh_verify.verify_diagnostics import collect_native_failure_logs
pcb = tmp_path/'Work/PCB/CBB.pcb'
log = pcb.parent/'LogFiles'/name
log.parent.mkdir(parents=True)
evidence = tmp_path/'evidence'
(evidence/'diagnostics').mkdir(parents=True)
log.write_text('old text', encoding='utf-8')
(evidence/'diagnostics/startup-log-baseline.json').write_text(json.dumps({
'source': str(pcb.parent/'LogFiles/PCBLogFile.txt'),
'baseline': snapshot_log(pcb.parent/'LogFiles/PCBLogFile.txt'),
'integration_logs': {str(log): snapshot_log(log)}}), encoding='utf-8')
log.write_text(ERROR, encoding='utf-8')
collect_native_failure_logs(pcb, evidence)
report = json.loads((evidence/'diagnostics/icdb-recovery.json').read_text('utf-8'))
assert report['scope'] == 'central_library'
assert report['source'] == str(log)
assert log.read_text('utf-8') == ERROR
def test_contents_session_loss_stops_batch_before_any_pcb_launch(tmp_path, monkeypatch):
from test_verify_runner import fixture, request
fixture(tmp_path)
monkeypatch.setattr(runner, 'resolve_importer', lambda *_: Path('ReuseBlockImporter.exe'))
calls = []
def content_check(*args):
calls.append(args)
return 1, ERROR, '', False
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 results[0].error_category == 'ICDB_REPAIR_REQUIRED'
assert results[0].safe_to_continue is False
assert 'Repair project' in results[0].stderr
assert results[1].status == 'SKIPPED'
def test_supervisor_enriches_generic_failure_from_fresh_native_log(tmp_path, monkeypatch):
from test_verify_runner import fixture, request
from cbb_refresh_verify.icdb_recovery import snapshot_log
from cbb_refresh_verify.verify_diagnostics import failure_logs_main
work = fixture(tmp_path)
log = work/'PCB/LogFiles/PCBLogFile.txt'
log.parent.mkdir()
class Worker:
desktop = None
returncode = 1
def __init__(self, command, *_a, **_kw):
root = Path(command[-1]).parent
(root/'diagnostics').mkdir()
(root/'diagnostics/startup-log-baseline.json').write_text(json.dumps({
'source': str(log), 'baseline': snapshot_log(log)}), encoding='utf-8')
log.write_text(ERROR, encoding='utf-8')
(root/'outcome.json').write_text(json.dumps({
'status': 'FAIL', 'stderr': 'MENTOR_DATABASE_LOAD_FAILED: opening failed',
'safe_to_continue': False}), encoding='utf-8')
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': True})
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 'opening failed' in result.stderr
assert '200091-CBB' in result.stderr
assert '__ReusableBlocksSymb' in result.stderr
assert '2026-10-24 08.22.29-10308' in result.stderr
assert json.loads(result.evidence_path.read_text('utf-8'))['error_category'] == 'ICDB_REPAIR_REQUIRED'
+215
View File
@@ -0,0 +1,215 @@
from concurrent.futures import ThreadPoolExecutor
import pytest
import win32con
import win32file
def test_library_lock_excludes_other_thread_and_uploader_but_reenters(tmp_path):
from cbb_refresh_verify.library_lock import LibraryLock, LibraryBusy
library = tmp_path/'test.lmc'
library.write_bytes(b'fixture')
with LibraryLock(library) as lock:
assert lock.path.name == '.test.cbb-upload.lock'
with LibraryLock(library):
assert lock.snapshot_bytes()
with pytest.raises(Exception):
win32file.CreateFile(str(lock.path), win32con.GENERIC_READ | win32con.GENERIC_WRITE,
0, None, win32con.OPEN_ALWAYS, 0, None)
def competing():
with pytest.raises(LibraryBusy):
with LibraryLock(library):
pass
with ThreadPoolExecutor(1) as pool:
pool.submit(competing).result()
assert lock.path.exists()
with LibraryLock(library):
pass
def test_complete_copy_reads_owned_lock_without_reopening(tmp_path):
from cbb_refresh_verify.library_lock import LibraryLock
from cbb_refresh_verify.scoped_manifest import copy_verified
source = tmp_path/'library'
source.mkdir()
library = source/'test.lmc'
library.write_bytes(b'fixture')
with LibraryLock(library) as lock:
expected = lock.snapshot_bytes()
copy_verified(source, tmp_path/'snapshot')
assert (tmp_path/'snapshot'/lock.path.name).read_bytes() == expected
def test_external_lock_never_gets_snapshot_exception(tmp_path):
from cbb_refresh_verify.scoped_manifest import copy_verified
source = tmp_path/'library'
source.mkdir()
path = source/'.test.cbb-upload.lock'
path.write_bytes(b'external')
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ | win32con.GENERIC_WRITE,
0, None, win32con.OPEN_EXISTING, 0, None)
try:
with pytest.raises(OSError):
copy_verified(source, tmp_path/'snapshot')
finally:
handle.Close()
def test_verification_refuses_uploader_exclusive_lock_before_native_work(tmp_path, monkeypatch):
import cbb_refresh_verify.verify_runner as runner
library = tmp_path/'lib.lmc'
library.touch()
lock = tmp_path/'.lib.cbb-upload.lock'
handle = win32file.CreateFile(str(lock), win32con.GENERIC_READ | win32con.GENERIC_WRITE,
0, None, win32con.OPEN_ALWAYS, 0, None)
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
finally:
handle.Close()
def test_unsafe_verify_retains_lease_and_persistent_blocker(tmp_path, monkeypatch):
import cbb_refresh_verify.verify_runner as runner
import cbb_refresh_verify.library_lock as locks
library = tmp_path/'lib.lmc'; library.touch()
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k:
runner.VerifyResult('FAIL', safe_to_continue=False))
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
def test_explicit_release_requires_fresh_proof_and_never_deletes_sidecar(tmp_path, monkeypatch):
import cbb_refresh_verify.library_lock as locks
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
with locks.LibraryLock(library, safe_to_release=lambda: False) as lease:
pass
try:
def denied(*a):
raise ValueError('native owner remains')
monkeypatch.setattr(locks, '_prove_library_released', denied)
with pytest.raises(ValueError, match='native owner'):
locks.release_retained_library(library, tmp_path/'release')
assert locks.blocker_path(library).is_file()
from contextlib import contextmanager
@contextmanager
def proof(*a):
yield {'native_owners': [], 'addresses': [], 'exclusive_files': [str(library)]}
monkeypatch.setattr(locks, '_prove_library_released', proof)
result = locks.release_retained_library(library, tmp_path/'release')
assert result['status'] == 'RELEASE_CONFIRMED'
assert lease.path.is_file() and not locks.blocker_path(library).exists()
with locks.LibraryLock(library): pass
finally:
with locks._guard:
owner = locks._owners.pop(str(lease.path.resolve()).casefold(), None)
if owner: owner['handle'].Close()
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 *_: []))
library = tmp_path/'lib.lmc'; library.touch()
address = tmp_path/'database/cdbsvr/sAddress.adr'; address.parent.mkdir(parents=True)
address.touch()
with pytest.raises(locks.LibraryBusy):
with locks._prove_library_released(library): pass
address.unlink() # Test-created empty marker, never a native address file.
handle = win32file.CreateFile(str(library), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, 0, None)
try:
with pytest.raises(Exception):
with locks._prove_library_released(library): pass
finally:
handle.Close()
with locks._prove_library_released(library) as proof:
assert proof['exclusive_files'] == [str(library)]
def test_public_verify_initializes_com_in_its_operation_thread(tmp_path, monkeypatch):
import ctypes
import cbb_refresh_verify.verify_runner as runner
library = tmp_path/'lib.lmc'; library.touch()
def serialized(*a, **k):
apartment, qualifier = ctypes.c_int(), ctypes.c_int()
ole32 = ctypes.WinDLL('ole32')
ole32.CoGetApartmentType.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)]
initialized = ole32.CoGetApartmentType(ctypes.byref(apartment), ctypes.byref(qualifier)) == 0
return runner.VerifyResult('PASS' if initialized else 'FAIL', stderr='COM apartment check')
monkeypatch.setattr(runner, '_run_verify_serialized', serialized)
with ThreadPoolExecutor(1) as pool:
result = pool.submit(runner.run_verify, runner.VerifyRequest(library, 'Block', tmp_path/'out')).result()
assert result.status == 'PASS'
@pytest.mark.parametrize('mode,expected', [(0, 1), (2, 0)])
def test_public_verify_preserves_existing_apartment(tmp_path, monkeypatch, mode, expected):
import ctypes, pythoncom
import cbb_refresh_verify.verify_runner as runner
library = tmp_path/'lib.lmc'; library.touch()
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: runner.VerifyResult('PASS'))
def existing_mta():
pythoncom.CoInitializeEx(mode)
try:
apartment, qualifier = ctypes.c_int(), ctypes.c_int()
ole32 = ctypes.WinDLL('ole32')
ole32.CoGetApartmentType.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)]
assert ole32.CoGetApartmentType(ctypes.byref(apartment), ctypes.byref(qualifier)) == 0
before = apartment.value
# A thread can be the main STA (3) when it creates the process's
# first remaining STA. Verify must preserve either STA flavor.
assert before in ((1,) if mode == 0 else (0, 3))
runner.run_verify(runner.VerifyRequest(library, 'Block', tmp_path/'out'))
result = ole32.CoGetApartmentType(ctypes.byref(apartment), ctypes.byref(qualifier))
return result, apartment.value, before
finally:
pythoncom.CoUninitialize()
with ThreadPoolExecutor(1) as pool:
result, after, before = pool.submit(existing_mta).result()
assert result == 0 and after == before
def test_nested_snapshot_retains_runtime_checkpoint_bytes_without_semantic_conflicts(tmp_path):
import cbb_refresh_verify.library_lock as locks
from cbb_refresh_verify.scoped_manifest import copy_verified, build_manifest, ManifestScope
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.write_bytes(b'library')
scope = ManifestScope.library('Block', library.name)
with locks.LibraryLock(library) as lease:
before = copy_verified(library.parent, tmp_path/'snapshot', scope=scope)
marker = locks.blocker_path(library)
assert (tmp_path/'snapshot'/marker.name).read_bytes() == marker.read_bytes()
with locks.LibraryLock(library):
owner = locks._owners[lease.key]
locks._persist_blocker(library, lease_id=owner['lease_id'])
assert build_manifest(library.parent, scope=scope) == before
assert not marker.exists() and lease.path.exists()
def test_arbitrary_guard_filename_is_preserved_and_primary(tmp_path, monkeypatch):
import cbb_refresh_verify.library_lock as locks
from cbb_refresh_verify.scoped_manifest import build_manifest, ManifestScope
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
marker = locks.blocker_path(library); marker.write_bytes(b'{not a guard record')
with pytest.raises(locks.LibraryBusy):
with locks.LibraryLock(library): pass
manifest = build_manifest(library.parent, scope=ManifestScope.library('Block', library.name))
assert marker.name in manifest['files']
from contextlib import contextmanager
@contextmanager
def proof(*a): yield {'native_owners': [], 'addresses': [], 'exclusive_files': [str(library)]}
monkeypatch.setattr(locks, '_prove_library_released', proof)
with pytest.raises(locks.LibraryBusy):
locks.release_retained_library(library, tmp_path/'release')
assert marker.read_bytes() == b'{not a guard record'
+292
View File
@@ -0,0 +1,292 @@
"""Explicit maintenance for preexisting advertisements; native writes forbidden."""
from dataclasses import replace
from contextlib import contextmanager
import json
import os
from pathlib import Path
from types import SimpleNamespace
import pytest
@pytest.fixture(autouse=True)
def no_native_launch(monkeypatch):
import subprocess, win32process, win32com.client
import cbb_refresh_verify.desktop_worker as desktop
def forbidden(*a, **k): raise AssertionError('No native launch allowed in maintenance tests')
monkeypatch.setattr(subprocess, 'Popen', forbidden)
monkeypatch.setattr(win32process, 'CreateProcess', forbidden)
monkeypatch.setattr(win32com.client, 'Dispatch', forbidden)
monkeypatch.setattr(win32com.client, 'DispatchEx', forbidden)
monkeypatch.setattr(desktop, 'DesktopWorker', forbidden)
@pytest.fixture
def case(tmp_path, monkeypatch):
from cbb_refresh_verify.verify_runner import VerifyRequest
import cbb_refresh_verify.maintenance_entry as entry
library = tmp_path/'library/mentor.lmc'; library.parent.mkdir(); library.write_bytes(b'library')
work = library.parent/'ReusableBlocksLP/IP101GR/Work'
(work/'database/cdbsvr').mkdir(parents=True)
(work/'database/icdb.dat').write_bytes(b'schematic')
address = work/'database/cdbsvr/sAddress.adr'; address.write_bytes(b'old server address - preserved')
(work/'PCB/Layout').mkdir(parents=True)
(work/'PCB/Layout/LayoutDB.lyt').write_bytes(b'layout')
project = work/'IP101GR.prj'
project.write_text('KEY iCDBDir ".\\database"\nKEY PCBDesignPath "PCB/IP101GR.pcb"\n')
(work/'PCB/IP101GR.pcb').write_text('KEY ProjectFile "../IP101GR.prj"\n')
(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)
yield request, project, address
import cbb_refresh_verify.library_lock as locks
key = locks.LibraryLock(library).key
with locks._guard:
owner = locks._owners.pop(key, None)
if owner: owner['handle'].Close()
def test_explicit_maintenance_enters_official_repair_once_without_lostsession_fabrication(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 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()
return complete_native_success(target)
monkeypatch.setattr(native_repair, 'run_native_repair', repair)
monkeypatch.setattr(native_repair, 'repair_release_state', lambda *a:
{'safe_to_continue': True, 'native_exited': True, 'addresses': []})
def verify(req, **kwargs):
calls.append('verify')
from cbb_refresh_verify.post_repair_consent import PostRepairProof
assert isinstance(req.post_repair_proof, PostRepairProof)
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
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):
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
assert address.read_bytes() == b'old server address - preserved'
@pytest.mark.parametrize('obstacle', ['active_owner', 'exclusive', 'shared_address', 'ambiguous', 'address_mutation'])
def test_maintenance_guard_blocks_before_native(case, monkeypatch, obstacle):
from cbb_refresh_verify import maintenance_entry as entry, native_repair, verify_runner as runner
import win32file, win32con
request, project, address = case
handle = None
if obstacle == 'active_owner':
monkeypatch.setattr(entry, 'assert_native_idle', lambda: (_ for _ in ()).throw(ValueError('native owner')))
if obstacle == 'exclusive':
handle = win32file.CreateFile(str(project.parent/'database/icdb.dat'), win32con.GENERIC_READ,
0, None, win32con.OPEN_EXISTING, 0, None)
if obstacle == 'shared_address':
shared = request.lmc_file.parent/'SymbolLibs/__ReusableBlocksSymb/cdbsvr/sAddress.adr'
shared.parent.mkdir(parents=True); shared.write_bytes(b'shared owner')
if obstacle == 'ambiguous': project.write_text(project.read_text() + 'KEY iCDBDir "other"\n')
if obstacle == 'address_mutation':
original = entry.address_snapshot
def mutate(paths):
result = original(paths)
address.write_bytes(b'changed after snapshot')
return result
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)
assert result.status == 'BLOCKED' and not result.safe_to_continue
finally:
if handle: handle.Close()
@pytest.mark.parametrize('change', ['dead', 'same_process', 'live_foreign', 'malformed', 'foreign_library', 'guard_failure'])
def test_takeover_preserves_old_checkpoint_until_every_guard_passes(case, monkeypatch, change):
from cbb_refresh_verify import library_lock as locks, maintenance_entry as entry
request, _, address = case
library = request.lmc_file
with locks.LibraryLock(library, safe_to_release=lambda: False): pass
marker = locks.blocker_path(library)
record = json.loads(marker.read_text(encoding='utf-8'))
if change != 'same_process':
with locks._guard: locks._owners.pop(locks.LibraryLock(library).key)['handle'].Close()
record['pid'] = 789123
if change == 'foreign_library': record['library'] = str(library.parent.parent/'foreign/mentor.lmc')
marker.write_text('broken json' if change == 'malformed' else json.dumps(record), encoding='utf-8')
old = marker.read_bytes()
monkeypatch.setattr(locks, '_supervisor_alive', lambda pid: change == 'live_foreign')
if change == 'guard_failure':
monkeypatch.setattr(entry, 'assert_native_idle', lambda: (_ for _ in ()).throw(ValueError('guard failed')))
archive = request.evidence_dir/'takeover'
guard = lambda: entry.maintenance_target_guard(request)
if change in ('dead', 'same_process'):
lease = locks.LibraryLock.for_maintenance(library, archive, guard, safe_to_release=lambda: True)
with lease:
assert (archive/'previous-checkpoint.json').read_bytes() == old
assert address.exists()
import win32file, win32con
with pytest.raises(Exception):
win32file.CreateFile(str(lease.path), win32con.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None)
assert lease.path.exists() and not marker.exists()
else:
with pytest.raises((ValueError, OSError)):
with locks.LibraryLock.for_maintenance(library, archive, guard): pass
assert marker.read_bytes() == old
@pytest.mark.parametrize('status', ['MISSING_HEALTHY_BACKUP', 'RESTORED_REVIEW_REQUIRED', 'DATABASE_BUSY', 'TIMEOUT_UNRELEASED'])
def test_nonrepair_outcomes_never_verify_or_count_success(case, monkeypatch, status):
from cbb_refresh_verify import native_repair, verify_runner as runner
request, _, _ = case
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)
assert result.status != 'PASS' and not result.safe_to_continue
assert result.recovery_attempts[0]['status'] == status
def test_native_success_cannot_bypass_remaining_address(case, monkeypatch):
from cbb_refresh_verify import native_repair, verify_runner as runner
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'))
# 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)
assert result.status != 'PASS' and not result.safe_to_continue
@pytest.mark.parametrize('output', ['', 'Checking if project is in use.',
"Project is not in use. Full iCDB Project Backup's functionality is available.",
"Project is not in use. Full iCDB Project Backup's functionality is available.\nProject is in use."])
def test_explicit_worker_requires_positive_native_idle_before_repair(tmp_path, monkeypatch, output):
import win32con
from test_native_repair import repair_worker_fixture
import cbb_refresh_verify.maintenance_entry as entry
from cbb_refresh_verify.native_repair import RepairTarget
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
values = json.loads(job.read_text())
values['maintenance_context'] = {'library': str(tmp_path/'lib.lmc'), 'block': 'CBB1'}
job.write_text(json.dumps(values))
@contextmanager
def guard(*args):
yield {'target': RepairTarget(Path(values['project']), Path(values['database']))}
monkeypatch.setattr(entry, 'maintenance_target_guard', guard)
monkeypatch.setattr(ui, '_native_output', lambda windows: output)
ui.repair_worker_main(job)
expected = output == "Project is not in use. Full iCDB Project Backup's functionality is available."
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):
from test_native_repair import repair_worker_fixture
import cbb_refresh_verify.maintenance_entry as entry
from cbb_refresh_verify.native_repair import RepairTarget
ui, root, job, _ = repair_worker_fixture(tmp_path, monkeypatch, 'active')
values = json.loads(job.read_text()); values['maintenance_context'] = {'library': str(tmp_path/'lib.lmc'), 'block': 'CBB1'}
job.write_text(json.dumps(values))
calls = []
@contextmanager
def guard(*args):
calls.append('guard')
if len(calls) == 2: raise ValueError('address changed during complete backup')
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 'address changed' in json.loads((root/'repair-result.json').read_text())['detail']
def test_guard_failure_keeps_takeover_checkpoint_byte_exact_when_address_changes(case, monkeypatch):
from cbb_refresh_verify import library_lock as locks, maintenance_entry as entry
request, _, address = case
with locks.LibraryLock(request.lmc_file, safe_to_release=lambda: False): pass
marker = locks.blocker_path(request.lmc_file); old = marker.read_bytes()
snapshot = entry.address_snapshot
def mutate(paths):
result = snapshot(paths); address.write_bytes(b'changed'); return result
monkeypatch.setattr(entry, 'address_snapshot', mutate)
with pytest.raises(ValueError):
with locks.LibraryLock.for_maintenance(request.lmc_file, request.evidence_dir/'takeover',
lambda: entry.maintenance_target_guard(request)): pass
assert marker.read_bytes() == old
def test_independent_cbb_address_does_not_select_or_block_current_project(case):
from cbb_refresh_verify.maintenance_entry import maintenance_target_guard
request, project, address = case
other = request.lmc_file.parent/'ReusableBlocksLP/1GPHY_8212/Work/database/cdbsvr/sAddress.adr'
other.parent.mkdir(parents=True); other.write_bytes(b'independent CBB original address')
with maintenance_target_guard(request) as checked:
assert checked['target'].project == project
assert set(checked['context']['addresses']) == {str(address.resolve())}
assert other.read_bytes() == b'independent CBB original address'
assert other.read_bytes() == b'independent CBB original address'
@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),
('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):
from cbb_refresh_verify import native_repair, verify_runner as runner, library_lock
from test_native_repair import complete_native_success
request, _, address = case
def repair(target, *args, **kwargs):
address.unlink() # Simulate official process releasing its test-only advertisement.
result = complete_native_success(target)
result.update(status=status, detail='native completed')
result['evidence']['failure_complete'] = complete
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)
assert result.status != 'PASS'
assert result.safe_to_continue is expected_safe
assert result.recovery_attempts[0]['status'] == status
assert library_lock.has_blocker(request.lmc_file) is not expected_safe
def test_successful_icdb_repair_then_version_choice_reports_partial_completion(case, monkeypatch):
from cbb_refresh_verify import native_repair, verify_runner as runner
from test_native_repair import complete_native_success
request, _, address = case
def repair(target, *a, **k):
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'])
monkeypatch.setattr(runner, '_run_verify_serialized', 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
assert result.recovery_attempts[0]['native_status'] == 'REPAIRED'
assert result.recovery_attempts[0]['status'] == 'PCB_VERSION_CHOICE_REQUIRED'
assert result.recovery_attempts[0]['validation_passed'] is False
+97
View File
@@ -0,0 +1,97 @@
import json
from pathlib import Path
import pytest
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QMessageBox
def test_only_confirmed_maintenance_sets_explicit_flag(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', safe_to_continue=True)),
status_refresher=lambda names, path: {name: 'PENDING' for name in names})
window.search_edit.setText('Beta')
window.verify_all(); qtbot.waitUntil(lambda: not window.busy)
assert calls and calls[-1].maintenance is False
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.No)
window.repair_icdb_all(); assert len(calls) == 1
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
window.repair_icdb_all(); qtbot.waitUntil(lambda: not window.busy)
assert len(calls) == 2 and calls[-1].maintenance is True
@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):
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
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()
marker = blocker_path(library)
if marker_kind == 'malformed': marker.write_text('{}')
if marker_kind == 'foreign':
record = json.loads(marker.read_text()); record['library'] = str(tmp_path/'foreign/mentor.lmc')
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'),
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')
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()
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
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
window.repair_icdb_all(); qtbot.waitUntil(lambda: not window.busy)
assert len(calls) == 1 and calls[0].maintenance is True
def test_safe_maintenance_reloads_authoritative_catalog_after_worker_finishes(qtbot, tmp_path, monkeypatch):
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.models import LibraryReadResult, CbbRecord
from cbb_refresh_verify.verify_runner import VerifyResult
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 lease: pass
with _guard: _owners.pop(lease.key)['handle'].Close()
reads = []
def reader(path):
reads.append(path)
return LibraryReadResult((CbbRecord('IP101GR', 'Reusable Blocks', status='READY'),))
def verify(req):
assert req.maintenance
blocker_path(library).unlink() # Simulate normal cleanup at the injected boundary.
return VerifyResult('PASS', library_flag='GREEN')
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'))
qtbot.addWidget(window)
window.lmc_edit.setText(str(library)); window.load_library(); qtbot.waitUntil(lambda: not window.busy)
assert reads == []
window.search_edit.setText('IP101')
window.repair_icdb_all()
qtbot.waitUntil(lambda: not window.busy and bool(reads))
assert window.visible_records()[0].status == 'READY'
assert not window._maintenance_recovery_view and window.search_edit.text() == 'IP101'
+326
View File
@@ -0,0 +1,326 @@
"""Operation safety tests use a file-only native boundary; never launch Mentor."""
from dataclasses import replace
import json
from pathlib import Path
from threading import Event
import pytest
def project(root, name='Source', marker=b'original'):
root.mkdir(parents=True)
(root/'database').mkdir()
(root/'database/icdb.dat').write_bytes(marker)
(root/'PCB/Layout').mkdir(parents=True)
(root/'PCB/Layout/LayoutDB.lyt').write_bytes(marker)
(root/'PCB/pcb.prj').write_text('KEY iCDBDir "../database"\n', encoding='utf-8')
(root/'PCB/main.pcb').write_text(f'KEY ProjectFile "../{name}.prj"\n', encoding='utf-8')
path = root/f'{name}.prj'
path.write_text('KEY RootBlock "Top"\nKEY PCBDesignPath "PCB/main.pcb"\n'
'KEY iCDBDir "database"\n', encoding='utf-8')
return path
class FileAdapter:
def __init__(self):
self.records = []
self.calls = []
self.fail_add = False
self.lie = False
self.released = True
def capabilities(self):
from cbb_refresh_verify.management import Capability
return {op: Capability(True, 'test boundary') for op in ('add', 'update', 'remove')}
def catalog(self, library, evidence):
from cbb_refresh_verify.management import Catalog
return Catalog(library, 1, tuple(self.records), safe_to_continue=self.released)
def remove(self, request, evidence):
from cbb_refresh_verify.management import NativeOutcome
self.calls.append('remove')
if not self.lie:
self.records = [r for r in self.records if r.name != request.name]
return NativeOutcome(True, self.released, 'native removal accepted')
def add(self, request, evidence):
from cbb_refresh_verify.management import NativeOutcome, CatalogEntry, engineering_identity
self.calls.append(('add', request.source))
if self.fail_add:
return NativeOutcome(False, self.released, 'native add failed')
if not self.lie:
self.records.append(CatalogEntry(request.name, request.partition,
engineering_identity(request.source)))
return NativeOutcome(True, self.released, 'native add accepted')
@pytest.fixture
def setup(tmp_path):
from cbb_refresh_verify.management import ManagementRequest, CatalogEntry
library = tmp_path/'library/mentor.lmc'
library.parent.mkdir()
library.write_bytes(b'library')
old = project(library.parent/'ReusableBlocksLP/Block/Work', 'Block')
source = project(tmp_path/'source')
adapter = FileAdapter()
adapter.records = [CatalogEntry('Block', 'Logical-Physical')]
request = ManagementRequest('remove', library, 'Block', evidence_dir=tmp_path/'evidence')
yield request, adapter, source
# FileAdapter never launches native owners. Release only this test's
# intentionally retained lease so pytest can remove its temporary tree.
from cbb_refresh_verify.library_lock import _guard, _owners
key = str(library.with_name('.mentor.cbb-upload.lock').resolve()).casefold()
with _guard:
owner = _owners.pop(key, None)
if owner:
owner['handle'].Close()
def execute(request, adapter, **kwargs):
from cbb_refresh_verify.management import run_management
return run_management(request, adapter=adapter, idle_check=lambda *_: None, **kwargs)
def test_remove_backup_and_strict_absence(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()
record = json.loads(result.evidence_path.read_text(encoding='utf-8'))
assert record['operation'] == 'remove' and record['partition'] == 'Logical-Physical'
assert record['stage'] == 'complete'
def test_add_conflict_cannot_overwrite(setup):
request, adapter, source = setup
result = execute(replace(request, operation='add', source=source), adapter)
assert result.status == 'UPLOAD_FAILED' and adapter.calls == []
@pytest.mark.parametrize('verify_status,flag,expected', [('PASS', 'GREEN', 'UPLOADED_VERIFIED'),
('FAIL', 'RED', 'UPLOADED_VERIFY_FAILED'), ('PASS', 'UNKNOWN', 'UPLOADED_VERIFY_FAILED')])
def test_add_stages_source_and_requires_authoritative_verify(setup, verify_status, flag, expected):
from cbb_refresh_verify.verify_runner import VerifyResult
request, adapter, source = setup
original = source.read_bytes()
def verifier(req, **_):
assert adapter.released
return VerifyResult(verify_status, library_flag=flag)
result = execute(replace(request, operation='add', name='New', source=source), adapter,
verifier=verifier)
assert result.status == expected and source.read_bytes() == original
assert adapter.calls[0][1] != source
assert adapter.calls[0][1].is_relative_to(result.evidence_path.parent)
def test_add_no_auto_verify_and_reimport_after_remove(setup):
request, adapter, source = setup
assert execute(request, adapter).status == 'REMOVED'
result = execute(replace(request, operation='add', source=source, auto_verify=False), adapter,
verifier=lambda *_: pytest.fail('auto verify disabled'))
assert result.status == 'UPLOADED'
def test_update_failed_readd_keeps_removed_checkpoint_and_recovery_snapshot(setup):
request, adapter, source = setup
adapter.fail_add = True
result = execute(replace(request, operation='update', source=source), adapter)
assert result.status == 'RECOVERY_REQUIRED' and not result.safe_to_continue
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()
@pytest.mark.parametrize('operation', ['remove', 'add'])
def test_lying_native_output_does_not_report_success(setup, operation):
request, adapter, source = setup
adapter.lie = True
request = replace(request, operation=operation, source=source,
name='New' if operation == 'add' else 'Block')
result = execute(request, adapter)
assert result.status == 'RECOVERY_REQUIRED' and not result.safe_to_continue
def test_unreleased_native_owner_prevents_postread_and_verification(setup):
request, adapter, _ = setup
original = adapter.remove
def unreleased(*args):
adapter.released = False
return original(*args)
adapter.remove = unreleased
reads = []
catalog = adapter.catalog
adapter.catalog = lambda *a: (reads.append(1) or catalog(*a))
result = execute(request, adapter, verifier=lambda *_: pytest.fail('unsafe verify'))
assert not result.safe_to_continue and len(reads) == 1
from cbb_refresh_verify.library_lock import LibraryLock, LibraryBusy
with pytest.raises(LibraryBusy):
with LibraryLock(request.library):
pass
@pytest.mark.parametrize('name', ['../escape', 'A\tB', 'A\nB', 'A/B', 'NUL', 'a.', ''])
def test_invalid_native_identity_rejected_before_writes(setup, name):
request, adapter, _ = setup
result = execute(replace(request, name=name), adapter)
assert result.status == 'BLOCKED' and adapter.calls == []
def test_evidence_inside_target_rejected(setup):
request, adapter, _ = setup
result = execute(replace(request, evidence_dir=request.library.parent/'evidence'), adapter)
assert result.status == 'BLOCKED' and not (request.library.parent/'evidence').exists()
def test_cancel_and_restart_never_replay(setup):
from cbb_refresh_verify.management import run_management_batch, unfinished_operations
request, adapter, _ = setup
stop = Event(); stop.set()
assert run_management_batch([request], stop=stop, adapter=adapter) == []
checkpoint = request.evidence_dir/'interrupted/checkpoint.json'
checkpoint.parent.mkdir(parents=True)
checkpoint.write_text('{"stage":"native_remove", "status":"RUNNING"}', encoding='utf-8')
found = unfinished_operations(request.evidence_dir)
assert len(found) == 1 and found[0]['evidence_path'] == str(checkpoint)
assert adapter.calls == []
def test_capability_gate_enforced_below_ui(setup):
from cbb_refresh_verify.management import Capability
request, adapter, source = setup
adapter.capabilities = lambda: {'add': Capability(False, 'isolated add not validated')}
result = execute(replace(request, operation='add', name='New', source=source), adapter)
assert result.status == 'UNSUPPORTED' and 'isolated' in result.detail
assert adapter.calls == []
def test_timeout_stops_batch_and_persists_ambiguous_native_stage(setup):
from cbb_refresh_verify.management import run_management_batch
request, adapter, _ = setup
def timeout(*_):
raise TimeoutError('network timeout')
adapter.remove = timeout
results = run_management_batch([request, replace(request, name='Other')], adapter=adapter,
idle_check=lambda *_: None)
assert len(results) == 1 and not results[0].safe_to_continue
assert results[0].status == 'RECOVERY_REQUIRED'
def test_catalog_timeout_is_not_safe_to_continue(setup):
request, adapter, _ = setup
def timeout(*_):
raise TimeoutError('catalog owner still running')
adapter.catalog = timeout
result = execute(request, adapter)
assert not result.safe_to_continue and adapter.calls == []
def test_replaced_source_bytes_fail_identity_even_with_same_name(setup):
request, adapter, source = setup
real_add = adapter.add
def wrong_source(*args):
from cbb_refresh_verify.management import CatalogEntry
result = real_add(*args)
entry = adapter.records[-1]
adapter.records[-1] = CatalogEntry(entry.name, entry.partition, {'wrong': 'project'})
return result
adapter.add = wrong_source
result = execute(replace(request, operation='add', name='New', source=source), adapter)
assert result.status == 'RECOVERY_REQUIRED' and not result.safe_to_continue
def test_update_success_requires_same_identity_and_no_implicit_partition_move(setup):
request, adapter, source = setup
result = execute(replace(request, operation='update', source=source, partition='Other'), adapter)
assert result.status == 'BLOCKED' and not adapter.calls
result = execute(replace(request, operation='update', source=source, auto_verify=False), adapter)
assert result.status == 'UPLOADED'
assert adapter.calls[0] == 'remove' and adapter.calls[1][0] == 'add'
def test_verify_exception_after_upload_retains_coordination_lock(setup):
from cbb_refresh_verify.library_lock import LibraryLock, LibraryBusy
request, adapter, source = setup
def broken_verifier(*a, **k):
raise OSError('verification worker disconnected')
result = execute(replace(request, operation='add', name='New', source=source), adapter,
verifier=broken_verifier)
assert result.status == 'UPLOADED_VERIFY_FAILED' and not result.safe_to_continue
with pytest.raises(LibraryBusy):
with LibraryLock(request.library):
pass
@pytest.mark.parametrize('nested', [True, False])
def test_library_inside_source_tree_rejected_before_catalog_or_guard(setup, nested):
request, adapter, source = setup
library = source.parent/('nested/lib.lmc' if nested else 'lib.lmc')
library.parent.mkdir(exist_ok=True)
library.write_bytes(b'library')
adapter.catalog = lambda *a: pytest.fail('overlapping library reached native catalog')
result = execute(replace(request, operation='add', name='New', source=source, library=library), adapter)
assert result.status == 'BLOCKED' and not adapter.calls
assert not library.with_name('.lib.cbb-upload.lock').exists()
assert not request.evidence_dir.exists()
def test_mapped_library_spelling_and_context_survive_engine_verify_boundary(setup, monkeypatch):
import shutil
from cbb_refresh_verify.verify_runner import VerifyResult
request, adapter, source = setup
alias_root = request.library.parent
canonical_root = alias_root.with_name('canonical-library')
shutil.copytree(alias_root, canonical_root)
original_resolve = Path.resolve
def resolve(path, *a, **k):
if path.is_relative_to(alias_root):
return original_resolve(canonical_root/path.relative_to(alias_root), *a, **k)
return original_resolve(path, *a, **k)
monkeypatch.setattr(Path, 'resolve', resolve)
catalogs, verified = [], []
catalog = adapter.catalog
adapter.catalog = lambda library, evidence: (catalogs.append(library) or catalog(library, evidence))
def verifier(req, **k):
verified.append(req)
return VerifyResult('PASS', library_flag='GREEN')
request = replace(request, operation='add', name='New', source=source,
mapped_drive='S:', mapped_remote_root=r'\\server\share')
result = execute(request, adapter, verifier=verifier)
assert result.status == 'UPLOADED_VERIFIED'
assert catalogs == [request.library, request.library]
assert verified[0].lmc_file == request.library
assert verified[0].mapped_drive == 'S:' and verified[0].mapped_remote_root == r'\\server\share'
def test_source_inside_target_library_rejected_before_catalog(setup):
request, adapter, _ = setup
source = request.library.parent/'ReusableBlocksLP/Block/Work/Block.prj'
adapter.catalog = lambda *a: pytest.fail('overlapping source reached native catalog')
result = execute(replace(request, operation='add', name='New', source=source), adapter)
assert result.status == 'BLOCKED' and not request.evidence_dir.exists()
@pytest.mark.parametrize('matched', [True, False])
def test_prepared_native_identity_is_required_after_exact_catalog(setup, matched):
from cbb_refresh_verify.native_engineering_identity import IdentityOutcome
from cbb_refresh_verify.management import NativeOutcome
request, adapter, source = setup
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()
adapter.calls.append('prepare_identity')
return staged, IdentityOutcome(expected, True, 'baseline captured', root)
adapter.prepare_add_transaction = prepare
original_add = adapter.add
def add(staged, evidence):
original_add(staged, evidence)
return NativeOutcome(True, True, 'native registered', identity_matches=matched,
identity_proof=expected if matched else {'different': True})
adapter.add = add
result = execute(replace(request, operation='update', source=source, auto_verify=False), adapter)
assert adapter.calls[0:2] == ['prepare_identity', 'remove']
assert result.status == ('UPLOADED' if matched else 'RECOVERY_REQUIRED')
+138
View File
@@ -0,0 +1,138 @@
import json
from pathlib import Path
from types import ModuleType, SimpleNamespace
import pytest
def test_raw_dispatch_diagnostics_preserve_hresult_and_known_member_ids(tmp_path):
from cbb_refresh_verify.native_management import _dispatch_diagnostics
class Error(RuntimeError):
hresult = -2147221008
class Raw:
def GetIDsOfNames(self, name):
if name == 'Quit': raise Error('COM apartment unavailable')
return 17 if name == 'Close' else 21
obj = SimpleNamespace(_oleobj_=Raw())
_dispatch_diagnostics(tmp_path, 'before-import', obj, obj)
record = json.loads((tmp_path/'dispatch-diagnostics.jsonl').read_text(encoding='utf-8'))
assert record['members']['application.OnReusableBlocksEditor']['dispid'] == 21
assert record['members']['library.Close']['dispid'] == 17
error = record['members']['application.Quit']['error']
assert error['hresult'] == -2147221008 and error['args'] == ['COM apartment unavailable']
assert error['type'].endswith('Error')
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
source = tmp_path/'source/Block.prj'
source.parent.mkdir()
source.write_text('KEY RootBlock "Block"\nKEY PCBDesignPath "PCB/Block.pcb"\n'
'KEY iCDBDir "database"\nKEY CentralLibrary "old.lmc"\n')
(source.parent/'database').mkdir(); (source.parent/'database/icdb.dat').write_bytes(b'fixture')
pcb = source.parent/'PCB/Block.pcb'; (pcb.parent/'Layout').mkdir(parents=True)
pcb.write_text('KEY ProjectFile "../Block.prj"\n')
(pcb.parent/'pcb.prj').write_text('KEY CentralLibrary "old.lmc"\n')
(pcb.parent/'Layout/LayoutDB.lyt').write_bytes(b'fixture')
root = tmp_path/'native-add'; root.mkdir()
library = root/'fixture/mentor_lib.lmc'; library.parent.mkdir(); library.touch()
phase = ['before']
class Raw:
def GetIDsOfNames(self, name): return 1 if phase[0] == 'before' else 2
class App:
_oleobj_ = Raw()
def OnReusableBlocksEditor(self): raise RuntimeError('stop before native UI')
class Uia(ModuleType):
def __getattr__(self, name):
if name == 'Desktop':
phase[0] = 'after'
return None
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}
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()]
assert [r['stage'] for r in records] == ['before-pywinauto-import', 'after-pywinauto-import', 'after-source-alignment']
assert records[0]['members']['application.Quit']['dispid'] == 1
assert records[1]['members']['application.Quit']['dispid'] == 2
assert records[2]['paths'] == {'source': str(source), 'pcb': str(pcb), 'library_argument': str(library)}
assert 'old.lmc' not in source.read_text()
@pytest.mark.parametrize('operation', ['probe_create_add', 'probe_readd', 'catalog'])
def test_probe_preloads_uia_before_com_proxy_creation_but_catalog_stays_read_only(tmp_path, monkeypatch, operation):
import sys, win32com.client
import cbb_refresh_verify.native_management as native
import cbb_refresh_verify.mentor_adapter as mentor
root = tmp_path/'job'; root.mkdir()
library_path = tmp_path/'fixture.lmc'; library_path.touch()
events, running = [], [False]
class Uia(ModuleType):
def __getattr__(self, name):
if name == 'Desktop':
events.append('uia-loaded')
return object
raise AttributeError(name)
monkeypatch.setitem(sys.modules, 'pywinauto', Uia('pywinauto'))
library = SimpleNamespace(FullName=str(library_path), FlowType=1,
Partitions=lambda kind: SimpleNamespace(Count=0), Close=lambda: events.append('library-close'))
class App:
def OpenLibrary(self, path): return library
def CreateLibrary(self, path, flow): return library
def Quit(self): events.append('quit'); running[0] = False
def dispatch(progid):
events.append('dispatch'); running[0] = True
return App()
monkeypatch.setattr(win32com.client, 'DispatchEx', dispatch)
monkeypatch.setattr(native, '_current_desktop', lambda:
(SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test'))
monkeypatch.setattr(mentor, '_process_details', lambda name:
[(123, str(tmp_path/'lm/win32/bin/LibraryManager.exe'), '', 0)] if running[0] else [])
monkeypatch.setattr(native, 'prepare_probe_library', lambda *a: library_path)
monkeypatch.setattr(native, 'validate_probe_readd', lambda *a: library_path)
class Disconnected(RuntimeError):
hresult = -2147220995
def editor(*a, **k): raise Disconnected('controlled native failure')
monkeypatch.setattr(native, '_probe_add_dialog', editor)
monkeypatch.setattr(native, '_wait_native_exit', lambda pids: True)
result = native._catalog_native({'operation': operation, 'desktop': 'CbbManagement_test',
'library': str(library_path), 'mentor_home': str(tmp_path), 'probe_token': 'fixture'}, root)
assert events[:2] == (['dispatch', 'library-close'] if operation == 'catalog' else ['uia-loaded', 'dispatch'])
if operation == 'catalog':
assert result['success'] and 'uia-loaded' not in events
else:
assert result['exception']['hresult'] == -2147220995
assert result['exception']['args'] == ['controlled native failure']
def test_probe_converts_desktop_pyhandle_before_uia_boundary(tmp_path, monkeypatch):
import sys, win32gui, win32process
import cbb_refresh_verify.native_management as native
import cbb_refresh_verify.management as management
import cbb_refresh_verify.backup_recovery as recovery
source = tmp_path/'source/Block.prj'
pcb = source.parent/'PCB/Block.pcb'
root = tmp_path/'native-add'; root.mkdir()
class Handle:
def __int__(self): return 200
handle = Handle()
desktop = SimpleNamespace(EnumDesktopWindows=lambda: [handle])
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda hwnd: (1, 9))
monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda hwnd: True)
monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: 'Reusable Blocks')
monkeypatch.setattr(management, 'source_project', lambda *a: (source, pcb, 'Block'))
monkeypatch.setattr(recovery, '_align_library', lambda *a: None)
class Desktop:
def __init__(self, **kwargs): pass
def window(self, *, handle):
assert type(handle) is int and handle == 200
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',
'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)
+152
View File
@@ -0,0 +1,152 @@
"""Run the real management engine with only the native/export boundaries faked."""
from dataclasses import replace
import json
from pathlib import Path
import shutil
import pytest
@pytest.fixture
def transaction(tmp_path, monkeypatch):
from test_management import project
import cbb_refresh_verify.native_management as native
import cbb_refresh_verify.native_engineering_identity as identity
import cbb_refresh_verify.backup_recovery as recovery
from cbb_refresh_verify.management import ManagementRequest, engineering_identity, _write_json
from cbb_refresh_verify.management_transaction import validate_transaction
root = tmp_path/'probe'
library = root/'native-add/fixture/mentor_lib.lmc'
library.parent.mkdir(parents=True); library.write_bytes(b'fixture library')
(root/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': 'owned'}), encoding='utf-8')
source = project(tmp_path/'source')
for path in (source, source.parent/'PCB/pcb.prj'):
with path.open('a') as stream: stream.write(f'KEY CentralLibrary "{library}"\n')
state = {'entries': [], 'calls': [], 'corrupt': False, 'fail_add': False}
monkeypatch.setattr(native.NativeManagementAdapter, '_binary_capability', lambda _: '')
monkeypatch.setattr(identity, 'check_exporters', lambda _: None)
monkeypatch.setattr(recovery, '_idle_check', lambda *_: None)
def capture(source, evidence, *, expected_library, **kwargs):
evidence = Path(evidence); evidence.mkdir(parents=True, exist_ok=False)
value = identity.asset_identity(source, expected_library)
value.update(ascii_sha256='logical', csv={'work/identity': 'tables'}, edif_sha256='geometry')
_write_json(evidence/'identity.json', {'identity': value, 'safe_to_continue': True})
return identity.IdentityOutcome(value, True, 'file-only export proof', evidence)
monkeypatch.setattr(identity, 'capture_identity', capture)
def worker(adapter, job, evidence):
evidence = Path(evidence); evidence.mkdir(parents=True, exist_ok=False)
state['calls'].append(job['operation'])
if job['operation'] == 'catalog':
return {'success': True, 'safe_to_continue': True, 'library': str(library), 'flow': 1,
'entries': list(state['entries'])}
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') == 'source':
(Path(job['source']).parent/'database/icdb.dat').write_bytes(b'changed staged input')
validate_transaction(job, evidence.parent)
if state['fail_add']: return {'success': False, 'safe_to_continue': True, 'detail': 'native failure'}
staged = Path(job['source'])
(staged.parent/'database/icdb.dat').write_bytes(b'native database normalization')
work = library.parent/'ReusableBlocksLP'/job['name']/'Work'
shutil.copytree(staged.parent, work)
pcb_project = work/'PCB/pcb.prj'
text = pcb_project.read_text()
import re
pcb_project.write_text(re.sub(r'KEY CentralLibrary "[^"]*"', 'KEY CentralLibrary "wrong-relative.lmc"', text))
if state['corrupt'] == 'unknown_cdbsvr':
unknown = work/'database/cdbsvr/persistent.dat'; unknown.parent.mkdir(parents=True, exist_ok=True)
unknown.write_bytes(b'unexpected engineering content')
elif state['corrupt']: (work/'PCB/Layout/LayoutDB.lyt').write_bytes(b'wrong physical design')
state['entries'] = [{'name': job['name'], 'partition': job['partition'],
'engineering_identity': engineering_identity(work/staged.name)}]
return {'success': True, 'safe_to_continue': True, 'identity_matches': False}
if job['operation'] == 'remove':
state['entries'] = []
shutil.rmtree(library.parent/'ReusableBlocksLP'/job['name'])
return {'success': True, 'safe_to_continue': True}
pytest.fail('unexpected native operation')
monkeypatch.setattr(native.NativeManagementAdapter, '_worker', worker)
request = ManagementRequest('add', library, 'Block', source=source, auto_verify=False,
evidence_dir=tmp_path/'evidence')
yield root, request, state
from cbb_refresh_verify.library_lock import LibraryLock, _owners, _guard, blocker_path
with _guard:
owner = _owners.pop(LibraryLock(library).key, None)
if owner: owner['handle'].Close()
blocker_path(library).unlink(missing_ok=True)
def execute(root, request):
from cbb_refresh_verify.native_management import run_owned_fixture_management
return run_owned_fixture_management(request, root, probe_token='owned', idle_check=lambda *_: None)
def test_owned_fixture_engine_add_conflict_update_remove_and_identity(transaction):
from cbb_refresh_verify.native_engineering_identity import project_library
root, request, state = transaction
original = request.source.read_bytes()
assert execute(root, request).status == 'UPLOADED'
registered = request.library.parent/'ReusableBlocksLP/Block/Work/Source.prj'
assert project_library(registered) == request.library.resolve()
calls = len(state['calls'])
assert execute(root, request).status == 'UPLOAD_FAILED'
assert state['calls'][calls:] == ['catalog']
(request.source.parent/'PCB/Layout/LayoutDB.lyt').write_bytes(b'replacement physical design')
assert execute(root, replace(request, operation='update')).status == 'UPLOADED'
assert (registered.parent/'PCB/Layout/LayoutDB.lyt').read_bytes() == b'replacement physical design'
assert execute(root, replace(request, operation='remove', source=None)).status == 'REMOVED'
assert execute(root, request).status == 'UPLOADED'
assert request.source.read_bytes() == original
@pytest.mark.parametrize('corrupt', [True, 'unknown_cdbsvr'])
def test_native_registered_but_asset_mismatch_retains_recovery(transaction, corrupt):
root, request, state = transaction
state['corrupt'] = corrupt
result = execute(root, request)
assert result.status == 'RECOVERY_REQUIRED' and not result.safe_to_continue
def test_update_readd_failure_preserves_snapshot_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 'removed' in [entry['stage'] for entry in json.loads(result.evidence_path.read_text())['history']]
def test_fixture_grant_cannot_authorize_arbitrary_library(transaction, tmp_path):
from cbb_refresh_verify.native_management import run_owned_fixture_management
root, request, state = transaction
other = tmp_path/'production.lmc'; other.write_bytes(b'unchanged')
with pytest.raises(ValueError):
run_owned_fixture_management(replace(request, library=other), root, probe_token='owned')
assert other.read_bytes() == b'unchanged' and not state['calls']
@pytest.mark.parametrize('tamper', ['nonce', 'supervisor', 'backup', 'source'])
def test_worker_rejects_modified_management_authority_before_add(transaction, tamper):
root, request, state = transaction
state['tamper'] = tamper
original = request.source.read_bytes()
result = execute(root, request)
assert result.status == 'RECOVERY_REQUIRED' and not result.safe_to_continue
assert state['entries'] == [] and request.source.read_bytes() == original
def test_long_staged_runtime_path_blocks_update_before_native_remove(transaction):
root, request, state = transaction
assert execute(root, request).status == 'UPLOADED'
runtime = request.source.parent/'CES/LogFiles'/('long-'+'x'*100)/('y'*60+'.log')
runtime.parent.mkdir(parents=True); runtime.write_bytes(b'complete original runtime history')
before = len(state['calls'])
result = execute(root, replace(request, operation='update'))
assert result.status == 'UPLOAD_FAILED' and result.safe_to_continue
assert 'NATIVE_PATH_TOO_LONG' in result.detail
assert state['calls'][before:] == ['catalog']
assert len(state['entries']) == 1 and runtime.read_bytes() == b'complete original runtime history'
+189
View File
@@ -0,0 +1,189 @@
"""Exercise actual guards/snapshots; only the native worker transport is fake."""
from dataclasses import asdict
import json
from pathlib import Path
import pytest
@pytest.fixture(autouse=True)
def prohibit_native_launch(monkeypatch):
"""Backstop independent of the boundary under development: no live apps."""
import subprocess, win32process, win32com.client
import cbb_refresh_verify.desktop_worker as desktop
def forbidden(*a, **k):
raise AssertionError('Native/process launch is forbidden in probe-guard tests')
monkeypatch.setattr(desktop, 'DesktopWorker', forbidden)
monkeypatch.setattr(win32process, 'CreateProcess', forbidden)
monkeypatch.setattr(subprocess, 'Popen', forbidden)
monkeypatch.setattr(win32com.client, 'Dispatch', forbidden)
monkeypatch.setattr(win32com.client, 'DispatchEx', forbidden)
@pytest.fixture
def probe_files(tmp_path):
def source(root, data):
(root/'database').mkdir(parents=True)
(root/'database/icdb.dat').write_bytes(data)
(root/'PCB/Layout').mkdir(parents=True)
(root/'PCB/Layout/LayoutDB.lyt').write_bytes(data)
(root/'PCB/pcb.prj').write_text('KEY CentralLibrary "old.lmc"\n')
(root/'PCB/Block.pcb').write_text('KEY ProjectFile "../Block.prj"\n')
project = root/'Block.prj'
project.write_text('KEY RootBlock "Block"\nKEY iCDBDir "database"\nKEY PCBDesignPath "PCB/Block.pcb"\n')
return project
original = source(tmp_path/'original', b'original')
replacement = source(tmp_path/'replacement', b'replacement')
root = tmp_path/'probe'
yield original, replacement, root
# Only file fakes ran; close this test's deliberately retained OS handle.
import cbb_refresh_verify.library_lock as locks
library = root/'native-add/fixture/mentor_lib.lmc'
with locks._guard:
owner = locks._owners.pop(locks._key(library.with_name('.mentor_lib.cbb-upload.lock')), None)
if owner:
owner['handle'].Close()
@pytest.mark.parametrize('fault', ['create_unsafe', 'first_catalog_exception', 'remove_unsafe',
'remove_exception', 'after_remove_exception', 'readd_unsafe', 'readd_exception', 'final_catalog_exception'])
def test_isolated_probe_retains_guard_on_uncertain_native_lifecycle(probe_files, monkeypatch, fault):
import cbb_refresh_verify.native_management as native
import cbb_refresh_verify.library_lock as locks
from cbb_refresh_verify.management import Capability, CatalogEntry, engineering_identity
original, replacement, root = probe_files
records = []
monkeypatch.setattr(native.NativeManagementAdapter, 'capabilities', lambda self:
{'remove': Capability(True, 'file transport fixture')})
def launch(self, job, evidence):
nonlocal records
evidence = Path(evidence)
operation = job['operation']
library = Path(job['library'])
if operation == 'probe_create_add':
# Directory creation belongs to the real supervising adapter.
assert native.prepare_probe_library(job, evidence) == library
library.write_bytes(b'native-created fixture')
(root/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': job['probe_token']}))
records = [CatalogEntry(job['name'], 'Logical-Physical', engineering_identity(job['source']))]
if fault == 'create_unsafe':
return {'success': False, 'safe_to_continue': False, 'detail': 'creation owner retained'}
elif operation == 'remove':
if fault == 'remove_exception':
raise TimeoutError('native removal transport disconnected')
if fault == 'remove_unsafe':
return {'success': False, 'safe_to_continue': False, 'detail': 'removal owner retained'}
records = []
elif operation == 'probe_readd':
if fault == 'readd_exception':
raise TimeoutError('native readd transport disconnected')
if fault == 'readd_unsafe':
return {'success': False, 'safe_to_continue': False, 'detail': 'readd owner retained'}
records = [CatalogEntry(job['name'], 'Logical-Physical', engineering_identity(job['source']))]
elif operation == 'catalog':
stage_fault = {'reopen': 'first_catalog_exception', 'after-remove': 'after_remove_exception',
'reopen-update': 'final_catalog_exception'}.get(evidence.name)
if stage_fault == fault:
raise TimeoutError('catalog owner release unknown')
return {'success': True, 'safe_to_continue': True, 'library': str(library), 'flow': 1,
'entries': [asdict(entry) for entry in records], 'detail': 'file fixture result'}
class Worker:
def __init__(self, command, desktop):
request = Path(command[-1])
job = json.loads(request.read_text(encoding='utf-8'))
result = launch(None, job, request.parent)
(request.parent/'result.json').write_text(json.dumps(result), encoding='utf-8')
def poll(self): return 0
def close(self): pass
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker)
try:
native.run_isolated_probe(original, root, 'Block', replacement_source=replacement)
except TimeoutError:
pass
library = root/'native-add/fixture/mentor_lib.lmc'
assert locks.has_blocker(library)
with pytest.raises(locks.LibraryBusy):
with locks.LibraryLock(library): pass
assert (root/'probe-result.json').is_file()
from contextlib import contextmanager
@contextmanager
def denied(*a):
raise locks.LibraryBusy('fresh proof still sees a native owner')
yield
monkeypatch.setattr(locks, '_prove_library_released', denied)
with pytest.raises(locks.LibraryBusy):
locks.release_retained_library(library, root/'release-checks')
assert locks.has_blocker(library)
@contextmanager
def released(*a):
yield {'native_owners': [], 'addresses': [], 'exclusive_files': [str(library)]}
monkeypatch.setattr(locks, '_prove_library_released', released)
assert locks.release_retained_library(library, root/'release-checks')['status'] == 'RELEASE_CONFIRMED'
with locks.LibraryLock(library): pass
def test_mapping_context_is_serialized_and_restored_before_catalog(tmp_path, monkeypatch):
import cbb_refresh_verify.native_management as native
import cbb_refresh_verify.network_path as network
captured = []
class Worker:
def __init__(self, command, desktop):
request = Path(command[-1])
job = json.loads(request.read_text(encoding='utf-8'))
captured.append(job)
(request.parent/'result.json').write_text(json.dumps({'success': True, 'safe_to_continue': True,
'library': job['library'], 'flow': 1, 'entries': []}), encoding='utf-8')
def poll(self): return 0
def close(self): pass
adapter = native.NativeManagementAdapter(worker_factory=Worker)
adapter.bind_library_mapping('S:', r'\\server\share')
library = Path('S:/library/mentor.lmc')
adapter.catalog(library, tmp_path/'catalog')
assert captured[0]['library'] == str(library)
assert captured[0]['mapped_drive'] == 'S:'
order = []
monkeypatch.setattr(native, '_current_desktop', lambda: (None, captured[0]['desktop']))
monkeypatch.setattr(network, 'ensure_mapped_drive_visible', lambda drive, remote:
order.append(('mapping', drive, remote)))
monkeypatch.setattr(native, '_catalog_native', lambda job, root:
(order.append(('catalog', job['library'])) or {'success': True, 'safe_to_continue': True}))
assert native.management_worker_main(tmp_path/'catalog/request.json') == 0
assert order == [('mapping', 'S:', r'\\server\share'), ('catalog', str(library))]
def test_removal_cli_keeps_mapped_drive_spelling(tmp_path, monkeypatch):
import cbb_refresh_verify.native_management as native
from cbb_refresh_verify.management import Capability
job = {'operation': 'remove', 'library': 'S:\\library\\mentor.lmc', 'name': 'Block',
'partition': 'Logical-Physical', 'desktop': 'CbbManagement_fixture',
'mentor_home': str(tmp_path), 'timeout_seconds': 10}
request = tmp_path/'request.json'; request.write_text(json.dumps(job), encoding='utf-8')
monkeypatch.setattr(native, '_current_desktop', lambda: (None, job['desktop']))
monkeypatch.setattr(native.NativeManagementAdapter, 'capabilities', lambda self: {'remove': Capability(True, 'fake transport')})
commands = []
class Process:
pid = 1234
def __init__(self, command, *, stdout, **kwargs):
commands.append(command)
stdout.write(b"# Note: Removed REUSE_BLOCK 'Block' from partition 'Logical-Physical'.\n")
stdout.flush()
def wait(self, **kwargs): return 0
monkeypatch.setattr(native.subprocess, 'Popen', Process)
assert native.management_worker_main(request) == 0
assert commands[0][1] == job['library']
def test_staged_project_alignment_keeps_selected_mapped_drive(tmp_path, monkeypatch):
from cbb_refresh_verify.backup_recovery import _align_library
project = tmp_path/'Block.prj'
project.write_text('KEY CentralLibrary "old.lmc"\n', encoding='utf-8')
pcb = tmp_path/'PCB/Block.pcb'; pcb.parent.mkdir(); pcb.touch()
pcb_project = pcb.parent/'pcb.prj'
pcb_project.write_text('KEY CentralLibrary "old.lmc"\n', encoding='utf-8')
library = Path('S:/library/mentor.lmc')
original_resolve = Path.resolve
monkeypatch.setattr(Path, 'resolve', lambda path, *a, **k:
Path(r'\\server\share\library\mentor.lmc') if path == library else original_resolve(path, *a, **k))
_align_library(project, pcb, library)
for path in (project, pcb_project):
assert 'KEY CentralLibrary "S:\\library\\mentor.lmc"' in path.read_text(encoding='utf-8')
+58
View File
@@ -0,0 +1,58 @@
"""Real EE7.9.5 PRJ shape: PCB pcb.prj may use LayoutDB without iCDBDir."""
import pytest
from cbb_refresh_verify.management import source_project, engineering_identity
@pytest.fixture
def healthy_source(tmp_path):
(tmp_path/'database').mkdir()
(tmp_path/'database/icdb.dat').write_bytes(b'schematic database')
(tmp_path/'PCB/Layout').mkdir(parents=True)
(tmp_path/'PCB/Layout/LayoutDB.lyt').write_bytes(b'layout database')
source = tmp_path/'IP101GR.prj'
source.write_text('KEY RootBlock "IP101GR"\nKEY FlowType "DX"\n'
'KEY iCDBDir ".\\database"\nKEY PCBDesignPath "PCB\\IP101GR.pcb"\n', encoding='utf-8')
(tmp_path/'PCB/IP101GR.pcb').write_text('KEY ProjectFile "..\\IP101GR.prj"\n', encoding='utf-8')
(tmp_path/'PCB/pcb.prj').write_text('SECTION Project\nKEY CentralLibrary "old.lmc"\nENDSECTION\n', encoding='utf-8')
return source
def test_layout_based_pcb_without_independent_icdb_directory_is_complete(healthy_source):
source, pcb, top = source_project(healthy_source)
assert source == healthy_source
assert pcb == healthy_source.parent/'PCB/IP101GR.pcb'
assert top == 'IP101GR'
assert engineering_identity(source)['top_level_block'] == 'IP101GR'
@pytest.mark.parametrize('missing', ['database/icdb.dat', 'PCB/Layout/LayoutDB.lyt', 'PCB/pcb.prj'])
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_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')
with pytest.raises(ValueError, match='iCDBDir'):
source_project(healthy_source)
@pytest.mark.parametrize('declared', [
'KEY iCDBDir "missing"\n',
'KEY iCDBDir "..\\..\\outside"\n',
'KEY iCDBDir "C:\\external"\n',
'KEY iCDBDir ""\n',
'KEY iCDBDir "..\\database"\nKEY iCDBDir "..\\database"\n',
])
def test_explicit_pcb_icdb_reference_must_be_unique_contained_and_exist(healthy_source, declared):
(healthy_source.parent/'PCB/pcb.prj').write_text(declared, encoding='utf-8')
with pytest.raises(ValueError):
source_project(healthy_source)
def test_valid_explicit_pcb_icdb_directory_remains_supported(healthy_source):
(healthy_source.parent/'PCB/pcb.prj').write_text('KEY iCDBDir "..\\database"\n', encoding='utf-8')
assert source_project(healthy_source)[0] == healthy_source
+102
View File
@@ -0,0 +1,102 @@
from dataclasses import replace
from pathlib import Path
from types import SimpleNamespace
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QMessageBox
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
def test_management_can_select_ready_and_capability_disabled_explanation(qtbot, tmp_path, monkeypatch):
from cbb_refresh_verify.management import Capability
from cbb_refresh_verify.ui.main_window import MainWindow
caps = {name: Capability(name == 'remove', name + ' not validated') for name in ('add', 'update', 'remove')}
window = MainWindow(reader=lambda _: LibraryReadResult((CbbRecord('Ready', 'Logical-Physical', status='READY'),)),
data_root=tmp_path, management_adapter=SimpleNamespace(capabilities=lambda: caps))
qtbot.addWidget(window)
window.lmc_edit.setText('library.lmc'); window.load_library()
qtbot.waitUntil(lambda: not window.busy)
window.select_visible_button.click()
assert window.remove_button.isEnabled()
assert not window.add_button.isEnabled() and not window.update_button.isEnabled()
assert 'not validated' in window.management_capability_label.text()
assert not window.selected_batch_button.isEnabled()
window.remove_button.click()
assert window.management_dialog.requests()[0].name == 'Ready'
assert window.management_dialog.requests()[0].partition == 'Logical-Physical'
window.management_dialog.reject()
def test_management_dialog_preview_confirmation_and_result_status(qtbot, tmp_path, monkeypatch):
from cbb_refresh_verify.management import ManagementRequest, ManagementResult
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
requests = [ManagementRequest('remove', tmp_path/'lib.lmc', 'Block', evidence_dir=tmp_path/'out')]
calls, confirmations = [], []
def runner(items, **_):
calls.extend(items)
return [ManagementResult('remove', items[0].library, 'Block', 'Logical-Physical', None,
False, 'complete', 'REMOVED', True, 'removed', tmp_path/'checkpoint.json')]
dialog = ManagementDialog(requests, runner=runner)
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]
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
dialog.execute_button.click()
qtbot.waitUntil(lambda: not dialog.busy)
assert len(calls) == 1 and '已移除' in dialog.status_label.text()
assert str(tmp_path/'checkpoint.json') in dialog.output.toPlainText()
assert not dialog.execute_button.isEnabled()
def test_add_dialog_default_auto_verify_and_source_identity_rows(qtbot, tmp_path):
from cbb_refresh_verify.management import ManagementRequest
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
dialog = ManagementDialog([ManagementRequest('add', tmp_path/'lib.lmc', '', evidence_dir=tmp_path/'out')])
qtbot.addWidget(dialog)
dialog.add_sources([tmp_path/'One.prj', tmp_path/'Two.prj'])
requests = dialog.requests()
assert [r.name for r in requests] == ['One', 'Two']
assert all(r.auto_verify and r.source.suffix == '.prj' for r in requests)
dialog.auto_verify.setChecked(False)
assert not any(r.auto_verify for r in dialog.requests())
dialog._progress({'stage': 'prepare_identity', 'block': 'One'})
assert '正在核对来源工程内容' in dialog.status_label.text()
assert 'prepare_identity' not in dialog.status_label.text()
def test_restart_shows_unfinished_without_starting_worker(qtbot, tmp_path):
import json
from cbb_refresh_verify.management import Capability
from cbb_refresh_verify.ui.main_window import MainWindow
checkpoint = tmp_path/'management/interrupted/checkpoint.json'
checkpoint.parent.mkdir(parents=True)
checkpoint.write_text(json.dumps({'status': 'RUNNING', 'stage': 'native_remove', 'name': 'Block'}), encoding='utf-8')
adapter = SimpleNamespace(capabilities=lambda: {n: Capability(False, 'disabled') for n in ('add', 'update', 'remove')})
window = MainWindow(data_root=tmp_path, management_adapter=adapter)
qtbot.addWidget(window)
assert '未完成' in window.unfinished_label.text() and not window.busy
assert 'Block' in window.output.toPlainText()
def test_persistent_owner_blocker_prevents_native_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')
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.release_library_button.isEnabled()
assert '释放检查' in window.status_label.text()
calls = []
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
monkeypatch.setattr(locks, 'release_retained_library', lambda *a:
(calls.append(a) or {'status': 'RELEASE_CONFIRMED', 'evidence_path': 'proof.json'}))
window.release_library_button.click()
qtbot.waitUntil(lambda: not window.busy)
assert len(calls) == 1 and 'proof.json' in window.output.toPlainText()
+109
View File
@@ -0,0 +1,109 @@
"""File-only native failure and legacy path-boundary checks."""
from pathlib import Path
import pytest
ERROR = b'REUSE BLOCK: INFORMATION: Block\tError! Cannot copy iCDB base of Reusable Block project.\r\n'
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()
log = tmp_path/'LogFiles/ReuseBlockLogLO.txt'; log.parent.mkdir(); log.write_bytes(ERROR)
baseline = snapshot_add_log(library)
assert fresh_add_failure(baseline, 'Block') is None
with log.open('ab') as stream: stream.write(ERROR.replace(b'Block\t', b'Other\t'))
assert fresh_add_failure(baseline, 'Block') is None
with log.open('ab') as stream: stream.write(ERROR)
assert 'Cannot copy iCDB base' in fresh_add_failure(baseline, 'Block')
# A replaced/rotated prefix is not evidence that an old error is new.
log.write_bytes(b'replaced\n'+ERROR)
assert fresh_add_failure(baseline, 'Block') is None
def test_newly_created_failure_log_is_current_round_evidence(tmp_path):
from cbb_refresh_verify.native_add_failures import snapshot_add_log, fresh_add_failure
library = tmp_path/'lib.lmc'
baseline = snapshot_add_log(library)
log = tmp_path/'LogFiles/ReuseBlockLogLO.txt'; log.parent.mkdir(); log.write_bytes(ERROR)
assert fresh_add_failure(baseline, 'Block')
@pytest.mark.parametrize('change', ['none', 'title', 'question', 'button_id', 'button_text', 'disabled', 'extra_button'])
def test_only_observed_path_error_dialog_can_be_acknowledged(change):
from cbb_refresh_verify.native_add_failures import failure_ack_button
title, text = 'Library Manager', '\n系统找不到指定的路径。\r\n'
buttons = [{'hwnd': 123, 'id': 2, 'class': 'Button', 'text': '确定', 'enabled': True}]
if change == 'title': title = 'Unrelated'
if change == 'question': text += '是否继续?'
if change == 'button_id': buttons[0]['id'] = 1
if change == 'button_text': buttons[0]['text'] = '是'
if change == 'disabled': buttons[0]['enabled'] = False
if change == 'extra_button': buttons.append({**buttons[0], 'hwnd': 456})
assert failure_ack_button(title, text, buttons) == (123 if change == 'none' else None)
def test_native_path_guard_includes_runtime_files_and_projected_target(tmp_path):
from cbb_refresh_verify.native_add_failures import validate_native_copy_paths
source = tmp_path/'source/Block.prj'; source.parent.mkdir(); source.touch()
validate_native_copy_paths(source, tmp_path/'library/lib.lmc', 'Block')
runtime = source.parent/'CES/LogFiles'/('x'*120)/('y'*90+'.log')
runtime.parent.mkdir(parents=True); runtime.touch()
with pytest.raises(ValueError, match='NATIVE_PATH_TOO_LONG'):
validate_native_copy_paths(source, tmp_path/'library/lib.lmc', 'Block')
assert runtime.exists()
runtime.unlink()
# Even a short staged tree can exceed the legacy limit at its target.
target = tmp_path/('library-'+'x'*150)/'lib.lmc'
with pytest.raises(ValueError, match='目标'):
validate_native_copy_paths(source, target, 'Block')
@pytest.mark.parametrize('kind', ['known', 'unknown', 'foreign'])
def test_failure_observer_only_acknowledges_owned_known_dialog(tmp_path, monkeypatch, kind):
import json
from types import SimpleNamespace
import win32gui, win32process
from cbb_refresh_verify.native_add_failures import observe_add_failure, snapshot_add_log
state = {'open': True, 'clicks': []}
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda _: (1, 999 if kind == 'foreign' else 123))
monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda _: True)
monkeypatch.setattr(win32gui, 'GetClassName', lambda h: {1: '#32770', 10: 'Button', 11: 'Static'}[h])
monkeypatch.setattr(win32gui, 'GetWindowText', lambda h: {1: 'Library Manager', 10: '确定',
11: '系统找不到指定的路径。' if kind == 'known' else '未确认的原生提示'}[h])
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda h, callback, p: [callback(c, p) for c in [10, 11]])
monkeypatch.setattr(win32gui, 'GetDlgCtrlID', lambda h: 2 if h == 10 else 0)
monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda _: True)
monkeypatch.setattr(win32gui, 'IsWindow', lambda _: state['open'])
def post(hwnd, message, *_):
state['clicks'].append(hwnd); state['open'] = False
monkeypatch.setattr(win32gui, 'PostMessage', post)
monkeypatch.setattr(win32gui, 'SetForegroundWindow', lambda *_: pytest.fail('foreground input is forbidden'))
args = (SimpleNamespace(EnumDesktopWindows=lambda: [1]), {123}, tmp_path,
snapshot_add_log(tmp_path/'lib.lmc'), 'Block', {})
if kind == 'known':
with pytest.raises(RuntimeError, match='NATIVE_ADD_FAILED'): observe_add_failure(*args)
result = json.loads((tmp_path/'native-add-output.json').read_text(encoding='utf-8'))
assert result['success_message'] is None and result['failure']['acknowledged']
assert state['clicks'] == [10]
else:
observe_add_failure(*args)
assert not state['clicks'] and not (tmp_path/'native-add-output.json').exists()
assert (tmp_path/'native-add-dialogs.jsonl').exists() is (kind == 'unknown')
def test_path_rejection_returns_safe_before_any_native_identity_or_alignment(tmp_path, monkeypatch):
from cbb_refresh_verify.management import Capability, ManagementRequest
from cbb_refresh_verify.native_management import NativeManagementAdapter
import cbb_refresh_verify.management_transaction as authority
source = tmp_path/'source/Block.prj'; source.parent.mkdir(); source.touch()
runtime = source.parent/('x'*150)/('y'*100+'.log')
runtime.parent.mkdir(); runtime.write_bytes(b'preserved history')
adapter = NativeManagementAdapter(mentor_home=tmp_path)
monkeypatch.setattr(adapter, 'capabilities', lambda: {'add': Capability(True, 'test boundary')})
monkeypatch.setattr(authority, 'current_lease', lambda _: pytest.fail('long path reached native transaction setup'))
request = ManagementRequest('update', tmp_path/'lib.lmc', 'Block', source=source)
staged, result = adapter.prepare_add_transaction(request, tmp_path/'evidence', original_source=source)
assert staged == request and result.identity is None and result.safe_to_continue
assert 'NATIVE_PATH_TOO_LONG' in result.detail and runtime.read_bytes() == b'preserved history'
+201
View File
@@ -0,0 +1,201 @@
"""Native export and asset identity boundaries; never launch native tools."""
from pathlib import Path
import pytest
def ascii_report(date=b'Tue Nov 03 11:19:39 2026', directory=b'C:\\copy\\database'):
return (b'iCDB Ascii Report Generation Date: '+date+b'\r\n\r\n\r\n\tReport Criteria:\r\n'
b'\t iCDB directory: '+directory+b'\r\n\t DATE: '+date+b'\r\n\r\n'
b'\t REPORT FORMAT: FREEFORM\r\n\t MODE: HIER AND FLAT BLOCKS\r\n'
b'\t CONNECTION LISTS: ON\r\n\t TEXT LISTS: ON\r\n\r\n'
b'Block Top \tRoot\r\n\tPort A\r\nConfig default\tview none\r\n\tPin A\r\n')
def test_ascii_only_normalizes_three_validated_header_values():
from cbb_refresh_verify.native_engineering_identity import normalize_ascii
first = ascii_report()
changed = ascii_report(b'Wed Nov 04 12:00:00 2026', b'D:\\other\\database')
assert normalize_ascii(first, 'Top') == normalize_ascii(changed, 'Top')
assert normalize_ascii(first, 'Top') != normalize_ascii(first.replace(b'Port A', b'Port B'), 'Top')
body = b'\tiCDB Ascii Report Generation Date: design property\r\n'
assert normalize_ascii(first+body, 'Top') != normalize_ascii(first+body.replace(b'property', b'value'), 'Top')
@pytest.mark.parametrize('change', ['empty', 'wrong_root', 'missing_config', 'header_duplicate', 'wrong_mode'])
def test_ascii_rejects_missing_or_unrecognized_structure(change):
from cbb_refresh_verify.native_engineering_identity import normalize_ascii
data = ascii_report()
data = {'empty': b'', 'wrong_root': data.replace(b'Block Top ', b'Block Other '),
'missing_config': data.replace(b'Config default', b'Partial default'),
'header_duplicate': data.replace(b'\tReport Criteria:', b'\t DATE: extra'),
'wrong_mode': data.replace(b'HIER AND FLAT BLOCKS', b'FLAT ONLY')}[change]
with pytest.raises(ValueError): normalize_ascii(data, 'Top')
def test_inf_only_normalizes_unique_timestamp_column():
from cbb_refresh_verify.native_engineering_identity import normalize_inf, INF_HEADER
row = [b'identity', b'Design Capture', b'VB99.0', b'11/03/26 11:21:34']+[b'value']*12
first = INF_HEADER+b'\r\n'+b'\t'.join(row)+b'\r\n'
assert normalize_inf(first) == normalize_inf(first.replace(b'11:21:34', b'11:21:37'))
assert normalize_inf(first) != normalize_inf(first.replace(b'value', b'changed', 1))
with pytest.raises(ValueError): normalize_inf(first.replace(b'System_Date', b'Unknown'))
with pytest.raises(ValueError): normalize_inf(first+b'extra row\r\n')
@pytest.fixture
def project(tmp_path):
from test_management import project
source = project(tmp_path/'project', name='Source')
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.write_bytes(b'library')
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')
return source, library
def test_assets_require_correct_library_references_and_unknown_bytes(project):
from cbb_refresh_verify.native_engineering_identity import asset_identity
source, library = project
before = asset_identity(source, library)
runtime = source.parent/'database/cdbsvr/events/events.dat'
runtime.parent.mkdir(parents=True); runtime.write_bytes(b'runtime')
(source.parent/'database/icdb.dat').write_bytes(b'native normalized database')
assert asset_identity(source, library) == before
unknown = source.parent/'unknown-engineering.bin'; unknown.write_bytes(b'engineering')
assert asset_identity(source, library) != before
unknown.unlink()
(source.parent/'PCB/Layout/LayoutDB.lyt').write_bytes(b'changed physical design')
assert asset_identity(source, library) != before
text = (source.parent/'PCB/pcb.prj').read_text()
(source.parent/'PCB/pcb.prj').write_text(text.replace(str(library), 'missing.lmc'))
with pytest.raises(ValueError, match='CentralLibrary'):
asset_identity(source, library)
@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'])
def test_unknown_cdbsvr_assets_remain_part_of_identity(project, relative):
from cbb_refresh_verify.native_engineering_identity import asset_identity
source, library = project
baseline = asset_identity(source, library)
unknown = source.parent/relative; unknown.parent.mkdir(parents=True, exist_ok=True)
unknown.write_bytes(b'first engineering content')
added = asset_identity(source, library)
assert added != baseline
unknown.write_bytes(b'changed engineering content')
assert asset_identity(source, library) != added
unknown.unlink()
assert asset_identity(source, library) == baseline
def test_observed_guid_and_events_runtime_does_not_change_identity(project):
from cbb_refresh_verify.native_engineering_identity import asset_identity
source, library = project
baseline = asset_identity(source, library)
for relative in ['database/cdbsvr/plog/2026.11.03.guid.48432.txt',
'database/cdbsvr/events/events.dat', 'database/cdbsvr/events/events.idx']:
path = source.parent/relative; path.parent.mkdir(parents=True, exist_ok=True); path.write_bytes(b'runtime')
assert asset_identity(source, library) == baseline
@pytest.mark.parametrize('failure', ['empty', 'missing_completion', 'error', 'exit'])
def test_export_evidence_requires_successful_complete_native_output(tmp_path, failure):
from cbb_refresh_verify.native_engineering_identity import validate_export_output
report = tmp_path/'design.rpt'; report.write_bytes(b'report')
log = tmp_path/'native.log'
log.write_text(f'Report generation complete, report file is {report}\n')
code = 0
if failure == 'empty': report.write_bytes(b'')
if failure == 'missing_completion': log.write_text('partial report\n')
if failure == 'error':
with log.open('a') as stream: stream.write('ERROR: database corrupt\n')
if failure == 'exit': code = 2
with pytest.raises(ValueError): validate_export_output('ascii', code, report, log)
def test_capture_only_exports_fresh_copy_and_leaves_source_unchanged(project, tmp_path, monkeypatch):
import cbb_refresh_verify.native_engineering_identity as identity
from cbb_refresh_verify.library_lock import LibraryLock
from cbb_refresh_verify.scoped_manifest import build_manifest
source, library = project
original = build_manifest(source.parent)
monkeypatch.setattr(identity, 'check_exporters', lambda _: None)
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
def exports(clone, root, *_):
assert clone.parent == root/'project' and clone != source
(clone.parent/'database/icdb.dat').write_bytes(b'export changed disposable copy')
(root/'design.rpt').write_bytes(ascii_report())
(root/'design.edf').write_bytes(edif_report())
(root/'export-launch.json').write_text('{"started": false}')
return {'success': True, 'safe_to_continue': True, 'detail': ''}
monkeypatch.setattr(identity, '_run_exports', exports)
monkeypatch.setattr(identity, 'csv_identity', lambda _: {'work/identity': 'csv proof'})
with LibraryLock(library):
result = identity.capture_identity(source, tmp_path/'analysis', expected_library=library,
owner_library=library, mentor_home=tmp_path)
assert result.identity['policy'] == identity.POLICY and result.safe_to_continue
assert build_manifest(source.parent) == original
def test_capture_unreleased_exporter_retains_caller_lease(project, tmp_path, monkeypatch):
import cbb_refresh_verify.native_engineering_identity as identity
from cbb_refresh_verify.library_lock import LibraryLock, LibraryBusy, blocker_path, _owners, _guard
source, library = project
monkeypatch.setattr(identity, 'check_exporters', lambda _: None)
monkeypatch.setattr(identity, '_run_exports', lambda *a: {
'success': False, 'safe_to_continue': False, 'detail': 'TIMEOUT: native exporter retained'})
lease = LibraryLock(library)
try:
with lease:
result = identity.capture_identity(source, tmp_path/'analysis', expected_library=library,
owner_library=library, mentor_home=tmp_path)
assert result.identity is None and not result.safe_to_continue
with pytest.raises(LibraryBusy):
with LibraryLock(library): pass
finally:
with _guard:
owner = _owners.pop(lease.key, None)
if owner: owner['handle'].Close()
blocker_path(library).unlink(missing_ok=True)
def test_export_timeout_retains_process_without_kill(project, tmp_path, monkeypatch):
import cbb_refresh_verify.native_engineering_identity as identity
source, _ = project
root = tmp_path/'exports'; root.mkdir()
seen = []
class Running:
pid = 987654
def __init__(self, command, **kwargs): seen.append(command)
def poll(self): return None
def kill(self): pytest.fail('native owner cannot be killed')
def terminate(self): pytest.fail('native owner cannot be terminated')
monkeypatch.setattr(identity, '_retained_exports', [])
monkeypatch.setattr(identity.subprocess, 'Popen', Running)
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
monkeypatch.setattr(identity, '_database_released', lambda _: True)
result = identity._run_exports(source, root, tmp_path, 0)
assert not result['safe_to_continue'] and 'TIMEOUT' in result['detail']
assert len(identity._retained_exports) == 1
assert seen[0][-5:] == ['-f', '-h', '-c', '-t', '-nostrip']
assert (root/'ascii-process.json').is_file()
def edif_report(timestamp=b'2026 11 3 11 40 56'):
return (b'(edif DxD (edifVersion 2 0 0) (status (written (timestamp '+timestamp+b')'
b' (program "DxDesigner Edif Exporter"))) (library Board1 (cell Top'
b' (view SCHEMATIC_VIEW (viewType SCHEMATIC) (page sheet1 (figure LINE (pt 1 2)))'
b' (property timestamp (string "2026 11 3 11 40 56")))))'
b' (design Board1 (cellRef Top (libraryRef Board1))))')
def test_edif_only_normalizes_root_written_timestamp_preserving_geometry_and_properties():
from cbb_refresh_verify.native_engineering_identity import normalize_edif
first = edif_report()
assert normalize_edif(first, 'Top') == normalize_edif(edif_report(b'2026 11 3 11 40 59'), 'Top')
assert normalize_edif(first, 'Top') != normalize_edif(first.replace(b'(pt 1 2)', b'(pt 1 3)'), 'Top')
assert normalize_edif(first, 'Top') != normalize_edif(first.replace(b'"2026 11 3 11 40 56"', b'"changed"'), 'Top')
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')
+118
View File
@@ -0,0 +1,118 @@
"""Fresh release/adoption proof for retained export copies; no native launch."""
from contextlib import contextmanager
import json
import os
from types import SimpleNamespace
import pytest
@pytest.fixture
def export_case(tmp_path, monkeypatch):
import cbb_refresh_verify.library_lock as locks
import cbb_refresh_verify.native_engineering_identity as identity
import win32com.client
monkeypatch.setattr(win32com.client, 'GetObject', lambda *_: SimpleNamespace(ExecQuery=lambda *_: []))
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
monkeypatch.setattr(identity, '_retained_exports', [])
monkeypatch.setattr(locks, '_supervisor_alive', lambda _: False)
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.write_bytes(b'original library')
root = tmp_path/'analysis'; (root/'project/database').mkdir(parents=True)
source = root/'project/Source.prj'; source.write_bytes(b'copied project')
(root/'project/database/icdb.dat').write_bytes(b'copied database')
lease = locks.LibraryLock(library, safe_to_release=lambda: False)
with lease:
from cbb_refresh_verify.native_export_guard import begin_export_analysis
token = begin_export_analysis(library, root, source)
(root/'ascii-process.json').write_text(json.dumps({'pid': 123456, 'observed_pids': [123456],
'command': ['icdb2ascii.exe'], 'safe_to_continue': False}))
yield library, root, token, lease
with locks._guard:
owner = locks._owners.pop(lease.key, None)
if owner: owner['handle'].Close()
locks.blocker_path(library).unlink(missing_ok=True)
@pytest.mark.parametrize('action', ['release', 'maintenance'])
@pytest.mark.parametrize('obstacle', ['active_exporter', 'active_child', 'copy_address', 'copy_exclusive', 'invalid_record', 'missing_copy'])
def test_release_and_takeover_cannot_bypass_export_copy(export_case, monkeypatch, tmp_path, action, obstacle):
import cbb_refresh_verify.library_lock as locks
import cbb_refresh_verify.native_engineering_identity as identity
import win32api, win32con, win32file
library, root, token, lease = export_case
handle = None
if obstacle == 'active_exporter':
# Restart case: no in-memory exporter, but a known native owner remains.
monkeypatch.setattr(identity, '_process_snapshot', lambda: [
{'pid': 123456, 'name': 'iCDBNetServer.exe', 'parent': 0, 'executable': 'native'}])
if obstacle == 'active_child':
handle = win32api.OpenProcess(win32con.SYNCHRONIZE, False, os.getpid())
monkeypatch.setattr(identity, '_retained_exports', [(SimpleNamespace(poll=lambda: 0), {os.getpid(): handle})])
if obstacle == 'copy_address':
address = root/'project/database/cdbsvr/sAddress.adr'; address.parent.mkdir(); address.write_bytes(b'copy owner')
if obstacle == 'copy_exclusive':
handle = win32file.CreateFile(str(root/'project/database/icdb.dat'), win32con.GENERIC_READ,
0, None, win32con.OPEN_EXISTING, 0, None)
if obstacle == 'invalid_record': (root/'export-owner.json').write_text('{invalid')
if obstacle == 'missing_copy': (root/'project/database/icdb.dat').unlink()
@contextmanager
def target_guard(): yield {'target': 'file-only maintenance proof'}
try:
marker = locks.blocker_path(library); before = marker.read_bytes()
with pytest.raises((ValueError, OSError)):
if action == 'release': locks.release_retained_library(library, tmp_path/'release')
else:
with locks.LibraryLock.for_maintenance(library, tmp_path/'takeover', target_guard,
safe_to_release=lambda: True): pass
assert marker.read_bytes() == before
assert lease.path.exists()
finally:
if handle: handle.Close()
@pytest.mark.parametrize('action', ['release', 'maintenance'])
def test_restarted_export_copy_can_release_only_after_fresh_proof(export_case, tmp_path, action):
import cbb_refresh_verify.library_lock as locks
library, root, token, lease = export_case
# Simulate interpreter exit: all process-local registries/lease handles lost.
with locks._guard: locks._owners.pop(lease.key)['handle'].Close()
@contextmanager
def target_guard(): yield {'target': 'file-only maintenance proof'}
if action == 'release':
assert locks.release_retained_library(library, tmp_path/'release')['status'] == 'RELEASE_CONFIRMED'
else:
with locks.LibraryLock.for_maintenance(library, tmp_path/'takeover', target_guard,
safe_to_release=lambda: True): pass
assert not locks.blocker_path(library).exists()
assert (root/'project/database/icdb.dat').read_bytes() == b'copied database'
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))
with pytest.raises(ValueError, match='MAINTENANCE_OWNER_ACTIVE'): assert_native_idle()
def test_successful_export_clears_only_its_bound_guard_after_fresh_copy_proof(tmp_path, monkeypatch):
import cbb_refresh_verify.library_lock as locks
import cbb_refresh_verify.native_engineering_identity as identity
from cbb_refresh_verify.native_export_guard import begin_export_analysis, finish_export_analysis
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
monkeypatch.setattr(identity, '_retained_exports', [])
monkeypatch.setattr(locks, '_supervisor_alive', lambda _: False)
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
root = tmp_path/'analysis'; (root/'project/database').mkdir(parents=True)
project = root/'project/Source.prj'; project.touch()
(project.parent/'database/icdb.dat').write_bytes(b'copied db')
with locks.LibraryLock(library):
token = begin_export_analysis(library, root, project)
marker = locks.blocker_path(library)
assert json.loads(marker.read_text())['export_analysis'][0]['token'] == token
(root/'export-launch.json').write_text('{"started": false}')
finish_export_analysis(library, token)
assert 'export_analysis' not in json.loads(marker.read_text())
assert not marker.exists()
+468
View File
@@ -0,0 +1,468 @@
import json
from pathlib import Path
from types import SimpleNamespace
import pytest
def test_installed_binary_mismatch_disables_removal(tmp_path):
from cbb_refresh_verify.native_management import NativeManagementAdapter
adapter = NativeManagementAdapter(mentor_home=tmp_path)
caps = adapter.capabilities()
assert not caps['remove'].supported and 'CleanWGLib' in caps['remove'].reason
assert not caps['add'].supported and not caps['update'].supported
def test_public_add_cannot_bypass_disabled_capability(tmp_path, monkeypatch):
import cbb_refresh_verify.native_management as native
from cbb_refresh_verify.management import ManagementRequest
adapter = native.NativeManagementAdapter(mentor_home=tmp_path)
monkeypatch.setattr(adapter, '_worker', lambda *a: pytest.fail('public disabled Add launched worker'))
monkeypatch.setattr(native, 'engineering_identity', lambda *a: pytest.fail('public disabled Add accessed source'))
result = adapter.add(ManagementRequest('add', tmp_path/'arbitrary.lmc', 'Block',
source=tmp_path/'source/original.prj'), tmp_path/'add')
assert not result.success and result.safe_to_continue
def test_empty_fixture_creation_uses_existing_new_library_guard_route(tmp_path, monkeypatch):
import cbb_refresh_verify.native_management as native
seen = []
monkeypatch.setattr(native.NativeManagementAdapter, '_binary_capability', lambda _: '')
monkeypatch.setattr(native.NativeManagementAdapter, '_worker',
lambda adapter, job, evidence: (seen.append((job, evidence)) or
{'success': True, 'safe_to_continue': True, 'entries': []}))
root = tmp_path/'fresh'
result = native.create_owned_fixture(root)
assert result['success'] and result['entries'] == []
assert seen[0][0]['operation'] == 'probe_create'
assert Path(seen[0][0]['library']) == root/'native-add/fixture/mentor_lib.lmc'
assert seen[0][0]['probe_token'] == result['probe_token']
existing = tmp_path/'existing'; existing.mkdir()
with pytest.raises(ValueError): native.create_owned_fixture(existing)
assert len(seen) == 1
def test_unprepared_add_rejected_before_native_activation(tmp_path, monkeypatch):
import cbb_refresh_verify.native_management as native
import win32com.client
monkeypatch.setattr(win32com.client, 'DispatchEx', lambda *a: pytest.fail('unprepared native activation'))
with pytest.raises(ValueError):
native._catalog_com({'operation': 'add', 'library': str(tmp_path/'arbitrary.lmc')}, tmp_path/'add')
def test_removed_marker_cannot_cross_carriage_return_record():
from cbb_refresh_verify.native_management import removal_output_ok
assert not removal_output_ok(0, "# Note: Removed unrelated\rrecord 'Block' from partition 'Logical-Physical'.",
'Block', 'Logical-Physical')
@pytest.mark.parametrize('invalid', ['', 'nonce', 'lease', 'source', 'backup', 'expired', 'token'])
def test_fixture_add_authority_requires_live_lease_and_fresh_staging(tmp_path, monkeypatch, invalid):
import cbb_refresh_verify.native_management as native
from cbb_refresh_verify.management import ManagementRequest
from cbb_refresh_verify.library_lock import LibraryLock
library = tmp_path/'native-add/fixture/mentor_lib.lmc'
library.parent.mkdir(parents=True); library.write_bytes(b'owned fixture')
source = tmp_path/'original/Source.prj'
source.parent.mkdir(); source.write_bytes(b'original source')
(tmp_path/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': 'owned'}), encoding='utf-8')
adapter = native.NativeManagementAdapter(mentor_home=tmp_path)
monkeypatch.setattr(adapter, 'route_capabilities', lambda: {'add': native.Capability(True, 'ready')})
monkeypatch.setattr(native, 'engineering_identity', lambda _: {'source': 'bytes'})
def launch(job, root):
staged = Path(job['source'])
assert staged == root/'source/Source.prj' and staged != source
prepared_path = root/'add-prepared.json'
prepared = json.loads(prepared_path.read_text(encoding='utf-8'))
if invalid == 'nonce': job['transaction_nonce'] = 'foreign'
if invalid == 'token': job['probe_token'] = 'foreign'
if invalid == 'lease': prepared['lease_id'] = 'foreign'
if invalid == 'source': job['source'] = str(source)
if invalid == 'backup': (root/'library-before/mentor_lib.lmc').write_bytes(b'changed')
if invalid == 'expired':
import cbb_refresh_verify.library_lock as locks
monkeypatch.setattr(locks, '_supervisor_alive', lambda _: False)
prepared_path.write_text(json.dumps(prepared), encoding='utf-8')
if invalid:
with pytest.raises(ValueError): native.validate_owned_fixture_add(job, root)
else:
assert native.validate_owned_fixture_add(job, root) == staged
assert source.read_bytes() == b'original source'
return {'success': not invalid, 'safe_to_continue': True, 'identity_matches': not invalid}
monkeypatch.setattr(adapter, '_launch_worker', launch)
with LibraryLock(library):
result = adapter.add_owned_fixture(ManagementRequest('add', library, 'Block', source=source),
tmp_path/'shared-add', probe_token='owned')
assert result.success is (not invalid)
def test_fixture_metadata_without_current_thread_lease_cannot_stage_source(tmp_path):
import cbb_refresh_verify.native_management as native
library = tmp_path/'native-add/fixture/mentor_lib.lmc'
library.parent.mkdir(parents=True); library.touch()
(tmp_path/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': 'owned'}), encoding='utf-8')
root = tmp_path/'add'; root.mkdir()
with pytest.raises(ValueError, match='current thread'):
native.prepare_owned_fixture_add({'library': str(library), 'probe_token': 'owned'}, root)
assert not (root/'source').exists()
@pytest.mark.parametrize('outcome', ['unsafe', 'exception', 'safe'])
def test_owned_fixture_retains_default_caller_lease_until_native_release(tmp_path, monkeypatch, outcome):
import cbb_refresh_verify.native_management as native
from cbb_refresh_verify.management import ManagementRequest
from cbb_refresh_verify.library_lock import LibraryLock, LibraryBusy, blocker_path, _owners, _guard
library = tmp_path/'native-add/fixture/mentor_lib.lmc'
library.parent.mkdir(parents=True); library.write_bytes(b'fixture')
source = tmp_path/'original/Source.prj'; source.parent.mkdir(); source.write_bytes(b'source')
(tmp_path/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': 'owned'}), encoding='utf-8')
adapter = native.NativeManagementAdapter(mentor_home=tmp_path)
monkeypatch.setattr(adapter, 'route_capabilities', lambda: {'add': native.Capability(True, 'ready')})
monkeypatch.setattr(native, 'engineering_identity', lambda _: {'source': 'bytes'})
def launch(*args):
if outcome == 'exception': raise OSError('worker result lost after dispatch')
return {'success': outcome == 'safe', 'safe_to_continue': outcome == 'safe'}
monkeypatch.setattr(adapter, '_launch_worker', launch)
lease = LibraryLock(library)
try:
with lease:
if outcome == 'exception':
with pytest.raises(OSError, match='after dispatch'):
adapter.add_owned_fixture(ManagementRequest('add', library, 'Block', source=source),
tmp_path/'add', probe_token='owned')
else:
adapter.add_owned_fixture(ManagementRequest('add', library, 'Block', source=source),
tmp_path/'add', probe_token='owned')
assert blocker_path(library).exists() is (outcome != 'safe')
if outcome != 'safe':
with pytest.raises(LibraryBusy):
with LibraryLock(library): pass
import win32file, win32con, pywintypes
with pytest.raises(pywintypes.error):
win32file.CreateFile(str(lease.path), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, 0, None)
else:
with LibraryLock(library): pass
finally:
# Only the file-only fake worker above ran; release its test lease.
with _guard:
owner = _owners.pop(lease.key, None)
if owner: owner['handle'].Close()
blocker_path(library).unlink(missing_ok=True)
def test_fixture_nested_inside_source_tree_rejected_before_staging(tmp_path):
import cbb_refresh_verify.native_management as native
from cbb_refresh_verify.library_lock import LibraryLock
library = tmp_path/'native-add/fixture/mentor_lib.lmc'
library.parent.mkdir(parents=True); library.write_bytes(b'fixture')
source = tmp_path/'native-add/Source.prj'; source.write_bytes(b'original source')
(tmp_path/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': 'owned'}), encoding='utf-8')
root = tmp_path/'add'; root.mkdir()
with LibraryLock(library):
with pytest.raises(ValueError, match='independent'):
native.prepare_owned_fixture_add({'library': str(library), 'source': str(source),
'name': 'Block', 'partition': 'Logical-Physical', 'source_identity': {},
'probe_token': 'owned'}, root)
assert source.read_bytes() == b'original source' and library.read_bytes() == b'fixture'
assert not (root/'source').exists()
def test_add_route_readiness_is_separate_from_conservative_capability_gate(tmp_path, monkeypatch):
import hashlib
import cbb_refresh_verify.native_management as native
proof = {'lm/win32/bin/CleanWGLib.exe': hashlib.sha256(b'verified').hexdigest()}
monkeypatch.setattr(native, '_BINARY_PROOF', proof)
path = tmp_path/next(iter(proof)); path.parent.mkdir(parents=True); path.write_bytes(b'verified')
adapter = native.NativeManagementAdapter(mentor_home=tmp_path)
assert adapter.route_capabilities()['add'].supported
assert not adapter.capabilities()['add'].supported
assert 'icdb2ascii' in adapter.capabilities()['add'].reason
@pytest.mark.parametrize('bad', [None, 'CleanWGLib.exe', 'LibraryManager.exe', 'LMCDLL70.dll',
'LMCDocAddin70.dll', 'icdb2ascii.exe', 'icdb2csv.exe', 'edifExporter.exe'])
def test_public_crud_requires_pinned_core_and_every_identity_exporter(tmp_path, monkeypatch, bad):
import hashlib
import cbb_refresh_verify.native_management as native
import cbb_refresh_verify.native_engineering_identity as identity
core = {relative: hashlib.sha256(Path(relative).name.encode()).hexdigest() for relative in native._BINARY_PROOF}
exporters = {name: hashlib.sha256(name.encode()).hexdigest() for name in identity.EXPORTER_PROOF}
monkeypatch.setattr(native, '_BINARY_PROOF', core)
monkeypatch.setattr(identity, 'EXPORTER_PROOF', exporters)
for relative in core:
path = tmp_path/relative; path.parent.mkdir(parents=True, exist_ok=True); path.write_bytes(path.name.encode())
for name in exporters:
path = tmp_path/('wv/win32/bin' if name == 'edifExporter.exe' else 'iCDB/win32/bin')/name
path.parent.mkdir(parents=True, exist_ok=True); path.write_bytes(name.encode())
if bad:
next(tmp_path.rglob(bad)).write_bytes(b'changed binary')
caps = native.NativeManagementAdapter(mentor_home=tmp_path).capabilities()
assert caps['add'].supported is (bad is None)
assert caps['update'].supported is (bad is None)
if bad in exporters: assert caps['remove'].supported
@pytest.mark.parametrize('operation', ['add', 'update', 'remove'])
@pytest.mark.parametrize('flow,partition', [(2, 'Logical-Physical'), (1, 'Unsupported')])
def test_public_crud_scope_refuses_unproven_flow_or_partition(tmp_path, operation, flow, partition):
from cbb_refresh_verify.management import ManagementRequest, Catalog
from cbb_refresh_verify.native_management import NativeManagementAdapter
request = ManagementRequest(operation, tmp_path/'lib.lmc', 'Block', partition=partition)
with pytest.raises(ValueError):
NativeManagementAdapter(mentor_home=tmp_path).preflight(request, Catalog(request.library, flow, ()))
def test_owned_fixture_add_passes_existing_library_and_source_to_worker(tmp_path, monkeypatch):
from cbb_refresh_verify.management import ManagementRequest
import cbb_refresh_verify.native_management as native
source = tmp_path/'source.prj'; source.write_bytes(b'source')
library = tmp_path/'library.lmc'; library.write_bytes(b'library')
seen = {}
adapter = native.NativeManagementAdapter(mentor_home=tmp_path)
monkeypatch.setattr(adapter, 'route_capabilities', lambda: {
'add': native.Capability(True, 'route ready')})
monkeypatch.setattr(native, 'engineering_identity', lambda path: {'source': str(path)})
def worker(job, evidence):
seen.update(job=job, evidence=evidence)
return {'success': True, 'safe_to_continue': True, 'identity_matches': True,
'detail': 'native add accepted'}
monkeypatch.setattr(adapter, '_worker', worker)
request = ManagementRequest('add', library, 'Block', source=source,
mapped_drive='S:', mapped_remote_root=r'\\server\share', timeout_seconds=23)
result = adapter.add_owned_fixture(request, tmp_path/'evidence', probe_token='owned')
assert result.success and result.safe_to_continue and result.identity_matches is True
assert seen['job'] == {
'operation': 'add', 'library': str(library), 'source': str(source),
'name': 'Block', 'partition': 'Logical-Physical', 'top_level_block': '',
'mapped_drive': 'S:', 'mapped_remote_root': r'\\server\share',
'timeout_seconds': 23, 'source_identity': {'source': str(source)}, 'probe_token': 'owned',
}
def test_native_add_identity_mismatch_is_native_success_with_evidence(tmp_path, monkeypatch):
from cbb_refresh_verify.management import ManagementRequest
import cbb_refresh_verify.native_management as native
source = tmp_path/'source.prj'; source.write_bytes(b'source')
library = tmp_path/'library.lmc'; library.write_bytes(b'library')
adapter = native.NativeManagementAdapter(mentor_home=tmp_path)
monkeypatch.setattr(adapter, 'route_capabilities', lambda: {
'add': native.Capability(True, 'route ready')})
monkeypatch.setattr(native, 'engineering_identity', lambda path: {'source': str(path)})
monkeypatch.setattr(adapter, '_worker', lambda job, evidence: {
'success': True, 'safe_to_continue': True, 'identity_matches': False,
'detail': 'engineering identity readback mismatch',
})
original = source.read_bytes()
result = adapter.add_owned_fixture(ManagementRequest('add', library, 'Block', source=source),
tmp_path/'evidence', probe_token='owned')
assert result.success and result.identity_matches is False
assert 'identity' in result.detail
assert result.evidence_path == tmp_path/'evidence'
assert source.read_bytes() == original
@pytest.mark.parametrize('name', ['A\tB', 'A\nB', '../A', '中文'])
def test_delete_record_rejects_ambiguous_encoding_or_injection(name):
from cbb_refresh_verify.native_management import removal_input
with pytest.raises(ValueError):
removal_input(name, 'Logical-Physical')
def test_delete_record_is_exact_shipped_tcl_contract():
from cbb_refresh_verify.native_management import removal_input, removal_output_ok
assert removal_input('Block', 'Logical-Physical') == b'REUSE_BLOCK\tLogical-Physical\tBlock\n'
assert not removal_output_ok(0, '', 'Block', 'Logical-Physical')
assert not removal_output_ok(0, "# Warning: Unable to remove REUSE_BLOCK 'Block' from partition 'Logical-Physical'.", 'Block', 'Logical-Physical')
assert removal_output_ok(0, "# Note: Removed REUSE_BLOCK 'Block' from partition 'Logical-Physical'.", 'Block', 'Logical-Physical')
def test_upgrade_dialog_is_refused_and_only_cancel_is_allowed():
from cbb_refresh_verify.native_management import catalog_dialog_action
assert catalog_dialog_action('Library Manager', 'This Central Library must be updated before it can be opened in Library Manager. Select OK to continue.') == 'cancel'
assert catalog_dialog_action('Select flow type', '') == 'cancel'
assert catalog_dialog_action('Library Manager', 'Would you like to save?') == 'observe'
def test_catalog_never_falls_back_to_folder_list(tmp_path):
from cbb_refresh_verify.native_management import NativeManagementAdapter
library = tmp_path/'lib.lmc'; library.touch()
(tmp_path/'ReusableBlocksLP/Ghost').mkdir(parents=True)
adapter = NativeManagementAdapter()
adapter._worker = lambda *_: {'success': False, 'safe_to_continue': True, 'detail': 'upgrade refused'}
with pytest.raises(RuntimeError, match='upgrade refused'):
adapter.catalog(library, tmp_path/'evidence')
def test_private_worker_timeout_retains_native_and_never_kills(tmp_path, monkeypatch):
import cbb_refresh_verify.native_management as native
monkeypatch.setattr(native, '_retained_workers', [])
from cbb_refresh_verify.native_management import NativeManagementAdapter
class Running:
def __init__(self, *a): pass
def poll(self): return None
def close(self): pytest.fail('closing live DesktopWorker kills automation')
def kill(self): pytest.fail('must preserve native owner')
adapter = NativeManagementAdapter(worker_factory=Running, timeout_seconds=0)
result = adapter._worker({'operation': 'catalog', 'library': str(tmp_path/'lib.lmc')}, tmp_path/'out')
assert result['safe_to_continue'] is False
assert 'TIMEOUT' in result['detail']
def test_hidden_worker_and_probe_dispatch_before_qt(monkeypatch, tmp_path):
import cbb_refresh_verify.native_management as native
from cbb_refresh_verify.application import main
seen = []
monkeypatch.setattr(native, 'management_worker_main', lambda p: (seen.append(p) or 17))
assert main(['--management-worker', str(tmp_path/'job.json')]) == 17
assert seen == [tmp_path/'job.json']
def test_probe_cannot_use_existing_fixture_or_mutate_source(tmp_path):
from cbb_refresh_verify.native_management import run_isolated_probe
existing = tmp_path/'existing'
existing.mkdir()
with pytest.raises(ValueError, match='new|新'):
run_isolated_probe(tmp_path/'source.prj', existing, 'Block')
def test_probe_requires_owned_new_native_library_path(tmp_path):
import os
from cbb_refresh_verify.native_management import prepare_probe_library
from cbb_refresh_verify.library_lock import LibraryLock
outside = tmp_path/'production.lmc'; outside.write_bytes(b'unchanged')
root = tmp_path/'worker'; root.mkdir()
with pytest.raises(ValueError):
prepare_probe_library({'library': str(outside)}, root)
assert outside.read_bytes() == b'unchanged'
owned = root/'fixture/mentor_lib.lmc'
owned.parent.mkdir()
job = {'library': str(owned), 'probe_token': 'test-token', 'supervisor_pid': os.getpid()}
(root/'probe-prepared.json').write_text(json.dumps({'library': str(owned), 'token': 'test-token',
'supervisor_pid': os.getpid()}), encoding='utf-8')
with LibraryLock(owned):
assert prepare_probe_library(job, root) == owned
owned.write_bytes(b'first creation')
with pytest.raises(ValueError):
prepare_probe_library(job, root)
@pytest.mark.parametrize('records', [[], [('Actual', 'Logical-Physical')]])
@pytest.mark.parametrize('mapped', [False, True])
@pytest.mark.parametrize('flow', [1, 2])
def test_native_catalog_only_uses_com_records_and_checks_exact_process(tmp_path, monkeypatch, records, mapped, flow):
import cbb_refresh_verify.native_management as native
import cbb_refresh_verify.mentor_adapter as mentor
import win32com.client
library_path = tmp_path/'lib.lmc'; library_path.touch()
if mapped:
original_resolve = Path.resolve
def resolve(path, *a, **k):
return tmp_path/'canonical/lib.lmc' if path == library_path else original_resolve(path, *a, **k)
monkeypatch.setattr(Path, 'resolve', resolve)
(tmp_path/'ReusableBlocksLP/Ghost').mkdir(parents=True)
class Collection:
def __init__(self, items): self.items = items; self.Count = len(items)
def Item(self, index): return self.items[index - 1]
items = Collection([SimpleNamespace(Name=name, PartitionName=partition) for name, partition in records])
class Library:
FullName = str(library_path)
FlowType = flow
def Partitions(self, kind):
assert kind == 7
return Collection([items])
def Close(self): pass
state = {'running': False}
class App:
def OpenLibrary(self, path):
assert path == str(library_path)
return Library()
def Quit(self): state['running'] = False
def dispatch(_): state['running'] = True; return App()
monkeypatch.setattr(win32com.client, 'DispatchEx', dispatch)
monkeypatch.setattr(native, '_current_desktop', lambda: (SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test'))
monkeypatch.setattr(mentor, '_process_details', lambda _: [(123, str(tmp_path/'lm/win32/bin/LibraryManager.exe'), '', 0)] if state['running'] else [])
monkeypatch.setattr(native, '_wait_native_exit', lambda _: not state['running'])
result = native._catalog_native({'operation': 'catalog', 'library': str(library_path),
'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path)}, tmp_path)
assert result['success'] and result['safe_to_continue']
assert [(entry['name'], entry['partition']) for entry in result['entries']] == records
assert result['flow'] == flow
def test_production_caps_require_all_validated_binary_hashes(tmp_path, monkeypatch):
import hashlib
import cbb_refresh_verify.native_management as native
proof = {'lm/win32/bin/CleanWGLib.exe': hashlib.sha256(b'verified').hexdigest()}
monkeypatch.setattr(native, '_BINARY_PROOF', proof)
path = tmp_path/next(iter(proof)); path.parent.mkdir(parents=True); path.write_bytes(b'verified')
adapter = native.NativeManagementAdapter(mentor_home=tmp_path)
assert adapter.capabilities()['remove'].supported
assert not adapter.capabilities()['add'].supported
path.write_bytes(b'different')
assert not adapter.capabilities()['remove'].supported
def test_probe_readd_requires_creation_token_and_fixed_owned_library(tmp_path):
from cbb_refresh_verify.native_management import validate_probe_readd
root = tmp_path/'native-readd'; root.mkdir()
library = tmp_path/'native-add/fixture/mentor_lib.lmc'
library.parent.mkdir(parents=True); library.touch()
job = {'library': str(library), 'probe_token': 'owned-token'}
with pytest.raises(ValueError):
validate_probe_readd(job, root)
(tmp_path/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': 'other'}), encoding='utf-8')
with pytest.raises(ValueError):
validate_probe_readd(job, root)
(tmp_path/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': 'owned-token'}), encoding='utf-8')
assert validate_probe_readd(job, root) == library
outside = tmp_path/'production.lmc'; outside.touch()
with pytest.raises(ValueError):
validate_probe_readd({**job, 'library': str(outside)}, root)
def test_com_failure_without_owner_identity_cannot_claim_release(tmp_path, monkeypatch):
import cbb_refresh_verify.native_management as native
monkeypatch.setattr(native, '_catalog_com', lambda *a: {'success': False,
'safe_to_continue': False, 'native_pids': [], 'detail': 'COM startup ambiguous'})
assert native._catalog_native({}, tmp_path)['safe_to_continue'] is False
@pytest.mark.parametrize('registered', [True, False])
def test_shared_add_reopens_exact_catalog_and_reports_identity_mismatch(tmp_path, monkeypatch, registered):
import cbb_refresh_verify.native_management as native
import cbb_refresh_verify.mentor_adapter as mentor
import win32com.client
library_path = tmp_path/'lib.lmc'; library_path.touch()
events = []
class Collection:
def __init__(self, items): self.items = items; self.Count = len(items)
def Item(self, index): return self.items[index - 1]
class Library:
FullName = str(library_path)
FlowType = 1
def Partitions(self, kind):
events.append('catalog')
return Collection([Collection([SimpleNamespace(Name='Block', PartitionName='Logical-Physical')]
if registered else [])])
def Close(self): events.append('close')
state = {'running': False}
class App:
def OpenLibrary(self, path):
assert path == str(library_path)
events.append('open')
return Library()
def Quit(self): state['running'] = False
def dispatch(_): state['running'] = True; return App()
monkeypatch.setattr(win32com.client, 'DispatchEx', dispatch)
monkeypatch.setattr(native, '_current_desktop', lambda: (SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test'))
monkeypatch.setattr(mentor, '_process_details', lambda _: [(123, str(tmp_path/'lm/win32/bin/LibraryManager.exe'), '', 0)] if state['running'] else [])
monkeypatch.setattr(native, '_probe_add_dialog', lambda *a, **k: events.append('add'))
monkeypatch.setattr(native, 'validate_owned_fixture_add', lambda *a: None)
result = native._catalog_com({'operation': 'add', 'library': str(library_path),
'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path),
'name': 'Block', 'partition': 'Logical-Physical', 'source_identity': {'expected': 'bytes'}}, tmp_path)
assert events == ['open', 'add', 'close', 'open', 'catalog', 'close']
assert result['success'] is registered
assert result['identity_matches'] is False
assert ('engineering identity' if registered else 'exact name and partition') in result['detail']
+58
View File
@@ -0,0 +1,58 @@
import ctypes
import json
from types import SimpleNamespace
import pytest
@pytest.mark.parametrize('expected,actual', [('S:\\source\\项目.prj', 'S:\\source\\项目.prj'), ('', '')])
def test_field_uses_bounded_set_and_remote_gettext_with_exact_readback(tmp_path, monkeypatch, expected, actual):
from cbb_refresh_verify import native_management as native
calls = []
class Send:
def __call__(self, hwnd, message, wparam, lparam, flags, timeout, result):
calls.append((hwnd, message, flags, timeout))
if message == 0x000C:
assert ctypes.wstring_at(lparam) == expected
result._obj.value = 1
elif message == 0x000D:
buffer = ctypes.create_unicode_buffer(actual)
ctypes.memmove(lparam, ctypes.addressof(buffer), ctypes.sizeof(buffer))
result._obj.value = len(actual)
else:
pytest.fail('unproven field message')
return 1
monkeypatch.setattr(native.ctypes, 'WinDLL', lambda *a, **k: SimpleNamespace(SendMessageTimeoutW=Send()))
assert native._set_probe_field(123, 1217, expected, tmp_path) == actual
assert [item[1] for item in calls] == [0x000C, 0x000D]
assert all(item[0] == 123 and item[2] == 0x0002 and 0 < item[3] <= 1000 for item in calls)
record = json.loads((tmp_path/'native-field-readback.jsonl').read_text(encoding='utf-8'))
assert record['expected'] == expected and record['actual'] == actual and record['matched']
@pytest.mark.parametrize('failure', ['empty', 'mismatch', 'set_timeout', 'read_timeout', 'set_rejected', 'truncated'])
def test_field_failure_is_recorded_before_rejection_without_foreground_fallback(tmp_path, monkeypatch, failure):
from cbb_refresh_verify import native_management as native
calls = []
class Send:
def __call__(self, hwnd, message, wparam, lparam, flags, timeout, result):
calls.append(message)
if message == 0x000C:
result._obj.value = 0 if failure == 'set_rejected' else 1
return 0 if failure == 'set_timeout' else 1
if failure == 'read_timeout': return 0
actual = '' if failure == 'empty' else 'other project'
buffer = ctypes.create_unicode_buffer(actual)
ctypes.memmove(lparam, ctypes.addressof(buffer), ctypes.sizeof(buffer))
result._obj.value = wparam - 1 if failure == 'truncated' else len(actual)
return 1
monkeypatch.setattr(native.ctypes, 'WinDLL', lambda *a, **k: SimpleNamespace(SendMessageTimeoutW=Send()))
with pytest.raises((RuntimeError, TimeoutError)):
native._set_probe_field(123, 1217, 'expected project', tmp_path)
record = json.loads((tmp_path/'native-field-readback.jsonl').read_text(encoding='utf-8'))
assert record['expected'] == 'expected project' and not record['matched']
assert record['control_id'] == 1217 and record['exception']['type']
if failure in ('empty', 'mismatch'):
assert record['actual'] == ('' if failure == 'empty' else 'other project')
if failure in ('set_timeout', 'set_rejected'):
assert calls == [0x000C]
+958
View File
@@ -0,0 +1,958 @@
import json
from pathlib import Path
import pytest
def target_fixture(tmp_path):
from test_verify_runner import fixture, request
from cbb_refresh_verify.native_repair import select_repair_target
work = fixture(tmp_path)
database = work/'database'
database.mkdir()
(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)
def complete_native_success(target):
"""A complete successful worker result, with no contradictory native state."""
return {'status': 'REPAIRED', 'project': str(target.project), 'database': str(target.database),
'native_pid': 777,
'release': {'native_exited': True, 'safe_to_continue': True, 'addresses': []},
'evidence': {'confirmed': True, 'native_backup': True, 'outcome': 'UNCONFIRMED',
'failure_complete': False, 'restore_complete': False, 'restored_from_backup': '',
'diagnostic_tail': 'Diagnostic: START\nDiagnostic: FINISH',
'database_tail': f'{target.database}\niCDBProjectBackupRepair\nIC: Closing project',
'restore_tail': '', 'output_tail': '', 'backup_log_tail': '',
'log_paths': []}}
def test_repair_target_matches_actual_database_not_guessed_cbb_name(tmp_path):
request, record, target = target_fixture(tmp_path)
assert target.project.name == 'CBB1.prj'
assert target.database == target.project.parent/'database'
@pytest.mark.parametrize('change', ['foreign', 'shared', 'missing_session', 'unknown_scope'])
def test_repair_target_rejects_unresolved_or_shared_database(tmp_path, change):
from cbb_refresh_verify.native_repair import select_repair_target
request, record, target = target_fixture(tmp_path)
if change == 'foreign': record['database_path'] = str(tmp_path/'foreign/database')
if change == 'shared':
record.update(scope='central_library', database_path=str(tmp_path/'SymbolLibs/__ReusableBlocksSymb'))
if change == 'missing_session': record['session'] = ''
if change == 'unknown_scope': record['scope'] = 'unknown'
with pytest.raises(ValueError):
select_repair_target(request, record)
def test_repair_backup_contains_database_locks_backups_and_original_files(tmp_path):
from cbb_refresh_verify.native_repair import backup_project
request, record, target = target_fixture(tmp_path)
for relative in ('database/cdbsvr/sAddress.adr', 'ProjectBackup/backups/old.zip',
'PCB/copy.lock', 'Log Files/ProjectBackupLog.txt'):
path = target.project.parent/relative
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(b'original '+relative.encode())
destination = tmp_path/'repair-backup'
manifest = backup_project(target, destination)
assert manifest['complete'] is True
assert (destination/'database/icdb.dat').read_bytes() == b'original damaged database'
assert (destination/'database/cdbsvr/sAddress.adr').read_bytes().startswith(b'original')
assert (destination/'ProjectBackup/backups/old.zip').is_file()
assert (destination/'PCB/copy.lock').is_file()
def test_repair_backup_refuses_database_open_by_another_client(tmp_path):
import win32file, win32con
from cbb_refresh_verify.native_repair import backup_project
request, record, target = target_fixture(tmp_path)
handle = win32file.CreateFile(str(target.database/'icdb.dat'), win32con.GENERIC_READ,
win32con.FILE_SHARE_READ, None, win32con.OPEN_EXISTING, 0, None)
try:
with pytest.raises(OSError):
backup_project(target, tmp_path/'backup')
finally:
handle.Close()
assert not (tmp_path/'backup/backup-manifest.json').exists()
def test_repair_backup_rejects_reparse_directory(tmp_path):
import _winapi
from cbb_refresh_verify.native_repair import backup_project
request, record, target = target_fixture(tmp_path)
outside = tmp_path/'outside'
outside.mkdir()
_winapi.CreateJunction(str(outside), str(target.project.parent/'linked'))
with pytest.raises(ValueError):
backup_project(target, tmp_path/'backup')
def test_native_confirmation_requires_exact_target_and_known_repair_prompt():
from cbb_refresh_verify.native_repair_ui import confirmation_allowed
assert confirmation_allowed('iCDB Project Backup - C:\\exact.prj', r'C:\exact.prj',
'The project content will be validated and repaired if necessary.\n'
'A project backup will be created before any action take place.\n'
'You will be able to revert all changes using that backup.')
assert not confirmation_allowed('iCDB Project Backup - C:\\OTHER.prj', r'C:\exact.prj',
'The project content will be validated and repaired if necessary.')
assert not confirmation_allowed('iCDB Project Backup - C:\\exact.prj', r'C:\exact.prj',
'Confirm no other clients are connected. Continue anyway?')
def test_native_diagnostics_finish_alone_does_not_prove_repair_success():
from cbb_refresh_verify.native_repair_ui import repair_completed
assert not repair_completed('Diagnostic: FINISH', 'IC: Closing project', native_backup=False)
assert not repair_completed('ERROR: invalid database\nDiagnostic: FINISH',
'iCDBProjectBackupRepair\nIC: Closing project', native_backup=True)
assert repair_completed('Diagnostic: START\nDiagnostic: FINISH',
'iCDBProjectBackupRepair\nIC: Closing project', native_backup=True)
def test_native_restore_of_old_backup_requires_review_even_when_diagnostics_finish(tmp_path):
from cbb_refresh_verify.native_repair_ui import _native_evidence
from cbb_refresh_verify.icdb_recovery import snapshot_log
project = tmp_path/'project.prj'
database = tmp_path/'database'
project.touch()
log = tmp_path/'Log Files/ProjectBackupLog.txt'
log.parent.mkdir()
baseline = snapshot_log(log)
for folder, text in (
('dbcheck', 'Diagnostic: START\nDiagnostic: FINISH'),
('dbrestore', f'iCDB database restored from backup: {tmp_path}/old.zip\n[0] DONE')):
path = database/'cdbsvr'/folder/'new-1234/log.txt'
path.parent.mkdir(parents=True)
path.write_text(text)
evidence = _native_evidence(project, database, 1234, 0, baseline)
assert evidence['restored_from_backup'] == f'{tmp_path}/old.zip'
assert evidence['restore_complete'] is True
assert evidence['confirmed'] is False
def test_automatic_repair_retries_only_once_and_preserves_original_failure(tmp_path, monkeypatch):
from dataclasses import replace
from cbb_refresh_verify import verify_runner as runner
from cbb_refresh_verify import native_repair
request, record, target = target_fixture(tmp_path)
evidence = tmp_path/'first/result.json'
evidence.parent.mkdir()
(evidence.parent/'diagnostics').mkdir()
(evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(record))
original = runner.VerifyResult('FAIL', stderr='native lost session',
safe_to_continue=False, error_category='ICDB_REPAIR_REQUIRED', evidence_path=evidence)
calls = []
def verify(req, **kwargs):
calls.append(req)
return original
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: complete_native_success(target))
outcome = runner.run_verify(request)
assert len(calls) == 2
assert outcome.status == 'FAIL'
assert outcome.stderr == 'native lost session'
assert outcome.recovery_attempts[0]['original_error'] == 'native lost session'
assert outcome.recovery_attempts[0]['status'] == 'REPAIR_VALIDATION_FAILED'
assert outcome.recovery_attempts[0]['native_status'] == 'REPAIRED'
@pytest.mark.parametrize('text,expected,terminal', [
('There is no backup of iCDB.\nRepair project error [Cannot repair the project - there is no backup of missing iCDB].',
'MISSING_HEALTHY_BACKUP', True),
('Repair project error [Database validation failed].', 'NATIVE_REPAIR_FAILED', True),
('Project is in use. Full functionality is unavailable.', 'DATABASE_BUSY', False),
('Repairing the project. Diagnostic: START', 'UNCONFIRMED', False),
])
def test_current_native_output_classifies_failure_and_terminal_evidence(text, expected, terminal):
from cbb_refresh_verify.native_repair_ui import classify_repair_evidence
result = classify_repair_evidence('', '', '', text)
assert result['outcome'] == expected
assert result['failure_complete'] is terminal
def test_historical_no_backup_output_replay_is_conclusive_failure():
from cbb_refresh_verify.native_repair_ui import classify_repair_evidence
# Sanitized actual native Output from the 2026-10-28 no-history fixture.
text = ('Repairing the project [<project>/CBB.prj].\n'
'Repair backup [repair.zip] created successfully.\n'
'The iCDB database is corrupted.\nThere is no backup of iCDB.\n'
'Repair project error [Cannot repair the project - there is no backup of missing iCDB].\n'
'The project is probably in inconsistent state. Please restore the project from one of previous backups.')
result = classify_repair_evidence('', '', '', text)
assert result == {'outcome': 'MISSING_HEALTHY_BACKUP', 'failure_complete': True}
@pytest.mark.parametrize('repair_status', ['BLOCKED', 'RESTORED_REVIEW_REQUIRED'])
def test_automatic_repair_does_not_retry_busy_or_unsupported_target(tmp_path, monkeypatch, repair_status):
from cbb_refresh_verify import verify_runner as runner
from cbb_refresh_verify import native_repair
request, record, target = target_fixture(tmp_path)
evidence = tmp_path/'first/result.json'
evidence.parent.mkdir()
(evidence.parent/'diagnostics').mkdir()
(evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(record))
calls = []
def verify(req, **kwargs):
calls.append(req)
return runner.VerifyResult('FAIL', stderr='native lost session',
error_category='ICDB_REPAIR_REQUIRED', safe_to_continue=False, evidence_path=evidence)
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: {'status':repair_status})
outcome = runner.run_verify(request)
assert len(calls) == 1
assert outcome.safe_to_continue is False
assert outcome.recovery_attempts[0]['status'] == repair_status
def test_timeout_never_enters_automatic_repair(tmp_path, monkeypatch):
from cbb_refresh_verify import verify_runner as runner, native_repair
request, record, target = target_fixture(tmp_path)
evidence = tmp_path/'first/result.json'
evidence.parent.mkdir()
(evidence.parent/'diagnostics').mkdir()
(evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(record))
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **kw:
runner.VerifyResult('TIMEOUT', error_category='ICDB_REPAIR_REQUIRED',
safe_to_continue=False, evidence_path=evidence))
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw:
pytest.fail('A timed-out native owner must not be repaired'))
assert runner.run_verify(request).status == 'TIMEOUT'
def test_retained_importer_blocks_repair_even_without_an_open_database_handle(tmp_path, monkeypatch):
from cbb_refresh_verify import native_repair
request, record, target = target_fixture(tmp_path)
evidence = tmp_path/'original'
evidence.mkdir()
(evidence/'content-check-process.json').write_text(json.dumps({'status':'RETAINED','pid':123}))
monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **kw:
pytest.fail('Do not repair between importer transactions'))
outcome = native_repair.attempt_recovery(request, record, evidence)
assert outcome['status'] == 'BLOCKED'
assert 'IMPORTER_RELEASE_UNCONFIRMED' in outcome['detail']
def test_repair_cancellation_during_backup_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'
root.mkdir()
cancel = root/'cancel.signal'
job = root/'request.json'
job.write_text(json.dumps({'project':str(target.project),'database':str(target.database),
'root':str(root),'cancel_signal':str(cancel),'timeout':1,
'supervisor_pid':123,'desktop':'CbbRepair_test'}))
calls = []
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.start_supervisor_watchdog',
lambda *a, **kw: calls.append('watchdog'))
monkeypatch.setattr(ui, '_current_desktop_name', lambda: 'CbbRepair_test', raising=False)
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'
cancel.touch()
calls.append('backup')
monkeypatch.setattr(native_repair, 'backup_project', backup)
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']
def test_repair_worker_refuses_the_input_desktop_before_backup(tmp_path, monkeypatch):
from cbb_refresh_verify import native_repair_ui as ui, native_repair
request, record, target = target_fixture(tmp_path)
root = tmp_path/'worker'
root.mkdir()
job = root/'request.json'
job.write_text(json.dumps({'project':str(target.project),'database':str(target.database),
'root':str(root),'cancel_signal':str(root/'cancel.signal'),'timeout':1,
'supervisor_pid':123,'desktop':'CbbRepair_test'}))
monkeypatch.setattr(ui, '_current_desktop_name', lambda: 'Default', raising=False)
monkeypatch.setattr(native_repair, 'backup_project', lambda *a: pytest.fail('Input desktop repair forbidden'))
assert ui.repair_worker_main(job) == 1
assert 'REPAIR_PRIVATE_DESKTOP_REQUIRED' in json.loads((root/'repair-result.json').read_text('utf-8'))['detail']
def test_repair_worker_job_binds_supervisor_and_private_desktop(tmp_path, monkeypatch):
from cbb_refresh_verify.native_repair import run_native_repair
request, record, target = target_fixture(tmp_path)
class Worker:
returncode = 0
def __init__(self, command, desktop):
job = json.loads(Path(command[-1]).read_text('utf-8'))
assert job['supervisor_pid'] > 0
assert job['desktop'] == desktop
assert desktop.startswith('CbbRepair_')
(Path(job['root'])/'repair-result.json').write_text('{"status":"BLOCKED"}')
def poll(self): return 0
def bind_cancellation(self, path): pass
def close(self): pass
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker)
assert run_native_repair(target, tmp_path/'native')['status'] == 'BLOCKED'
def test_backup_detects_a_file_added_during_the_copy(tmp_path, monkeypatch):
from cbb_refresh_verify import native_repair
request, record, target = target_fixture(tmp_path)
original = native_repair.shutil.copy2
def changed(source, destination):
result = original(source, destination)
(target.project.parent/'new-file.txt').write_bytes(b'concurrent writer')
return result
monkeypatch.setattr(native_repair.shutil, 'copy2', changed)
with pytest.raises(OSError, match='REPAIR_BACKUP_CHANGED'):
native_repair.backup_project(target, tmp_path/'backup')
def repair_worker_fixture(tmp_path, monkeypatch, scenario):
"""Replay native window/log transitions without launching a native client."""
from types import SimpleNamespace
import win32con, win32gui
from cbb_refresh_verify import native_repair_ui as ui, native_repair, mentor_adapter
request, diagnosis, target = target_fixture(tmp_path)
root = tmp_path/'worker'
root.mkdir()
job = root/'request.json'
job.write_text(json.dumps({'project': str(target.project), 'database': str(target.database),
'root': str(root), 'cancel_signal': str(root/'cancel.signal'), 'timeout': 1,
'supervisor_pid': 123, 'desktop': 'CbbRepair_test'}))
ticks = [0.0]
state = {'requested': False, 'confirmed': False, 'closed': False}
actions = []
monkeypatch.setattr(ui, 'time', SimpleNamespace(monotonic=lambda: ticks[0], time_ns=lambda: 0,
sleep=lambda seconds: ticks.__setitem__(0, ticks[0]+seconds)))
monkeypatch.setattr(ui, '_current_desktop_name', lambda: 'CbbRepair_test')
monkeypatch.setattr(ui, '_repair_command', lambda *_: 32924)
monkeypatch.setattr(ui, 'discover_sdd_home', lambda *_: tmp_path, raising=False)
monkeypatch.setattr('cbb_refresh_verify.mentor_paths.discover_sdd_home', lambda *_: tmp_path)
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.start_supervisor_watchdog', lambda *a, **kw: None)
monkeypatch.setattr(native_repair, 'backup_project', lambda *a: {})
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: [])
monkeypatch.setattr(mentor_adapter, '_process_details', lambda *_: [])
monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **kw: SimpleNamespace(
pid=777, poll=lambda: 0 if state['closed'] and ticks[0] >= .6 else None))
terminal = 'Repair project error [Cannot repair the project - there is no backup of missing iCDB].'
def output(_):
if scenario == 'busy_before': return 'Project is in use. Full functionality is unavailable.'
if scenario == 'stale': return terminal
if not state['confirmed']: return ''
if scenario == 'busy': return 'Repair project error [Project is in use].'
if scenario == 'active': return 'Repairing the project. Please wait.'
if scenario in {'success', 'restore'}: return 'Repair project finished.'
return terminal
monkeypatch.setattr(ui, '_native_output', output, raising=False)
def windows(_):
main = {'hwnd': 100, 'class': 'Afx:main', 'title': 'iCDB Project Backup - '+str(target.project),
'enabled': True, 'children': []}
if state['confirmed'] and scenario in {'unknown', 'custom_prompt'}:
return [main, {'hwnd': 300, 'class': 'CustomDialog' if scenario == 'custom_prompt' else '#32770', 'title': 'Unexpected',
'enabled': True, 'children': [{'text': 'Overwrite design?', 'class': 'Button',
'id': 1, 'hwnd': 301, 'enabled': True}]}]
if state['requested'] and not state['confirmed']:
return [main, {'hwnd': 200, 'class': '#32770', 'title': '', 'enabled': True,
'children': [{'hwnd': 201, 'class': 'Button', 'id': 1, 'enabled': True,
'text': 'The project content will be validated and repaired if necessary.\n'
'A project backup will be created before any action take place.\n'
'You will be able to revert all changes using that backup.'}]}]
return [main]
monkeypatch.setattr(ui, '_windows', windows)
def post(hwnd, message, *args):
actions.append((hwnd, message))
if message == win32con.WM_COMMAND: state['requested'] = True
if message == win32con.BM_CLICK:
state['confirmed'] = True
if scenario in {'success', 'restore'}:
import zipfile
log = target.project.parent/'Log Files/ProjectBackupLog.txt'
log.parent.mkdir(parents=True)
log.write_text('Successfully created [Project Repair] backup [repair.zip]')
archive = target.project.parent/'ProjectBackup/backups/repair.zip'
archive.parent.mkdir(parents=True)
with zipfile.ZipFile(archive, 'w') as zipped: zipped.writestr('database/icdb.dat', b'backup')
logs = {'dbcheck': 'Diagnostic: START\nDiagnostic: FINISH',
'log': f'{target.database}\niCDBProjectBackupRepair\nIC: Closing project'}
if scenario == 'restore':
logs['dbrestore'] = 'iCDB database restored from backup: old.zip\n[0] DONE'
for folder, text in logs.items():
path = target.database/'cdbsvr'/folder/'new-777/log.txt'
path.parent.mkdir(parents=True)
path.write_text(text)
if scenario == 'address':
address = target.database/'cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True)
address.write_text('owner')
if message == win32con.WM_CLOSE: state['closed'] = True
monkeypatch.setattr(win32gui, 'PostMessage', post)
return ui, root, job, actions
@pytest.mark.parametrize('scenario,expected,closed', [
('failed', 'MISSING_HEALTHY_BACKUP', True), ('busy', 'DATABASE_BUSY', False),
('unknown', 'UNKNOWN_DIALOG', False), ('custom_prompt', 'UNKNOWN_DIALOG', False),
('active', 'TIMEOUT_UNRELEASED', False),
('stale', 'TIMEOUT_UNRELEASED', False), ('address', 'MISSING_HEALTHY_BACKUP', False),
])
def test_native_worker_closes_only_conclusively_failed_idle_tool(tmp_path, monkeypatch, scenario, expected, closed):
import win32con
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, scenario)
assert ui.repair_worker_main(job) == 1
result = json.loads((root/'repair-result.json').read_text('utf-8'))
assert result['status'] == expected
assert result['release']['safe_to_continue'] is closed
assert ((100, win32con.WM_CLOSE) in actions) is closed
assert actions[:2] == [(100, win32con.WM_COMMAND), (201, win32con.BM_CLICK)]
assert bool(result['evidence']['output_tail']) is (scenario != 'stale')
if scenario == 'unknown': assert result['unknown_dialogs'][0]['title'] == 'Unexpected'
@pytest.mark.parametrize('scenario,expected', [('success', 'REPAIRED'), ('restore', 'RESTORED_REVIEW_REQUIRED')])
def test_native_worker_preserves_success_and_historical_restore_distinction(tmp_path, monkeypatch, scenario, expected):
from cbb_refresh_verify.native_repair import RepairTarget, native_success_confirmed
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, scenario)
assert ui.repair_worker_main(job) == (0 if scenario == 'success' else 1)
result = json.loads((root/'repair-result.json').read_text('utf-8'))
assert result['status'] == expected
assert result['release']['safe_to_continue'] is True
assert result['evidence']['native_backup'] is True
assert result['evidence']['confirmed'] is (scenario == 'success')
assert (root/'native-logs/dbcheck/new-777/log.txt').exists()
request = json.loads(job.read_text('utf-8'))
target = RepairTarget(Path(request['project']), Path(request['database']))
assert native_success_confirmed(target, result) is (scenario == 'success')
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
result = json.loads((root/'repair-result.json').read_text('utf-8'))
assert result['status'] == 'DATABASE_BUSY'
assert actions == []
assert not result['release']['safe_to_continue']
@pytest.mark.parametrize('readback', ['missing', 'timeout', 'truncated'])
def test_unavailable_initial_output_never_requests_or_confirms_repair(tmp_path, monkeypatch, readback):
from types import SimpleNamespace
from cbb_refresh_verify import native_repair_ui as module
actual_read = module._native_output
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
windows = ui._windows
def observe(pid):
result = windows(pid)
if readback != 'missing':
result[0]['children'].append({'hwnd': 400, 'class': 'RichEdit20A'})
return result
monkeypatch.setattr(ui, '_windows', observe)
class Readback:
def __call__(self, hwnd, message, length, buffer, flags, timeout, copied):
if readback == 'timeout': return 0
copied._obj.value = length-1
return 1
monkeypatch.setattr(ui.ctypes, 'WinDLL', lambda *a, **kw: SimpleNamespace(SendMessageTimeoutW=Readback()))
monkeypatch.setattr(ui, '_native_output', actual_read)
assert ui.repair_worker_main(job) == 1
result = json.loads((root/'repair-result.json').read_text('utf-8'))
assert actions == []
assert result['status'] == 'TIMEOUT_UNRELEASED'
assert result['release']['safe_to_continue'] is False
assert json.loads((root/'native-output.json').read_text('utf-8'))['baseline'] is None
def test_initial_output_waits_until_readable_and_accepts_empty_baseline(tmp_path, monkeypatch):
import win32con
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
reads = []
def output(_):
reads.append(len(reads))
if len(reads) <= 2:
assert not actions
return None
return ''
monkeypatch.setattr(ui, '_native_output', output)
assert ui.repair_worker_main(job) == 1
assert actions == [(100, win32con.WM_COMMAND), (201, win32con.BM_CLICK)]
assert json.loads((root/'native-output.json').read_text('utf-8'))['baseline'] == ''
def test_invoked_busy_native_result_never_reopens_or_continues_queue(tmp_path, monkeypatch):
import win32con
from test_verify_runner import request
from cbb_refresh_verify import verify_runner as runner, native_repair
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'busy')
assert ui.repair_worker_main(job) == 1
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)
target = json.loads(job.read_text('utf-8'))
evidence = tmp_path/'first/result.json'
evidence.parent.mkdir()
(evidence.parent/'diagnostics').mkdir()
(evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps({
'error_code': 'ICDB_REPAIR_REQUIRED', 'scope': 'project',
'session': 'original-session', 'database_path': target['database']}))
opens = []
def verify(*a, **kw):
opens.append('open')
return runner.VerifyResult('FAIL', error_category='ICDB_REPAIR_REQUIRED',
safe_to_continue=False, evidence_path=evidence)
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: busy)
results = runner.run_batch([req, req], verifier=runner.run_verify)
assert opens == ['open']
assert results[0].recovery_attempts[0]['status'] == 'DATABASE_BUSY'
assert results[0].safe_to_continue is False and results[1].status == 'SKIPPED'
@pytest.mark.parametrize('status,released,scope,expected', [
('MISSING_HEALTHY_BACKUP', True, 'project', True),
('NATIVE_REPAIR_FAILED', True, 'project', True),
('MISSING_HEALTHY_BACKUP', False, 'project', False),
('MISSING_HEALTHY_BACKUP', True, 'central_library', False),
('MISSING_HEALTHY_BACKUP', True, 'unknown', False),
('UNKNOWN_DIALOG', True, 'project', False), ('TIMEOUT_UNRELEASED', True, 'project', False),
('DATABASE_BUSY', True, 'project', False),
])
def test_failed_repair_continues_only_released_project_local_items(
tmp_path, monkeypatch, status, released, scope, expected):
from cbb_refresh_verify import verify_runner as runner, native_repair
request, diagnosis, target = target_fixture(tmp_path)
diagnosis['scope'] = scope
evidence = tmp_path/'first/result.json'
evidence.parent.mkdir()
(evidence.parent/'diagnostics').mkdir()
(evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(diagnosis))
original = runner.VerifyResult('FAIL', stderr='original session lost', safe_to_continue=False,
error_category='ICDB_REPAIR_REQUIRED', error_stage='PCB_STARTING', evidence_path=evidence)
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **kw: original)
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: {
'status': status, 'release': {'safe_to_continue': released},
'evidence': {'failure_complete': True}, 'project': str(target.project),
'database': str(target.database)})
result = runner.run_verify(request)
assert result.safe_to_continue is expected
assert result.status == 'FAIL'
assert result.error_stage == 'PCB_STARTING'
assert result.stderr.startswith('original session lost')
assert status in result.stderr
assert result.recovery_attempts[0]['original_stage'] == 'PCB_STARTING'
@pytest.mark.parametrize('validation_status,flag,expected', [
('PASS', 'GREEN', True), ('PASS', 'UNKNOWN', False), ('FAIL', 'GREEN', False),
])
def test_maintenance_counts_require_native_success_then_verify_green(
tmp_path, monkeypatch, validation_status, flag, expected):
from cbb_refresh_verify import verify_runner as runner, native_repair
from cbb_refresh_verify.icdb_maintenance import maintenance_counts
request, diagnosis, target = target_fixture(tmp_path)
evidence = tmp_path/'first/result.json'
evidence.parent.mkdir()
(evidence.parent/'diagnostics').mkdir()
(evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(diagnosis))
original = runner.VerifyResult('FAIL', stderr='original lost session', safe_to_continue=False,
error_category='ICDB_REPAIR_REQUIRED', evidence_path=evidence)
evidence.write_text(json.dumps({'stderr': original.stderr}))
validated = runner.VerifyResult(validation_status, library_flag=flag,
evidence_path=tmp_path/'second.json', safe_to_continue=True)
calls = []
def verify(req, **kwargs):
calls.append(req)
return original if len(calls) == 1 else validated
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: complete_native_success(target))
result = runner.run_verify(request)
assert len(calls) == 2 and calls[1].auto_repair is False
assert result.recovery_attempts[0]['validation_passed'] is expected
assert maintenance_counts([result])['repaired'] == int(expected)
assert original.evidence_path.exists(), 'Original result evidence must remain available'
assert json.loads(original.evidence_path.read_text('utf-8'))['stderr'] == 'original lost session'
def test_native_success_without_release_does_not_reopen(tmp_path, monkeypatch):
from cbb_refresh_verify import verify_runner as runner, native_repair
request, diagnosis, target = target_fixture(tmp_path)
evidence = tmp_path/'first/result.json'
evidence.parent.mkdir()
(evidence.parent/'diagnostics').mkdir()
(evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(diagnosis))
calls = []
def verify(*args, **kwargs):
calls.append('open')
return runner.VerifyResult('FAIL', error_category='ICDB_REPAIR_REQUIRED',
safe_to_continue=False, evidence_path=evidence)
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: {'status': 'REPAIRED'})
result = runner.run_verify(request)
assert calls == ['open']
assert not result.safe_to_continue
assert result.recovery_attempts[0]['status'] == 'UNCONFIRMED'
@pytest.mark.parametrize('obstacle', ['none', 'launcher', 'repair_tool', 'importer', 'address', 'handle', 'shared_handle', 'probe'])
def test_repair_release_requires_process_address_and_database_handle_release(tmp_path, monkeypatch, obstacle):
import win32con, win32file
from cbb_refresh_verify import native_repair, mentor_adapter
request, diagnosis, target = target_fixture(tmp_path)
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda:
[(123, 'ExpeditionPCB.exe', 'launcher')] if obstacle == 'launcher' else [])
def processes(name):
if obstacle == 'probe': raise OSError('process observation unavailable')
if ((obstacle == 'repair_tool' and name == 'iCDBProjectBackup.exe')
or (obstacle == 'importer' and name == 'ReuseBlockImporter.exe')):
return [(456, name, 'unconfirmed owner', 0)]
return []
monkeypatch.setattr(mentor_adapter, '_process_details', processes)
if obstacle == 'address':
address = target.database/'cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True)
address.touch()
handle = None
try:
if obstacle in {'handle', 'shared_handle'}:
database_file = target.database/'icdb.dat'
if obstacle == 'shared_handle':
database_file = request.lmc_file.parent/'SymbolLibs/__ReusableBlocksSymb/icdb.dat'
database_file.parent.mkdir(parents=True)
database_file.touch()
handle = win32file.CreateFile(str(database_file), win32con.GENERIC_READ,
0, None, win32con.OPEN_EXISTING, 0, None)
result = native_repair.repair_release_state(request, target, complete_native_success(target))
assert result['safe_to_continue'] is (obstacle == 'none')
finally:
if handle: handle.Close()
def test_attempt_persists_distinct_native_failure_and_release_result(tmp_path, monkeypatch):
from cbb_refresh_verify import native_repair, mentor_adapter
request, diagnosis, target = target_fixture(tmp_path)
evidence = tmp_path/'evidence'
evidence.mkdir()
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: [])
monkeypatch.setattr(mentor_adapter, '_process_details', lambda *_: [])
monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **kw: {
'status': 'MISSING_HEALTHY_BACKUP', 'project': str(target.project),
'database': str(target.database), 'native_pid': 777,
'release': {'safe_to_continue': True, 'native_exited': True, 'addresses': []},
'evidence': {'failure_complete': True, 'output_tail': 'no backup'}})
result = native_repair.attempt_recovery(request, diagnosis, evidence)
assert result['status'] == 'MISSING_HEALTHY_BACKUP'
assert result['release']['database_exclusive'] is True
assert result['release']['safe_to_continue'] is True
assert isinstance(result['evidence'], dict)
assert result['evidence_path'] == str(evidence/'native-repair')
assert json.loads((evidence/'native-repair/attempt.json').read_text('utf-8')) == result
def test_retry_exception_keeps_original_error_and_native_repair_evidence(tmp_path, monkeypatch):
from cbb_refresh_verify import verify_runner as runner, native_repair
request, diagnosis, target = target_fixture(tmp_path)
evidence = tmp_path/'first/result.json'
evidence.parent.mkdir()
(evidence.parent/'diagnostics').mkdir()
(evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(diagnosis))
calls = []
def verify(*a, **kw):
calls.append('open')
if len(calls) > 1: raise OSError('retry infrastructure failure')
return runner.VerifyResult('FAIL', stderr='original native error', safe_to_continue=False,
error_category='ICDB_REPAIR_REQUIRED', evidence_path=evidence)
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
native_result = complete_native_success(target)
native_result['evidence']['diagnostic_tail'] += '\noriginal repair evidence'
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: native_result)
result = runner.run_verify(request)
assert not result.safe_to_continue
assert 'original native error' in result.stderr
assert 'retry infrastructure failure' in result.stderr
assert 'original repair evidence' in result.recovery_attempts[0]['evidence']['diagnostic_tail']
assert result.recovery_attempts[0]['status'] == 'REPAIR_VALIDATION_FAILED'
assert json.loads(evidence.read_text('utf-8'))['recovery_attempts']
def test_sanitized_field_open_failure_replay_closes_launcher_then_repairs_once(tmp_path, monkeypatch):
from types import SimpleNamespace
from dataclasses import replace
from test_failed_startup import startup_fixture
from cbb_refresh_verify import verify_runner as runner, native_repair, failed_session, mentor_adapter
from cbb_refresh_verify.pcb_bridge import wait_for_target_document, PcbBridgeError
replay = json.loads((Path(__file__).parent/'fixtures/issue2-lost-session-sanitized.json').read_text('utf-8'))
request, diagnosis, target = target_fixture(tmp_path)
# Retain a different PRJ name: the field CBB name never authorizes guessing it.
block_root = target.project.parent.parent
block_root.rename(block_root.with_name(replay['block']))
request = replace(request, block_name=replay['block'])
project, pcb = runner.preflight(request)
diagnosis['database_path'] = str(project.parent/'database')
target = native_repair.select_repair_target(request, diagnosis)
job, records, messages = startup_fixture(tmp_path, monkeypatch)
job.update(project=str(project), pcb=str(pcb), lmc_file=str(request.lmc_file))
records[0] = (12, records[0][1], f'ExpeditionPCB.exe "{pcb}" -ReusableCircuit', 11)
diagnosis.update(session=replay['diagnosis']['session'], machine='FIELD-PC')
(tmp_path/'diagnostics/icdb-recovery.json').write_text(json.dumps(diagnosis))
(tmp_path/'dialogs.jsonl').write_text(json.dumps(replay['dialog'])+'\n')
ticks = [0.0]
monkeypatch.setattr(failed_session, 'time', SimpleNamespace(monotonic=lambda: ticks[0],
sleep=lambda seconds: ticks.__setitem__(0, ticks[0]+seconds)))
launcher = SimpleNamespace(pid=11, poll=lambda: 0 if ticks[0] >= .4 else None)
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: [])
trace = []
evidence = tmp_path/'result.json'
original = runner.VerifyResult('FAIL', stderr=replay['native_error'], safe_to_continue=False,
error_category=replay['original_result']['error_category'],
error_stage=replay['original_result']['error_stage'], evidence_path=evidence)
assert runner.classify_failure_category(original.stderr) == original.error_category
assert runner.phase_for_event(replay['observed_events'][2]).value == original.error_stage
opens = []
def verify(req, **kwargs):
opens.append(req)
trace.append('open')
if len(opens) == 1:
errors = iter(('', replay['native_error']))
with pytest.raises(PcbBridgeError, match='Repair project'):
wait_for_target_document(job, lambda: SimpleNamespace(ActiveDocument=None),
process_alive=lambda: True, error_reader=lambda: next(errors),
emit=lambda **e: trace.append(e['stage']), sleep=lambda _: None)
closed = failed_session.close_failed_startup(job, 12, launcher_process=launcher,
emit=lambda **e: trace.append(e['stage']), timeout_seconds=1)
assert closed['status'] == 'CLOSED'
trace.append('launcher_exited')
return original # Repeated field error after one repair must not loop.
def repair(actual, root, **kwargs):
assert actual == target
assert trace[-1] == 'launcher_exited'
assert not records and launcher.poll() == 0
trace.append('native_repair')
return complete_native_success(actual)
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
monkeypatch.setattr(native_repair, 'run_native_repair', repair)
result = runner.run_verify(request)
assert trace == ['open', 'pcb_document_wait', 'startup_close_requested', 'startup_close_result',
'launcher_exited', 'native_repair', 'open']
assert len(opens) == 2 and opens[1].auto_repair is False
assert result.error_stage == 'PCB_STARTING'
assert result.recovery_attempts[0]['status'] == 'REPAIR_VALIDATION_FAILED'
assert result.recovery_attempts[0]['original_error'] == replay['native_error']
assert json.loads((tmp_path/'pre-repair-result.json').read_text('utf-8'))['stderr'] == replay['native_error']
MALFORMED_SUCCESS = [
('minimal', None),
('native_pid', None), ('native_pid', True),
('project', None), ('project', '<other>/CBB.prj'), ('project', []),
('database', None), ('database', '<other>/database'),
('release', []), ('release', 'released'),
('release.native_exited', None), ('release.native_exited', False),
('release.native_exited', 1), ('release.native_exited', 'true'),
('release.safe_to_continue', 1), ('release.addresses', ['owner']), ('release.addresses', ''),
('evidence', None), ('evidence', []), ('evidence', 'confirmed'),
('evidence.confirmed', None), ('evidence.confirmed', False),
('evidence.confirmed', 1), ('evidence.confirmed', 'true'),
('evidence.native_backup', False), ('evidence.failure_complete', True),
('evidence.outcome', 'DATABASE_BUSY'), ('evidence.restore_complete', True),
('evidence.restored_from_backup', 'old.zip'), ('unknown_dialogs', [{'title': 'Unknown'}]),
]
def malformed_native_success(target, key, value):
result = complete_native_success(target)
if key == 'minimal': return {'status': 'REPAIRED', 'release': {'safe_to_continue': True}}
if key in {'project', 'database'} and isinstance(value, str) and value.startswith('<other>'):
other = target.project.parent.parent.parent/'other-target'
other.mkdir(exist_ok=True)
if key == 'project':
other = other/'other.prj'
other.touch()
value = str(other.resolve())
if '.' in key:
parent, field = key.split('.')
result[parent][field] = value
else:
result[key] = value
return result
@pytest.mark.parametrize('key,value', MALFORMED_SUCCESS)
def test_malformed_native_success_never_authorizes_release(tmp_path, monkeypatch, key, value):
from cbb_refresh_verify import native_repair, mentor_adapter
request, diagnosis, target = target_fixture(tmp_path)
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: [])
monkeypatch.setattr(mentor_adapter, '_process_details', lambda *_: [])
result = native_repair.repair_release_state(request, target, malformed_native_success(target, key, value))
assert result['safe_to_continue'] is False
@pytest.mark.parametrize('key,value', MALFORMED_SUCCESS)
def test_malformed_native_success_never_reopens_or_counts_repaired(tmp_path, monkeypatch, key, value):
from cbb_refresh_verify import verify_runner as runner, native_repair
from cbb_refresh_verify.icdb_maintenance import maintenance_counts
request, diagnosis, target = target_fixture(tmp_path)
evidence = tmp_path/'first/result.json'
evidence.parent.mkdir()
(evidence.parent/'diagnostics').mkdir()
(evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(diagnosis))
calls = []
def verify(*a, **kw):
calls.append('open')
if len(calls) == 1:
return runner.VerifyResult('FAIL', stderr='original error', error_category='ICDB_REPAIR_REQUIRED',
safe_to_continue=False, evidence_path=evidence)
return runner.VerifyResult('PASS', library_flag='GREEN', evidence_path=evidence)
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw:
malformed_native_success(target, key, value))
result = runner.run_verify(request)
assert calls == ['open']
assert result.status == 'FAIL' and result.safe_to_continue is False
assert result.recovery_attempts[0]['status'] == 'UNCONFIRMED'
assert result.recovery_attempts[0]['release']['safe_to_continue'] is False
assert maintenance_counts([result])['repaired'] == 0
@pytest.mark.parametrize('owner', [None, 'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe'])
def test_repair_release_uses_real_process_query_contract(tmp_path, monkeypatch, owner):
from types import SimpleNamespace
import win32com.client
from cbb_refresh_verify.native_repair import repair_release_state
request, diagnosis, target = target_fixture(tmp_path)
queried = []
names = ('ExpeditionPCB.exe', 'LibraryManager.exe', 'iCDBProjectBackup.exe',
'ReuseBlockImporter.exe', 'cscript.exe')
queries = {"SELECT ProcessId, ParentProcessId, ExecutablePath, CommandLine "
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',
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)
# 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
assert queried == list(names)
assert state['safe_to_continue'] is (owner is None)
assert state['remaining_pids'] == ([] if owner is None else [456])
assert state['database_exclusive'] is (owner is None)
@pytest.mark.parametrize('name', [
'other.exe', 'icdbprojectbackup.exe',
"iCDBProjectBackup.exe' OR Name='other.exe",
"ReuseBlockImporter.exe' OR Name='other.exe",
])
def test_repair_process_queries_still_reject_arbitrary_input(monkeypatch, name):
import win32com.client
from cbb_refresh_verify.mentor_adapter import _process_details
monkeypatch.setattr(win32com.client, 'GetObject', lambda *a: pytest.fail('Unsupported name reached WMI'))
with pytest.raises(ValueError, match='Unsupported process query'):
_process_details(name)
def real_shape_repair_fixture(tmp_path, monkeypatch, scenario, window_state='loads'):
"""Replay recorded UI structures through the real bounded Output reader."""
from copy import deepcopy
from types import SimpleNamespace
from cbb_refresh_verify import native_repair_ui
actual_output_reader = native_repair_ui._native_output
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, scenario)
capture = json.loads((Path(__file__).parent/'fixtures/icdb-repair-startup-windows-sanitized.json').read_text('utf-8'))
project = json.loads(job.read_text('utf-8'))['project']
original_windows, operation_output = ui._windows, ui._native_output
polls = []
current = {'loading': True}
def windows(pid):
polls.append(ui.time.monotonic())
loading = len(polls) <= 2 or window_state == 'shell_stuck'
if loading: assert not actions, 'Startup shell must never receive a command'
original = original_windows(pid)
main = deepcopy(capture['startup_shell'])
current['loading'] = loading
if not loading:
main['title'] = capture['loaded_title_prefix']+project
if window_state == 'wrong_target': main['title'] = capture['loaded_title_prefix']+'C:\\Other\\other.prj'
if window_state == 'shell_after_invoke' and actions: main['title'] = 'iCDB Project Backup'
auxiliary = deepcopy(capture['auxiliary_windows'])
if window_state == 'named_aux': auxiliary[0]['title'] = 'Unrecognized prompt'
if window_state == 'lookalike_aux': auxiliary[0]['class'] += '.Other'
if window_state == 'duplicate_shell' and loading:
auxiliary.append({**deepcopy(main), 'hwnd': 101})
if window_state == 'duplicate_target' and not loading:
auxiliary.append({**deepcopy(main), 'hwnd': 101})
return [main, *original[1:], *auxiliary]
class Readback:
def __call__(self, hwnd, message, length, buffer, flags, timeout, copied):
assert hwnd == 400
if window_state == 'missing_output': return 0
text = '' if current['loading'] else capture['loaded_output']+operation_output([])
if window_state == 'busy_loading': text = 'Project is in use. Full functionality is unavailable.'
ui.ctypes.cast(buffer, ui.ctypes.POINTER(ui.ctypes.c_wchar * length)).contents.value = text
copied._obj.value = len(text)
return 1
monkeypatch.setattr(ui, '_windows', windows)
monkeypatch.setattr(ui.ctypes, 'WinDLL', lambda *a, **kw: SimpleNamespace(SendMessageTimeoutW=Readback()))
monkeypatch.setattr(ui, '_native_output', actual_output_reader)
return ui, root, job, actions, polls
@pytest.mark.parametrize('scenario,expected,closed', [
('failed', 'MISSING_HEALTHY_BACKUP', True), ('success', 'REPAIRED', True),
('restore', 'RESTORED_REVIEW_REQUIRED', True), ('busy', 'DATABASE_BUSY', False),
('unknown', 'UNKNOWN_DIALOG', False),
])
def test_recorded_startup_shell_loads_target_with_input_indicator_windows(
tmp_path, monkeypatch, scenario, expected, closed):
import win32con
ui, root, job, actions, polls = real_shape_repair_fixture(tmp_path, monkeypatch, scenario)
assert ui.repair_worker_main(job) == (0 if scenario == 'success' else 1)
result = json.loads((root/'repair-result.json').read_text('utf-8'))
assert len(polls) >= 4 and polls[2] >= .4
assert result['status'] == expected
assert actions[:2] == [(100, win32con.WM_COMMAND), (201, win32con.BM_CLICK)]
assert ((100, win32con.WM_CLOSE) in actions) is closed
assert result['release']['safe_to_continue'] is closed
assert 'Project is not in use' in json.loads((root/'native-output.json').read_text('utf-8'))['baseline']
@pytest.mark.parametrize('state,expected', [
('shell_stuck', 'TIMEOUT_UNRELEASED'), ('wrong_target', 'UNKNOWN_DIALOG'),
('duplicate_shell', 'UNKNOWN_DIALOG'), ('duplicate_target', 'UNKNOWN_DIALOG'),
('named_aux', 'UNKNOWN_DIALOG'), ('lookalike_aux', 'UNKNOWN_DIALOG'),
('missing_output', 'TIMEOUT_UNRELEASED'), ('busy_loading', 'DATABASE_BUSY'),
])
def test_recorded_startup_shape_retains_unconfirmed_or_unknown_state(tmp_path, monkeypatch, state, expected):
ui, root, job, actions, polls = real_shape_repair_fixture(tmp_path, monkeypatch, 'failed', state)
assert ui.repair_worker_main(job) == 1
result = json.loads((root/'repair-result.json').read_text('utf-8'))
assert result['status'] == expected
assert actions == []
assert result['release']['safe_to_continue'] is False
def test_generic_shell_after_invocation_is_not_a_startup_exception(tmp_path, monkeypatch):
import win32con
ui, root, job, actions, polls = real_shape_repair_fixture(tmp_path, monkeypatch, 'failed', 'shell_after_invoke')
assert ui.repair_worker_main(job) == 1
result = json.loads((root/'repair-result.json').read_text('utf-8'))
assert result['status'] == 'UNKNOWN_DIALOG'
assert actions == [(100, win32con.WM_COMMAND)]
assert result['release']['safe_to_continue'] is False
@pytest.mark.parametrize('verdict,expected', [
('', 'UNCONFIRMED'),
("Project is not in use. Full iCDB Project Backup's functionality is available.", 'UNCONFIRMED'),
('Project is in use. Full functionality is unavailable.', 'DATABASE_BUSY'),
])
def test_native_usage_check_progress_waits_for_actual_busy_verdict(verdict, expected):
from cbb_refresh_verify.native_repair_ui import classify_repair_evidence
output = '[2026-11-02 12:00:00] Checking if project is in use.\r\n'
output += '[2026-11-02 12:00:00] '+verdict
assert classify_repair_evidence('', '', '', output)['outcome'] == expected
+14
View File
@@ -12,3 +12,17 @@ def test_spec_packages_adaptive_dialog_rules_and_uia_modules():
text = Path('packaging/CbbRefreshVerify.spec').read_text(encoding='utf-8') text = Path('packaging/CbbRefreshVerify.spec').read_text(encoding='utf-8')
assert 'dialog_rules.v1.json' in text assert 'dialog_rules.v1.json' in text
assert 'pywinauto' in text assert 'pywinauto' in text
def test_spec_analysis_includes_pywin32_timezone_dynamic_import():
from types import SimpleNamespace
captured = {}
def analysis(*args, **kwargs):
captured.update(kwargs)
return SimpleNamespace(pure=[], scripts=[], binaries=[], zipfiles=[], datas=[])
path = Path('packaging/CbbRefreshVerify.spec')
namespace = {'SPECPATH': str(path.parent.resolve()), 'Analysis': analysis,
'PYZ': lambda *a, **k: None, 'EXE': lambda *a, **k: None,
'COLLECT': lambda *a, **k: None}
exec(compile(path.read_text(encoding='utf-8'), str(path), 'exec'), namespace)
assert 'win32timezone' in captured['hiddenimports']
+12
View File
@@ -89,3 +89,15 @@ def test_success_requires_save_and_pcb_exit():
assert execution_outcome(save_complete=True, pcb_exited=True)['status'] == 'PASS' assert execution_outcome(save_complete=True, pcb_exited=True)['status'] == 'PASS'
assert execution_outcome(save_complete=False, pcb_exited=True)['status'] == 'FAIL' assert execution_outcome(save_complete=False, pcb_exited=True)['status'] == 'FAIL'
assert execution_outcome(save_complete=True, pcb_exited=False)['status'] == 'FAIL' assert execution_outcome(save_complete=True, pcb_exited=False)['status'] == 'FAIL'
def test_connected_com_without_document_remains_startup_and_checks_native_failure(tmp_path):
errors = iter(('', 'ICDB_REPAIR_REQUIRED: original lost session'))
events = []
with pytest.raises(PcbBridgeError) as raised:
wait_for_target_document(job(tmp_path), lambda: Application(None), process_alive=lambda: True,
error_reader=lambda: next(errors), emit=lambda **e: events.append(e), sleep=lambda _: None)
assert raised.value.error_code == 'PCB_STARTUP_FAILED'
assert 'original lost session' in str(raised.value)
assert [e['stage'] for e in events] == ['pcb_document_wait']
assert events[0]['error_code'] == 'PCB_DOCUMENT_NOT_READY'
+51
View File
@@ -0,0 +1,51 @@
from dataclasses import replace
import json
from pathlib import Path
from cbb_refresh_verify.dialog_models import WindowSnapshot
def captured():
path = Path(__file__).parent/'fixtures/pcb-version-choice-sanitized.json'
return WindowSnapshot.from_record(json.loads(path.read_text(encoding='utf-8')))
def test_actual_version_choice_is_descriptive_fatal_without_action(tmp_path):
from cbb_refresh_verify.dialog_rules import decide, pcb_version_choice, archive_version_choice
from cbb_refresh_verify.post_repair_consent import exact_prompt
value = captured()
decision = decide(value, ())
assert decision.error_code == 'PCB_VERSION_CHOICE_REQUIRED' and not decision.action and not decision.channels
assert '2026/9/24 23:06' in decision.detail
assert '最后用户保存' in decision.detail and '自动保存' in decision.detail
assert not exact_prompt(value)
choice = pcb_version_choice(value)
assert [c['kind'] for c in choice['candidates']] == ['last_user_saved', 'autosave']
assert [c['date'] for c in choice['candidates']] == ['2026/9/24 23:06'] * 2
assert [c['selected'] for c in choice['candidates']] == [False, True]
path = archive_version_choice(value, tmp_path)
record = json.loads(path.read_text(encoding='utf-8'))
assert WindowSnapshot.from_record(record['snapshot']) == value
assert record['candidates'] == choice['candidates']
assert record['automatic_selection'] is False
def test_nonmatching_restoration_remains_blocked_with_original_context():
from cbb_refresh_verify.dialog_rules import decide, pcb_version_choice
value = replace(captured(), title='Other recovery choice')
decision = decide(value, ())
assert pcb_version_choice(value) is None
assert decision.error_code == 'DATABASE_RECOVERY_REQUIRED' and not decision.action
assert 'last user saved' in decision.detail
def test_version_choice_counts_as_pending_review_not_unknown_native_repair():
from cbb_refresh_verify.icdb_maintenance import maintenance_counts
from cbb_refresh_verify.verify_runner import VerifyResult, classify_failure_category
result = VerifyResult('FAIL', error_category='PCB_VERSION_CHOICE_REQUIRED', safe_to_continue=False,
recovery_attempts=({'status': 'PCB_VERSION_CHOICE_REQUIRED', 'native_status': 'REPAIRED',
'validation_passed': False},))
counts = maintenance_counts([result])
assert counts['repaired'] == 0 and counts['version_choice_required'] == 1
assert counts['repair_unconfirmed'] == 0 and counts['passed'] == 0
assert classify_failure_category('PCB_VERSION_CHOICE_REQUIRED: version pending\nPCB_RELEASE_UNCONFIRMED') == 'PCB_VERSION_CHOICE_REQUIRED'
+242
View File
@@ -0,0 +1,242 @@
"""Local recovery consent boundaries. No native application may be launched."""
from dataclasses import replace
import json
import os
from pathlib import Path
from types import SimpleNamespace
import pytest
@pytest.fixture(autouse=True)
def no_native_launch(monkeypatch):
import subprocess, win32process, win32com.client
def forbidden(*a, **k): raise AssertionError('native launching forbidden in consent tests')
monkeypatch.setattr(subprocess, 'Popen', forbidden)
monkeypatch.setattr(win32process, 'CreateProcess', forbidden)
monkeypatch.setattr(win32com.client, 'DispatchEx', forbidden)
monkeypatch.setattr(win32com.client, 'Dispatch', forbidden)
@pytest.fixture
def context(tmp_path, monkeypatch):
from test_native_repair import target_fixture, complete_native_success
from cbb_refresh_verify import post_repair_consent as consent
request, _, target = target_fixture(tmp_path)
request = replace(request, maintenance=True)
# Existing fixture contains only required native files and no address.
(target.project.parent/'PCB/pcb.prj').write_text('KEY CentralLibrary "old.lmc"\n')
monkeypatch.setattr(consent, '_process_records', lambda: [])
monkeypatch.setattr('cbb_refresh_verify.native_repair_ui._current_desktop_name', lambda: 'CbbVerify_fixture')
proof = consent.PostRepairProof.create(request, target, complete_native_success(target))
job = {'root': str(tmp_path/'verify'), 'lmc_file': str(request.lmc_file),
'project': str(target.project), 'pcb': str(target.project.parent/'PCB/actual.pcb'),
'block_name': request.block_name, 'desktop': 'CbbVerify_fixture', 'supervisor_pid': 55,
'interactive_input': False, 'native_lm_verify': False}
Path(job['root']).mkdir()
job['post_repair_consent'] = proof.for_job(job)
return request, target, proof, job
def snapshot():
from cbb_refresh_verify.post_repair_consent import PROMPT_TEXT
from cbb_refresh_verify.dialog_models import WindowSnapshot, ControlSnapshot, DialogPhase
return WindowSnapshot(100, 20, 'ExpeditionPCB.exe', 'pcb', '#32770', 'Expedition PCB',
DialogPhase.PCB_STARTING, (
ControlSnapshot(106, 6, 'Button', '是(&Y)'), ControlSnapshot(107, 7, 'Button', '否(&N)'),
ControlSnapshot(120, 20, 'Static', ''), ControlSnapshot(199, 65535, 'Static', PROMPT_TEXT)))
def test_no_generic_maintenance_flag_can_mint_consent(tmp_path):
from cbb_refresh_verify.post_repair_consent import PostRepairProof
from test_native_repair import target_fixture, complete_native_success
request, _, target = target_fixture(tmp_path)
with pytest.raises(ValueError): PostRepairProof.create(request, target, complete_native_success(target))
for status in ('RESTORED_REVIEW_REQUIRED', 'UNCONFIRMED', 'FAIL'):
result = complete_native_success(target); result['status'] = status
with pytest.raises(ValueError): PostRepairProof.create(replace(request, maintenance=True), target, result)
@pytest.mark.parametrize('kind', ['unc', 'network', 'removable', 'reparse'])
def test_consent_rejects_nonlocal_or_reparse_paths(context, monkeypatch, kind):
from cbb_refresh_verify import post_repair_consent as consent
request, _, _, _ = context
path = request.lmc_file
if kind == 'unc': path = Path(r'\\server\share\library.lmc')
monkeypatch.setattr(consent, '_drive_type', lambda path: {'network': 4, 'removable': 2}.get(kind, 3))
if kind == 'reparse':
original = Path.lstat
monkeypatch.setattr(Path, 'lstat', lambda self: SimpleNamespace(st_file_attributes=0x400)
if self == path.parent else original(self))
with pytest.raises(ValueError, match='LOCAL_FIXED'):
consent.require_local_fixed(path)
@pytest.mark.parametrize('obstacle', ['owner', 'address', 'exclusive', 'wrong_target', 'network', 'desktop'])
def test_prelaunch_proof_blocks_without_launch(context, monkeypatch, obstacle):
import win32file, win32con
from cbb_refresh_verify import post_repair_consent as consent
_, target, _, job = context
handle = None
if obstacle == 'owner': monkeypatch.setattr(consent, '_process_records', lambda: [(777, 'viewdraw.exe', '', '', 0)])
if obstacle == 'address':
p = target.database/'cdbsvr/sAddress.adr'; p.parent.mkdir(parents=True); p.touch()
if obstacle == 'exclusive':
handle = win32file.CreateFile(str(target.project.parent/'PCB/Layout/LayoutDB.lyt'), win32con.GENERIC_READ,
0, None, win32con.OPEN_EXISTING, 0, None)
if obstacle == 'wrong_target': job['pcb'] = str(Path(job['pcb']).with_name('other.pcb'))
if obstacle == 'network': monkeypatch.setattr(consent, '_drive_type', lambda path: 4)
if obstacle == 'desktop': monkeypatch.setattr('cbb_refresh_verify.native_repair_ui._current_desktop_name', lambda: 'Default')
try:
with pytest.raises((ValueError, OSError)):
consent.prepare_launch(job, ['C:/Mentor/common/win32/bin/ExpeditionPCB.exe', job['pcb'], '-ReusableCircuit'])
assert not (Path(job['root'])/'post-repair-prelaunch.json').exists()
finally:
if handle: handle.Close()
def test_exact_dialog_after_bound_prelaunch_is_allowed_only_once(context, monkeypatch):
from cbb_refresh_verify import post_repair_consent as consent
_, _, proof, job = context
command = ['C:/Mentor/common/win32/bin/ExpeditionPCB.exe', job['pcb'], '-ReusableCircuit']
consent.prepare_launch(job, command)
controller = consent.ConsentController(proof, job)
monkeypatch.setattr(consent, '_validate_current_processes', lambda *args: None)
calls = []
def perform(snap, payload, phase):
calls.append(payload)
return SimpleNamespace(accepted_controls=(6,), channel='win32_button_click', error_code='', detail='')
first = controller.handle(snapshot(), (snapshot(),), target_pid=20, launcher_pid=19,
worker_pid=os.getpid(), companion_pids=(), perform=perform)
assert first.action_sent and calls[0]['target'] == {'control_id': 6}
again = controller.handle(snapshot(), (snapshot(),), target_pid=20, launcher_pid=19,
worker_pid=os.getpid(), companion_pids=(), perform=perform)
assert not again.action_sent and len(calls) == 1
changed = replace(snapshot(), hwnd=101)
rejected = controller.handle(changed, (changed,), target_pid=20, launcher_pid=19,
worker_pid=os.getpid(), companion_pids=(), perform=perform)
assert rejected.error_code == 'DATABASE_RECOVERY_REQUIRED' and len(calls) == 1
@pytest.mark.parametrize('change', ['pid', 'phase', 'text', 'button', 'extra', 'proof', 'foreign_owner'])
def test_consent_rejects_unbound_or_changed_prompt(context, monkeypatch, change):
from cbb_refresh_verify import post_repair_consent as consent
from cbb_refresh_verify.dialog_models import DialogPhase, ControlSnapshot
_, _, proof, job = context
consent.prepare_launch(job, ['C:/Mentor/common/win32/bin/ExpeditionPCB.exe', job['pcb'], '-ReusableCircuit'])
controller = consent.ConsentController(proof, job)
snap = snapshot()
if change == 'pid': snap = replace(snap, pid=99)
if change == 'phase': snap = replace(snap, phase=DialogPhase.SAVE)
if change == 'text': snap = replace(snap, controls=(*snap.controls[:-1], replace(snap.controls[-1], name='Confirm read/write?')))
if change == 'button': snap = replace(snap, controls=(replace(snap.controls[0], enabled=False), *snap.controls[1:]))
if change == 'extra': snap = replace(snap, controls=(*snap.controls, ControlSnapshot(300, 99, 'Button', 'Overwrite')))
if change == 'proof': (Path(job['root'])/'post-repair-prelaunch.json').write_text('{}')
def processes(*a):
if change == 'foreign_owner': raise ValueError('unexpected owner')
monkeypatch.setattr(consent, '_validate_current_processes', processes)
result = controller.handle(snap, (snap,), target_pid=20, launcher_pid=19, worker_pid=os.getpid(),
companion_pids=(), perform=lambda *a: pytest.fail('unapproved consent sent'))
assert result.error_code == 'DATABASE_RECOVERY_REQUIRED'
@pytest.mark.parametrize('change', ['', 'other_owner', 'target_command', 'launcher_command', 'target_parent',
'launcher_parent', 'executable', 'missing_launcher'])
def test_current_process_identity_requires_exact_owned_launch_chain(context, monkeypatch, change):
from cbb_refresh_verify import post_repair_consent as consent
_, _, _, job = context
launcher = r'C:\Mentor\common\win32\bin\ExpeditionPCB.exe'
worker = r'C:\Mentor\wg\win32\bin\ExpeditionPCB.exe'
command = lambda exe: f'"{exe}" "{job["pcb"]}" -ReusableCircuit'
rows = [(19, 'ExpeditionPCB.exe', launcher, command(launcher), 18),
(20, 'ExpeditionPCB.exe', worker, command(worker), 19)]
if change == 'other_owner': rows.append((99, 'viewdraw.exe', 'viewdraw.exe', '', 0))
if change == 'target_command': rows[1] = (20, 'ExpeditionPCB.exe', worker, 'other.pcb -ReusableCircuit', 19)
if change == 'launcher_command': rows[0] = (19, 'ExpeditionPCB.exe', launcher, 'other.pcb -ReusableCircuit', 18)
if change == 'target_parent': rows[1] = (*rows[1][:4], 999)
if change == 'launcher_parent': rows[0] = (*rows[0][:4], 999)
if change == 'executable': rows[1] = (20, 'ExpeditionPCB.exe', 'C:/unrelated/ExpeditionPCB.exe', command(worker), 19)
if change == 'missing_launcher': rows.pop(0)
monkeypatch.setattr(consent, '_process_records', lambda: rows)
args = (job, {'command': [launcher, job['pcb'], '-ReusableCircuit']}, 20, 19, 18, ())
if change:
with pytest.raises(ValueError): consent._validate_current_processes(*args)
else:
consent._validate_current_processes(*args)
@pytest.mark.parametrize('change', ['', 'desktop', 'pid', 'text', 'button', 'generic_action'])
def test_agent_revalidates_real_window_before_single_button_message(monkeypatch, change):
import win32gui, win32process
from cbb_refresh_verify.dialog_agent import DialogActionExecutor
from cbb_refresh_verify import native_repair_ui
value = snapshot()
controls = {c.handle: c for c in value.controls}
monkeypatch.setattr(native_repair_ui, '_current_desktop_name', lambda: 'Default' if change == 'desktop' else 'CbbVerify_fixture')
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda hwnd: (1, 99 if change == 'pid' else 20))
monkeypatch.setattr(win32gui, 'GetClassName', lambda hwnd: '#32770' if hwnd == 100 else controls[hwnd].class_name)
monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: 'Expedition PCB' if hwnd == 100 else
'changed prompt' if change == 'text' and hwnd == 199 else controls[hwnd].name)
monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda hwnd: True)
monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda hwnd: not (change == 'button' and hwnd == 106))
monkeypatch.setattr(win32gui, 'GetDlgCtrlID', lambda hwnd: controls[hwnd].control_id)
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda hwnd, callback, arg:
[callback(child, arg) for child in controls])
calls = []
monkeypatch.setattr(win32gui, 'PostMessage', lambda *args: calls.append(args))
payload = {'action': 'post_repair_local_read_write', 'channels': ['win32_button_click'],
'target': {'control_id': 6}, 'pid': 20, 'desktop': 'CbbVerify_fixture'}
if change == 'generic_action': payload.pop('desktop')
result = DialogActionExecutor().perform(value, payload)
assert bool(result.accepted_controls) is (not change)
assert len(calls) == (0 if change else 1)
def test_ordinary_rule_remains_hard_blocked_for_exact_recovery_prompt():
from cbb_refresh_verify.dialog_rules import decide
assert decide(snapshot(), ()).error_code == 'DATABASE_RECOVERY_REQUIRED'
def enriched_snapshot():
"""Sanitized actual aa-r2 merged Win32/UIA capture (only HWNDs changed)."""
from cbb_refresh_verify.dialog_models import ControlSnapshot
value = snapshot()
native = (replace(value.controls[0], name='是(Y)', automation_id='6', control_type='Button', patterns=('Invoke',)),
replace(value.controls[1], name='否(N)', automation_id='7', control_type='Button', patterns=('Invoke',)),
replace(value.controls[2], automation_id='20', control_type='Image'),
replace(value.controls[3], automation_id='65535', control_type='Text'))
return replace(value, controls=(*native,
ControlSnapshot(value.hwnd, 0, '#32770', 'Expedition PCB', control_type='Window', patterns=('Window',)),
ControlSnapshot(0, 0, '', '', control_type='TitleBar', patterns=('Value',)),
ControlSnapshot(0, 0, '', '关闭', control_type='Button', enabled=False, patterns=('Invoke',))))
@pytest.mark.parametrize('change', ['', 'extra_real_child', 'enabled_close', 'titlebar_text', 'other_self'])
def test_enriched_native_prompt_ignores_only_observed_uia_chrome(change):
from cbb_refresh_verify.post_repair_consent import exact_prompt
from cbb_refresh_verify.dialog_models import ControlSnapshot
value = enriched_snapshot()
if change == 'extra_real_child':
value = replace(value, controls=(*value.controls, ControlSnapshot(888, 0, '', '关闭',
control_type='Button', enabled=False, patterns=('Invoke',))))
if change == 'enabled_close': value = replace(value, controls=(*value.controls[:-1], replace(value.controls[-1], enabled=True)))
if change == 'titlebar_text': value = replace(value, controls=(*value.controls[:-2], replace(value.controls[-2], name='unexpected'), value.controls[-1]))
if change == 'other_self': value = replace(value, controls=(*value.controls[:4], replace(value.controls[4], handle=999), *value.controls[5:]))
assert exact_prompt(value) is (not change)
def test_enriched_prompt_still_reaches_live_native_child_check(monkeypatch):
import win32gui, win32process
from cbb_refresh_verify.post_repair_consent import validate_action_window
from cbb_refresh_verify import native_repair_ui
value = enriched_snapshot()
native = {c.handle: c for c in value.controls[:4]}
monkeypatch.setattr(native_repair_ui, '_current_desktop_name', lambda: 'CbbVerify_fixture')
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda hwnd: (1, 20))
monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda hwnd: True)
monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda hwnd: True)
monkeypatch.setattr(win32gui, 'GetClassName', lambda hwnd: value.window_class if hwnd == value.hwnd else native[hwnd].class_name)
monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: value.title if hwnd == value.hwnd else native[hwnd].name)
monkeypatch.setattr(win32gui, 'GetDlgCtrlID', lambda hwnd: native[hwnd].control_id)
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda hwnd, fn, arg: [fn(child, arg) for child in native])
validate_action_window(value, {'pid':20, 'desktop':'CbbVerify_fixture'})
+99 -2
View File
@@ -1,11 +1,16 @@
"""Production safeguards: no input injection, no desktop switching, no menu driving. """Production safeguards: no input injection or uncontrolled menu driving.
These asserts encode the operating rules for this tool: the user's mouse, These asserts encode the operating rules for this tool: the user's mouse,
keyboard and desktop are never touched. Dialogs that belong to a process this keyboard and desktop are never touched. Dialogs that belong to a process this
run started are answered with a posted BM_CLICK, which is a message to that run started are answered with a posted BM_CLICK, which is a message to that
dialog and not user input. dialog and not user input. Native Project Backup Repair is restricted to an
owned private desktop/PID, a resolved resource command and an exact PRJ.
""" """
from pathlib import Path from pathlib import Path
import ast
import json
import pytest
SOURCE_ROOT = Path(__file__).resolve().parents[1]/'src'/'cbb_refresh_verify' SOURCE_ROOT = Path(__file__).resolve().parents[1]/'src'/'cbb_refresh_verify'
@@ -40,6 +45,11 @@ def test_no_input_injection_or_desktop_switching_in_production_code():
for path in production_sources(): for path in production_sources():
text = path.read_text(encoding='utf-8') text = path.read_text(encoding='utf-8')
for api in FORBIDDEN_APIS: for api in FORBIDDEN_APIS:
if path.name == 'native_repair_ui.py' and api == 'WM_COMMAND':
# Only the installed Project Backup Repair menu is allowed:
# resolve its native resource, own the private desktop/PID,
# and confirm the exact PRJ before posting the command.
continue
if path.name == 'library_manager_verify.py' and api in {'WM_MOUSEMOVE', 'TVM_SELECTITEM'}: if path.name == 'library_manager_verify.py' and api in {'WM_MOUSEMOVE', 'TVM_SELECTITEM'}:
continue continue
if path.name == 'library_manager_verify.py' and api == 'click_input': if path.name == 'library_manager_verify.py' and api == 'click_input':
@@ -98,9 +108,44 @@ def test_desktop_worker_close_kills_unbound_worker_tree():
assert 'self.kill()' in text assert 'self.kill()' in text
def _without_authorized_checkpoint_cleanup(text):
"""Exempt exact protocol-checkpoint callsites, never the whole module."""
tree = ast.parse(text)
parents = {child: parent for parent in ast.walk(tree) for child in ast.iter_child_nodes(parent)}
allowed = {('LibraryLock', '_exit_owned'): 'marker', ('release_retained_library',): 'checkpoint'}
used, spans = set(), []
for call in ast.walk(tree):
if not (isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute)
and call.func.attr == 'unlink' and isinstance(call.func.value, ast.Name) and not call.args):
continue
scope, parent = [], parents.get(call)
while parent is not None:
if isinstance(parent, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)):
scope.insert(0, parent.name)
parent = parents.get(parent)
scope = tuple(scope)
if scope in used or allowed.get(scope) != call.func.value.id:
continue
expected = ([] if scope == ('release_retained_library',) else [('missing_ok', True)])
keywords = [(k.arg, k.value.value if isinstance(k.value, ast.Constant) else None) for k in call.keywords]
if keywords == expected and call.lineno == call.end_lineno:
spans.append((call.lineno - 1, call.col_offset, call.end_col_offset))
used.add(scope)
lines = text.splitlines(keepends=True)
for line, start, end in sorted(spans, reverse=True):
# AST column offsets are UTF-8 byte offsets.
data = lines[line].encode('utf-8')
lines[line] = (data[:start] + b'checkpoint_cleanup' + data[end:]).decode('utf-8')
return ''.join(lines)
def test_verification_never_deletes_or_moves_library_files(): def test_verification_never_deletes_or_moves_library_files():
for path in production_sources(): for path in production_sources():
text = path.read_text(encoding='utf-8') text = path.read_text(encoding='utf-8')
if path == SOURCE_ROOT/'library_lock.py':
# Approved runtime JSON lifecycle only. Actual sidecar/engineering
# protection is also exercised against real files below.
text = _without_authorized_checkpoint_cleanup(text)
for operation in ('os.remove', '.unlink('): for operation in ('os.remove', '.unlink('):
assert operation not in text, f'{path.name} 不得删除/移动中心库文件' assert operation not in text, f'{path.name} 不得删除/移动中心库文件'
adapter = (SOURCE_ROOT/'mentor_adapter.py').read_text(encoding='utf-8') adapter = (SOURCE_ROOT/'mentor_adapter.py').read_text(encoding='utf-8')
@@ -110,3 +155,55 @@ def test_verification_never_deletes_or_moves_library_files():
# cdbsvr address advertisement; stable CBB content remains untouched. # cdbsvr address advertisement; stable CBB content remains untouched.
assert 'shutil.move' not in adapter assert 'shutil.move' not in adapter
assert "sAddress.adr" in adapter assert "sAddress.adr" in adapter
def test_checkpoint_cleanup_exception_does_not_allow_other_deletions():
source = '''
class LibraryLock:
def _exit_owned(self):
marker.unlink(missing_ok=True)
self.path.unlink()
def release_retained_library():
checkpoint.unlink()
os.remove('lib.lmc')
def other_operation():
marker.unlink(missing_ok=True)
'''
checked = _without_authorized_checkpoint_cleanup(source)
assert 'self.path.unlink()' in checked and 'os.remove(' in checked
assert checked.count('marker.unlink(missing_ok=True)') == 1
@pytest.mark.parametrize('replacement', ['', 'malformed', 'foreign_lease'])
def test_guard_cleanup_only_removes_current_validated_checkpoint(tmp_path, replacement):
from cbb_refresh_verify import library_lock as locks
library = tmp_path/'library.lmc'
protected = {library: b'LMC engineering', tmp_path/'icdb.dat': b'schematic engineering',
tmp_path/'LayoutDB.lyt': b'layout engineering', tmp_path/'ordinary.json': b'ordinary data'}
for path, data in protected.items(): path.write_bytes(data)
lease = locks.LibraryLock(library)
lease.__enter__()
marker = locks.blocker_path(library)
try:
if replacement:
if replacement == 'malformed':
data = b'ordinary file replacing a checkpoint'
else:
record = json.loads(marker.read_text(encoding='utf-8'))
record['lease_id'] = '0' * 32
data = json.dumps(record).encode('utf-8')
marker.write_bytes(data)
with pytest.raises(locks.LibraryBusy): lease.__exit__(None, None, None)
assert marker.read_bytes() == data
with pytest.raises(locks.LibraryBusy):
with locks.LibraryLock(library): pass
else:
lease.__exit__(None, None, None)
assert not marker.exists()
assert lease.path.is_file() # The uploader's actual exclusive sidecar is never deleted.
assert all(path.read_bytes() == data for path, data in protected.items())
finally:
# This test never launches native owners; release only its retained fake lease.
with locks._guard:
owner = locks._owners.pop(lease.key, None)
if owner: owner['handle'].Close()
+335
View File
@@ -0,0 +1,335 @@
"""File-level regressions: complete snapshots, scoped semantic conflicts."""
import hashlib
import os
from pathlib import Path
import shutil
import pytest
from cbb_refresh_verify import backup_recovery as recovery
def put(root, relative, data=b'engineering'):
path = root / relative
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
return path
@pytest.mark.parametrize('relative', [
'A.prj', 'PCB/A.pcb', 'PCB/A.dxp', 'database/icdb.dat',
'PCB/Layout/LayoutDB.lyt', 'schematic/sheet.1', 'logic/block.1',
'symbols/device.sym', 'CES/constraints.ces', 'config/native.cfg',
'unknown/new-engineering-format.bin', 'notes.txt',
])
def test_primary_edits_additions_and_deletions_change_semantics(tmp_path, relative):
path = put(tmp_path, relative)
before = recovery._manifest(tmp_path)
assert before['version'] == 1
entry = before['files'][relative]
assert entry == {'size': len(b'engineering'),
'sha256': hashlib.sha256(b'engineering').hexdigest(), 'scope': 'project'}
path.write_bytes(b'changed')
assert recovery._manifest(tmp_path) != before
path.unlink()
assert recovery._manifest(tmp_path) != before
put(tmp_path, relative, b'engineering')
put(tmp_path, 'additional.dat')
assert recovery._manifest(tmp_path) != before
@pytest.mark.parametrize('relative', [
'logs/session.txt', 'log/native.log', 'session.log', 'temp/native.bin',
'tmp/native.bin', 'session.tmp', 'database/icdb.lck',
'database/cdbsvr/sAddress.adr', '.target.cbb-upload.lock',
'backups/old/A.prj', 'backup/old/icdb.dat', 'A.prj.bak',
'drawing.pdf', 'output/netlist.txt', 'reports/check.txt',
])
def test_runtime_history_and_generated_content_is_copied_but_not_hashed(tmp_path, relative):
source = tmp_path/'source'
put(source, 'A.prj')
runtime = put(source, relative, b'old')
destination = tmp_path/'copy'
progress = []
manifest = recovery._copy_verified(source, destination, progress=progress.append)
assert (destination/relative).read_bytes() == b'old'
assert manifest['version'] == 1
assert set(manifest['files']) == {'A.prj'}
assert progress[-1]['hashed_files'] == 1
assert progress[-1]['hashed_bytes'] == len(b'engineering')
assert progress[-1]['stage'] == 'copy'
runtime.write_bytes(b'new runtime content')
put(source, 'logs/new-session.log')
assert recovery._manifest(source) == manifest
runtime.unlink()
assert recovery._manifest(source) == manifest
def test_central_scope_hashes_target_work_cert_root_config_and_shared_dependencies(tmp_path):
from cbb_refresh_verify.scoped_manifest import ManifestScope
scope = ManifestScope.library('A', 'target.lmc')
expected = {
'target.lmc': 'library_config',
'library.xml': 'library_config',
'ReusableBlocksLP/A/Work/A.prj': 'target_work',
'ReusableBlocksLP/A/Cert/A.prj': 'target_cert',
'SymbolLibs/__ReusableBlocksSymb/icdb.dat': 'shared_dependency',
'CellDB/custom.cell': 'shared_dependency',
'PartDB/parts.pdb': 'shared_dependency',
'NewRequiredDependency/native.bin': 'shared_dependency',
}
for relative in expected:
put(tmp_path, relative)
unrelated = put(tmp_path, 'ReusableBlocksLP/B/Work/B.prj')
put(tmp_path, 'ReusableBlocksLP/A/Backups/old.prj')
put(tmp_path, 'other.lmc')
before = recovery._manifest(tmp_path, scope=scope)
assert before['scope'] == {'kind': 'library', 'block_name': 'A', 'library_name': 'target.lmc'}
assert {p: e['scope'] for p, e in before['files'].items()} == expected
unrelated.write_bytes(b'other project changed')
put(tmp_path, 'ReusableBlocksLP/C/Work/C.prj')
assert recovery._manifest(tmp_path, scope=scope) == before
for relative in expected:
path = tmp_path/relative
path.write_bytes(b'changed')
assert recovery._manifest(tmp_path, scope=scope) != before
path.write_bytes(b'engineering')
destination = tmp_path.parent/(tmp_path.name + '-copy')
assert recovery._copy_verified(tmp_path, destination, scope=scope) == before
assert (destination/'ReusableBlocksLP/B/Work/B.prj').read_bytes() == b'other project changed'
@pytest.mark.parametrize('relative', ['A.prj', 'database/icdb.dat', 'target.lmc'])
def test_corrupted_destination_bytes_are_rejected_and_evidence_is_preserved(tmp_path, monkeypatch, relative):
source = tmp_path/'source'
put(source, relative)
destination = tmp_path/'destination'
real_hash = recovery._hash
def corrupt_then_hash(path):
if path == destination/relative:
metadata = path.stat()
path.write_bytes(b'X' * metadata.st_size)
os.utime(path, ns=(metadata.st_atime_ns, metadata.st_mtime_ns))
return real_hash(path)
monkeypatch.setattr(recovery, '_hash', corrupt_then_hash)
with pytest.raises(OSError):
recovery._copy_verified(source, destination)
assert (source/relative).read_bytes() == b'engineering'
assert (destination/relative).exists()
def test_source_byte_changes_with_preserved_metadata_are_rejected(tmp_path, monkeypatch):
source, destination = tmp_path/'source', tmp_path/'destination'
primary = put(source, 'A.prj')
real_copy = shutil.copy2
def copy_then_change_source(src, dst, *args, **kwargs):
result = real_copy(src, dst, *args, **kwargs)
metadata = primary.stat()
primary.write_bytes(b'X' * metadata.st_size)
os.utime(primary, ns=(metadata.st_atime_ns, metadata.st_mtime_ns))
return result
monkeypatch.setattr(shutil, 'copy2', copy_then_change_source)
with pytest.raises(OSError):
recovery._copy_verified(source, destination)
assert (destination/'A.prj').read_bytes() == b'engineering'
@pytest.mark.parametrize('change', ['changed', 'deleted', 'added'])
def test_complete_tree_metadata_must_stay_stable_during_copy(tmp_path, monkeypatch, change):
source = tmp_path/'source'
put(source, 'A.prj')
runtime = put(source, 'logs/session.log')
destination = tmp_path/'destination'
real_copy = shutil.copy2
def copy_then_mutate(src, dst, *args, **kwargs):
result = real_copy(src, dst, *args, **kwargs)
if Path(src).name == 'A.prj':
if change == 'changed':
runtime.write_bytes(b'changed while copying')
elif change == 'deleted':
runtime.unlink()
else:
put(source, 'logs/added.log')
return result
monkeypatch.setattr(shutil, 'copy2', copy_then_mutate)
with pytest.raises(OSError):
recovery._copy_verified(source, destination)
assert destination.exists()
def test_destination_nonprimary_membership_and_size_are_validated(tmp_path, monkeypatch):
source = tmp_path/'source'
put(source, 'logs/session.log')
destination = tmp_path/'destination'
real_copy = shutil.copy2
def truncated(src, dst, *args, **kwargs):
result = real_copy(src, dst, *args, **kwargs)
Path(dst).write_bytes(b'x')
return result
monkeypatch.setattr(shutil, 'copy2', truncated)
with pytest.raises(OSError):
recovery._copy_verified(source, destination)
def test_semantic_scan_does_not_visit_runtime_or_unrelated_cbb_trees(tmp_path, monkeypatch):
from cbb_refresh_verify.scoped_manifest import ManifestScope
scope = ManifestScope.library('A', 'target.lmc')
put(tmp_path, 'target.lmc')
put(tmp_path, 'ReusableBlocksLP/A/Work/A.prj')
put(tmp_path, 'ReusableBlocksLP/B/Work/B.prj')
put(tmp_path, 'logs/transient.log')
before = recovery._manifest(tmp_path, scope=scope)
real_scan = os.scandir
def runtime_unavailable(path):
# These trees may be actively changing after the successful snapshot.
if Path(path) in (tmp_path/'logs', tmp_path/'ReusableBlocksLP/B'):
raise OSError('transient runtime/unrelated tree is unavailable')
return real_scan(path)
monkeypatch.setattr(os, 'scandir', runtime_unavailable)
assert recovery._manifest(tmp_path, scope=scope) == before
def test_only_primary_paths_are_read_for_sha256_and_manifest_is_relocatable(tmp_path, monkeypatch):
from cbb_refresh_verify.scoped_manifest import ManifestScope
scope = ManifestScope.library('A', 'target.lmc')
source, destination = tmp_path/'source', tmp_path/'destination'
primary = {'target.lmc', 'ReusableBlocksLP/A/Work/A.prj',
'SymbolLibs/shared/icdb.dat', 'config.xml'}
excluded = {'ReusableBlocksLP/B/Work/B.prj', 'logs/native.log', 'export.pdf',
'.target.cbb-upload.lock', 'backup/old/icdb.dat'}
for relative in primary | excluded:
put(source, relative)
real_hash = recovery._hash
hashed = []
def record_hash(path):
root = source if path.is_relative_to(source) else destination
relative = path.relative_to(root).as_posix()
assert relative in primary, f'Nonprimary content hashed: {relative}'
hashed.append(relative)
return real_hash(path)
monkeypatch.setattr(recovery, '_hash', record_hash)
manifest = recovery._copy_verified(source, destination, scope=scope)
assert set(hashed) == primary
assert recovery._manifest(source, scope=scope) == manifest
assert recovery._manifest(destination, scope=scope) == manifest
assert {p.relative_to(destination).as_posix() for p in destination.rglob('*') if p.is_file()} == primary | excluded
@pytest.mark.parametrize('block', ['Logs', 'lOgS', 'Temp', 'tEmP', 'Backup', 'bAcKuP', 'Output', 'rEpOrT',
'Log Files', 'ProjectBackup', 'Work.before-restore-engineering'])
@pytest.mark.parametrize('role', ['Work', 'Cert'])
def test_structural_cbb_identity_is_primary_in_semantic_and_copy_manifests(tmp_path, block, role):
from cbb_refresh_verify.scoped_manifest import ManifestScope
scope = ManifestScope.library(block, 'target.lmc')
source, destination = tmp_path/'source', tmp_path/'destination'
relative = f'ReusableBlocksLP/{block}/{role}/database/icdb.dat'
primary = put(source, relative)
runtime = f'ReusableBlocksLP/{block}/{role}/logs/session.txt'
put(source, runtime)
before = recovery._copy_verified(source, destination, scope=scope)
assert set(before['files']) == {relative}
assert (destination/runtime).read_bytes() == b'engineering'
assert recovery._manifest(source, scope=scope) == before
primary.write_bytes(b'concurrent primary edit')
assert recovery._manifest(source, scope=scope) != before
@pytest.mark.parametrize('relative', [
'SymbolLibs/temp/icdb.dat', 'SymbolLibs/Temp_a/device.sym',
'SymbolLibs/Logs/device.sym', 'SymbolLibs/BACKUP/device.sym',
'SymbolLibs/temp/cdbsvr/persistent.bin',
'ReusableBlocksLP/A/Work/hdl/Logs/design.v',
'ReusableBlocksLP/A/Cert/hdl/bAcKuP/design.v',
'SymbolLibs/temp/hdl/Backup/design.v', 'SharedDependency/hdl/Logs/design.v',
])
def test_library_engineering_partition_names_are_not_runtime_categories(tmp_path, relative):
from cbb_refresh_verify.scoped_manifest import ManifestScope
scope = ManifestScope.library('A', 'target.lmc')
source, destination = tmp_path/'source', tmp_path/'destination'
primary = put(source, relative)
before = recovery._copy_verified(source, destination, scope=scope)
assert relative in before['files']
assert recovery._manifest(source, scope=scope) == before
primary.write_bytes(b'concurrent shared/design edit')
assert recovery._manifest(source, scope=scope) != before
@pytest.mark.parametrize('relative', ['hdl/Logs/design.v', 'hdl/Backup/design.v', 'symbols/Temp/device.sym',
'hdl/Log Files/design.v', 'hdl/ProjectBackup/backups/design.v',
'hdl/Work.before-restore-engineering/design.v', 'database/cdbsvr/persistent.bin'])
def test_nested_project_engineering_names_remain_primary(tmp_path, relative):
primary = put(tmp_path, relative)
before = recovery._manifest(tmp_path)
assert relative in before['files']
primary.unlink()
assert recovery._manifest(tmp_path) != before
@pytest.mark.parametrize('relative', [
'ReusableBlocksLP/Logs/Work/Logs.prj',
'ReusableBlocksLP/Backup/Cert/Backup.prj',
'SymbolLibs/temp/device.sym', 'SharedDependency/hdl/Logs/design.v',
])
@pytest.mark.parametrize('side', ['source', 'destination'])
def test_colliding_engineering_names_cannot_bypass_primary_copy_byte_checks(tmp_path, monkeypatch, relative, side):
from cbb_refresh_verify.scoped_manifest import ManifestScope
block = relative.split('/')[1] if relative.startswith('ReusableBlocksLP/') else 'A'
scope = ManifestScope.library(block, 'target.lmc')
source, destination = tmp_path/'source', tmp_path/'destination'
put(source, relative)
real_copy = shutil.copy2
def copy_then_corrupt(src, dst, *args, **kwargs):
result = real_copy(src, dst, *args, **kwargs)
corrupt = Path(src) if side == 'source' else Path(dst)
metadata = corrupt.stat()
corrupt.write_bytes(b'X' * metadata.st_size)
os.utime(corrupt, ns=(metadata.st_atime_ns, metadata.st_mtime_ns))
return result
monkeypatch.setattr(shutil, 'copy2', copy_then_corrupt)
with pytest.raises(OSError):
recovery._copy_verified(source, destination, scope=scope)
assert (destination/relative).exists()
@pytest.mark.parametrize('prefix', ['', 'ReusableBlocksLP/Logs/Work/', 'ReusableBlocksLP/Temp/Cert/'])
@pytest.mark.parametrize('relative', [
'Log Files/ProjectBackupLog.txt', 'ProjectBackup/backups/old.zip',
'database/cdbsvr/log/session/text.txt', 'database/cdbsvr/dbcheck/session/text.txt',
'PCB/database/cdbsvr/dbrestore/session/text.txt',
])
def test_known_native_runtime_and_history_locations_are_ignored_contextually(tmp_path, prefix, relative):
from cbb_refresh_verify.scoped_manifest import ManifestScope
scope = ManifestScope.library(prefix.split('/')[1], 'target.lmc') if prefix else None
runtime = put(tmp_path, prefix + relative)
before = recovery._manifest(tmp_path, scope=scope)
assert not before['files']
runtime.write_bytes(b'updated runtime')
assert recovery._manifest(tmp_path, scope=scope) == before
@pytest.mark.parametrize('relative', ['SymbolLibs/temp/icdb.dat',
'ReusableBlocksLP/Logs/Work/database/icdb.dat'])
def test_locked_critical_bytes_in_colliding_names_are_checked_independently(tmp_path, relative):
from cbb_refresh_verify.scoped_manifest import ManifestScope
source, destination = tmp_path/'source', tmp_path/'destination'
put(source, relative)
def corrupt_after_copy(event):
if event['copied_files'] == event['total_files']:
copied = destination/relative
metadata = copied.stat()
copied.write_bytes(b'X' * metadata.st_size)
os.utime(copied, ns=(metadata.st_atime_ns, metadata.st_mtime_ns))
with pytest.raises(OSError):
recovery._copy_verified(source, destination,
scope=ManifestScope.library('Logs', 'target.lmc'), progress=corrupt_after_copy)
assert (source/relative).read_bytes() == b'engineering'
assert (destination/relative).read_bytes() == b'XXXXXXXXXXX'
@pytest.mark.parametrize('relative', ['SymbolLibs/temp/cdbsvr/log/session/text.txt',
'SymbolLibs/Temp_a/cdbsvr/dbcheck/session/text.txt',
'CellDB/cdbsvr/dbrestore/session/text.txt'])
def test_shared_native_runtime_has_explicit_database_context(tmp_path, relative):
from cbb_refresh_verify.scoped_manifest import ManifestScope
put(tmp_path, relative)
assert not recovery._manifest(tmp_path, scope=ManifestScope.library('A', 'target.lmc'))['files']
+100 -6
View File
@@ -1,4 +1,5 @@
import os import os
import pytest
from pathlib import Path from pathlib import Path
os.environ.setdefault('QT_QPA_PLATFORM','offscreen') os.environ.setdefault('QT_QPA_PLATFORM','offscreen')
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
@@ -20,6 +21,98 @@ def test_application_palette_keeps_table_text_readable(qtbot):
assert base.value() > 180 assert base.value() > 180
def fake_reader(_): return LibraryReadResult((CbbRecord('CBB1','Reusable Blocks'),)) def fake_reader(_): return LibraryReadResult((CbbRecord('CBB1','Reusable Blocks'),))
@pytest.fixture(autouse=True)
def isolate_authoritative_native_refresh(monkeypatch):
# 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})
def test_global_icdb_action_confirms_and_excludes_ready_rows(qtbot, tmp_path, monkeypatch):
from PySide6.QtWidgets import QMessageBox
calls = []
window = MainWindow(reader=lambda _: LibraryReadResult((
CbbRecord('READY', 'LP', status='READY'), CbbRecord('PENDING', 'LP'))),
verifier=lambda req: (calls.append(req.block_name) or VerifyResult('PASS')),
data_root=tmp_path)
qtbot.addWidget(window)
window.lmc_edit.setText('lib.lmc'); window.load_library()
qtbot.waitUntil(lambda: not window.busy)
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.No)
window.icdb_repair_button.click()
assert calls == []
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
window.icdb_repair_button.click()
qtbot.waitUntil(lambda: not window.busy)
assert calls == ['PENDING']
def test_global_icdb_action_disabled_without_library_or_while_busy(qtbot):
window = MainWindow(reader=fake_reader)
qtbot.addWidget(window)
assert not window.icdb_repair_button.isEnabled()
window.lmc_edit.setText('lib.lmc'); window.load_library()
qtbot.waitUntil(lambda: not window.busy)
assert window.icdb_repair_button.isEnabled()
window.busy = True; window._update()
assert not window.icdb_repair_button.isEnabled()
def test_global_icdb_failure_preserves_untargeted_ready_and_stops_queue(qtbot, tmp_path, monkeypatch):
from PySide6.QtWidgets import QMessageBox
calls = []
window = MainWindow(reader=lambda _: LibraryReadResult((
CbbRecord('A', 'LP', status='READY'), CbbRecord('B', 'LP'), CbbRecord('C', 'LP'))),
verifier=lambda req: (calls.append(req.block_name) or VerifyResult(
'FAIL', stderr='unconfirmed', safe_to_continue=False)), data_root=tmp_path)
qtbot.addWidget(window)
window.lmc_edit.setText('lib.lmc'); window.load_library()
qtbot.waitUntil(lambda: not window.busy)
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
window.icdb_repair_button.click()
qtbot.waitUntil(lambda: not window.busy)
assert calls == ['B']
assert 'A' in window.ready_names
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):
from PySide6.QtWidgets import QMessageBox
confirmations = []
def confirm(*args, **kwargs):
confirmations.append(args[2])
return QMessageBox.Yes
monkeypatch.setattr(QMessageBox, 'question', confirm)
window = MainWindow(reader=fake_reader, data_root=tmp_path,
verifier=lambda _: VerifyResult('FAIL', safe_to_continue=False, recovery_attempts=(
{'status': 'RESTORED_REVIEW_REQUIRED', 'detail': 'restored old backup'},)))
qtbot.addWidget(window)
window.lmc_edit.setText('lib.lmc'); window.load_library()
qtbot.waitUntil(lambda: not window.busy)
window.icdb_repair_button.click()
qtbot.waitUntil(lambda: not window.busy)
assert 'lib.lmc' in confirmations[0]
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 检查与修复结果'
reports = list((tmp_path/'reports').glob('icdb-*.json'))
assert len(reports) == 1
def test_ready_row_missing_project_is_skipped_by_global_maintenance(qtbot, tmp_path):
library = tmp_path/'library.lmc'
library.touch()
window = MainWindow(reader=lambda _: LibraryReadResult((CbbRecord('MISSING', 'LP', status='READY'),)),
data_root=tmp_path)
qtbot.addWidget(window)
window.lmc_edit.setText(str(library)); window.load_library()
qtbot.waitUntil(lambda: not window.busy)
assert window.skipped_names == {'MISSING'}
assert 'MISSING' not in window.ready_names
assert not window.icdb_repair_button.isEnabled()
assert '缺少工程' in window.cbb_table.item(0, 2).text()
def test_verify_requires_loaded_library_and_invalidates_on_path_change(qtbot): def test_verify_requires_loaded_library_and_invalidates_on_path_change(qtbot):
window=MainWindow(reader=fake_reader, verifier=lambda _: VerifyResult('PASS')); qtbot.addWidget(window) window=MainWindow(reader=fake_reader, verifier=lambda _: VerifyResult('PASS')); qtbot.addWidget(window)
assert not window.batch_button.isEnabled() assert not window.batch_button.isEnabled()
@@ -72,8 +165,8 @@ def test_import_incomplete_rows_are_skipped_and_disabled(qtbot, tmp_path):
window.lmc_edit.setText(str(lmc)) window.lmc_edit.setText(str(lmc))
window.load_library() window.load_library()
qtbot.waitUntil(lambda: window.batch_button.isEnabled()) qtbot.waitUntil(lambda: window.batch_button.isEnabled())
assert window.cbb_table.item(0, 2).text().startswith('跳过:') assert '缺少工程' in window.cbb_table.item(0, 2).text()
assert not (window.cbb_table.item(0, 0).flags() & Qt.ItemIsUserCheckable) assert window.cbb_table.item(0, 0).flags() & Qt.ItemIsUserCheckable
window.verify_all() window.verify_all()
qtbot.waitUntil(lambda: not window.busy) qtbot.waitUntil(lambda: not window.busy)
assert calls == ['VALID_CBB'] assert calls == ['VALID_CBB']
@@ -134,7 +227,7 @@ def test_large_library_load_does_not_update_controls_for_every_table_cell(qtbot,
assert window._row_by_name['CBB_0299'] == 299 assert window._row_by_name['CBB_0299'] == 299
assert len(calls) < 20 assert len(calls) < 20
def test_ready_rows_show_status_and_cannot_be_selected_or_verified(qtbot, tmp_path): def test_ready_rows_allow_management_selection_but_cannot_be_verified(qtbot, tmp_path):
def reader(_): def reader(_):
return LibraryReadResult((CbbRecord('READY_CBB', 'LP', status='READY'), CbbRecord('PENDING_CBB', 'LP', status='PENDING'))) return LibraryReadResult((CbbRecord('READY_CBB', 'LP', status='READY'), CbbRecord('PENDING_CBB', 'LP', status='PENDING')))
calls = [] calls = []
@@ -145,15 +238,16 @@ def test_ready_rows_show_status_and_cannot_be_selected_or_verified(qtbot, tmp_pa
qtbot.waitUntil(lambda: window.batch_button.isEnabled()) qtbot.waitUntil(lambda: window.batch_button.isEnabled())
assert window.cbb_table.columnCount() == 4 assert window.cbb_table.columnCount() == 4
assert window.cbb_table.item(0, 2).text() == '绿色 / Ready' assert window.cbb_table.item(0, 2).text() == '绿色 / Ready'
assert not (window.cbb_table.item(0, 0).flags() & Qt.ItemIsUserCheckable) assert window.cbb_table.item(0, 0).flags() & Qt.ItemIsUserCheckable
assert window.cbb_table.item(0, 0).background().color().name().lower() == '#e8f5e9' assert window.cbb_table.item(0, 0).background().color().name().lower() == '#e8f5e9'
window.cbb_table.item(0, 0).setCheckState(Qt.Checked) window.cbb_table.item(0, 0).setCheckState(Qt.Checked)
assert 'READY_CBB' not in window._selected_names() assert 'READY_CBB' in window._selected_names()
assert not window.selected_batch_button.isEnabled()
window.verify_all() window.verify_all()
qtbot.waitUntil(lambda: not window.busy) qtbot.waitUntil(lambda: not window.busy)
assert calls == ['PENDING_CBB'] assert calls == ['PENDING_CBB']
assert window.cbb_table.item(1, 0).checkState() == Qt.Unchecked assert window.cbb_table.item(1, 0).checkState() == Qt.Unchecked
assert not (window.cbb_table.item(1, 0).flags() & Qt.ItemIsUserCheckable) assert window.cbb_table.item(1, 0).flags() & Qt.ItemIsUserCheckable
assert window.cbb_table.item(1, 0).background().color().name().lower() == '#e8f5e9' assert window.cbb_table.item(1, 0).background().color().name().lower() == '#e8f5e9'
+290
View File
@@ -0,0 +1,290 @@
"""Local catalog scope and authoritative status refresh regression tests."""
import json
import time
from threading import Event
from pathlib import Path
from types import SimpleNamespace
import pytest
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QMessageBox
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
from cbb_refresh_verify.ui.main_window import MainWindow
from cbb_refresh_verify.verify_runner import VerifyResult
MIXED = (
CbbRecord('Alpha', 'Power', status='READY'),
CbbRecord('Beta', 'Power', status='PENDING'),
CbbRecord('Gamma', 'Analog', status='UNKNOWN'),
CbbRecord('Delta', 'Analog', status='ERROR'),
CbbRecord('Missing', 'Power', status='READY'),
)
def load_window(qtbot, tmp_path, monkeypatch, records=MIXED, **kwargs):
import cbb_refresh_verify.ui.main_window as ui
monkeypatch.setattr(ui, 'preflight_skip_reason',
lambda _, name: 'missing project' if name == 'Missing' else None)
lease = SimpleNamespace(mentor_path=Path('test.lmc'), close=lambda: None,
retain_for_recovery=lambda: None)
window = MainWindow(reader=lambda _: LibraryReadResult(records), data_root=tmp_path,
path_lease_factory=lambda _: lease, **kwargs)
qtbot.addWidget(window)
window.lmc_edit.setText('test.lmc')
window.load_library()
qtbot.waitUntil(lambda: not window.busy)
return window
def names(records):
return [record.name for record in records]
def test_search_and_filters_use_cached_catalog_and_count_visible_states(qtbot, tmp_path, monkeypatch):
window = load_window(qtbot, tmp_path, monkeypatch)
window.reader = lambda _: pytest.fail('filter reread Mentor')
assert window.visible_counts() == {'visible': 5, 'ready': 2, 'error': 3}
expected = {
'ready': ['Alpha', 'Missing'], 'non_ready': ['Beta', 'Gamma', 'Delta'],
'pending': ['Beta'], 'errors': ['Gamma', 'Delta'], 'missing': ['Missing'],
}
for mode, wanted in expected.items():
window.status_filter.setCurrentIndex(window.status_filter.findData(mode))
assert names(window.visible_records()) == wanted
window.status_filter.setCurrentIndex(window.status_filter.findData('all'))
window.search_edit.setText(' ANALOG ')
assert names(window.visible_records()) == ['Gamma', 'Delta']
assert window.visible_counts() == {'visible': 2, 'ready': 0, 'error': 2}
window.search_edit.setText('aLpH')
assert names(window.visible_records()) == ['Alpha']
assert '1' in window.counts_label.text()
def test_management_selection_includes_ready_and_missing_but_hiding_clears_checks(qtbot, tmp_path, monkeypatch):
window = load_window(qtbot, tmp_path, monkeypatch)
window.select_visible_button.click()
assert names(window.selected_records()) == ['Alpha', 'Beta', 'Gamma', 'Delta', 'Missing']
assert window.selected_records()[0].logical_type == 'LP'
window.search_edit.setText('power')
assert names(window.selected_records()) == ['Alpha', 'Beta', 'Missing']
window.search_edit.clear()
assert names(window.selected_records()) == ['Alpha', 'Beta', 'Missing']
window.clear_selection_button.click()
assert window.selected_records() == ()
def test_verify_all_and_selected_only_target_visible_non_ready_with_projects(qtbot, tmp_path, monkeypatch):
calls = []
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda req: (calls.append(req.block_name) or VerifyResult('PASS')),
status_refresher=lambda names, _: {name: 'READY' for name in names})
window.search_edit.setText('power')
window.select_visible_button.click()
window.verify_selected()
qtbot.waitUntil(lambda: not window.busy)
assert calls == ['Beta']
window.search_edit.setText('analog')
window.verify_all()
qtbot.waitUntil(lambda: not window.busy)
assert calls == ['Beta', 'Gamma', 'Delta']
def test_maintenance_confirmation_progress_and_report_use_visible_checked_subset(qtbot, tmp_path, monkeypatch):
calls, confirmations, refreshes = [], [], []
def refresh(targets, _):
refreshes.append(tuple(targets))
return {name: 'PENDING' for name in targets}
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda req: (calls.append(req.block_name) or VerifyResult('PASS')),
status_refresher=refresh)
window.search_edit.setText('analog')
window.cbb_table.item(3, 0).setCheckState(Qt.Checked)
monkeypatch.setattr(QMessageBox, 'question', lambda *args, **_: (
confirmations.append(args[2]) or QMessageBox.Yes))
window.repair_icdb_all()
qtbot.waitUntil(lambda: not window.busy)
assert calls == ['Delta']
assert refreshes == [('Delta',)]
assert '1' in confirmations[0] and '非 READY' in confirmations[0]
assert window.icdb_progress.maximum() == 1 and window.icdb_progress.value() == 1
report = json.loads(next((tmp_path/'reports').glob('icdb-*.json')).read_text(encoding='utf-8'))
assert report['includes_ready'] is False
assert report['target_names'] == ['Delta']
assert report['preflight_skipped'] == []
assert report['counts']['total'] == 1
assert window.search_edit.text() == 'analog'
assert window.cbb_table.item(3, 3).text() == 'PASS'
assert names(window.visible_records()) == ['Gamma', 'Delta']
assert window.visible_records()[1].status == 'PENDING'
def test_maintenance_defaults_to_visible_eligible_and_ready_only_checks_do_not_fallback(qtbot, tmp_path, monkeypatch):
calls = []
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda req: (calls.append(req.block_name) or VerifyResult('PASS')),
status_refresher=lambda targets, _: {name: 'PENDING' for name in targets})
monkeypatch.setattr(QMessageBox, 'question', lambda *_, **__: QMessageBox.Yes)
window.cbb_table.item(0, 0).setCheckState(Qt.Checked)
window.repair_icdb_all()
assert not window.busy and calls == []
window.clear_selection_button.click()
window.search_edit.setText('power')
window.repair_icdb_all()
qtbot.waitUntil(lambda: not window.busy)
assert calls == ['Beta']
def test_recovery_defaults_to_visible_checked_non_ready_and_skips_ready(qtbot, tmp_path, monkeypatch):
window = load_window(qtbot, tmp_path, monkeypatch)
window.search_edit.setText('power')
window.restore_backup()
assert [window.backup_dialog.block_combo.itemText(i)
for i in range(window.backup_dialog.block_combo.count())] == ['Beta']
window.backup_dialog.reject()
window.search_edit.clear()
window.cbb_table.item(3, 0).setCheckState(Qt.Checked)
window.restore_backup()
assert window.backup_dialog.block_combo.currentText() == 'Delta'
assert window.backup_dialog.block_combo.count() == 1
window.backup_dialog.reject()
def test_action_pass_does_not_promote_pending_without_authoritative_ready(qtbot, tmp_path, monkeypatch):
entered = []
window = load_window(qtbot, tmp_path, monkeypatch,
status_refresher=lambda targets, _: (entered.extend(targets) or {'Beta': 'READY'}))
window.status_filter.setCurrentIndex(window.status_filter.findData('pending'))
window.cbb_table.item(1, 0).setCheckState(Qt.Checked)
window._progress({'block': 'Beta', 'stage': 'PASS'})
assert names(window.visible_records()) == ['Beta']
assert window.visible_records()[0].status == 'PENDING'
window.refresh_affected_records(['Beta'])
qtbot.waitUntil(lambda: not window.busy)
assert entered == ['Beta']
assert window.visible_records() == ()
assert window.selected_records() == ()
assert window.status_filter.currentData() == 'pending'
window.status_filter.setCurrentIndex(window.status_filter.findData('ready'))
assert names(window.visible_records()) == ['Alpha', 'Beta', 'Missing']
assert window.cbb_table.item(1, 3).text() == 'PASS'
def test_refresh_failure_demotes_affected_without_losing_other_statuses(qtbot, tmp_path, monkeypatch):
def fail(*_):
raise OSError('bridge unavailable')
window = load_window(qtbot, tmp_path, monkeypatch, status_refresher=fail)
window.refresh_affected_records(['Alpha'])
qtbot.waitUntil(lambda: not window.busy)
assert window.visible_records()[0].status == 'UNKNOWN'
assert window.visible_records()[1].status == 'PENDING'
assert 'Alpha' not in window.ready_names
assert 'bridge unavailable' in window.output.toPlainText()
def test_unsafe_result_defers_native_refresh_and_retains_action_evidence(qtbot, tmp_path, monkeypatch):
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda _: VerifyResult('FAIL', stderr='owner release unconfirmed',
safe_to_continue=False, evidence_path=tmp_path/'evidence.json'),
status_refresher=lambda *_: pytest.fail('unsafe owner was reopened'))
window.search_edit.setText('beta')
window.verify_all()
qtbot.waitUntil(lambda: not window.busy)
assert window.visible_records()[0].status == 'UNKNOWN'
assert window.cbb_table.item(1, 3).text() == 'FAIL: owner release unconfirmed'
assert str(tmp_path/'evidence.json') in window.output.toPlainText()
assert '暂缓原生状态复核' in window.cbb_table.item(1, 2).toolTip()
def test_refresh_callback_uses_only_known_affected_records_and_preserves_logical_type(qtbot, tmp_path, monkeypatch):
observed, callbacks = [], []
def refresh(targets, path):
observed.append((targets, path))
return {'X': 'READY'}
window = load_window(qtbot, tmp_path, monkeypatch,
records=(CbbRecord('X', 'Display label', logical_type='RULP', status='PENDING'),),
status_refresher=refresh)
assert window.refresh_affected_records(['unknown']) is False
assert window.refresh_affected_records(['X', 'X', 'unknown'], callbacks.append) is True
assert window.refresh_affected_records(['X']) is False
qtbot.waitUntil(lambda: not window.busy)
assert observed == [(('X',), Path('test.lmc'))]
assert callbacks == [(CbbRecord('X', 'Display label', logical_type='RULP', status='READY'),)]
def test_backup_completion_refreshes_status_without_dialog_close_unlocking_pending_refresh(qtbot, tmp_path, monkeypatch):
entered, release = Event(), Event()
def refresh(targets, _):
entered.set()
release.wait(3)
return {name: 'PENDING' for name in targets}
window = load_window(qtbot, tmp_path, monkeypatch, status_refresher=refresh)
window.search_edit.setText('beta')
window.restore_backup()
window.backup_dialog.started.emit('Beta')
window.backup_dialog.completed.emit('Beta', VerifyResult('PASS'))
try:
qtbot.waitUntil(entered.is_set)
window.backup_dialog.reject()
assert window.busy
finally:
release.set()
qtbot.waitUntil(lambda: not window.busy)
assert window.visible_records()[0].status == 'PENDING'
assert window.cbb_table.item(1, 3).text() == 'PASS'
def test_missing_project_keeps_explicit_authoritative_status(qtbot, tmp_path, monkeypatch):
window = load_window(qtbot, tmp_path, monkeypatch)
assert 'Ready' in window.cbb_table.item(4, 2).text()
assert '缺少工程' in window.cbb_table.item(4, 2).text()
def test_open_backup_dialog_cannot_restore_target_that_became_ready(qtbot, tmp_path, monkeypatch):
calls = []
window = load_window(qtbot, tmp_path, monkeypatch,
status_refresher=lambda targets, _: {name: 'READY' for name in targets})
window.search_edit.setText('beta')
window.restore_backup()
dialog = window.backup_dialog
source = tmp_path/'Beta.prj'
source.touch()
dialog.source_edit.setText(str(source))
dialog.recoverer = lambda *_, **__: (calls.append('restore') or VerifyResult('PASS'))
window.refresh_affected_records(['Beta'])
qtbot.waitUntil(lambda: not window.busy)
dialog.restore_button.click()
qtbot.waitUntil(lambda: not dialog.busy)
assert calls == []
assert '非 READY' in dialog.status_label.text()
dialog.reject()
@pytest.mark.parametrize('status', ['UNKNOWN', 'UNAVAILABLE', 'ERROR', 'TIMEOUT', 'MALFORMED', 'CRASHED',
'UNRECOGNIZED'])
def test_unconfirmed_statuses_are_non_ready_and_error_filter_candidates(qtbot, tmp_path, monkeypatch, status):
window = load_window(qtbot, tmp_path, monkeypatch, records=(CbbRecord('X', 'LP', status=status),))
window.status_filter.setCurrentIndex(window.status_filter.findData('non_ready'))
assert names(window.visible_records()) == ['X']
window.status_filter.setCurrentIndex(window.status_filter.findData('errors'))
assert names(window.visible_records()) == ['X']
@pytest.mark.parametrize('size', [381, 3000])
def test_large_catalog_local_filter_and_selection_remain_responsive(qtbot, tmp_path, monkeypatch, size):
records = tuple(CbbRecord(f'CBB{i:04}', 'Power' if i % 2 else 'Analog',
status='READY' if i % 3 == 0 else 'PENDING') for i in range(size))
start = time.perf_counter()
window = load_window(qtbot, tmp_path, monkeypatch, records=records)
loaded = time.perf_counter() - start
window.reader = lambda _: pytest.fail('local actions reread Mentor')
start = time.perf_counter()
window.search_edit.setText('power')
window.select_visible_button.click()
window.status_filter.setCurrentIndex(window.status_filter.findData('pending'))
window.clear_selection_button.click()
elapsed = time.perf_counter() - start
print(f'catalog rows={size} load={loaded:.3f}s local_actions={elapsed:.3f}s')
assert elapsed < 2.0
assert window.selected_records() == ()
+52
View File
@@ -0,0 +1,52 @@
"""Destructive probe restricted to a fresh copy of the local test fixture."""
from pathlib import Path
import argparse
import hashlib
import json
import shutil
from cbb_refresh_verify.native_repair import RepairTarget, run_native_repair
def main():
base = Path(__file__).resolve().parents[1]
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output', default='icdb-corruption-probe-20261028-r2')
parser.add_argument('--without-history', action='store_true',
help='Exclude historical ProjectBackup/cdbback data from the new test copy')
args = parser.parse_args()
source = base / 'diagnostics/icdb-auto-recovery-20261027/project-copy'
root = (base/'diagnostics'/args.output).resolve()
if root.parent != (base/'diagnostics').resolve():
raise ValueError('Output must be a new direct child of the diagnostics directory')
root.mkdir(parents=True, exist_ok=False)
project_dir = root / 'project'
if any(p.is_symlink() or p.is_junction() for p in source.rglob('*')):
raise RuntimeError('Fixture contains links')
shutil.copytree(source, project_dir, ignore=(
shutil.ignore_patterns('ProjectBackup', 'cdbback') if args.without_history else None))
if args.without_history:
storage = project_dir/'ProjectBackup'
(storage/'backups').mkdir(parents=True)
shutil.copy2(source/'ProjectBackup/ProjectBackup.cfg', storage/'ProjectBackup.cfg')
if list(project_dir.rglob('*.zip')):
raise RuntimeError('Historical archives remain in the no-history test copy')
database = project_dir / 'database/icdb.dat'
original = database.read_bytes()
damaged = bytes(64) + original[64:]
database.write_bytes(damaged)
record = {'source_sha256': hashlib.sha256(original).hexdigest(),
'damaged_sha256': hashlib.sha256(damaged).hexdigest(),
'damage': 'first 64 bytes zeroed in isolated copy',
'without_historical_backups': args.without_history}
(root/'damage.json').write_text(json.dumps(record, indent=2), encoding='utf-8')
result = run_native_repair(RepairTarget(project_dir/'IP101GR.prj', database.parent),
root/'repair', timeout_seconds=180)
result['database_sha256_after'] = hashlib.sha256(database.read_bytes()).hexdigest()
result['damaged_bytes_unchanged'] = result['database_sha256_after'] == record['damaged_sha256']
(root/'probe-result.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps(result, ensure_ascii=False))
if __name__ == '__main__':
main()
+147
View File
@@ -0,0 +1,147 @@
"""Real damaged-open / popup recovery / reopened-target comparison.
All damage and recovery are confined to a fresh diagnostics fixture. The popup
uses the production backend and native verifier without injected substitutes.
"""
from dataclasses import asdict
import argparse
import json
from pathlib import Path
import shutil
import subprocess
from cbb_refresh_verify.backup_recovery import _manifest
from cbb_refresh_verify.verify_runner import VerifyRequest, run_verify, read_library_flag_if_available
def write(path, value):
path.write_text(json.dumps(value, ensure_ascii=False, default=str, indent=2), encoding='utf-8')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('phase', choices=('setup', 'open-before', 'restore', 'compare'))
args = parser.parse_args()
base = Path(__file__).resolve().parents[1]
root = base/'diagnostics/icdb-backup-dialog-live-20261028'
library = root/'library/mentor_lib.lmc'
source = base/'diagnostics/icdb-auto-recovery-20261027/verify-library'
project = library.parent/'ReusableBlocksLP/IP101GR/Work/IP101GR.prj'
if args.phase == 'setup':
root.mkdir(parents=True, exist_ok=False)
if any(p.is_symlink() or p.is_junction() for p in source.rglob('*')):
raise ValueError('Source contains links')
copied = subprocess.run(['robocopy', str(source), str(library.parent), '/E', '/COPY:DAT',
'/DCOPY:T', '/MT:8', '/R:1', '/W:1', '/NFL', '/NDL', '/NJH', '/NJS', '/NP'],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
(root/'copy.log').write_bytes(copied.stdout)
if copied.returncode > 7:
raise RuntimeError(f'Fixture copy failed: {copied.returncode}')
# Remove historical backups only in this new, resolved fixture Work.
for path in sorted(project.parent.rglob('*'), reverse=True):
if path.is_dir() and path.name in {'ProjectBackup', 'cdbback'}:
resolved = path.resolve()
if not resolved.is_relative_to((root/'library').resolve()):
raise ValueError('History cleanup escaped test fixture')
shutil.rmtree(resolved)
database = project.parent/'database/icdb.dat'
healthy = database.read_bytes()
if healthy[:64] == bytes(64):
raise ValueError('Fixture baseline is not healthy')
database.write_bytes(bytes(64) + healthy[64:])
write(root/'source-before.json', _manifest(source))
write(root/'setup.json', {'project': project, 'database': database,
'damage': 'First 64 bytes zeroed in isolated Work database',
'historical_backups_removed': True})
print('SETUP_DONE', flush=True)
return
request = VerifyRequest(library, 'IP101GR', root/args.phase, timeout_seconds=300, auto_repair=False)
if args.phase == 'open-before':
result = run_verify(request, progress=lambda e: print(json.dumps(e, ensure_ascii=True), flush=True),
flag_reader=read_library_flag_if_available)
write(root/'open-before.json', asdict(result))
log = project.parent/'PCB/LogFiles/PCBLogFile.txt'
if log.is_file():
(root/'open-before-PCBLogFile.txt').write_bytes(log.read_bytes())
print(json.dumps(asdict(result), default=str, ensure_ascii=True), flush=True)
return
if args.phase == 'restore':
before = json.loads((root/'open-before.json').read_text('utf-8'))
log = (root/'open-before-PCBLogFile.txt').read_text('utf-8', errors='replace')
if before['status'] != 'FAIL' or 'Database cannot be loaded' not in log:
raise ValueError('Actual damaged target opening failure must be confirmed first')
from PySide6.QtCore import QTimer, Qt
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication
from cbb_refresh_verify.application import configure_qt_application
from cbb_refresh_verify.ui.main_window import MainWindow
app = QApplication([]); configure_qt_application(app)
window = MainWindow(data_root=root/'data'); window.resize(1060, 860)
window.show(); window.lmc_edit.setText(str(library))
window.libspec_edit.clear(); window.dms_edit.clear()
state = {'phase': 'loading'}
def tick():
if state['phase'] == 'loading' and not window.busy:
if not window.loaded_path:
raise RuntimeError(window.status_label.text())
state['phase'] = 'restoring'
QTest.mouseClick(window.backup_restore_button, Qt.LeftButton)
dialog = window.backup_dialog
def progress(event):
print(json.dumps(event, ensure_ascii=True, default=str), flush=True)
if event.get('stage') == 'validate_source':
candidates = list((root/'data/evidence').glob('backup-restore-*/recovery-request.json'))
current = max(candidates, key=lambda p: p.stat().st_mtime_ns)
config = json.loads(current.read_text('utf-8'))
flag = read_library_flag_if_available(Path(config['validation_library']), 'IP101GR')
write(current.parent/'source-before-native-flag.json', asdict(flag))
dialog.signals.progress.connect(progress)
dialog.source_edit.setText(str(source/'ReusableBlocksLP/IP101GR/Work/IP101GR.prj'))
dialog.grab().save(str(root/'dialog-before.png'))
def done(name, result):
write(root/'restore-ui-result.json', asdict(result))
state['phase'] = 'finishing'
QTimer.singleShot(200, finish)
dialog.completed.connect(done)
QTest.mouseClick(dialog.restore_button, Qt.LeftButton)
def finish():
timer.stop()
dialog = window.backup_dialog
dialog.grab().save(str(root/'dialog-after.png'))
window.grab().save(str(root/'window-after.png'))
write(root/'ui-state.json', {'status': dialog.status_label.text(),
'target_ready': 'IP101GR' in window.ready_names, 'busy': dialog.busy})
dialog.reject(); window.close(); app.quit()
timer=QTimer(); timer.setInterval(100); timer.timeout.connect(tick)
window.load_library(); timer.start(); app.exec()
print((root/'restore-ui-result.json').read_text('utf-8'), flush=True)
return
before = json.loads((root/'open-before.json').read_text('utf-8'))
restored = json.loads((root/'restore-ui-result.json').read_text('utf-8'))
record = json.loads(Path(restored['evidence_path']).read_text('utf-8'))
final = record['result']
retained = Path(record.get('retained_work', ''))
after_evidence = Path(final['evidence_path']).parent
events = [json.loads(line) for line in (after_evidence/'events.jsonl').read_text('utf-8').splitlines()]
native_log = project.parent/'PCB/LogFiles/PCBLogFile.txt'
text = native_log.read_text('utf-8', errors='replace')
checks = {
'real_open_failed_before': before['status'] == 'FAIL' and before['error_category'] == 'MENTOR_DATABASE_LOAD_FAILED',
'source_copy_verified': record['source_validation']['status'] == 'PASS'
and record['source_validation']['library_flag'] == 'GREEN',
'same_target_opened_after': any(e.get('stage') == 'identity_verified'
and e.get('project') == str(project) for e in events),
'restored_target_passed': final['status'] == 'PASS' and final['library_flag'] == 'GREEN'
and final['safe_to_continue'],
'old_damaged_work_retained': (retained/'database/icdb.dat').read_bytes()[:64] == bytes(64),
'original_source_unchanged': _manifest(source) == json.loads((root/'source-before.json').read_text('utf-8')),
'load_error_absent_after': 'Database cannot be loaded' not in text,
}
write(root/'comparison.json', {'checks': checks, 'passed': all(checks.values())})
print(json.dumps(checks), flush=True)
if not all(checks.values()):
raise RuntimeError('Real recovery comparison failed')
if __name__ == '__main__':
main()
+99
View File
@@ -0,0 +1,99 @@
"""Exercise the real Qt button and native verifier on a fresh local fixture copy.
Run with PYTHONPATH=src. No verifier/reader stubs or synthetic errors are used.
The source library is fingerprinted before and after the run.
"""
from pathlib import Path
import hashlib
import json
import shutil
import time
from PySide6.QtCore import QTimer, Qt
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QMessageBox
from cbb_refresh_verify.application import configure_qt_application
from cbb_refresh_verify.ui.main_window import MainWindow
def fingerprint(root):
result = {}
for path in root.rglob('*'):
if path.is_symlink() or path.is_junction():
raise ValueError('Test source contains links')
if path.is_file():
with path.open('rb') as stream:
result[str(path.relative_to(root))] = hashlib.file_digest(stream, 'sha256').hexdigest()
return result
def main():
base = Path(__file__).resolve().parents[1]
source = base/'diagnostics/icdb-auto-recovery-20261027/verify-library'
root = base/'diagnostics/icdb-button-live-20261028'
root.mkdir(parents=True, exist_ok=False)
before = fingerprint(source)
(root/'source-before.json').write_text(json.dumps(before), encoding='utf-8')
library = root/'library'
shutil.copytree(source, library)
app = QApplication([])
configure_qt_application(app)
window = MainWindow(data_root=root/'data')
window.resize(1060, 820)
window.show()
window.libspec_edit.clear()
window.dms_edit.clear()
window.lmc_edit.setText(str(library/'mentor_lib.lmc'))
state = {'phase': 'loading', 'started': time.monotonic()}
def event(record):
if record.get('stage') in {'icdb_check_start', 'native_repair_start', 'PASS', 'FAIL', 'BLOCKED', 'TIMEOUT'}:
print(json.dumps(record, ensure_ascii=True), flush=True)
window.signals.event.connect(event)
def tick():
for widget in app.topLevelWidgets():
if isinstance(widget, QMessageBox) and widget.isVisible() and widget.windowTitle() == '全库 ICDB 检查与修复':
widget.grab().save(str(root/'confirmation.png'))
state['confirmation'] = widget.text()
QTest.mouseClick(widget.button(QMessageBox.Yes), Qt.LeftButton)
if state['phase'] == 'loading' and not window.busy:
if not window.loaded_path:
state.update(phase='load_failed', detail=window.status_label.text())
finish()
return
state.update(phase='running', rows=window.cbb_table.rowCount(),
ready_before=len(window.ready_names), preflight_skipped=len(window.skipped_names))
window.grab().save(str(root/'loaded.png'))
QTimer.singleShot(0, lambda: QTest.mouseClick(window.icdb_repair_button, Qt.LeftButton))
elif state['phase'] == 'running' and not window.busy and hasattr(window, 'summary'):
state.update(phase='finished', detail=window.status_label.text(), ready_after=len(window.ready_names))
window.grab().save(str(root/'finished.png'))
window.summary.grab().save(str(root/'summary.png'))
finish()
elif time.monotonic()-state['started'] > 900 and not window.stop.is_set():
window.request_stop()
def finish():
timer.stop()
after = fingerprint(source)
state.update(source_unchanged=before == after, source_file_count=len(before),
elapsed_seconds=time.monotonic()-state['started'])
(root/'outcome.json').write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps(state, ensure_ascii=True), flush=True)
if hasattr(window, 'summary'):
window.summary.close()
window.close()
app.quit()
timer = QTimer()
timer.setInterval(100)
timer.timeout.connect(tick)
window.load_library()
timer.start()
app.exec()
if __name__ == '__main__':
main()
+136
View File
@@ -0,0 +1,136 @@
"""Real before/repair/after test, confined to a newly cloned local fixture.
Run each phase separately so the actual native failure can be reviewed before
repair. The opening phases use the production verifier with auto repair off.
"""
import argparse
from dataclasses import asdict
import hashlib
import json
from pathlib import Path
import subprocess
from cbb_refresh_verify.native_repair import RepairTarget, run_native_repair
from cbb_refresh_verify.verify_runner import VerifyRequest, preflight, run_verify, read_library_flag_if_available
def write(path, record):
path.write_text(json.dumps(record, ensure_ascii=False, default=str, indent=2), encoding='utf-8')
def require_released():
from cbb_refresh_verify.mentor_adapter import pcb_processes, _process_details
if pcb_processes() or _process_details('LibraryManager.exe'):
raise RuntimeError('Native PCB or Library Manager remains open; stop before repair/reopen')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('phase', choices=('setup', 'open-before', 'repair', 'open-after', 'compare'))
parser.add_argument('--output', default='icdb-open-repair-reopen-20261028')
args = parser.parse_args()
base = Path(__file__).resolve().parents[1]
root = (base/'diagnostics'/args.output).resolve()
if root.parent != (base/'diagnostics').resolve():
raise ValueError('Output must be a direct child of diagnostics')
require_released()
if args.phase == 'setup':
root.mkdir(parents=True, exist_ok=False)
source = base/'diagnostics/icdb-auto-recovery-20261027/verify-library'
if any(p.is_symlink() or p.is_junction() for p in source.rglob('*')):
raise ValueError('Source contains directory/file links')
command = ['robocopy', str(source), str(root/'library'), '/E', '/COPY:DAT', '/DCOPY:T',
'/MT:8', '/R:1', '/W:1', '/NFL', '/NDL', '/NJH', '/NJS', '/NP']
copied = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
(root/'copy.log').write_bytes(copied.stdout)
if copied.returncode > 7:
raise RuntimeError(f'Fixture copy failed: {copied.returncode}')
request = VerifyRequest(root/'library/mentor_lib.lmc', 'IP101GR', root/'preflight')
project, pcb = preflight(request)
database = project.parent/'database/icdb.dat'
original = database.read_bytes()
if not original or original[:64] == bytes(64):
raise ValueError('Source is not a healthy baseline')
(root/'original-icdb.dat').write_bytes(original)
damaged = bytes(64)+original[64:]
database.write_bytes(damaged)
write(root/'setup.json', {'source': source, 'library': request.lmc_file,
'project': project, 'pcb': pcb, 'database': database,
'source_sha256': hashlib.sha256(original).hexdigest(),
'damaged_sha256': hashlib.sha256(damaged).hexdigest(),
'damage': 'Zero first 64 bytes in the new isolated Work database',
'auto_repair_during_open': False})
print('SETUP_DONE', flush=True)
return
config = json.loads((root/'setup.json').read_text('utf-8'))
project, database = Path(config['project']), Path(config['database'])
if not project.resolve().is_relative_to(root) or not database.resolve().is_relative_to(root):
raise ValueError('Target escaped the isolated test directory')
if args.phase == 'compare':
before = json.loads((root/'open-before.json').read_text('utf-8'))
after = json.loads((root/'open-after.json').read_text('utf-8'))
repair = json.loads((root/'repair/repair-result.json').read_text('utf-8'))
before_job = json.loads(Path(before['evidence_path']).with_name('request.json').read_text('utf-8'))
after_job = json.loads(Path(after['evidence_path']).with_name('request.json').read_text('utf-8'))
before_log = (root/'open-before-PCBLogFile.txt').read_text('utf-8', errors='replace')
after_log = (root/'open-after-PCBLogFile.txt').read_text('utf-8', errors='replace')
events = [json.loads(line) for line in
Path(after['evidence_path']).with_name('events.jsonl').read_text('utf-8').splitlines()]
source_database = Path(config['source'])/'ReusableBlocksLP/IP101GR/Work/database/icdb.dat'
checks = {
'same_project': before_job['project'] == after_job['project'] == str(project),
'same_database_repaired': repair['database'] == str(database.parent),
'native_icdb_error_confirmed_before': before['status'] == 'FAIL'
and str(database) in before_log and 'iCDB Project Backup' in before_log,
'identity_verified_after': any(e.get('stage') == 'identity_verified'
and e.get('project') == str(project) for e in events),
'opening_error_absent_after': 'Database cannot be loaded' not in after_log and not after['stderr'],
'verification_passed_after': after['status'] == 'PASS' and after['safe_to_continue']
and after['library_flag'] == 'GREEN',
'original_source_database_unchanged': hashlib.sha256(source_database.read_bytes()).hexdigest()
== config['source_sha256'],
}
result = {'checks': checks, 'comparison_passed': all(checks.values()),
'before_error_category': before['error_category'],
'native_repair_status': repair['status'],
'restored_from_backup': repair.get('evidence', {}).get('restored_from_backup', ''),
'after_library_flag': after['library_flag_detail'],
'server_session_loss_reproduced': 'last server session' in before_log.casefold()}
write(root/'comparison.json', result)
print(json.dumps(result, ensure_ascii=True), flush=True)
if not result['comparison_passed']:
raise RuntimeError('Before/repair/reopen comparison did not pass every check')
return
from cbb_refresh_verify.icdb_ownership import unreleased_addresses
addresses = unreleased_addresses(config['library'], project, config['pcb'])
if addresses:
raise RuntimeError(f'Database ownership not released: {addresses}')
if args.phase == 'repair':
before = json.loads((root/'open-before.json').read_text('utf-8'))
if before['status'] in {'PASS', 'TIMEOUT'}:
raise RuntimeError('No confirmed opening failure available for a repair comparison')
native_error = (root/'open-before-PCBLogFile.txt').read_text('utf-8', errors='replace')
if str(database).casefold() not in native_error.casefold() or 'iCDB Project Backup' not in native_error:
raise RuntimeError('Native log does not confirm an iCDB repair request for the damaged target')
result = run_native_repair(RepairTarget(project, database.parent), root/'repair', timeout_seconds=240)
write(root/'repair-summary.json', result)
else:
if args.phase == 'open-after':
repaired = json.loads((root/'repair-summary.json').read_text('utf-8'))
if repaired['status'] not in {'REPAIRED', 'RESTORED_REVIEW_REQUIRED'}:
raise RuntimeError('Repair did not reach a completed native result')
request = VerifyRequest(Path(config['library']), 'IP101GR', root/args.phase,
timeout_seconds=300, auto_repair=False)
def progress(event):
print(json.dumps(event, ensure_ascii=True, default=str), flush=True)
result = asdict(run_verify(request, progress=progress,
flag_reader=read_library_flag_if_available))
write(root/(args.phase+'.json'), result)
native_log = Path(config['pcb']).parent/'LogFiles/PCBLogFile.txt'
if native_log.is_file():
(root/(args.phase+'-PCBLogFile.txt')).write_bytes(native_log.read_bytes())
print(json.dumps(result, ensure_ascii=True, default=str), flush=True)
if __name__ == '__main__':
main()
+28
View File
@@ -0,0 +1,28 @@
"""Explicit isolated Add research, never a production capability override.
python tools/validate_native_management.py SOURCE.prj NEW_OUTPUT_DIRECTORY NAME
"""
import argparse
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[1]/'src'))
from cbb_refresh_verify.native_management import run_isolated_probe
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('source', type=Path)
parser.add_argument('new_output_directory', type=Path)
parser.add_argument('name')
parser.add_argument('--replacement-source', type=Path,
help='同一新建隔离库中额外验证同名移除并重新导入此完整工程')
args = parser.parse_args()
result = run_isolated_probe(args.source, args.new_output_directory, args.name,
replacement_source=args.replacement_source)
print(args.new_output_directory/'probe-result.json')
return 0 if result.get('accepted') else 2
if __name__ == '__main__':
raise SystemExit(main())