feat: add ICDB maintenance and verified CBB backup recovery dialog
This commit is contained in:
1 parent
a851e47eca
commit
cdb8a6a28b
23 files changed
+1868
-23
No files matched your search
@@ -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,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,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,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,315 @@
|
||||
"""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 contextlib import ExitStack
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import asdict, replace
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import stat
|
||||
from uuid import uuid4
|
||||
|
||||
from .verify_runner import VerifyResult, preflight
|
||||
|
||||
|
||||
def _hash(path):
|
||||
digest = hashlib.sha256()
|
||||
with path.open('rb') as stream:
|
||||
for data in iter(lambda: stream.read(1024 * 1024), b''):
|
||||
digest.update(data)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _scan(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:
|
||||
metadata = entry.stat(follow_symlinks=False)
|
||||
if metadata.st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
|
||||
raise ValueError(f'目录含文件或目录链接,停止恢复:{entry.path}')
|
||||
path = Path(entry.path)
|
||||
entries[path] = metadata
|
||||
if stat.S_ISDIR(metadata.st_mode):
|
||||
folders.append(path)
|
||||
return dict(sorted(entries.items()))
|
||||
|
||||
|
||||
def _paths(root):
|
||||
return list(_scan(root))
|
||||
|
||||
|
||||
def _manifest(root, *, exclude=None):
|
||||
entries = _scan(root)
|
||||
paths = [path for path in entries
|
||||
if exclude is None or not path.is_relative_to(exclude)]
|
||||
def entry(path):
|
||||
return str(path.relative_to(root)), _hash(path) if stat.S_ISREG(entries[path].st_mode) else None
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
return dict(pool.map(entry, paths))
|
||||
|
||||
|
||||
def _copy_verified(source, destination, *, progress=None):
|
||||
"""Copy every file, refusing links and changed files; lock native databases."""
|
||||
import win32con, win32file
|
||||
entries = _scan(source)
|
||||
paths = list(entries)
|
||||
destination.mkdir(parents=True, exist_ok=False)
|
||||
record = {}
|
||||
with ExitStack() as stack:
|
||||
locks = {}
|
||||
for path in paths:
|
||||
if stat.S_ISREG(entries[path].st_mode) and (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
|
||||
files = []
|
||||
for path in paths:
|
||||
relative = str(path.relative_to(source))
|
||||
copied = destination / relative
|
||||
if stat.S_ISDIR(entries[path].st_mode):
|
||||
copied.mkdir(parents=True, exist_ok=True)
|
||||
record[relative] = None
|
||||
continue
|
||||
files.append(path)
|
||||
def copy_file(path):
|
||||
relative = str(path.relative_to(source))
|
||||
copied = destination / relative
|
||||
before = entries[path]
|
||||
copied.parent.mkdir(parents=True, exist_ok=True)
|
||||
if path in locks:
|
||||
with copied.open('wb') as stream:
|
||||
while True:
|
||||
_, data = win32file.ReadFile(locks[path], 1024 * 1024)
|
||||
if not data:
|
||||
break
|
||||
stream.write(data)
|
||||
shutil.copystat(path, copied)
|
||||
digest = _hash(copied)
|
||||
else:
|
||||
digest = _hash(path)
|
||||
shutil.copy2(path, copied)
|
||||
if _hash(copied) != digest:
|
||||
raise OSError(f'副本校验失败:{path}')
|
||||
after = path.stat()
|
||||
if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
|
||||
raise OSError(f'复制期间文件变化:{path}')
|
||||
return relative, digest
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
for count, (relative, digest) in enumerate(pool.map(copy_file, files), 1):
|
||||
record[relative] = digest
|
||||
if progress and (count % 256 == 0 or count == len(files)):
|
||||
progress(count, len(files))
|
||||
if _manifest(source) != record:
|
||||
raise OSError(f'复制期间目录内容变化:{source}')
|
||||
return record
|
||||
|
||||
|
||||
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
|
||||
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):
|
||||
if progress:
|
||||
progress({'stage': stage, 'block': request.block_name, 'message': message})
|
||||
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)
|
||||
pythoncom.CoInitialize()
|
||||
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)
|
||||
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', '正在保留完整中心库副本…')
|
||||
original_manifest = _copy_verified(library_root, root/'library-before', progress=lambda n, total:
|
||||
emit('backup', f'正在保留中心库副本:{n} / {total} 个文件…'))
|
||||
(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')
|
||||
_copy_verified(root/'library-before', validation_dir, progress=lambda n, total:
|
||||
emit('prepare_source', f'正在准备验证库:{n} / {total} 个文件…'))
|
||||
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)
|
||||
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', '正在副本中打开备份工程并执行原生校验…')
|
||||
source_result = verifier(validation, progress=progress, flag_reader=read_library_flag_if_available)
|
||||
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)
|
||||
if _manifest(source.parent) != source_manifest:
|
||||
raise ValueError('备份来源在验证期间发生变化,目标未更改。')
|
||||
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)
|
||||
_align_library(incoming/source.name, incoming/source_pcb.relative_to(source.parent), library)
|
||||
if _manifest(library_root, 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', '正在重新打开恢复后的目标工程并校验…')
|
||||
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)
|
||||
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:
|
||||
if acquired:
|
||||
win32event.ReleaseMutex(mutex)
|
||||
mutex.Close()
|
||||
pythoncom.CoUninitialize()
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Reports for the explicit full-library 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' for attempt in attempts)
|
||||
review = sum(attempt.get('status') == 'RESTORED_REVIEW_REQUIRED' 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,
|
||||
'repair_unconfirmed': len(attempts)-repaired-review}
|
||||
|
||||
|
||||
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': 'full_library_icdb_check_and_repair',
|
||||
'library': str(requests[0].lmc_file), 'includes_ready': True,
|
||||
'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
|
||||
@@ -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
|
||||
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)
|
||||
if not project.is_file() or not target:
|
||||
return False
|
||||
@@ -214,6 +221,7 @@ def _process_details(name):
|
||||
'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'",
|
||||
'cscript.exe': "SELECT ProcessId, ParentProcessId, ExecutablePath, CommandLine FROM Win32_Process WHERE Name='cscript.exe'",
|
||||
'viewdraw.exe': "SELECT ProcessId, ParentProcessId, ExecutablePath, CommandLine FROM Win32_Process WHERE Name='viewdraw.exe'",
|
||||
}
|
||||
if name not in queries:
|
||||
raise ValueError(f'Unsupported process query: {name}')
|
||||
|
||||
@@ -120,10 +120,16 @@ def _native_evidence(project, database, pid, started_ns, baseline):
|
||||
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')
|
||||
valid = (str(database).casefold() in db_log.casefold()
|
||||
restore_log = read_logs('dbrestore')
|
||||
restored = re.search(r'iCDB database restored from backup:\s*([^\r\n]+)', restore_log)
|
||||
valid = (not restored and str(database).casefold() in db_log.casefold()
|
||||
and repair_completed(diagnostic, db_log, native_backup=native_backup))
|
||||
return {'confirmed': bool(valid), 'native_backup': native_backup,
|
||||
'diagnostic_tail': diagnostic[-8192:], 'database_tail': db_log[-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):
|
||||
@@ -194,12 +200,18 @@ def repair_worker_main(job_path):
|
||||
emit(stage='native_repair_confirmed', text=text)
|
||||
if confirmed and not closing and main and not dialogs and main['enabled']:
|
||||
evidence = _native_evidence(project, database, process.pid, started_ns, baseline)
|
||||
if evidence['confirmed']:
|
||||
if (evidence['confirmed'] or (evidence.get('restore_complete')
|
||||
and evidence['native_backup']
|
||||
and not (database/'cdbsvr/sAddress.adr').exists())):
|
||||
win32gui.PostMessage(main['hwnd'], win32con.WM_CLOSE, 0, 0)
|
||||
closing = True
|
||||
emit(stage='native_repair_finished', **evidence)
|
||||
time.sleep(.2)
|
||||
if (closing and process.poll() == 0 and evidence and evidence['confirmed']
|
||||
if (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:
|
||||
|
||||
@@ -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)
|
||||
@@ -8,7 +8,7 @@ from PySide6.QtCore import QObject, QThreadPool, Signal, Qt
|
||||
from PySide6.QtGui import QColor, QIcon
|
||||
from PySide6.QtWidgets import (QWidget, QLineEdit, QPushButton, QFormLayout,
|
||||
QTextEdit, QFileDialog, QHBoxLayout, QLabel, QSpinBox, QMessageBox, QToolButton,
|
||||
QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox)
|
||||
QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox, QGroupBox, QVBoxLayout, QProgressBar)
|
||||
from PySide6.QtWidgets import QStyle
|
||||
try:
|
||||
from dx_productivity.trial_task_center.ui.workers import ServiceWorker
|
||||
@@ -79,6 +79,8 @@ class MainWindow(QWidget):
|
||||
self.busy = False; self.loaded_path = None; self.stop = Event(); self.ready_names = set()
|
||||
self._row_by_name = {}
|
||||
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.lmc_edit = QLineEdit()
|
||||
self.libspec_edit = QLineEdit(os.environ.get('CBB_LIBSPEC', 'EE7.9'))
|
||||
@@ -112,6 +114,10 @@ class MainWindow(QWidget):
|
||||
self.browse_button = QPushButton('选择'); self.browse_button.clicked.connect(self.choose_library)
|
||||
self.selected_batch_button = QPushButton('批量校验已选'); self.selected_batch_button.clicked.connect(self.verify_selected)
|
||||
self.batch_button = QPushButton('批量校验全部 CBB'); self.batch_button.clicked.connect(self.verify_all)
|
||||
self.icdb_repair_button = QPushButton('全库 ICDB 检查与修复'); self.icdb_repair_button.clicked.connect(self.repair_icdb_all)
|
||||
self.icdb_repair_button.setToolTip('重新检查所有可用 CBB,包含 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.logs_button = QPushButton('打开日志目录'); self.logs_button.clicked.connect(self.open_logs)
|
||||
self.recovery_button = QPushButton('打开异常证据'); self.recovery_button.setEnabled(False)
|
||||
@@ -120,6 +126,7 @@ class MainWindow(QWidget):
|
||||
self.browse_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_DirOpenIcon))
|
||||
self.selected_batch_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_ArrowRight))
|
||||
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.logs_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_DirOpenIcon))
|
||||
self.recovery_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_MessageBoxWarning))
|
||||
@@ -128,6 +135,7 @@ class MainWindow(QWidget):
|
||||
self.recovery_path = None
|
||||
self.status_label = QLabel('请选择并读取中心库。校验期间可以使用其他前台应用。')
|
||||
self.status_label.setWordWrap(True)
|
||||
self.status_label.setMinimumHeight(self.status_label.fontMetrics().lineSpacing()*2)
|
||||
self.output = QTextEdit(); self.output.setReadOnly(True)
|
||||
# Integration emits repeated status snapshots. Keep the visible
|
||||
# diagnostic buffer bounded so a 3,000-CBB run cannot grow the GUI
|
||||
@@ -141,7 +149,25 @@ class MainWindow(QWidget):
|
||||
'填写 LibSpec 与 DMS 登录配置后,会先执行一次 ReuseBlockImporter 内容检查。'))
|
||||
controls = QHBoxLayout()
|
||||
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)
|
||||
layout.addRow(self.status_label); layout.addRow(self.output)
|
||||
layout.addRow(self.recovery_button)
|
||||
self.lmc_edit.textChanged.connect(self._invalidate)
|
||||
for field in (self.libspec_edit, self.dms_edit, self.mentor_bin_edit):
|
||||
@@ -154,6 +180,8 @@ class MainWindow(QWidget):
|
||||
self._release_library_lease()
|
||||
self.loaded_path = None; self.mentor_lmc_path = None; self.cbb_table.setRowCount(0); self._row_by_name = {}
|
||||
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):
|
||||
lease, self.library_lease = self.library_lease, None
|
||||
@@ -173,6 +201,10 @@ class MainWindow(QWidget):
|
||||
and self.cbb_table.item(row, 0).text() not in self.skipped_names
|
||||
for row in range(self.cbb_table.rowCount())))
|
||||
self.selected_batch_button.setEnabled(ready and bool(self._selected_names()))
|
||||
self.icdb_repair_button.setEnabled(ready and any(
|
||||
self.cbb_table.item(row, 0).text() not in self.skipped_names
|
||||
for row in range(self.cbb_table.rowCount())))
|
||||
self.backup_restore_button.setEnabled(ready)
|
||||
for widget in (self.lmc_edit, self.browse_button, self.load_button, self.cbb_table,
|
||||
self.timeout_spin, self.advanced_toggle, self.advanced_panel):
|
||||
widget.setEnabled(not self.busy)
|
||||
@@ -192,6 +224,8 @@ class MainWindow(QWidget):
|
||||
|
||||
def load_library(self):
|
||||
if self.busy or not self.lmc_edit.text(): return
|
||||
self._global_icdb_run = False
|
||||
self.icdb_progress.hide(); self.icdb_phase.hide()
|
||||
self._release_library_lease()
|
||||
self.loaded_path = None; self.cbb_table.setRowCount(0); self._row_by_name = {}; self.ready_names = set()
|
||||
self.skipped_names = set(); self.skip_reasons = {}
|
||||
@@ -223,10 +257,9 @@ class MainWindow(QWidget):
|
||||
skip_reasons = {}
|
||||
if not result.error:
|
||||
for record in result.records:
|
||||
if record.status != 'READY':
|
||||
reason = preflight_skip_reason(mentor_path, record.name)
|
||||
if reason:
|
||||
skip_reasons[record.name] = reason
|
||||
reason = preflight_skip_reason(mentor_path, record.name)
|
||||
if reason:
|
||||
skip_reasons[record.name] = reason
|
||||
return result, skip_reasons, lease, mentor_path
|
||||
except Exception:
|
||||
if 'lease' in locals():
|
||||
@@ -245,7 +278,7 @@ class MainWindow(QWidget):
|
||||
self.mentor_lmc_path = mentor_path
|
||||
self.loaded_path = path
|
||||
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.skipped_names = set(skip_reasons)
|
||||
# Populating a large library emits itemChanged for every cell.
|
||||
@@ -274,7 +307,7 @@ class MainWindow(QWidget):
|
||||
# synchronously in this GUI callback, making large libraries
|
||||
# appear frozen. The verify worker performs it when queued.
|
||||
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)
|
||||
elif record.name in self.skipped_names:
|
||||
self.cbb_table.item(row, 0).setToolTip(self.skip_reasons[record.name])
|
||||
@@ -326,24 +359,97 @@ class MainWindow(QWidget):
|
||||
names = [self.cbb_table.item(row, 0).text() for row in range(self.cbb_table.rowCount())]
|
||||
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
|
||||
names = [name for name in names if name not in self.ready_names and name not in self.skipped_names]
|
||||
names = [self.cbb_table.item(row, 0).text() for row in range(self.cbb_table.rowCount())
|
||||
if self.cbb_table.item(row, 0).text() not in self.skipped_names]
|
||||
if not names: return
|
||||
answer = QMessageBox.question(self, '全库 ICDB 检查与修复',
|
||||
f'当前中心库:{self.loaded_path}\n\n'
|
||||
f'将检查 {len(names)} 个 CBB,其中 Ready {len(self.ready_names)} 个;'
|
||||
f'缺少工程文件跳过 {len(self.skipped_names)} 个。\n'
|
||||
'操作会重新校验并保存工程。确认失联问题后,完整备份目标工程并尝试一次原生修复。\n'
|
||||
'共享符号库不支持自动修复。若原生工具恢复了旧备份,需人工核对版本;'
|
||||
'会话安全无法确认时停止队列。\n\n是否开始检查与修复?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
|
||||
if answer == QMessageBox.Yes:
|
||||
self._run(names, include_ready=True)
|
||||
|
||||
def restore_backup(self):
|
||||
if self.busy or not self.loaded_path:
|
||||
return
|
||||
from .backup_recovery_dialog import BackupRecoveryDialog
|
||||
names = [self.cbb_table.item(row, 0).text() for row in range(self.cbb_table.rowCount())]
|
||||
if not names:
|
||||
return
|
||||
self.backup_dialog = BackupRecoveryDialog(names, self._request, self)
|
||||
row = self.cbb_table.currentRow()
|
||||
if row >= 0:
|
||||
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._finished())
|
||||
self.backup_dialog.setModal(True)
|
||||
self.backup_dialog.show()
|
||||
|
||||
def _backup_started(self, name):
|
||||
self.busy = True
|
||||
self._global_icdb_run = False
|
||||
self.ready_names.discard(name)
|
||||
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 '')})
|
||||
|
||||
def _run(self, names, *, include_ready=False):
|
||||
if self.busy or not self.loaded_path: return
|
||||
names = [name for name in names if (include_ready or name not in self.ready_names) and name not in self.skipped_names]
|
||||
if not names:
|
||||
self.status_label.setText('没有需要校验的 CBB(全部已经是绿色 / Ready)。')
|
||||
self._update()
|
||||
return
|
||||
requests = [self._request(name) for name in names]
|
||||
self._global_icdb_run = include_ready
|
||||
self._icdb_completed = 0
|
||||
self.icdb_progress.setVisible(include_ready)
|
||||
self.icdb_phase.setVisible(include_ready)
|
||||
if include_ready:
|
||||
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.output.clear(); self.status_label.setText(f'正在校验:共 {len(names)} 个 CBB')
|
||||
self.output.clear(); self.status_label.setText(
|
||||
f'正在全库 ICDB 检查与修复:共 {len(names)} 个 CBB' if include_ready
|
||||
else f'正在校验:共 {len(names)} 个 CBB')
|
||||
def action():
|
||||
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),
|
||||
flag_reader=read_library_flag_if_available))
|
||||
def verifier(req):
|
||||
if include_ready:
|
||||
self.signals.event.emit({'block': req.block_name, 'stage': 'icdb_check_start'})
|
||||
return verify(req)
|
||||
results = run_batch(requests, verifier=verifier, stop=self.stop,
|
||||
progress=lambda name, result: self.signals.event.emit({'block': name, 'stage': result.status, 'detail': result.stderr, 'evidence': str(result.evidence_path or '')}))
|
||||
report = write_batch_report(requests, results, self.data_root/'reports')
|
||||
if include_ready:
|
||||
from cbb_refresh_verify.icdb_maintenance import write_maintenance_report
|
||||
write_maintenance_report(requests, results, report, self.skipped_names)
|
||||
return results, report
|
||||
self._start(action, self._batch_done)
|
||||
|
||||
@@ -353,6 +459,18 @@ class MainWindow(QWidget):
|
||||
if event.get(key): line += f' | {event[key]}'
|
||||
self.output.append(line)
|
||||
block = event.get('block'); stage = event.get('stage')
|
||||
if self._global_icdb_run:
|
||||
if stage in {'PASS', 'FAIL', 'BLOCKED', 'TIMEOUT', 'SKIPPED', 'QUEUE_STOP'}:
|
||||
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'}:
|
||||
row = self._row_by_name.get(block)
|
||||
if row is not None:
|
||||
@@ -362,6 +480,13 @@ class MainWindow(QWidget):
|
||||
self.ready_names.add(block)
|
||||
self._mark_row_ready(row)
|
||||
else:
|
||||
if getattr(self, '_global_icdb_run', False) and stage != 'SKIPPED':
|
||||
self.ready_names.discard(block)
|
||||
self.cbb_table.item(row, 2).setText('未知 / 需确认')
|
||||
item = self.cbb_table.item(row, 0)
|
||||
item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
|
||||
for column in range(self.cbb_table.columnCount()):
|
||||
self.cbb_table.item(row, column).setBackground(QColor('#FFF8E1'))
|
||||
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)
|
||||
@@ -394,11 +519,25 @@ class MainWindow(QWidget):
|
||||
failed = len(results)-passed-skipped
|
||||
text = (f'已结束:成功 {passed},失败 {failed},预检跳过 {len(self.skipped_names)},'
|
||||
f'队列未执行 {skipped}。\n完整日志:{report}\n仅失败日志:{failure_report_path(report)}')
|
||||
if self._global_icdb_run:
|
||||
from cbb_refresh_verify.icdb_maintenance import maintenance_counts
|
||||
counts = maintenance_counts(results)
|
||||
text = ('全库 ICDB 检查已结束\n'
|
||||
f'校验通过 {passed},失败/受阻 {failed},队列未执行 {skipped},预检跳过 {len(self.skipped_names)}\n'
|
||||
f'原生修复完成 {counts["repaired"]},恢复备份待复核 {counts["review_required"]},'
|
||||
f'修复未确认 {counts["repair_unconfirmed"]}\n'
|
||||
f'完整日志:{report}\n仅失败日志:{failure_report_path(report)}')
|
||||
self.icdb_phase.setText('已停止,存在待处理项目' if failed or skipped else '已完成全库检查')
|
||||
if any(not result.safe_to_continue for result in results):
|
||||
text += '\n未确认数据库或会话安全,已停止剩余校验。请查看恢复现场。'
|
||||
self.status_label.setText(text); self.output.append(text)
|
||||
status_text = text
|
||||
if self._global_icdb_run:
|
||||
status_text = (f'全库检查结束:通过 {passed},失败/受阻 {failed},未执行 {skipped}。\n'
|
||||
f'原生修复 {counts["repaired"]},恢复备份待复核 {counts["review_required"]},'
|
||||
f'修复未确认 {counts["repair_unconfirmed"]}。')
|
||||
self.status_label.setText(status_text); self.output.append(text)
|
||||
self.summary = QMessageBox(self)
|
||||
self.summary.setWindowTitle('CBB 校验结果'); self.summary.setText(text)
|
||||
self.summary.setWindowTitle('全库 ICDB 检查与修复结果' if self._global_icdb_run else 'CBB 校验结果'); self.summary.setText(text)
|
||||
self.summary.setIcon(QMessageBox.Warning if failed else QMessageBox.Information)
|
||||
# Modeless notification: do not force activation or steal keyboard focus.
|
||||
from PySide6.QtCore import Qt
|
||||
|
||||
@@ -187,7 +187,7 @@ def preflight_skip_reason(lmc_file, block_name):
|
||||
return ''
|
||||
work = library.parent / 'ReusableBlocksLP' / str(block_name) / 'Work'
|
||||
if not work.is_dir():
|
||||
return ''
|
||||
return f'{block_name}: 缺少 Work 工程目录'
|
||||
request = VerifyRequest(library, str(block_name), library.parent / '.cbb-preflight-evidence')
|
||||
try:
|
||||
preflight(request)
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
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
|
||||
@@ -0,0 +1,90 @@
|
||||
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_simple_dialog_and_failure_clears_ready(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)
|
||||
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() == 'A'
|
||||
dialog.started.emit('A')
|
||||
assert window.busy
|
||||
assert 'A' not in window.ready_names
|
||||
dialog.completed.emit('A', VerifyResult('FAIL', stderr='损坏'))
|
||||
assert window.cbb_table.item(0, 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
|
||||
@@ -97,6 +97,27 @@ def test_native_diagnostics_finish_alone_does_not_prove_repair_success():
|
||||
'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
|
||||
@@ -121,7 +142,8 @@ def test_automatic_repair_retries_only_once_and_preserves_original_failure(tmp_p
|
||||
assert outcome.recovery_attempts[0]['original_error'] == 'native lost session'
|
||||
|
||||
|
||||
def test_automatic_repair_does_not_retry_busy_or_unsupported_target(tmp_path, monkeypatch):
|
||||
@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)
|
||||
@@ -135,11 +157,11 @@ def test_automatic_repair_does_not_retry_busy_or_unsupported_target(tmp_path, mo
|
||||
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':'BLOCKED'})
|
||||
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'] == 'BLOCKED'
|
||||
assert outcome.recovery_attempts[0]['status'] == repair_status
|
||||
|
||||
|
||||
def test_timeout_never_enters_automatic_repair(tmp_path, monkeypatch):
|
||||
|
||||
@@ -20,6 +20,90 @@ def test_application_palette_keeps_table_text_readable(qtbot):
|
||||
assert base.value() > 180
|
||||
|
||||
def fake_reader(_): return LibraryReadResult((CbbRecord('CBB1','Reusable Blocks'),))
|
||||
|
||||
def test_global_icdb_action_confirms_and_includes_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 == ['READY', '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_clears_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'))),
|
||||
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 == ['A']
|
||||
assert 'A' not in window.ready_names
|
||||
assert window.cbb_table.item(0, 2).text() == '未知 / 需确认'
|
||||
assert window.cbb_table.item(1, 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() == '全库 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 window.cbb_table.item(0, 2).text().startswith('跳过')
|
||||
|
||||
def test_verify_requires_loaded_library_and_invalidates_on_path_change(qtbot):
|
||||
window=MainWindow(reader=fake_reader, verifier=lambda _: VerifyResult('PASS')); qtbot.addWidget(window)
|
||||
assert not window.batch_button.isEnabled()
|
||||
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user