Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0fca6abb4e | ||
|
|
342a7266c7 | ||
|
|
e8a1714d95 | ||
|
|
e73f9c6edc | ||
|
|
b7baa24b5e | ||
|
|
3c1998f2ef | ||
|
|
807aa26baf | ||
|
|
8c2c60fab1 | ||
|
|
5b22787418 | ||
|
|
679f33b8cc | ||
|
|
746e5b5145 | ||
|
|
8eefecd9f0 | ||
|
|
d8156c57f0 | ||
|
|
959399b974 | ||
|
|
46dae81190 | ||
|
|
282be7be7f | ||
|
|
da67de026f | ||
|
|
9e230e1a46 | ||
|
|
a56fd17b60 | ||
|
|
766d67cb57 | ||
|
|
311d0dd9a4 | ||
|
|
3dbfca0f44 |
No files matched your search
@@ -1,6 +1,4 @@
|
||||
# CBB 中心库上传后校验工具
|
||||
|
||||
当前临时分支的备份策略(2026-11-03):应用不再自动备份中心库或 CBB 工程。新增、替换、移除、校验、ICDB 维护和恢复在执行前提示手动备份;请自行保留可用副本。导入暂存、恢复用隔离验证库和轻量操作证据仍会生成,Mentor 原生 Repair 自身的备份行为保持不变。详见[自动备份检查与调整](docs/releases/2026-11-03-manual-backup.md)。此条优先于下方历史版本的备份说明。
|
||||
|
||||
当前补丁:**[v0.2.3-beta.1](docs/releases/v0.2.3-beta.1.md)(Beta 预发布,待现场验收)**,替代 0.2.2-beta.1。数据库所有权或关闭状态不确定时停止批次、保留现场;不自动移走地址文件、接管带锁设计或强杀 PCB 进程树。新增全库 ICDB 维护、同名 CBB 完整备份恢复弹窗及严格的原生复核流程。详见 [v0.2.3-beta.1 发布说明](docs/releases/v0.2.3-beta.1.md)。下方日期记录描述历史版本,以本补丁说明为准。
|
||||
|
||||
@@ -9,7 +7,7 @@
|
||||
针对 `The last server session ... lost the connection to the database`,修复分支增加
|
||||
`ICDB_REPAIR_REQUIRED` 专项识别、共享符号库路径诊断及停止批次处理。现场原生修复步骤及实现边界见
|
||||
[iCDB 旧服务器会话失联分析](docs/diagnostics/2026-10-27-icdb-lost-server-session.md)。
|
||||
当前分支会在目标明确、所有权释放和独占访问证据齐全时尝试一次同版本原生 Repair;操作前请手动备份,共享符号库没有 PRJ 入口时停止并要求人工处理。
|
||||
当前分支会在目标明确、完整备份和所有权释放证据齐全时尝试一次同版本原生 Repair;共享符号库没有 PRJ 入口时停止并要求人工处理。
|
||||
|
||||
## 功能边界
|
||||
|
||||
@@ -203,7 +201,7 @@ Mentor 桥耗时需在目标机器另行测量。
|
||||
- `save.log`:`LICENSE_OK / SAVE_OK / IS_SAVED / POST_SAVE_SYNCHRONIZED / CLOSE_OK / QUIT_OK`;
|
||||
- `result.json`:状态、中心库标志读取结果、阻断原因;
|
||||
- `image-status-map.json`:按中心库路径隔离的本机动态 `image_id` 校准快照(当前格式 `schema_version=2`);旧版本或无版本缓存会自动忽略并重新校准,日志会记录当前样本、缓存样本、Ready 主 ID、未映射 ID 和逐项决策原因;
|
||||
- `backup/`:历史版本的辅助文件副本;当前分支不再生成,所有路径记录 `backup_skipped / manual_backup_policy`。已有历史副本不由本轮改动清理。
|
||||
- `backup/`:仅本地盘操作前的稳定文件副本;网络盘/UNC 跳过前置递归备份(`backup_skipped`);`database/LogFiles/tmp` 等易变目录和日志文件会排除,备份超时或失败不会阻断 PCB 校验。仅在成功且确认安全后清理该目录,失败时保留已有副本及日志;它不是完整数据库回滚备份。
|
||||
|
||||
超时采用无进展计时:界面和批量请求默认 600 秒无进展超时;它不是整个 CBB 的固定总时限,而是连续 600 秒没有可观察进展时才终止。PCB/COM 阶段切换、Project Integration 状态变化、保存标记变化和弹窗处理都会刷新计时器;重复的状态轮询不算进展。需要更快失败时仍可在界面将单项预算调低,但 30 秒只适合已确认 PCB 启动稳定的环境。
|
||||
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
# ICDB 持续失败:公开资料与实际入口核对
|
||||
|
||||
调查日期:2026-11-03。当前源码 `c856960`。本轮是网上资料检索及只读诊断,没有修改库、服务器设置或产品代码,不能作为修复验收。
|
||||
|
||||
## 本机确定的缺口
|
||||
|
||||
目前找到最近一次实际失败为隔离完整库 IP101GR 的 2026-11-03 16:19(北京时间)记录:
|
||||
|
||||
`diagnostics/feedback-final-ui/evidence/verify-85fd17bc6ed2/result.json`
|
||||
|
||||
错误为 `DATABASE_RECOVERY_REQUIRED`,阶段为 `PCB_STARTING`。原生提示询问:
|
||||
|
||||
> Continue to open the design with read/write access permission?
|
||||
|
||||
提示说明可能是文件系统/网络在 15 秒内未确定谁打开了设计,也可能是上一会话异常退出;要求确认没有其他用户正在使用。它没有证明数据库内容已损坏,也不是本轮原生 Repair 的失败结果。
|
||||
|
||||
代码及只读复核证据 `diagnostics/icdb-web-research-20261103/routing-evidence.json`:
|
||||
|
||||
1. `maintenance_entry.maintenance_needed` 仅在存在库阻止检查点或数据库地址记录时返回真。
|
||||
2. 当前 IP101GR 没有地址记录、没有阻止检查点,尽管请求 `maintenance=True`,仍返回 `routes_to_native_repair=false`。
|
||||
3. `select_maintenance_target` 额外要求恰好一个地址记录;无地址时返回 `需要唯一工程地址记录`,因此只改外层判断也不能打通流程。
|
||||
4. `verify_runner` 的自动补救仅针对 `ICDB_REPAIR_REQUIRED`;当前读写确认错误归入 `DATABASE_SAFETY_STOP`,不会触发该分支。
|
||||
5. 修复后一次性读写确认已有 `PostRepairProof` 机制,但只有本轮原生修复成功且释放已核实时才授权。当前入口绕过 Repair,自然没有这份证明。
|
||||
|
||||
因此,明确维护不能以“没有 sAddress.adr”推断无需维护。地址记录用于定位/占用判断,不应成为识别异常关闭状态的唯一依据。
|
||||
|
||||
## 网上资料:已读取原文
|
||||
|
||||
### 原生 Project Repair
|
||||
|
||||
[Mentor XP 如何修复文件](https://blog.csdn.net/qq_53931654/article/details/147240707)
|
||||
|
||||
原文步骤为打开 iCDB Project Backup,指定损坏工程路径,执行 `Project → Repair`。与本机已经接入的官方工具入口一致。本文是用户经验文章,没有证明当前完整自动链路或 CBB 校验限制已经解决。
|
||||
|
||||
本轮首次访问返回脚本验证页,后续正常请求取得正文;正文与截图链接保存在 `native-repair.json` / `native-repair.html`。
|
||||
|
||||
### 工程备份恢复
|
||||
|
||||
[“Unable to open iCDB connection”的解决方案](https://blog.csdn.net/zhangyang125/article/details/136188112)
|
||||
|
||||
原文建议从工程 `ProjectBackup/backups` 选择备份,恢复对应文件后重新打开。文章把复制/转移时文件丢失或损坏列为可能原因。该方案会回退版本,不等于保留最新内容的无损 Repair;仍需用户选择可接受版本,恢复后做工程身份与校验确认。
|
||||
|
||||
### 连接/监听地址
|
||||
|
||||
[Xpedition 2409 Designer 无法打开 iCDB 连接](https://blog.csdn.net/kkisscj/article/details/144323677)
|
||||
|
||||
原文描述在工作目录的 iCDB Server 配置中设置 `Network/Address` 为本机地址,并引用 VX2.8 管理文档。这说明“无法连接 iCDB”也可能是监听配置问题,不能一律解释为损坏。
|
||||
|
||||
但文章环境是 Xpedition 2409,本机是 EE7.9.5。现有日志未证实本机出现同类监听失败;本轮没有修改 Server 配置、服务或端口。
|
||||
|
||||
### 检索限制和排除项
|
||||
|
||||
英文 Google/DuckDuckGo 请求连接超时;Bing 多个精确错误查询无结果或结果无关,360 搜索提供了可进一步核对的中文线索。没有取得可直接适用于 EE7.9.5 当前弹窗的 Siemens 官方支持答复。检索及抓取原文保存在 `diagnostics/icdb-web-research-20261103/`。
|
||||
|
||||
标题/推荐摘要中含 “iCDB Server Monitor” 的另一页面,正文实际讨论 Android Studio Monitor,已排除,未把无关搜索结果当作技术依据。本机已有帮助文件检索也未找到能补足该弹窗处理条件的准确段落。
|
||||
|
||||
## 建议的修正与验证次序
|
||||
|
||||
1. 明确维护入口支持“无地址记录但需要检查”的工程:通过用户所选 CBB、唯一 PRJ/PCB 关系和明确数据库映射绑定目标;多个候选数据库必须明确区分,不能猜测共享库或另一个工程。
|
||||
2. 在本任务 PCB/启动器正常退出、库锁与数据库独占访问确认后,执行一次原生 Project Repair。不要因为看不到地址文件就直接退回打开 PCB。
|
||||
3. 仅在原生成功、目标一致、进程与地址释放确认后,使用已有修复后读写授权重新打开。未知或外部占用仍停止,不能把同意读写弹窗作为一般重试策略。
|
||||
4. 如要求选择 PCB 历史版本,明确记录选择及版本回退;随后验证集成、保存、关闭和权威 READY。
|
||||
5. 如果数据库检查通过,但仍被“已验证 CBB 不允许重新执行 BackAnnotate”阻止,应作为独立的 CBB 注册/校验状态问题处理。此前完整依赖库中“原生重新导入 → 自动校验 → READY”已通过,但不能把重新导入偷偷塞进 Repair 或称为无损修复。
|
||||
|
||||
此处已定位入口缺口和可验证的修正方向;尚未实现并完成“无地址记录”维护路径的真实自动链路验收。
|
||||
@@ -0,0 +1,366 @@
|
||||
# CBB 中心库上传后校验工具(cbb-refresh-verify-795)全面扫描与阻塞分析
|
||||
|
||||
- **扫描对象**:`https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795`
|
||||
- **默认分支**:`main` @ `39985f7`(`chore: release v0.2.3-beta.1`,2026-10-29)
|
||||
- **活跃分支**:`codex/temp-issue-2-icdb-recovery` @ `29959e2`(2026-11-04 14:16,领先 `main` **49 个提交 / +13,173 行**,未合并、未发布)
|
||||
- **标签**:`r4-stability-20260929`、`v0.2.2-beta.1`、`v0.2.3-beta.1`
|
||||
- **扫描时间**:2026-11-04
|
||||
- **扫描方式**:全量克隆 + 逐模块源码阅读(38 个源文件 / 8,180 行)+ 两个分支完整 pytest + 32 位桥 PE 导入表解析与实机启动 + 关键判定函数行为探针 + 与 `docs/` 现场记录交叉核对
|
||||
|
||||
---
|
||||
|
||||
> 关联工单:<https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/issues/4>
|
||||
>
|
||||
> 扫描基准:`main@39985f7`(v0.2.3-beta.1)、`codex/temp-issue-2-icdb-recovery@29959e2`。
|
||||
> 本文是扫描时的静态与实测记录;修复进展以工单和后续 PR 为准。
|
||||
|
||||
## 0. 一页结论
|
||||
|
||||
1. **单机、Win11、有 32 位状态桥、CBB 无异常** 的条件下,`v0.2.3-beta.1` 的"ReusableCircuit PCB → Project Integration → Save/Close → `IsVerifiedReuseBlock` READY"链路是成立的(发布说明有隔离实机 PASS 记录),工具没有伪造绿色状态,失败即阻塞的设计方向正确。
|
||||
2. **批量场景是这个工具真正的短板**:状态判定依赖外部 32 位桥,但**桥的 x86 VC++/MFC 运行时不随包提供**(本机实测 `0xC0000135` 无法启动);没有桥时工具仍会对每个 CBB 做完整刷新再判 FAIL;叠加"未知弹窗即停批""残留 `sAddress.adr` 即阻断""本机任何 PCB 打开即拒跑",批量任务在现场高概率中途停止。
|
||||
3. **Win10 是明确的未验收边界**:LM 原生菜单在私有桌面上不派发 MFC 命令(`docs/API-FINDINGS.md`),直接 PCB 路线在 Win10 上是否会提交 Verify 状态没有现场证据。
|
||||
4. **共享中心库并发没有真正的互斥**:`main` 只有进程内 `Local\` 命名互斥 + 本机进程探测;另一台机器/另一个工程师同时操作同名 CBB 时无任何防护。活跃分支新增了 sidecar 库锁,但它是"合作式"文件锁,Mentor 本身不参与。
|
||||
5. **ICDB 失联修复尚未闭环**:分支已经做到"原生 Repair → 重开 → 历史版本选择 → 校验 → READY",但文档明确"服务器会话失联经实际按钮触发的完整链路仍需通过",并且出现过"Repair 后 BackAnnotate 被原生拒绝"的失败结论。
|
||||
6. 代码质量整体高于同类现场工具(分层清晰、证据链完整、失败关闭),但存在若干**可复现的功能缺陷**(内容检查文本误判、`.prj` 编码假设、超时后孤儿 worker、save helper 无超时等),详见第 3 节。
|
||||
|
||||
**一句话**:这个工具现在能"证明一个 CBB 是否真的绿",但还不能稳定地"把一批 CBB 刷成绿";阻塞点不在算法,而在**判定链的部署完整性、现场弹窗/占用环境、以及批量的工程化**。
|
||||
|
||||
---
|
||||
|
||||
## 1. 系统定位与运行链路
|
||||
|
||||
### 1.1 定位
|
||||
|
||||
| 项 | 内容 |
|
||||
| --- | --- |
|
||||
| 处理对象 | 已上传到 Mentor 中心库(`.lmc` + `ReusableBlocksLP`)的 CBB 条目 |
|
||||
| 核心动作 | 打开该 CBB 的 ReusableCircuit PCB → Project Integration 四项同步 → 保存 Reusable Block cell → 关闭 → 只读读取权威 Verify 状态 |
|
||||
| 不做什么 | 不做 Part Number 替换、不做上传、不直接改写中心库数据来伪造绿色 |
|
||||
| 成功判据 | `worker` 完成 + 32 位桥 `IsVerifiedReuseBlock` 返回 `READY / raw=1`,二者缺一即 FAIL |
|
||||
|
||||
### 1.2 主链路(`main`)
|
||||
|
||||
```
|
||||
GUI (ui/main_window.py)
|
||||
└─ run_batch (verify_runner.py) # 串行,max_workers=1
|
||||
└─ run_verify # 会话级互斥 Local\CbbRefreshVerify795
|
||||
├─ preflight # Work 下唯一 PRJ / PCBDesignPath / 链接越界
|
||||
├─ unreleased_addresses # sAddress.adr 残留即 BLOCKED
|
||||
├─ ReuseBlockImporter -chkContents # 可选:LibSpec + DMS 登录配置
|
||||
├─ icdb_ports_bindable # 10000-10100 端口预检
|
||||
├─ DesktopWorker (私有桌面) # 32 位桥/弹窗代理同桌面
|
||||
│ └─ execute_job (mentor_adapter.py)
|
||||
│ ├─ 备份(仅本地盘) / CentralLibrary 路径修正
|
||||
│ ├─ ExpeditionPCB.exe <pcb> -ReusableCircuit
|
||||
│ ├─ wait_for_target_document (COM 身份核对)
|
||||
│ ├─ refresh_integration (四项 InSynch)
|
||||
│ └─ cscript save_verified_block.vbs (Validate/Save/IsSaved/Close/Quit)
|
||||
├─ cleanup_verify_processes # 只观察退出,不强杀
|
||||
└─ IsVerifiedReuseBlock (status_bridge.py) → READY / PENDING / UNAVAILABLE
|
||||
```
|
||||
|
||||
对话框监督是一条独立链路:`DesktopWorker` 在私有桌面启动 `--dialog-agent` 伴生进程,agent 用 Win32 + UIA 抓窗口快照,`dialog_supervisor` 按 `assets/dialog_rules.v1.json` 的**阶段化白名单规则**决策,通过 JSONL loopback IPC 回传。
|
||||
|
||||
### 1.3 每次校验的产物
|
||||
|
||||
`evidence/verify-*/`:`result.json`、`events.jsonl`、`dialogs.jsonl`、`save.log`、`performance.json`、`bridge-status.json`、`diagnostics/`(preflight、native-logs、icdb-recovery)、失败时的 `recovery-required.json`。
|
||||
|
||||
### 1.4 现场自述的验证状态(文档)
|
||||
|
||||
- `v0.2.3-beta.1`:`pytest` 471 passed;EE7.9.5 隔离实测"破坏 ICDB 文件头 → 备份恢复 → 重新打开 → PASS/GREEN/READY"。
|
||||
- 明确未验收:Win10、真实网络库大批量、现场 ICDB 失联的自动 Repair 全链路。
|
||||
- 旧批次 68 项中 51 PASS / 17 FAIL,失败类型已在 `docs/2026-09-29-stability-r4.md` 分类。
|
||||
|
||||
---
|
||||
|
||||
## 2. 规模与结构
|
||||
|
||||
| 指标 | main | temp-issue-2 分支 |
|
||||
| --- | --- | --- |
|
||||
| 提交数(相对 main) | — | +49 |
|
||||
| 源文件 / 行数 | 38 / 8,180 | 47 / 约 13,000+ |
|
||||
| 测试文件 / 行数 | 35 / 5,752 | 约 50 / 9,000+ |
|
||||
| 测试用例 | 471 | 1,196 |
|
||||
| 本机 pytest 结果 | **463 passed / 8 failed** | **1,178 passed / 18 failed** |
|
||||
| Python / 依赖 | 3.12 + PySide6 6.11 + pywin32 + pywinauto + Pillow | 同 main |
|
||||
| 打包 | PyInstaller onedir(`CbbRefreshVerify-Background`) | 同 main |
|
||||
|
||||
> 本机失败均与环境有关(未完成 `pip install -e .`、无 Mentor 安装、缺 x86 VC 运行时、长路径/编码),不是断言暴露的产品逻辑失败。具体归类见第 7 节。
|
||||
|
||||
---
|
||||
|
||||
## 3. 功能性问题清单
|
||||
|
||||
严重度:**P0** 阻塞交付 / 数据安全风险;**P1** 现场高概率失败或明显功能缺陷;**P2** 可用性、可维护性、规模化问题。
|
||||
|
||||
### 3.1 判定链与证据
|
||||
|
||||
| 编号 | 严重度 | 问题 | 代码证据 | 影响 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| **F-01** | P0 | **状态桥不可用时仍执行完整刷新,最后才判 FAIL**。批量入口不检查桥是否可用;桥只在 worker 成功后才查询 | `verify_runner.py:981-1000`;UI 读库 `ui/main_window.py:63-68`;`batch_status.authoritative_status_map` 失败只返回 `UNAVAILABLE` | 每个 CBB 白做 2-10 分钟原生刷新 + 一次 Save/Close,然后 `BRIDGE_UNAVAILABLE`;3000 项批量等于 3000 次无效写库 |
|
||||
| **F-02** | P0 | **32 位状态桥依赖 x86 `mfc140/MSVCP140/VCRUNTIME140`,打包清单只带 exe、未声明或检测该运行时**。本机 SysWOW64 无 x86 运行时,桥启动即 `0xC0000135`(发布 ZIP 不在仓库中,需在发布包上复核是否另行分发) | `packaging/CbbRefreshVerify.spec:4-14` 仅 `binaries=[CbbStatusBridge32.exe]`;PE 导入表实测:`KERNEL32, mfc140, MSVCP140, VCRUNTIME140, api-ms-win-crt-*` | 未额外安装 VC++ 2015-2022 x86 运行时的机器,桥永远不可用 → 所有项最终 FAIL |
|
||||
| **F-03** | P1 | 内容检查结果用正则 `failed\|error\|cannot connect\|bad data` 判失败,**"0 errors"、路径含 `error` 也会判 FAIL** | `verify_runner.py:30-31, 128-141`;本机实测 `classify_output(0, "...successfully! 0 errors...") == 'FAIL'` | 内容检查偶发误报阻断,且现场难以看出是文本匹配导致 |
|
||||
| **F-04** | P1 | `preflight` 用 `read_text(encoding='utf-8', errors='replace')` 解析 `.prj`;UTF-16/ANSI 工程会读不到 `PCBDesignPath` → 误判"工程没有 PCBDesignPath" | `verify_runner.py:157-161`;对照 `backup_recovery._project_text`(`backup_recovery.py:129-136`)已正确区分 UTF-16/UTF-8/mbcs | 老工程/修复后工程被预检直接判 BLOCKED,且看起来像"工程数据坏了" |
|
||||
| **F-05** | P1 | 内容检查报告写入**中心库目录** `LogFiles/`;写失败只拼进局部 `stderr`,PASS 路径下该信息被丢弃 | `verify_runner.py:688-693` | 只读共享/权限不足时无任何提示;中心库额外产生日志文件 |
|
||||
| **F-06** | P2 | 备份只在 PASS 且 `safe_to_continue` 时清理;失败项 `backup/`(可能数 GB)永久保留,无保留策略 | `verify_runner.py:641-651`;`mentor_adapter.cleanup_evidence_backup` | 长时间批量后磁盘被失败证据占满 |
|
||||
|
||||
### 3.2 现场自动化(弹窗 / 桌面 / 进程)
|
||||
|
||||
| 编号 | 严重度 | 问题 | 代码证据 | 影响 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| **F-07** | P0 | **任何不在白名单里的弹窗 = `UNKNOWN_DIALOG` = 当前项 FAIL + 整批停止**。规则要求精确英文文本、`GXWND`+`Button` 类名 | `dialog_rules.py:216-236`、`188-236`;`dialog_supervisor.py:458-471` | Mentor 版本/语言/主题差异、任何新提示("Reusable block already exists""license checkout failed"…)都会中断整批;现场 6 项 IME 语言栏误判即此类 |
|
||||
| **F-08** | P1 | 弹窗代理客户端**每请求 2 秒超时**,而 agent 端 `capture()` 最坏为"N 个窗口 × 0.75s UIA + 子控件枚举";UIA 探测超时后线程泄漏继续跑 | `dialog_agent.py:383-388`(默认 2.0s)、`dialog_probe.py:37-44, 242` | 机器繁忙/窗口多时 `DIALOG_PROTOCOL_TIMEOUT` 被当成致命错误;泄漏的 STA 线程与主探测并发调用 UIA,进一步拖慢 |
|
||||
| **F-09** | P1 | **Win10 私有桌面上 UIA `InvokePattern` 只关闭原生菜单、不派发 MFC 命令**;`native_lm_verify` 默认关闭,只有显式勾选才走菜单路线 | `docs/API-FINDINGS.md` §7、README「Win10/Win11 兼容性边界」;`verify_runner.py:466-470` | Win10 现场两条路线都不保证成功;目前只能以"Win11 已验证"交付 |
|
||||
| **F-10** | P1 | **本机只要有任何 `ExpeditionPCB.exe` 在跑就拒绝校验**(即使与本 CBB 无关) | `mentor_adapter.py:619-621` | 工程师日常开着 PCB 时无法点击校验;现场"先关掉所有 PCB"成为隐性前置条件 |
|
||||
| **F-11** | P1 | `sAddress.adr` 任一残留即 `ICDB_SESSION_UNCONFIRMED` 阻断;正常/异常退出后残留都要人工处理 | `icdb_ownership.py:13-16`;`mentor_adapter.py:644-650`;`verify_runner.py:661-670` | 一次现场崩溃会让后续每次校验都失败,且错误信息指向"未释放",与真实原因(陈旧文件)难区分 |
|
||||
| **F-12** | P1 | save helper 轮询循环**无超时、无取消检查**;helper 卡在 `doc.Save()` 时 worker 只能等监督器 600s 空闲超时 | `mentor_adapter.py:794-816` | 网络库/许可异常时单次长时间挂起;超时后 helper 仍可能继续写 |
|
||||
| **F-13** | P0 | **超时/取消只"请求停止"(touch 取消文件),不终止 worker**;worker 只在启动前、PCB 启动循环、保存前 3 处检查取消 | `desktop_worker.py:149-157`;`mentor_adapter.py:684-689, 744-746, 787-789`;`verify_runner.py:892-903` | 监督器已返回 TIMEOUT/FAIL 并释放互斥;worker 仍可能在随后的几秒内完成 Save/Close。若清理时恰好观察到 PCB 已退出,会判定 `safe_to_continue=True` 并启动下一项,而上一项仍可能有迟到的原生写入 |
|
||||
| **F-14** | P1 | supervisor 崩溃看门狗在 `cancel_path` 存在时(**生产总是存在**)只写取消文件然后返回,**不退出 worker**;只有 `cancel_path=None` 才 `os._exit(75)` | `desktop_worker.py:34-52`;`verify_runner.py:724` 恒写入 `cancel_signal` | 与 F-13 叠加:父进程崩溃后可能留下无监督的自动化进程继续写库 |
|
||||
|
||||
### 3.3 数据、权限与边界
|
||||
|
||||
| 编号 | 严重度 | 问题 | 代码证据 | 影响 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| **F-15** | P1 | 工具会**改写中心库内 `PCB/pcb.prj` 的 `CentralLibrary`**;修改前只在本次证据目录留单文件副本,网络库不做整工程备份 | `mentor_adapter.py:93-162, 707-712`;README 第 22 行亦承认 | 现场(网络中心库)没有可回退的工程副本;与 README「不允许直接改写中心库 .prj」的表述冲突 |
|
||||
| **F-16** | P2 | `Work` 下 `.prj` 不唯一即预检跳过;修复/导入后残留的备份 PRJ 会被当作"无法唯一确定" | `verify_runner.py:152-155`;`preflight_skip_reason` | 条目被静默跳过(黄行),用户以为已校验 |
|
||||
| **F-17** | P2 | Cert 完全不参与判定(设计取舍),但也没有"保存成功但未提交"的独立证据维度 | `verify_runner.py:313-330`;`collect_cert_evidence` 仅记路径 | 只能靠桥区分 PASS/PENDING;桥抖动时无法自证 |
|
||||
| **F-18** | P2 | 备份策略:网络盘直接跳过递归备份(`backup_skipped`),本地盘 3-30s 预算 | `mentor_adapter.py:632-640, 399-453` | 现场中心库基本都在网络盘 → 实际上没有前置备份 |
|
||||
|
||||
### 3.4 性能与规模化
|
||||
|
||||
| 编号 | 严重度 | 问题 | 代码证据 | 影响 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| **F-19** | P1 | 每次"读取 CBB"都会:整文件 SHA-256 `.lmc` + 顶层目录指纹 + 逐 CBB 桥查询 + **逐 CBB `preflight_skip_reason`(网络 stat/glob/读 PRJ)** | `batch_status.py:95-122, 194-197`;`ui/main_window.py:257-263` | 3000 项网络库首屏可能数分钟到数十分钟;期间只有一个"正在读取中心库…"标签,无进度、不可取消 |
|
||||
| **F-20** | P1 | 批量无进度条(仅全库 ICDB 模式有)、**不能取消当前项**(只能"当前项完成后停止")、崩溃后队列不持久化、不续跑 | `ui/main_window.py:417-454, 547-548`;`run_batch` 只在项间检查 stop | 长批次一旦中断只能从头再来;现场无法预估剩余时间 |
|
||||
| **F-21** | P2 | 每次桥查询(单条路径)都新起一个 32 位进程;批量依赖常驻 `--server`,桥崩溃后整段剩余项直接标 UNAVAILABLE | `status_bridge.py:141-203, 206-332`;`batch_status.py:258-270` | 单条校验慢;桥异常时"剩余全部不可用",无法只重试当前项 |
|
||||
| **F-22** | P2 | 多处 0.2s 轮询叠加 WMI 查询(`Win32_Process` 每次约 50-200ms)、integration 每次 `native_error()` 读 3 个原生日志 | `mentor_adapter.py:744-761, 800-809`;`integration.py:33-39`;`post_verify_diagnostics.py:32-39` | CPU/网络 I/O 放大;网络日志读取可能反过来拖慢原生操作 |
|
||||
|
||||
### 3.5 工程性 / 可维护性
|
||||
|
||||
| 编号 | 严重度 | 问题 | 证据 |
|
||||
| --- | --- | --- | --- |
|
||||
| **F-23** | P2 | 38 个源文件里 **102 处** `except Exception`/裸 `except`,大量 `except: pass`;故障常被降级成 `UNKNOWN/FAIL`,根因只留在日志 | 静态统计 |
|
||||
| **F-24** | P2 | GUI/CLI 顶层异常只 `return 1`,不打对话框、不打印到控制台;批处理用户只看到退出码 | `application.py:134` |
|
||||
| **F-25** | P2 | 无 CI 配置、无 lint/类型检查、无 LICENSE/CHANGELOG;300KB 二进制入库;`.gitattributes` 全量 `-text` | 仓库根目录 |
|
||||
| **F-26** | P2 | 测试依赖"本机已 `pip install -e .` + 已装 Mentor + 有 x86 运行时",新克隆机器直接 pytest 会有 8 项环境失败 | 第 7 节 |
|
||||
| **F-27** | P2 | 分支 49 个提交、+13k 行,`pyproject.toml` 版本仍是 `0.2.3b1`,候选包与正式包同版本号 | `pyproject.toml:6`(两分支相同) |
|
||||
|
||||
---
|
||||
|
||||
## 4. 阻塞点划分(任务视角)
|
||||
|
||||
把"阻塞"分成三类,避免把平台限制、工程缺陷、规模问题混在一起:
|
||||
|
||||
- **K1 平台/产品硬约束**:Mentor/Windows 决定,改代码无法消除,只能绕行、限定验收范围或推动替代方案。
|
||||
- **K2 交付阻塞**:团队可修,但当前版本不满足"可交付/可批量"的最低条件。
|
||||
- **K3 规模化阻塞**:单机少量可用,上批量/上团队前必须解决。
|
||||
|
||||
### 4.1 阻塞点总表
|
||||
|
||||
| 编号 | 阻塞点 | 类型 | 证据 | 受影响任务 | 解除条件 | 优先级 |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| **K1-1** | Library Manager 没有公开的 CBB `Verify()` COM 方法,只有内部 32 位导出 | K1 | `docs/API-FINDINGS.md` §3;`LibraryManager.tlb` 审计 | 所有"编程触发 Verify"的路线 | 接受"只读判定 + ReusableCircuit 刷新"路线,或继续 ABI 研究 | — |
|
||||
| **K1-2** | 状态判定只能靠 32 位 MFC ABI 桥,64 位 Python 不能直连 | K1 | `docs/API-FINDINGS.md` §3、§9 | 状态读取 | 保持独立 x86 桥(现状) | — |
|
||||
| **K1-3** | 私有桌面上 LM 原生菜单不派发(Win10 UIA),`SwitchDesktop` 在本机不可用 | K1 | `docs/API-FINDINGS.md` §7 | Win10 现场 | 现场 Windows 10 真机验收;或限定仅 Win11 | — |
|
||||
| **K1-4** | iCDB 服务器端口必须落在 10000–10100,可能被 Hyper-V/WSL 保留 | K1 | `mentor_adapter.py:978-1082`;文档 §8 | 所有 PCB 启动 | 管理员 `net stop winnat && net start winnat`(工具已给提示) | — |
|
||||
| **K1-5** | Mentor 对"已验证工程"禁止 BackAnnotate;共享符号库没有 PRJ 入口 | K1 | 工单 #2 文档、`integration.py:93-100` | 已绿工程复检、共享库修复 | 按原生限制记录为"已同步/不支持",或人工处理 | — |
|
||||
| **K2-1** | **桥不可用(缺 x86 运行时 / 未打包 / 路径找不到)仍可启动批量** | K2 | F-01、F-02 | 全部批量 | 打包 `VC_redist.x86` 或 `/MT` 静态链接;启动自检;无桥禁止批量 | **P0** |
|
||||
| **K2-2** | **未知弹窗即停批**,白名单覆盖不了现场提示 | K2 | F-07 | 批量、Win10 | 规则分级(致命/可确认/仅记录)、未知弹窗可配置停机或继续并留证 | **P0** |
|
||||
| **K2-3** | **超时/取消不终止 worker,孤儿进程可能继续写库** | K2 | F-13、F-14 | 数据安全、连续批量 | 明确"取消=停自动化客户端、保留原生会话"的边界;对 worker 进程做可验证的终止/对账;看门狗在崩溃时真正退出 | **P0** |
|
||||
| **K2-4** | 共享中心库无跨机互斥;`main` 只有进程内互斥 + 本机 PCB 探测 | K2 | `verify_runner.py:504-547, 742-746`;分支 `library_lock.py` | 多人/多机使用 | 合并分支库锁并让上传工具/Mentor 侧协同;或规定"单人独占窗口" | **P1** |
|
||||
| **K2-5** | 残留 `sAddress.adr` 永久阻断;本机任意 PCB 打开即拒跑 | K2 | F-10、F-11 | 日常使用 | 区分"陈旧地址文件"与"活会话"(探测可达性已具备,但策略过严);PCB 占用按 CBB/工程匹配而非全局 | **P1** |
|
||||
| **K2-6** | ICDB 失联的自动 Repair 全链路未验收;Repair 后 BackAnnotate 被拒 | K2(分支) | `docs/releases/2026-11-03-field-feedback.md`、`2026-11-04-icdb-review-fixes.md` | 库损坏恢复、全库维护 | 现场真实失联库端到端验收;修复后重开/保存/READY 全绿 | **P0(分支)** |
|
||||
| **K2-7** | Win10 未验证,且没有可用的菜单触发兜底 | K2 | F-09 | Win10 现场 | Win10 真机单 CBB 验收,或书面限定 Win11 | **P1** |
|
||||
| **K2-8** | 内容检查文本误判 + `.prj` 编码假设 | K2 | F-03、F-04 | 启用内容检查的批次 | 修正解析/判定,补回归 | **P1** |
|
||||
| **K3-1** | 首屏扫描 O(全库) + 逐 CBB 预检,无进度/不可取消 | K3 | F-19 | 3000 项批量 | 增量扫描、缓存指纹、预检并行/惰性、进度条 | **P1** |
|
||||
| **K3-2** | 队列不持久化、不能取消当前项、无断点续跑 | K3 | F-20 | 长批次 | 队列清单落盘 + 逐项检查点 + 取消当前项 | **P1** |
|
||||
| **K3-3** | 失败证据/备份无上限 | K3 | F-06 | 长期运行 | 证据保留策略(按天/按大小) | **P2** |
|
||||
| **K3-4** | 质量门禁缺失(无 CI、版本号不变、环境耦合) | K3 | F-25、F-26、F-27 | 发布/回归 | CI(无 Mentor 的 mock 层 + 一台 Mentor 自托管 runner)、版本号规范 | **P2** |
|
||||
|
||||
### 4.2 任务可达性矩阵
|
||||
|
||||
| 任务场景 | 结论 | 关键阻塞 |
|
||||
| --- | --- | --- |
|
||||
| 单 CBB,Win11,本地/网络库,桥可用,无人占用 | ✅ **可用**(有隔离实机 PASS 记录) | 无 |
|
||||
| 单 CBB,桥不可用/未装 x86 运行时 | ⛔ **必然 FAIL** | K2-1 |
|
||||
| 小批量(10–50),工作时段 | ⚠️ **可用但易中断** | K2-2、K2-5、F-12 |
|
||||
| 大批量(数百–3000) | ⛔ **时间与稳定性不可接受** | K3-1、K3-2、K2-2 |
|
||||
| Win10 现场 | ⛔ **未验收** | K2-7、K1-3 |
|
||||
| 共享中心库多人同时操作 | ⛔ `main` 无锁;分支为合作式锁 | K2-4 |
|
||||
| 库损坏/ICDB 失联恢复 | ⚠️ 诊断与手动路径可用;自动 Repair 未闭环 | K2-6 |
|
||||
| 无 Mentor 的开发机 | ✅ 仅单元测试(需先装包) | F-26 |
|
||||
|
||||
### 4.3 建议的解除顺序
|
||||
|
||||
1. **先让"批量的失败是可信且廉价的"**:桥预检 + 打包运行时(K2-1)→ 不做无用刷新。
|
||||
2. **再让"批量的中断可控"**:弹窗分级(K2-2)、取消/超时语义(K2-3)、占用与残留地址策略(K2-5)。
|
||||
3. **然后才谈规模化**:增量扫描、进度、续跑(K3-1、K3-2)。
|
||||
4. **平台边界单独验收**:Win10(K2-7)、共享库并发(K2-4)、ICDB 修复闭环(K2-6)。
|
||||
|
||||
---
|
||||
|
||||
## 5. 现场失败模式 → 代码根因映射
|
||||
|
||||
| 现场现象(文档) | 代码根因 | 对应问题 |
|
||||
| --- | --- | --- |
|
||||
| 6 项 `UNKNOWN_DIALOG: TF_FloatingLangBar_WndTitle` | IME 语言栏过滤条件过窄(类名+标题+无控件同时满足) | F-07 |
|
||||
| `TUNER_R836` Save/Close 后桥返回 PENDING | 桥判定 + Verify 未提交;或原生 BackAnnotate 被拒 | F-17、K1-5 |
|
||||
| `TUNER_R836_A` 数据库打开失败被记 UNKNOWN_DIALOG | 早期靠文本分类;现走规则白名单 | F-07 |
|
||||
| `1GPHY_8211` 打开时失联 → 后续 Repair `REPAIR_DATABASE_IN_USE` | 失败打开的 PCB 未被关闭(分支已修:启动失败关闭路径) | K2-6 |
|
||||
| 5 项 Project Integration 符号错误 | 工程/符号数据问题,工具只负责分类与留证 | — |
|
||||
| 3 项 JobPrefs / 本地 Cell Library 失败 | 环境/工程状态;工具仅诊断不修复 | — |
|
||||
| 端口 10000-10100 被保留 | `WinError 10013`,Hyper-V/WSL 动态预留 | K1-4 |
|
||||
| 桥 UNAVAILABLE 但报告"四绿"风险 | 已被 fail-closed 设计排除(不会伪造 READY) | — |
|
||||
|
||||
---
|
||||
|
||||
## 6. 活跃分支现状(`codex/temp-issue-2-icdb-recovery`)
|
||||
|
||||
### 6.1 新增能力(相对 main)
|
||||
|
||||
- 库锁与占用探测:`library_lock.py`、`owner_probe.py`、`native_occupancy.py`(与上传工具兼容的 `.cbb-upload.lock` / `.blocked.json` 协议)。
|
||||
- CBB 管理:`management.py`、`native_management.py`、`management_transaction.py`、`native_engineering_identity.py`、`native_export_guard.py`(新增/同名替换/移除、身份与导出副本保护)。
|
||||
- 恢复:`reimport_recovery.py`、`scoped_manifest.py`、`post_repair_consent.py`、`pcb_restore_prompt.py`、`maintenance_entry.py`(库外完整工程副本恢复、历史 PCB 版本选择)。
|
||||
- 策略调整:取消应用自动备份,改为**弹窗提醒手动备份**(`docs/releases/2026-11-03-manual-backup.md`)。
|
||||
- 启动失败关闭:`failed_session.py` 扩展为"预检失败/数据库打开失败也协作关闭 PCB"。
|
||||
|
||||
### 6.2 本机验证结果
|
||||
|
||||
- 1,178 passed / 18 failed;其中 8 项与 main 同因(环境),新增失败集中在:
|
||||
- **长路径**(`native_add_failures` 两个用例,150 字符目录名 → Windows `MAX_PATH`);
|
||||
- **owner probe 依赖安装**(`native_export_guard` 6 个用例:子进程 `-m cbb_refresh_verify` 不可用);
|
||||
- **编码**(`native_repair` 一个用例按 cp1252 解码失败);
|
||||
- **无 Mentor 安装**(`native_repair` 取消用例)。
|
||||
|
||||
### 6.3 分支仍未满足的门槛(文档自述)
|
||||
|
||||
- 服务器会话失联 → 实际按钮触发 → 自动 Repair → 重开 → 保存关闭 → READY 的**完整链路未验收**。
|
||||
- `1GPHY_8212` 原生 Repair 后 **BackAnnotate 仍被拒**,结论未变。
|
||||
- Windows 10 未验证(当前实机 Win11 / EE7.9.5)。
|
||||
- 历史 PCB 版本恢复记为 `RESTORED_REVIEW_REQUIRED`,**不等于无损修复**。
|
||||
- 目标缺 `PartsDB` 分区时无法完成完整校验。
|
||||
- 共享符号库不支持自动修复。
|
||||
- 版本号未递增、分支未合并。
|
||||
|
||||
> 结论:分支在"管理 + 恢复"上补齐了很多能力,但**没有解除 K2-6(ICDB 自动修复闭环)和 K2-7(Win10)**;同时引入了新的环境敏感性(长路径、owner probe 子进程、编码)。
|
||||
|
||||
---
|
||||
|
||||
## 7. 测试与质量评估
|
||||
|
||||
### 7.1 本机结果
|
||||
|
||||
```
|
||||
main: 463 passed, 8 failed, 1 warning, 37.09s
|
||||
branch: 1,178 passed, 18 failed, 1 warning, 92.29s
|
||||
```
|
||||
|
||||
main 的 8 项失败归因:
|
||||
|
||||
| 失败 | 原因 |
|
||||
| --- | --- |
|
||||
| `test_application`(2 项)、`test_abnormal_shutdown`、`test_extended_safety`、`test_failure_lifecycle`(共 5 项) | 子进程 `python -m cbb_refresh_verify` 依赖 `pip install -e .`,本机安装未完成 |
|
||||
| `test_native_repair::test_repair_cancellation...`、`test_verify_runner::test_pcb_launch...` | 本机无 `D:\Mentor\7.9.5EE` 安装 |
|
||||
| `test_packaging_status_bridge::test_compiled_bridge...` | 缺 x86 VC/MFC 运行时,`0xC0000135` |
|
||||
|
||||
### 7.2 覆盖情况
|
||||
|
||||
**做得好的**:状态判定(PASS 只能来自桥 READY)、对话框规则/后置条件、ICDB 日志新鲜度、备份/恢复、进程释放、UI 交互都有大量单测,且测试直接编码了"不得伪造绿色"的安全契约。
|
||||
|
||||
**缺口**:
|
||||
- 没有真实 Mentor 的集成测试(全部依赖 fake COM/进程边界);
|
||||
- 没有 Win10 测试矩阵;
|
||||
- 没有网络库并发/多人场景;
|
||||
- 没有长时间稳定性与性能回归(600s 空闲超时、3000 项批量);
|
||||
- 测试与"本机安装 + 本机 Mentor 路径"耦合,换机即红;
|
||||
- 无 CI,测试结果靠人工粘贴进 release note。
|
||||
|
||||
### 7.3 代码静态指标
|
||||
|
||||
- 38 个源文件 / 8,180 行;**102 处**宽泛异常捕获;15 处 `time.sleep`;15 处 subprocess 调用。
|
||||
- 硬编码 `D:\Mentor\7.9.5EE\SDD_HOME` 兜底 5 处(可作为默认,但需在 UI/日志里明确"发现失败")。新机器上会静默落到不存在的路径,报错信息偏底层。
|
||||
|
||||
---
|
||||
|
||||
## 8. 修复路线图(建议)
|
||||
|
||||
### P0(1–3 天,先让批量"失败得正确")
|
||||
|
||||
1. **桥部署闭环**
|
||||
- 打包 `VC_redist.x86.exe`(或桥改 `/MT` 静态链接),安装脚本检测/安装;
|
||||
- 启动时执行一次桥自检(`--codec-test` 或空查询),失败则禁用"批量校验"并给出可操作提示;
|
||||
- `read_library_fast` 返回 `UNAVAILABLE` 时,UI 明确"无法判定绿色,批量将全部失败",不静默入队。
|
||||
- 验收:干净 Win11 + 无 VC 运行时 → 工具提示安装而不是跑 3000 次无效刷新。
|
||||
|
||||
2. **未知弹窗分级**
|
||||
- 规则增加 `on_unknown: stop | record_continue | block_item`;
|
||||
- 默认对"无按钮/纯文本/IME/浏览器宿主"仅记录,对"数据库恢复/许可/保存失败"阻断;
|
||||
- 每次未知弹窗都落 `dialogs.jsonl` + 截图证据,批量结束汇总"待人工确认弹窗"。
|
||||
- 验收:新增一个未登记弹窗的模拟场景,批量不中断且证据可查。
|
||||
|
||||
3. **取消/超时语义**
|
||||
- 明确"取消 = 停止自动化客户端,保留原生会话";对 worker 增加强制终止开关(仅在未进入 Save 阶段可用);
|
||||
- 看门狗在 supervisor 退出时按"是否处于 Save/Close"决定终止或保留,并落 `watchdog-decision.json`;
|
||||
- `run_verify` 在 worker 未确认退出时不得释放互斥、不得继续下一项(当前已部分满足,需把"进程仍活"纳入 `safe_to_continue`)。
|
||||
- 验收:模拟 Save 卡死 → 工具超时后 worker 确实退出或明确标记"仍活",下一项不启动。
|
||||
|
||||
### P1(1–2 周,现场可用性)
|
||||
|
||||
4. 弹窗代理超时预算与 `capture()` 并发控制(F-08);UIA 探测改为按进程白名单 + 单窗口超时,禁止泄漏线程。
|
||||
5. 占用/残留策略(F-10、F-11):PCB 占用按 CBB 路径匹配;`sAddress.adr` 增加"不可达 + 非本机进程 + 超时"三条件判定为陈旧并可清理(需用户确认)。
|
||||
6. 内容检查判定(F-03)与 `.prj` 编码(F-04)。
|
||||
7. 中心库写入保护(F-15):改写 `pcb.prj` 前做整文件副本 + 变更清单,网络库至少保留原文件并可一键回滚。
|
||||
8. 合并分支库锁(K2-4),并与上传工具约定锁协议。
|
||||
|
||||
### P2(2–4 周,规模化)
|
||||
|
||||
9. 增量扫描/指纹缓存、预检惰性化、进度条、取消当前项、队列持久化与续跑(F-19、F-20)。
|
||||
10. 证据保留策略与磁盘配额(F-06)。
|
||||
11. CI:mock 层全量测试 + 一台 Mentor 自托管 runner 做冒烟;版本号规范(`0.2.3b1+candidate.49`)。
|
||||
12. 清理宽泛异常,至少在关键路径保留 `error_code` 与原始异常链(F-23)。
|
||||
|
||||
---
|
||||
|
||||
## 9. 附:关键证据索引
|
||||
|
||||
| 主题 | 文件:行 |
|
||||
| --- | --- |
|
||||
| 成功判据(桥 READY) | `src/cbb_refresh_verify/verify_runner.py:313-330, 981-1000` |
|
||||
| 内容检查判定 | `src/cbb_refresh_verify/verify_runner.py:30-31, 128-141` |
|
||||
| 预检(PRJ/PCB/链接) | `src/cbb_refresh_verify/verify_runner.py:144-174` |
|
||||
| 端口预检 | `src/cbb_refresh_verify/mentor_adapter.py:1061-1082` |
|
||||
| 数据库地址阻断 | `src/cbb_refresh_verify/icdb_ownership.py:13-16` |
|
||||
| PCB 全局占用检查 | `src/cbb_refresh_verify/mentor_adapter.py:619-621` |
|
||||
| CentralLibrary 改写 | `src/cbb_refresh_verify/mentor_adapter.py:93-162, 707-712` |
|
||||
| save helper 循环 | `src/cbb_refresh_verify/mentor_adapter.py:790-816` |
|
||||
| 取消信号 | `src/cbb_refresh_verify/desktop_worker.py:149-157`;`mentor_adapter.py:684-689, 744-746, 787-789` |
|
||||
| 看门狗 | `src/cbb_refresh_verify/desktop_worker.py:25-56` |
|
||||
| 弹窗规则 | `src/cbb_refresh_verify/dialog_rules.py:188-236`;`assets/dialog_rules.v1.json` |
|
||||
| 弹窗代理超时 | `src/cbb_refresh_verify/dialog_agent.py:383-388`;`dialog_probe.py:37-44, 242` |
|
||||
| 状态桥 | `src/cbb_refresh_verify/status_bridge.py:115-203, 206-332` |
|
||||
| 批量状态扫描 | `src/cbb_refresh_verify/batch_status.py:95-122, 184-277` |
|
||||
| UI 读库/队列 | `src/cbb_refresh_verify/ui/main_window.py:225-335, 417-548` |
|
||||
| 打包清单 | `packaging/CbbRefreshVerify.spec:4-25` |
|
||||
| 分支库锁 | `src/cbb_refresh_verify/library_lock.py:80-200`(分支) |
|
||||
|
||||
### 复现命令
|
||||
|
||||
```powershell
|
||||
git clone https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795.git
|
||||
cd cbb-refresh-verify-795
|
||||
python -m pip install -e .
|
||||
python -m pip install pytest pytest-qt
|
||||
python -m pytest -q # main: 463 passed / 8 failed(本机环境)
|
||||
git worktree add ..\cbb-branch origin/codex/temp-issue-2-icdb-recovery
|
||||
cd ..\cbb-branch; python -m pytest -q # branch: 1178 passed / 18 failed(本机环境)
|
||||
```
|
||||
|
||||
桥依赖验证:
|
||||
|
||||
```powershell
|
||||
# 1) 导入表:KERNEL32 / mfc140 / MSVCP140 / VCRUNTIME140 / api-ms-win-crt-*
|
||||
dumpbin /dependents .\tools\status_bridge\bin\CbbStatusBridge32.exe
|
||||
|
||||
# 2) 实机启动:缺 x86 运行时时的退出码 -1073741515 (0xC0000135)
|
||||
.\tools\status_bridge\bin\CbbStatusBridge32.exe --codec-test
|
||||
```
|
||||
@@ -0,0 +1,47 @@
|
||||
# Issue 5:私有桌面泄露
|
||||
|
||||
## 现象
|
||||
|
||||
代码与回归测试确认:原生 worker 创建私有 Windows Desktop 后,如果 Job Object 创建或 worker 进程启动失败,构造函数直接抛出异常,已创建的 Desktop 和 Job 句柄没有释放。重复失败存在累积私有桌面资源的风险;本次未对现场所有桌面异常作归因。
|
||||
|
||||
状态读取路径还有一个相同的边界:`read_library_flag` 在进入资源清理保护前加载 UI 依赖;依赖加载异常时,刚创建的私有桌面无法执行 `CloseDesktop`。
|
||||
|
||||
## 根因
|
||||
|
||||
1. `DesktopWorker.__init__` 的资源申请跨越多个可能失败的步骤,但没有事务式回滚。
|
||||
2. 进程句柄、Job 句柄和 Desktop 句柄的释放顺序没有覆盖构造阶段异常。
|
||||
3. `read_library_flag` 的依赖导入位于 `CreateDesktop` 之后、`try/finally` 之前。
|
||||
4. `read_library_flag` 和 `read_library_tree_image_map` 都在清理保护外先创建 Desktop,再执行 `Path(library)` 等准备逻辑;准备阶段抛异常时也会泄漏。
|
||||
|
||||
## 解决方案
|
||||
|
||||
- 在 `DesktopWorker` 构造开始时初始化资源字段,并把 Desktop、Job、worker 创建放入同一异常边界。
|
||||
- 构造失败时按 worker、Job、Desktop 顺序回滚;已启动的 worker 先终止,避免留下无父级的原生进程。
|
||||
- 在状态读取创建 Desktop 前完成 UI 依赖加载,确保依赖异常不会产生未受保护的 Desktop。
|
||||
- 两处状态读取均在准备逻辑完成后、`try/finally` 内创建 Desktop,清理时检查资源是否存在。
|
||||
- 测试中分离 Desktop、Job、Process、Thread 的接口,断言失败后关闭顺序;覆盖四个构造失败点与进程创建后的终止分支。
|
||||
|
||||
## 影响范围
|
||||
|
||||
- 覆盖原生 worker 构造失败,以及状态读取准备和启动阶段的资源清理路径。
|
||||
- 正常任务的私有桌面、Job Object、进程树和数据库释放策略不变。
|
||||
- 不会切换用户输入桌面,也不会改变中心库写入策略。
|
||||
|
||||
## 验证
|
||||
|
||||
- 修复分支完整 `python -m pytest -q --tb=short`:480 passed。
|
||||
- 同环境、同工作树切换到 `origin/main`(`39985f7`)完整运行相同命令:471 passed。两次运行依次执行,均仅有一条 pywinauto STA 警告。
|
||||
- `tests/test_desktop_worker.py`:9 passed。两处状态读取准备阶段泄漏的新增测试在修复前 2 failed,修复后通过。
|
||||
- 变异验证:把回滚中的 `self.job.Close()` 故意改为 `self.job.CloseDesktop()`,测试产生 2 failed;恢复正确代码后通过。
|
||||
- `python -m compileall -q src tests`:通过。
|
||||
- `git -c core.whitespace=cr-at-eol diff origin/main HEAD --check`:通过。命令显式识别 Windows CRLF;仓库 `.gitattributes` 为 `* -text`,保留源文件换行,不依赖本机 `core.whitespace` 配置。
|
||||
|
||||
此前 #7 将一次运行中的 `test_backup_recovery.py::test_invalid_source_does_not_touch_target` 失败称为既有基线问题,缺少同环境对照,撤回该归因。本次该用例在 main 与修复分支均通过。审查者在旧 WIP 基线测得的 19 个失败不属于本次从 main 独立提交后的测试范围。
|
||||
|
||||
## 合并范围修正
|
||||
|
||||
原 PR #7 以 ICDB WIP 分支为父提交,却以 main 为合并目标,实际携带 59 个提交、118 个文件。现从 main 单独 cherry-pick 桌面修复并补充上述审查修正;相对 main 只有本工单、两个源码文件和一个测试文件,共 4 个文件。独立代码复审未发现待处理问题。
|
||||
|
||||
## 分支
|
||||
|
||||
`codex/desktop-leak-main`
|
||||
@@ -1,95 +0,0 @@
|
||||
# CBB 管理候选实现(Issue #2 Task 4)
|
||||
|
||||
本次在当前应用增加新增、同名更新和移除入口、逐项检查点、库外完整备份、
|
||||
来源工程暂存和明确的结果状态。READY 条目可以勾选用于管理;原有校验和恢复
|
||||
仍仅处理当前可见的非 READY 合格条目。
|
||||
|
||||
## 原生能力边界
|
||||
|
||||
移除路线来自 EE 7.9.5 随附 Tcl 的 `CleanWGLib <lmc> F4 <list>`,输入为
|
||||
`REUSE_BLOCK\tLogical-Physical\t<name>`。协调端已在独立库副本完成真实移除
|
||||
和原生目录缺失复读。运行时核对已验证的 LibraryManager、CleanWGLib、
|
||||
LMCDLL70 和 LMCDocAddin70 文件 SHA256;仅允许匹配版本、DxDesigner 流程、
|
||||
Logical-Physical 分区及 ASCII 名称。输出必须包含对应名称/分区的 Removed
|
||||
消息且不含 Warning/Error,之后重新打开原生目录确认条目缺失。
|
||||
|
||||
新增和同名更新默认禁用,界面说明缺少哪项隔离验证。已发现原生新增对话框
|
||||
不等于完成库注册;不能仅凭返回值或出现目录启用。通用引擎已实现新增冲突
|
||||
拒绝、暂存来源、名称/分区/工程内容复读、可选自动校验,以及明确更新时的
|
||||
原生移除后重新导入。更新必须同时有两个原生路线和同名端到端验证才可启用。
|
||||
移除后重新导入失败会报告 `RECOVERY_REQUIRED`,停止队列,不自动回滚或重放。
|
||||
|
||||
## 操作与恢复证据
|
||||
|
||||
每项结果包含 operation、library、name、partition、source、auto_verify、stage、
|
||||
status、safe_to_continue 和 evidence_path。`management/management-<id>/`
|
||||
保存原子更新的 `checkpoint.json`、完整 `library-before`、主数据清单、来源
|
||||
暂存副本、原生请求/输出和后续校验记录。结果区区分:
|
||||
|
||||
- `UPLOAD_FAILED`:上传失败;不能解释为已上传。
|
||||
- `UPLOADED`:原生注册与工程身份已确认,本批次未自动校验。
|
||||
- `UPLOADED_VERIFY_FAILED`:已上传,但自动校验没有达到 PASS/GREEN。
|
||||
- `UPLOADED_VERIFIED`:已上传且自动校验达到 PASS/GREEN 并确认释放。
|
||||
- `REMOVED`:原生移除且重新读取目录确认缺失。
|
||||
- `RECOVERY_REQUIRED`:原生写入可能发生,或更新已移除但重新导入未完成;
|
||||
保留完整库备份和所有中间状态,需要人工审查。
|
||||
|
||||
启动时显示未完成和释放不确定的检查点,不自动执行。存在同一库的未完成
|
||||
检查点时,新的管理任务被阻止。先由管理员检查原生进程、目标目录和备份,
|
||||
按现场恢复流程处理;确认恢复完毕后把已审查的操作证据目录移至独立归档位置,
|
||||
再重新读取库。不要删除锁文件,不要强制结束持有数据库的原生程序。
|
||||
|
||||
## 并发和来源保护
|
||||
|
||||
管理、校验和备份恢复共享 `Local\CbbRefreshVerify795` 及原上传工具兼容的
|
||||
`.<LMC stem>.cbb-upload.lock` 独占句柄。只有相同线程持有的相同库锁允许嵌套;
|
||||
完整备份通过已经持有的句柄读取锁内容,不重新打开或删除独占锁。
|
||||
管理任务不能确认原生所有者释放时,在本应用进程内保留该独占句柄,阻止旧上传
|
||||
工具抢入;不会仅因自动化线程返回或超时而释放锁。
|
||||
直接校验与备份恢复也保留释放不明确的锁。库旁保存
|
||||
`.<stem>.cbb-upload.blocked.json`,本应用重启后拒绝写入和原生读取。
|
||||
该记录在取得库锁后、原生调用前写入,正常确认释放才清除。只有精确保留文件名、
|
||||
协议版本和所有权字段匹配的记录被归类为运行时元数据;完整副本仍保留其字节,
|
||||
主数据比较忽略其生命周期变化。同名普通文件或损坏记录保持原样并阻止自动解除。
|
||||
“检查会话释放并解除协调阻止”入口先确认管理工作进程已返回、相关原生进程
|
||||
均已退出、库内不存在 sAddress.adr,且能同时以独占只读句柄打开所有 LMC、
|
||||
icdb.dat 和 LayoutDB.lyt。全部通过才归档阻止记录并关闭本应用保留的句柄;
|
||||
不会删除上传锁文件,也不把会话释放解释为数据恢复成功。
|
||||
|
||||
进程崩溃会使 Windows 释放其句柄;旧上传工具不认识新增阻止记录,因此本方案
|
||||
不能保证本应用崩溃后旧上传工具仍被排除。崩溃后应先正常结束原生会话,并通过
|
||||
上述释放检查和未完成任务审查,再使用本工具或旧上传工具继续写入。
|
||||
|
||||
备份与来源不能置于目标库内部,来源必须是完整且引用位于工程内的 PRJ/PCB。
|
||||
来源工程根目录和目标库根目录也不能相互包含或相同,避免操作嵌套库时改变原始来源。
|
||||
链接、外部数据库引用、源文件变化、备份失败和同名新增冲突均会阻止写入。
|
||||
来源先完整复制;工程身份比较使用顶层块、原理图数据库和布局数据库内容指纹,
|
||||
原生规范化若改变数据库字节则保守拒绝确认,需要进一步语义验证,不能声称等价。
|
||||
|
||||
原生管理在私有 Windows 桌面运行,不移动鼠标或占用前台输入。只操作当前
|
||||
已识别原生进程。读取目录遇到旧库升级或 Select flow type 对话框时取消并报错,
|
||||
绝不将升级作为只读读取的一部分。超时保留原生所有者和证据,不强杀数据库进程;
|
||||
确认前不继续下一项,不启动最终 Verify。
|
||||
通过网络盘租约选择的盘符路径在原生 OpenLibrary、CLI、暂存工程库引用和后续
|
||||
Verify 中保持原样;规范化路径仅用于身份、包含关系和锁键比较。工作进程按原
|
||||
租约的盘符/共享目录上下文确认映射,不把原生盘符路径改回 UNC。
|
||||
|
||||
## 独立新增诊断
|
||||
|
||||
`python tools/validate_native_management.py SOURCE.prj NEW_OUTPUT_DIRECTORY NAME`
|
||||
只接受不存在的新目录,先完整复制来源,再由私有工作进程调用原生
|
||||
`CreateLibrary(..., kFLOW_DX=1)` 创建固定的新库。随后使用已验证的
|
||||
Reusable Blocks / UIA Logical - Physical 页签和 New 按钮、1103 对话框字段。
|
||||
诊断会记录原生消息、关闭后的重新打开清单、工程内容比较和原始来源不变检查。
|
||||
它不接收生产库参数,不存在跳过生产能力门禁的开关,也不自动修改能力门禁。
|
||||
可加 `--replacement-source OTHER.prj` 在同一个新建隔离库中验证同名更新:
|
||||
先备份完整旧库,再原生移除并检查缺失,然后重新导入替换工程。重新导入必须
|
||||
匹配本次 CreateLibrary 记录的固定路径和随机所有权令牌,不能指向外部库。
|
||||
监督进程先创建新的空 fixture 目录并持有库锁,原生工作进程核对准备令牌、
|
||||
检查点协议和监督 PID 后才创建 LMC。初次创建、所有复读和替换阶段均按生产
|
||||
操作的释放规则持锁;超时或释放异常保留独占句柄和重启阻止记录,必须重新
|
||||
通过会话释放检查才能解除。
|
||||
|
||||
本阶段单元测试通过注入文件模拟的原生边界执行,不启动 Mentor、不操作实际库。
|
||||
候选冻结包、最终 Windows 11 原生场景由协调端单独验收。Windows 10 和真实
|
||||
现场失联样本仍未验证;文件头损坏与模拟故障不能替代这些验收。
|
||||
@@ -1,77 +0,0 @@
|
||||
# 工单 #2 候选包验收记录
|
||||
|
||||
分支:`codex/temp-issue-2-icdb-recovery`。本记录区分软件回归、隔离原生试验和现场验收;未合并、发布或关闭工单。
|
||||
|
||||
最终候选程序源码提交:`8e486c1`。新增和同名更新保持禁用;原生新增虽已成功注册并复读,但原理图数据库被原生工具重写,尚未证明内容等价。移除已在新建隔离库通过完整管理流程验证。
|
||||
|
||||
最终全量回归:`python -m pytest -q` 在 `122bafc` 上 **887 passed,1 个已有 pywinauto STA 模式警告,68.62 秒**。`122bafc` 只调整安全测试,`src` 和 `packaging` 的 Git 树与打包提交 `8e486c1` 完全一致。编译检查及 `git diff --check` 通过;整分支审查和后续修正复审均无未处理问题。
|
||||
日志:`build/issue2-final-tests-122bafc.log`。安全测试明确保留工程文件、上传锁以及损坏/外来检查点,只有本工具拥有且验证通过的运行时检查点允许清理。
|
||||
|
||||
## 已实现范围
|
||||
|
||||
- ICDB 启动失败后,仅在任务进程、工程路径、私有桌面、空闲窗口及地址释放可确认时正常关闭 PCB;同时等待启动器退出。Repair 区分缺少健康备份、原生失败、占用、未知窗口和释放超时。最终重新打开、校验及 READY 状态共同决定修复成功。
|
||||
- 名称/分区搜索和状态筛选使用已加载数据;隐藏条目清除勾选。READY 可以用于管理,不能进入默认校验、维护和恢复队列。受影响条目刷新后重新判断资格。
|
||||
- 完整备份保留全部文件;版本化清单对主要工程文件和库依赖计算 SHA-256,复制时同时核对文件集合、大小和时间。日志及其他运行时变化不再等同于工程内容变化。
|
||||
- 管理请求、逐项结果、完整旧库备份、检查点、来源暂存、共享锁和安全释放入口已集成。新增/更新未达到原生验收门槛时禁用。重启只展示未完成任务,不自动重放写操作。
|
||||
|
||||
## 原生证据与边界
|
||||
|
||||
| 场景 | 实际观察 | 限制 |
|
||||
| --- | --- | --- |
|
||||
| 最终冻结程序启动失败退出 | `8e486c1` 的 PCB 和启动器自动正常退出、无数据库地址;`startup-close.json` 为 CLOSED,safe_to_continue=true | 人工损坏副本,不是现场服务器失联 |
|
||||
| 最终冻结程序 Repair 缺少健康备份 | `8e486c1` 返回 MISSING_HEALTHY_BACKUP,原生工具自动退出、地址为空、允许安全继续 | 验证明确失败和释放,不代表修复成功 |
|
||||
| 官方原生移除 | 独立副本中 CleanWGLib/F4 返回 0,之后原生目录重新读取为空 | 旧库升级存在告警;生产读取遇到升级必须拒绝 |
|
||||
| 隔离新增首次完整探测 | 新建库后打开编辑器失败,尚未提交新增;来源保持不变,保留失败证据及协调阻止记录 | 不启用新增或同名更新,不作为成功验收 |
|
||||
| 最终移除适配器命令 | 实际捕获 `# Note: Removed REUSE_BLOCK 'IP101GR' from partition 'Logical-Physical'.`,释放确认成功,来源清单未变 | 随后的旧库复读拒绝 Select flow type;不能宣称该库完整自动移除验收通过 |
|
||||
| 新建隔离库完整移除 | 管理引擎完成原生读取、完整旧库备份、原生删除、重新读取确认缺失;最终 REMOVED,safe_to_continue=true | 仅代表此安装版本、库流程和 Logical-Physical 分区 |
|
||||
| 新建隔离库原生新增 | 收到成功消息,正常关闭、重新打开仍有正确名称/分区,原始来源不变;布局哈希一致 | 原理图数据库哈希改变,identity_matches=false;新增/更新不启用,未执行同名更新和重新导入恢复验收 |
|
||||
|
||||
原始证据位于 `diagnostics/issue2-frozen-20261102/`、
|
||||
`diagnostics/issue2-management-native-20261102/` 和
|
||||
`C:/Users/ABS_Windows/.cbb-management-e2e-20261102-a/`。
|
||||
首次新增失败后,仅向已确认的隔离 Library Manager 主窗口发送正常 WM_CLOSE;
|
||||
随后进程查询为空,没有强制终止数据库所有者。
|
||||
|
||||
第二次新增探测的 `dispatch-diagnostics.jsonl` 在加载 pywinauto 前记录方法
|
||||
DISPID 17/26/6,加载后全部返回 `CO_E_OBJNOTCONNECTED`(-2147220995)。
|
||||
这证明失效发生在 UI 自动化依赖初始化边界,尚未提交新增;来源未变。
|
||||
第二次隔离会话同样正常关闭。移除适配器及旧库拒绝证据保存在
|
||||
`diagnostics/issue2-remove-adapter-20261102/`;旧库拒绝流程后出现的
|
||||
“Unable to determine flow type”通知由协调端确认后正常退出,不能记为无人值守释放通过。
|
||||
|
||||
`ffa7e84` 冻结包的 GUI 冒烟通过,但真实批处理在启动 Mentor 前报
|
||||
`No module named 'win32timezone'`。此包不能作为最终可用包交付;必须补齐打包依赖并重建验证。
|
||||
`1f69480` 补齐依赖后运行了真实 PCB 流程;`8e486c1` 又收紧了隐藏基础设施窗口的精确识别条件,最终冻结测试自动通过退出分支。
|
||||
|
||||
最终证据:
|
||||
|
||||
- `diagnostics/issue2-frozen-20261102/full-8e486c1-startup/evidence/verify-97173dae8a21/startup-close.json`
|
||||
- `diagnostics/issue2-frozen-20261102/full-8e486c1-nohistory/repair-result.json`
|
||||
- `diagnostics/issue2-management-final-20261102/probe-result.json`
|
||||
- `diagnostics/issue2-management-final-20261102/full-remove-result.json`
|
||||
- 移除前完整旧库保留在 `C:/Users/ABS_Windows/.cbb-management-e2e-20261102-e/full-remove/management-e90d69ad7f624fb18f5401119b96856d/library-before/`。
|
||||
|
||||
冻结启动失败试验的批处理退出码为 2,因为输入是损坏工程;通过项是自动安全退出,而不是工程校验成功。缺少健康备份的 Repair 同样是已验证的明确失败分支。
|
||||
|
||||
## 仍需现场验收
|
||||
|
||||
工单附件只有日志,没有现场 `1GPHY_8211` 故障工程及其必要共享库的一致副本。
|
||||
因此现场服务器会话失联尚未复现,也没有完成该现场故障经应用实际维护按钮触发的完整自动链路验收。
|
||||
必须取得副本、记录来源/工程身份/主要文件哈希,在隔离环境记录失败、退出、Repair 调用、重新打开、保存关闭和 READY 查询的完整证据,并核对来源未改变。
|
||||
复制后不能复现时应记录“未复现”,不能用数据库文件头损坏试验替代。
|
||||
|
||||
Windows 10 尚未验证。现有原生试验环境为 Windows 11 / Mentor EE 7.9.5。
|
||||
历史备份恢复保持“已恢复,版本待核对”,不宣称无损修复。
|
||||
|
||||
## 候选包
|
||||
|
||||
`dist/issue2-repair-candidate-877e3b4.zip` 保留独立修复候选包及构建清单。
|
||||
完整候选程序位于 `dist/issue2-full-candidate-8e486c1/`,由 `git archive 8e486c1` 的不可变源码构建。构建与 GUI 冒烟通过,真实冻结原生证据见上。
|
||||
分发压缩包:`dist/issue2-full-candidate-8e486c1.zip`。解压后运行 `CbbRefreshVerify-Background/CbbRefreshVerify.exe`;包根目录保留构建清单、本文及关键验证证据。
|
||||
`dist/issue2-full-candidate/` 和 `dist/issue2-full-candidate-1f69480/` 是被后续修正取代的中间试验构建,不作为交付包。
|
||||
|
||||
## 后续验收顺序
|
||||
|
||||
1. 取得现场故障工程及必要共享库一致副本,优先完成实际维护按钮触发的完整自动链路验收。
|
||||
2. 针对原生导入会重写 ICDB 的行为,使用经过验证的 Mentor 语义读取/导出建立工程内容等价证据;不能只放松哈希检查。之后才能启用新增,并验证重复冲突、同名更新、部分失败及备份重新导入。
|
||||
3. 在 Windows 10 / EE 7.9.5 重跑冻结关键路径,并在具备网络测试环境时验证真实断网、取消和恢复场景。现有模拟测试不能替代这些环境验收。
|
||||
@@ -1,182 +0,0 @@
|
||||
# Issue #2: release the PCB launched by a failed database open
|
||||
|
||||
Branch: `codex/temp-issue-2-icdb-recovery`.
|
||||
|
||||
## Field failure
|
||||
|
||||
The issue attachment records an iCDB lost-server-session error while opening
|
||||
`1GPHY_8211`. The supervisor declined the database log viewer and cancelled the
|
||||
worker. Because document identity had not been established, the existing
|
||||
document-close helper was never called. PCB and its launcher remained alive;
|
||||
the subsequent Repair attempt returned `REPAIR_DATABASE_IN_USE` and the other
|
||||
380 queued entries were skipped. There is no evidence of native Repair actually
|
||||
running on that field database.
|
||||
|
||||
## Change
|
||||
|
||||
The worker now has a separate startup-failure close path. It requires a current
|
||||
iCDB diagnosis or a database-load-failure dialog belonging to this PCB during
|
||||
startup. It checks the private desktop, excludes pre-existing process IDs, and
|
||||
matches the complete PCB path and ReusableCircuit argument. Only an enabled
|
||||
empty PCB main window, without modal dialogs, MDI documents or database address
|
||||
records, receives a cooperative `WM_CLOSE`. A requested close is not treated as
|
||||
success until process exit is observed. Ambiguous or busy sessions are retained.
|
||||
|
||||
The supervisor allows up to 40 seconds for fatal-error cleanup so that the
|
||||
worker's 20-second startup-close window can complete before recovery begins.
|
||||
The existing repair preconditions, backups and success checks remain in force.
|
||||
Each attempt writes `startup-close.json` and close-request/result events.
|
||||
|
||||
## Verification
|
||||
|
||||
Regression tests cover the missing pre-identity cleanup route, real observed
|
||||
empty-window titles, exact path matching, pre-existing processes, another
|
||||
desktop, live address records, modal and MDI windows, disabled windows, unrelated
|
||||
failure records and a close request that does not result in exit.
|
||||
Delayed dialog/address release and delayed process exit are also covered.
|
||||
Validation: `python -m pytest -q` — 491 passed, one existing pywinauto COM-mode
|
||||
warning; `python -m compileall -q src tests` and `git diff --check` passed.
|
||||
|
||||
A new isolated local library was created with the existing
|
||||
`tools/validate_icdb_open_repair_reopen.py` tool, output
|
||||
`diagnostics/issue2-startup-20261102`. No production library was changed.
|
||||
The test damages only the new copy's database header; it does not reproduce the
|
||||
field server-session-loss condition.
|
||||
|
||||
The real Mentor opening run produced `MENTOR_DATABASE_LOAD_FAILED`, then:
|
||||
|
||||
- `startup_close_requested` for the launched PCB PID 6532;
|
||||
- `startup_close_result: CLOSED`;
|
||||
- worker and supervisor both recorded `process_exit_confirmed`, with no
|
||||
remaining PCB processes.
|
||||
|
||||
The subsequent separate native Repair run was able to start and completed as
|
||||
`RESTORED_REVIEW_REQUIRED`, using the fixture's historical backup. This proves
|
||||
the failed-open session no longer blocks the next repair operation in this
|
||||
fixture. It does not prove automatic recovery of the field database or establish
|
||||
that an older backup contains the desired design revision.
|
||||
|
||||
The separate `open-after` run on the same restored fixture completed native
|
||||
integration, Save/IsSaved/Close/Quit, confirmed process release and returned
|
||||
`PASS`, `safe_to_continue=True`, `READY (IsVerifiedReuseBlock, raw=1)`.
|
||||
The `compare` phase passed all seven checks, including absence of the original
|
||||
opening error and unchanged source-fixture database SHA-256. Its
|
||||
`server_session_loss_reproduced` field is explicitly `false`.
|
||||
|
||||
Reproduction commands (set `PYTHONPATH=src`; setup requires a new output name):
|
||||
|
||||
```powershell
|
||||
python tools/validate_icdb_open_repair_reopen.py setup --output issue2-startup-20261102
|
||||
python tools/validate_icdb_open_repair_reopen.py open-before --output issue2-startup-20261102
|
||||
python tools/validate_icdb_open_repair_reopen.py repair --output issue2-startup-20261102
|
||||
python tools/validate_icdb_open_repair_reopen.py open-after --output issue2-startup-20261102
|
||||
python tools/validate_icdb_open_repair_reopen.py compare --output issue2-startup-20261102
|
||||
```
|
||||
|
||||
The stages are deliberately separate: the test fixture has a format-corruption
|
||||
error and historical-backup recovery, not the field lost-session auto-repair
|
||||
trigger. The test does not change production handling of old-backup recovery.
|
||||
|
||||
READY filtering, hash-scope changes and CBB CRUD are outside this focused fix.
|
||||
|
||||
## Approved Task 1 follow-up: lifecycle and repair outcomes
|
||||
|
||||
The empty-PCB close path now receives the launcher process handle and waits for
|
||||
its normal exit after PCB exits. It checks database addresses again during that
|
||||
wait, so a late address record prevents a false `CLOSED` result. The startup
|
||||
record includes PCB, launcher and address release state. A connected COM server
|
||||
with no active document emits `pcb_document_wait`; it remains in startup and
|
||||
continues reading the current native failure rather than implying identity.
|
||||
|
||||
Native Repair reads bounded Output text and records only the text appended after
|
||||
this run's Repair invocation as operation evidence. Database logs are restricted
|
||||
to the current native PID and start time. Output, native log copies, the complete
|
||||
backup, native result and attempt record remain available under `native-repair`.
|
||||
Detailed native evidence is preserved separately from its directory path.
|
||||
|
||||
The result distinguishes `MISSING_HEALTHY_BACKUP`, `NATIVE_REPAIR_FAILED`,
|
||||
`DATABASE_BUSY`, `UNKNOWN_DIALOG`, and `TIMEOUT_UNRELEASED`. A failed tool receives
|
||||
cooperative close only after a terminal native error, an enabled exact-project
|
||||
main window, no other windows/prompts and no target database address. The worker
|
||||
then waits for normal process exit. Unknown/custom prompts and incomplete native
|
||||
operations receive no close action. A failure classification can coexist with
|
||||
unreleased state; that state always stops the queue. Terminal `DATABASE_BUSY`
|
||||
errors also retain the native tool without close, reopen or queue continuation.
|
||||
Unreadable, absent, hung or truncated initial Output waits within the deadline
|
||||
and retains the tool without requesting Repair; a readable empty string is a
|
||||
valid invocation baseline. A busy-project message in
|
||||
this fresh native process's initial loading Output prevents Repair invocation
|
||||
entirely; it is not hidden by the later invocation baseline.
|
||||
|
||||
Before reopening or continuing, the parent independently checks relevant PCB,
|
||||
Library Manager, Repair, importer and close-helper processes, all known project/
|
||||
PCB/shared-library addresses, and exclusive read access to every existing known
|
||||
database. Process-observation errors and exclusive-access failures block reuse.
|
||||
Only a conclusively failed, released, independently revalidated project-local
|
||||
target may allow the next CBB. Shared or unknown scope, busy owners, timeouts,
|
||||
unknown prompts and historical restores stop for review.
|
||||
|
||||
Before accepting native success, the parent validates native process identity
|
||||
and true exit, exact project/database, empty address state, confirmed backup/
|
||||
repair evidence and absence of restore/failure/unknown-prompt contradictions.
|
||||
Missing or wrong-typed fields fail closed. Independent process, address and
|
||||
database-handle probes remain additional requirements.
|
||||
|
||||
Native `REPAIRED` is retained as `native_status`; summaries count a repair only
|
||||
after the same request reopens, completes Verify and returns authoritative
|
||||
`PASS/GREEN` with confirmed release. A failed reopen becomes
|
||||
`REPAIR_VALIDATION_FAILED`; incomplete or contradictory native success/release
|
||||
becomes `UNCONFIRMED` and prevents reopening.
|
||||
Historical restoration remains `RESTORED_REVIEW_REQUIRED`. The original error,
|
||||
stage and evidence references, a `pre-repair-result.json` snapshot, native
|
||||
evidence and validation evidence remain attached even if the retry raises.
|
||||
|
||||
`tests/fixtures/issue2-lost-session-sanitized.json` contains selected fields from
|
||||
the actual issue attachment, with paths, machine and process identities
|
||||
sanitized. Replay asserts `PCB_STARTING`, the selected PRJ/database, normal PCB
|
||||
and launcher release before native Repair, and exactly one automatic repair and
|
||||
one reopen even if the opening error repeats. Separate replays cover the actual
|
||||
2026-10-28 missing-backup Output, delayed exits/addresses, unknown custom prompts,
|
||||
successful native repair and historical restoration. These are nonnative tests.
|
||||
|
||||
The attachment contains logs only. No matching `1GPHY_8211` faulty project was
|
||||
found in the sibling `Skyworth_CBB_Lib` collection. This host runs Windows 11;
|
||||
Windows 10 behavior and recovery of the real field database remain unverified.
|
||||
The coordinator's prepared `diagnostics/issue2-frozen-20261102` fixture damages a
|
||||
copied database header; it does not reproduce field lost-server-session loss.
|
||||
Candidate packaging and frozen/native tests remain coordinator work after review.
|
||||
|
||||
Task 1 checks: full suite once, 532 passed with the existing pywinauto COM warning;
|
||||
after the final initial-busy gate regression, the related final suite passed all
|
||||
234 tests. Compileall and `git diff --check` passed. The coordinator will run
|
||||
candidate/frozen validation against the final implementation.
|
||||
|
||||
Task 1 review fix round: 259 related tests passed (17.86s); compileall and
|
||||
`git diff --check` passed. These checks include busy retention, real readback
|
||||
failure branches, 30 malformed-success variants at both release and reopen/
|
||||
counting boundaries, and a complete actual worker-result replay control.
|
||||
|
||||
Runtime fix round 2 adds `iCDBProjectBackup.exe` and `ReuseBlockImporter.exe` to
|
||||
the process helper's fixed query whitelist. Without these entries, the real
|
||||
parent release probe rejected its own required queries and always denied safe
|
||||
release. New tests keep the release validator and process helper real and stub
|
||||
only WMI: no owners permits release, either native owner prevents it, and
|
||||
arbitrary query names remain rejected. Focused validation: 172 passed. Candidate
|
||||
`c823a4b` must be rebuilt with this correction before frozen/native validation;
|
||||
field recovery remains unverified.
|
||||
|
||||
Runtime fix round 3 uses the actual frozen-worker window capture. A single Afx
|
||||
shell titled exactly `iCDB Project Backup` now waits, before invocation only,
|
||||
for the exact project title within the existing deadline. Two owned-process
|
||||
input-indicator classes (`UAC_InputIndicatorOverlayWnd`, `UAC Input Indicator`)
|
||||
are ignored only with empty titles. Wrong/duplicate target windows, ambiguous
|
||||
shells, named/lookalike auxiliary windows, unknown prompts, missing Output and
|
||||
busy verdicts still retain the tool without unsafe commands. The native loading
|
||||
line `Checking if project is in use.` is excluded from busy evidence; the actual
|
||||
ownership verdict continues to control the busy gate.
|
||||
|
||||
Sanitized recorded-shape replay includes real shell children, RichEdit Output
|
||||
readback, startup-to-loaded transition and both input indicators before and
|
||||
after load. Focused validation: 189 passed (12.40s); compile and scoped diff
|
||||
checks passed. New source/frozen native validation and rebuilding the candidate
|
||||
remain coordinator work; these replay results do not establish field recovery.
|
||||
@@ -1,251 +0,0 @@
|
||||
# Scoped recovery manifests and complete verified backups
|
||||
|
||||
Status: implemented; review finding P1 addressed with focused validation. Started on b90a9bb; paused at
|
||||
the RED checkpoint for the coordinator's native startup-window repair fix and
|
||||
resumed on 877e3b4. No native UI/process/live-library actions were performed by
|
||||
this implementer. Original untracked review.diff was preserved and not staged.
|
||||
|
||||
## Result and scope
|
||||
|
||||
Complete backup trees are still copied and retained. SHA256 and semantic
|
||||
before/after comparisons now cover only primary design/project/database/
|
||||
constraint files and required central-library dependencies. Runtime changes
|
||||
after a successful snapshot do not stop install. Primary content changes,
|
||||
additions and deletions do stop install, with copies retained as evidence.
|
||||
|
||||
The validate-copy -> conflict checks -> retain original Work -> install ->
|
||||
reopen/native verification flow is preserved. Source equality now runs after
|
||||
incoming Work preparation, immediately before target equality, closing the old
|
||||
late-source-change window. Source idle/address ownership is rechecked there as
|
||||
well: excluding address bytes from semantic hashes does not bypass idle checks.
|
||||
|
||||
Initial implementation: 29c154d. The review correction is described below.
|
||||
Durable documentation lives here; an ignored review copy remains at
|
||||
.superpowers/sdd/2026-11-02-issue-2-management/task-3-report.md.
|
||||
|
||||
Scoped production files: backup_recovery.py and new scoped_manifest.py. Scoped
|
||||
tests: test_backup_recovery.py and new test_scoped_manifest.py. No Verify public
|
||||
types, Task 2 helpers/READY logic, native repair classifiers/process whitelist,
|
||||
or library binary contents were changed.
|
||||
|
||||
## Exact classification rules
|
||||
|
||||
Project scope retains every unclassified file as primary. This includes PRJ,
|
||||
PCB, DXP, icdb.dat, Layout databases, schematic/logic/symbol assets, CES/config,
|
||||
unknown binary/engineering formats, and text files outside explicit excluded
|
||||
categories. Rules are case-insensitive; manifests preserve relative path case.
|
||||
|
||||
Explicit semantic exclusions, still copied and metadata-validated:
|
||||
|
||||
- Runtime/history child directories **at a project workspace root**, its PCB
|
||||
workspace root, a selected Work/Cert root, or the library root: log, logs,
|
||||
temp, tmp, __pycache__, backup, backups, output, outputs, report, reports,
|
||||
gerber, gerbers, odb++, Log Files, LogFiles, and Work.before-restore-*.
|
||||
- ProjectBackup/backups only at those workspace roots. Other ProjectBackup
|
||||
content remains conservative primary data.
|
||||
- Known native runtime below database/cdbsvr and PCB/database/cdbsvr: log,
|
||||
dbcheck and dbrestore subtrees. In shared library databases, those same
|
||||
subtrees below SymbolLibs/<partition>/cdbsvr or <shared-root>/cdbsvr. Other
|
||||
unknown files below cdbsvr remain primary; the directory is not dropped.
|
||||
- File suffixes: .log, .tmp, .temp, .lck, .lock, .bak, .backup, .pdf.
|
||||
- File names: sAddress.adr and editor files starting with ~$.
|
||||
|
||||
Directory exclusions are contextual rather than arbitrary ancestor matching.
|
||||
ReusableBlocksLP/<selected-block>/Work and Cert are structural identity
|
||||
components, never runtime labels. CBB names Logs, Temp, Backup, Output, Report,
|
||||
Log Files, ProjectBackup and Work.before-restore-engineering remain valid and
|
||||
their primary files are hashed in both semantic manifests and complete-copy
|
||||
validation. Case variants have the same protection.
|
||||
|
||||
Shared dependency partitions and nested engineering folders keep their names:
|
||||
SymbolLibs/temp/icdb.dat, SymbolLibs/Temp_a/device.sym,
|
||||
SymbolLibs/Backup/device.sym, hdl/Logs/design.v and hdl/Backup/design.v are
|
||||
primary. Runtime directory labels apply at the known roots above, not inside
|
||||
arbitrary engineering/dependency hierarchies. File suffix/name exclusions are
|
||||
applied to files, not to engineering directories with matching suffixes.
|
||||
|
||||
The uploader-compatible .<stem>.cbb-upload.lock falls under .lock, so it is
|
||||
runtime and never primary. It is **not** silently removed from complete copies.
|
||||
|
||||
Central-library scope includes only target ReusableBlocksLP/<block>/Work and
|
||||
Cert, root configuration files (the selected .lmc, other root config files),
|
||||
and shared/configuration dependency directories outside ReusableBlocksLP. Known
|
||||
examples include SymbolLibs/__ReusableBlocksSymb, CellDB and PartDB; new unknown
|
||||
dependency directory names remain primary conservatively. Other root .lmc files,
|
||||
other ReusableBlocksLP CBBs, target historical/non-Work/non-Cert trees and the
|
||||
explicit runtime/generated categories above do not enter semantic equality.
|
||||
Those unrelated files still enter the complete copy and its metadata checks.
|
||||
|
||||
Later semantic scans prune ignored/runtime/unrelated CBB directories before
|
||||
entering them, so transient/unavailable runtime or unrelated trees cannot
|
||||
interfere with the post-snapshot content check.
|
||||
|
||||
## Reusable API contract for Task 4
|
||||
|
||||
Import from cbb_refresh_verify.scoped_manifest:
|
||||
|
||||
```python
|
||||
scope = ManifestScope.library(block_name, selected_lmc.name)
|
||||
before = copy_verified(library_root, private_backup, scope=scope, progress=callback)
|
||||
current = build_manifest(library_root, scope=scope, exclude=private_incoming)
|
||||
if current != before:
|
||||
# stop install; retain evidence
|
||||
...
|
||||
```
|
||||
|
||||
- `ManifestScope()` is project scope. `ManifestScope.library(block_name,
|
||||
library_name)` requires nonempty single-component names; no path traversal.
|
||||
- `build_manifest(root, *, scope=None, exclude=None, progress=None,
|
||||
hash_function=hash_file)` returns a semantic manifest. `exclude` is an optional
|
||||
private incoming subtree, **not** a copy exclusion. Hash injection is a test
|
||||
hook; normal callers use the default.
|
||||
- `copy_verified(source, destination, *, scope=None, progress=None,
|
||||
hash_function=hash_file)` requires a fresh destination outside source. Copies
|
||||
all files/directories, returns the same semantic schema, retains partial
|
||||
destination on failure, and raises ValueError/OSError for unsafe/changed data.
|
||||
- `scan_tree(root)` scans complete membership and refuses links/junctions and
|
||||
special files. Its optional scope/exclude is used by semantic scans only;
|
||||
complete copies always scan without filters.
|
||||
- `hash_file(path)` streams SHA256 in 1 MiB chunks. Files are processed with up
|
||||
to eight workers, retaining the existing concurrency bound.
|
||||
- Progress callback accepts **one dict**, not the old private `(count,total)`
|
||||
pair: `stage` (`copy` or `hash`), `hashed_files`, `hashed_bytes`, `total_files`,
|
||||
plus `copied_files` for copy. Hash counts/bytes count unique primary snapshot
|
||||
files/logical bytes, not aggregate disk IO. `total_files` counts all files for
|
||||
copies and primary files for standalone manifest generation. Initial zero and
|
||||
each 256/final-file event are emitted. Recovery keeps existing public progress
|
||||
stage/message keys and adds `manifest_stage` and these counters.
|
||||
|
||||
Version 1 JSON-compatible output (relative paths are POSIX, no machine-specific
|
||||
absolute paths or mtimes in equality):
|
||||
|
||||
```json
|
||||
{
|
||||
"version": 1,
|
||||
"scope": {"kind": "library", "block_name": "A", "library_name": "target.lmc"},
|
||||
"files": {
|
||||
"ReusableBlocksLP/A/Work/A.prj": {
|
||||
"size": 123, "sha256": "<sha256>", "scope": "target_work"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Entry scope labels are project, target_work, target_cert, library_config and
|
||||
shared_dependency. Default project's descriptor uses empty block/library names.
|
||||
Recovery persists both library-before-manifest.json and
|
||||
source-before-manifest.json. The shape changed only for private backup helpers;
|
||||
VerifyRequest/VerifyResult contracts are unchanged. There is no old-manifest
|
||||
loader or destructive migration: existing historical evidence remains intact.
|
||||
|
||||
## Copy integrity and old strict equality compatibility
|
||||
|
||||
Copy validation remains strict for the **entire** snapshot: before/after source
|
||||
file/directory membership, file type, size and nanosecond mtime must agree;
|
||||
destination membership/type/size/mtime must match too. Primary regular source
|
||||
files are SHA256 read before copy and again for validation; destination hashes
|
||||
must match. All native icdb.dat and .lmc files retain exclusive read handles
|
||||
during copying. For scoped primary native files, the expected digest is built
|
||||
from the source ReadFile stream independently of destination SHA256. Identical
|
||||
size/mtime destination corruption is therefore rejected, including locked DBs.
|
||||
Unrelated native DBs are still locked/copied; their bytes are not SHA256 hashed.
|
||||
|
||||
The old final `_manifest(source) == complete_copy_record` was an all-file hash
|
||||
comparison that rehashed every runtime and unrelated project file. It is
|
||||
replaced by full-tree copy metadata validation and primary byte verification at
|
||||
snapshot time. Later equality compares version/scope and primary relative
|
||||
path/size/hash/scope only. Thus log-only additions/changes/deletions after a
|
||||
successful copy are accepted, while primary keyset/content changes remain real
|
||||
conflicts. No conflict tests were weakened or deleted; additional source,
|
||||
target, Cert, shared dependency, late-source and active-address regressions were
|
||||
added. Empty directory metadata is intentionally not part of semantic equality.
|
||||
|
||||
## RED/GREEN and verification evidence
|
||||
|
||||
The original full-suite evidence below belongs to initial commit 29c154d. The
|
||||
P1 review correction has fresh focused validation, and has **not** rerun the
|
||||
full suite; the coordinator requested focused tests only for this fix.
|
||||
|
||||
1. Initial RED, before production edits:
|
||||
`python -m pytest tests/test_scoped_manifest.py tests/test_backup_recovery.py -q`
|
||||
-> **29 failed, 26 passed in 7.89s**. Failures demonstrated missing versioned
|
||||
manifest/schema/progress and post-snapshot runtime/unrelated tolerance.
|
||||
Copy/conflict protections already present continued passing.
|
||||
2. Initial GREEN -> **55 passed in 11.93s**.
|
||||
3. Additional RED for semantic traversal of an unavailable ignored/unrelated
|
||||
tree -> **1 failed, 36 passed in 2.79s**; fixed by pruning semantic scans.
|
||||
4. Additional RED for source mutation during incoming Work preparation and
|
||||
source address reappearance -> **2 failed, 20 deselected in 1.56s**; both had
|
||||
incorrectly installed before the final-source-check changes.
|
||||
5. Final focused:
|
||||
`python -m pytest tests/test_scoped_manifest.py tests/test_backup_recovery.py tests/test_backup_recovery_dialog.py -q`
|
||||
-> **64 passed in 9.93s**.
|
||||
6. Coordinator was notified **before** the full suite and explicitly confirmed
|
||||
no native owner/mutex and paused all native probes. Exactly one final suite:
|
||||
`python -m pytest -q` -> **693 passed, 1 warning in 47.99s**. Warning:
|
||||
pywinauto's existing "Revert to STA COM threading mode" warning in
|
||||
test_library_reader.py::test_status_log_records_unseen_id_inference.
|
||||
7. `git diff --check` passed. Review confirmed no unrelated/native-helper edits.
|
||||
|
||||
Coverage includes every primary category, unknown engineering formats,
|
||||
runtime/history/generated exclusions with complete-copy retention, hash-path
|
||||
scope, relocatability, source changed/deleted/added during copy/validation,
|
||||
target changes/deletions/additions, Cert/shared-library conflicts, unrelated
|
||||
CBB tolerance, copied corruption with preserved metadata, locked stream bytes,
|
||||
source content changes with preserved metadata, complete copy membership and
|
||||
nonprimary size consistency, idle/address rechecks, retained copies on failure,
|
||||
and unchanged native reopen/retained-Work recovery behavior.
|
||||
|
||||
## Review correction: contextual runtime directory classification
|
||||
|
||||
Review found that the initial unconditional directory ancestor rules could
|
||||
classify valid selected CBB names (Logs/Temp/Backup) or real SymbolLibs/temp
|
||||
engineering partitions as runtime. That removed primary paths from both the
|
||||
baseline manifest and later conflict comparison, and from copy byte checks.
|
||||
|
||||
The classifier now resolves the structural role first and only applies the
|
||||
runtime directory rules at documented workspace/native DB locations. Semantic
|
||||
directory traversal and complete-copy byte classification share that rule.
|
||||
Complete tree copy/metadata validation remains unchanged. This also protects
|
||||
nested engineering folders with names Logs/Backup, and avoids broad dropping
|
||||
of unknown cdbsvr files.
|
||||
|
||||
Independent regressions cover Work and Cert under 11 colliding CBB names/case
|
||||
variants, real SymbolLibs/temp and Temp_a partitions, arbitrary nested
|
||||
engineering folders, source and destination corruption with unchanged size/
|
||||
mtime, independent locked database destination corruption, and end-to-end
|
||||
recovery conflicts that previously overwrote concurrent target/shared edits.
|
||||
Known native Log Files, ProjectBackup/backups and DB server log/dbcheck/
|
||||
dbrestore data remain semantically ignored and completely copied.
|
||||
|
||||
Review-fix RED:
|
||||
`python -m pytest tests/test_scoped_manifest.py tests/test_backup_recovery.py -q --tb=short`
|
||||
-> **47 failed, 74 passed in 18.41s**, before production changes. The failures
|
||||
included silently accepted primary corruption and installs over concurrent
|
||||
target/shared edits. Additional conservative-boundary regressions prevented
|
||||
reintroducing the same bug through Log Files/ProjectBackup/retained-Work names
|
||||
or broad cdbsvr directory exclusion.
|
||||
|
||||
Final review-fix focused GREEN:
|
||||
`python -m pytest tests/test_scoped_manifest.py tests/test_backup_recovery.py tests/test_backup_recovery_dialog.py -q --tb=short`
|
||||
-> **141 passed in 18.28s**. No native UI/process actions, live-library mutation,
|
||||
or full-suite run was performed during this fix round.
|
||||
|
||||
## Limitations / follow-up boundary
|
||||
|
||||
- No real field lost-session reproduction, native GUI success reproduction, or
|
||||
Windows 10 run was performed for this task; file-based tests do not substitute
|
||||
for those required native/field validations.
|
||||
- Task 4 must adapt complete-copy access to a live uploader lock **only when the
|
||||
operation actually owns that coordination lock**. The current helper copies
|
||||
readable locks and fails closed on unreadable/live exclusively owned files;
|
||||
it does not delete locks or broadly drop engineering data.
|
||||
- Native idle guards and later coordination locks remain necessary. Final
|
||||
equality and filesystem rename are not one cross-process atomic transaction
|
||||
against arbitrary noncooperating external writers.
|
||||
- Nonprimary byte hashes are intentionally absent. Their copy integrity uses
|
||||
complete membership and size/mtime checks, as specified; same-size,
|
||||
timestamp-preserving nonprimary corruption is outside the semantic guarantee.
|
||||
- All snapshots must be stable while copied, including runtime files. This
|
||||
deliberately differs from post-snapshot semantic checks, which tolerate
|
||||
runtime changes. Original and partial recovery evidence is retained on failure.
|
||||
@@ -1,122 +0,0 @@
|
||||
# 既存地址记录下的明确 ICDB 维护入口
|
||||
|
||||
2026-11-03 的现场报告显示,点击“非 READY ICDB 检查与修复”后,IP101GR 在
|
||||
0.172 秒内返回 BLOCKED,没有启动官方 Repair。原先维护按钮和普通校验使用
|
||||
相同请求;普通校验对任何 sAddress.adr 的阻止条件也挡住了明确维护入口。
|
||||
随后保留的库协调检查点使重新读取与维护都无法继续。
|
||||
|
||||
本次为用户明确确认的维护增加独立入口。普通校验遇到地址记录仍停止,不依据
|
||||
文件日期、TCP 不通或本机无 PCB 进程判断地址失效,不删除、移动或隔离地址。
|
||||
没有地址阻止时,维护继续沿用原有校验及本轮失联后的自动修复流程。
|
||||
|
||||
存在地址记录时,明确维护需要唯一可确认的工程 PRJ/database 映射。共享符号库
|
||||
地址、所选工程内多个地址、外部引用、歧义目标、不完整工程均会阻止执行。
|
||||
其他独立 CBB 的 Work 数据库地址不纳入当前修复目标,原文件保持不变。工具检查相关
|
||||
原生程序和保留工作进程,并同时独占读取库中的原生数据库文件;记录目标工程
|
||||
引用指纹和地址字节哈希,检查期间及完整备份后重新核对。完整工程备份保留
|
||||
原地址文件,再由官方 iCDB Project Backup 打开工程。只有其实际 Output 明确
|
||||
报告 `Project is not in use. Full iCDB Project Backup's functionality is available.`,
|
||||
且没有占用或未知窗口时才请求 Repair。
|
||||
|
||||
库旁已有协调检查点时,明确维护可以接续有效的同库记录,条件是原监督进程
|
||||
已退出,或当前进程确实持有已闲置的保留锁。相关所有者和目标独占访问检查
|
||||
必须先全部通过,再原样归档旧检查点并建立本次检查点;库 sidecar 和全局 mutex
|
||||
期间始终持有。未知、损坏、其他库的记录或仍存活的外部监督进程不会被接管。
|
||||
普通释放检查的地址要求没有放宽,上传锁文件不删除。
|
||||
|
||||
重启后有有效同库检查点时,界面仅按工程目录显示 UNKNOWN 状态,明确标注
|
||||
“状态未确认,不代表损坏”。此视图不调用原生状态读取,只允许明确维护或严格
|
||||
释放检查;普通校验、上传/更新/移除及备份恢复均禁用。安全完成维护后再重新
|
||||
读取权威状态,保留当前搜索条件。
|
||||
|
||||
Repair、原生退出、地址消失和最终校验仍是不同的判据。只有完整原生修复证据、
|
||||
所有者与地址释放及同一工程后验 PASS/GREEN 全部成立才计为修复通过。缺健康
|
||||
备份、恢复旧版本、占用、超时或不完整证据不会提升为成功,也不会盲目重试。
|
||||
|
||||
协调端在保留旧地址字节的用户工程副本上观察到:官方工具报告数据库曾在服务器
|
||||
运行时被复制、工程当前未使用,随后官方 Repair 自行清除副本地址并返回成功。
|
||||
这证明了明确维护入口的必要性;原始用户库没有由本次开发或测试修改。实际按钮、
|
||||
冻结包及最终全套回归的实际验收结果见下。
|
||||
|
||||
## 修复后的本地读写访问提示
|
||||
|
||||
实际副本验证发现,原理图 iCDB Repair 成功并清除地址后,PCB 仍可能显示上次
|
||||
异常退出后的读写访问确认。这与选择恢复旧数据库不同。明确维护确认现在说明:
|
||||
仅在本地固定磁盘、严格确认修复后,工具可对本次启动的这一完整提示确认一次。
|
||||
|
||||
该授权不能由普通 Verify 或通用对话框规则开启。维护代码先验证完整原生修复
|
||||
证据,生成绑定原库、PRJ、PCB 的内部凭据。实际 PCB 启动前,重新确认地址缺失、
|
||||
无其他原生所有者,并同时独占读取 LMC、相关 icdb.dat 和选中 LayoutDB.lyt,
|
||||
在本次私有桌面生成短时有效的启动证据。出现提示时再核对当前 PCB 与启动器的
|
||||
实际 PID、父子关系、安装路径和完整设计参数,以及其他所有者缺失。
|
||||
|
||||
只接受原始完整英文提示正文(仅忽略空白差异)、精确窗口类型/标题和唯一可用
|
||||
Yes6/No7 按钮。专用代理在自己的私有桌面再次读取实际窗口和控件;先消耗授权,
|
||||
再发送一次按钮消息。没有证据、提示变更、重复提示、额外弹窗或身份不符均停止,
|
||||
不使用鼠标、前台输入或通用 Yes 回退。后续文档身份、保存关闭和 READY 判据不变。
|
||||
|
||||
路径必须经 GetDriveType 确认为 LOCAL_FIXED,且没有重解析点祖先。UNC、网络
|
||||
映射盘、可移动盘和链接路径不自动确认。该检查不宣称具备跨主机分布式排他能力;
|
||||
数据库只读句柄在交给官方 PCB 启动前释放,任意非协作外部写入者之间仍不存在
|
||||
跨进程原子事务保证。普通校验及其他数据库恢复选择继续保持硬性阻断。
|
||||
|
||||
## PCB 恢复版本待用户决定
|
||||
|
||||
后续实际副本已完成 iCDB Repair 和一次本地读写确认,但 PCB 又要求在“最后
|
||||
用户保存数据库”和“自动保存数据库”之间选择恢复版本。本次两项显示的日期
|
||||
均为 `2026/9/24 23:06`;同日期不代表内容相同,工具没有自动选择任何版本。
|
||||
|
||||
这类结果单独标识为 `PCB_VERSION_CHOICE_REQUIRED`,展示候选日期,并在
|
||||
`pcb-version-choice.json` 保存完整窗口和候选状态。维护摘要显示“ICDB 已修复 /
|
||||
PCB 版本待选”,原生状态仍为 REPAIRED,但整项保持未完成、需人工决定,不能
|
||||
计为 PASS/GREEN。工具也不会因为显示了某个默认选中项就认可该版本。
|
||||
|
||||
## 最终验证(2026-11-03)
|
||||
|
||||
程序源码提交 `d76475a`:全量 `python -m pytest -q` **969 passed,1 条已有
|
||||
pywinauto STA 模式警告,107.69 秒**;编译、diff 检查和代码复审通过。
|
||||
由不可变 `git archive d76475a` 构建的 EXE 通过 GUI 冒烟。
|
||||
|
||||
在第二份完整隔离库上,通过打包 EXE 的实际“非 READY ICDB 检查与修复”按钮
|
||||
确认并运行 IP101GR:有效旧阻止记录接续、旧地址完整备份、官方 Repair 成功并
|
||||
正常释放、一次受约束的读写确认均实际执行。之后准确停在原生 PCB 版本选择,
|
||||
显示 `version_choice_required=1`、`repair_unconfirmed=0`、`repaired=0`。
|
||||
这是维护入口和结果分类通过验收,不代表未经用户选版本就达到 READY。
|
||||
|
||||
原始证据:
|
||||
|
||||
- 用户最初 0.172 秒失败:`diagnostics/issue2-user-maintenance-20261103/user-reports/`。
|
||||
- 冻结 EXE 实际按钮:`diagnostics/issue2-user-maintenance-20261103/actual-button-frozen-d76475a/outcome.json`。
|
||||
- 原生版本选项:上述目录的 `data/evidence/verify-8fa461b6d6fe/pcb-version-choice.json`。
|
||||
- 全量测试:`build/issue2-maintenance-final-tests-d76475a.log`。
|
||||
|
||||
### 用户明确选择最后手动保存版本后的副本验证
|
||||
|
||||
用户选择“用最后手动保存版本继续验证”,授权范围仅为隔离副本。诊断续跑使用
|
||||
真实校验器、原生工作进程、对话框代理及权威状态读取;只为这次用户决定提供
|
||||
版本动作:先点击 6213,重新观察其已选中且 6206 未选中,再确认 OK 1。
|
||||
选择前保留完整工程副本;没有改变程序的默认版本选择规则。
|
||||
|
||||
工程成功打开并核对身份,但在原长路径下两次 Project Integration 均产生本轮
|
||||
JobPrefsDB.jpf / local Cell Library 加载错误。原文件、临时目录及备份中的 JPF/CEL
|
||||
可读且哈希一致,日志前缀与时间证明是本轮错误,不能断言二进制数据已损坏。
|
||||
|
||||
随后保持同一工程数据,通过临时本地 `T:` 短路径进行对照,完成原生 Integration、
|
||||
保存关闭、进程释放及权威状态查询,结果为 **PASS / GREEN / READY
|
||||
(IsVerifiedReuseBlock, raw=1),safe_to_continue=true**。所有原生进程退出后已移除
|
||||
该临时盘符。此结果说明短路径试验可通过,尚不能证明确切路径长度限制或永久
|
||||
解决原长路径下的 JobPrefs/Cell Library 兼容问题;产品没有自动增加短路径映射。
|
||||
|
||||
这是**用户指定历史版本后的恢复与验证**,不是无人值守或无损自动修复验收。
|
||||
验证后的完整库副本保留在 `diagnostics/issue2-user-maintenance-20261103/frozen-library/`,
|
||||
原用户库没有被替换。结果和选择证据分别位于:
|
||||
|
||||
- `user-authorized-last-saved-r2/user-selection-events.jsonl`(实际 6213 → 复读 → OK 1)。
|
||||
- `user-authorized-last-saved-short-path/result.json`(最终 PASS/GREEN)。
|
||||
- `short-path-trial.json`(临时盘符及正常退出后清理记录)。
|
||||
- `source-unchanged-after-user-choice.json`(全部试验后原库 21,013 个主要文件清单仍一致,原地址字节哈希未变)。
|
||||
|
||||
以上相对路径均位于 `diagnostics/issue2-user-maintenance-20261103/`。
|
||||
现场原工单其他工程、网络共享读写确认和 Windows 10 仍不能由此验收代替。
|
||||
|
||||
交付候选包为 `dist/issue2-maintenance-20261103-d76475a.zip`。不合并发布、不自动关闭工单。
|
||||
@@ -1,46 +0,0 @@
|
||||
# 工单 #2:用户实测失败后的修订记录
|
||||
|
||||
分支 `codex/temp-issue-2-icdb-recovery`。本轮修订不能视为现场验收通过;未合并、发布或关闭工单。
|
||||
|
||||
## 用户失败的实际原因
|
||||
|
||||
用户运行 `b26e2f2` 冻结包。真实日志位于程序旁的 `data` 目录。中心库存在有效的未释放会话检查点,应用进入文件系统恢复视图,因此管理按钮被禁用;旧界面没有清楚显示原因,禁用外观也像可用按钮。该次没有启动增删改操作。
|
||||
|
||||
ICDB 批次的首项 `1GPHY_8212` 在预检查报 `MAINTENANCE_TARGET_UNCONFIRMED`,原生 Repair 没有执行。旧检查硬性要求 `PCB/pcb.prj`,但该工程的 PCB 明确反向引用主 `1GPHY_8212.prj`。主 PRJ 指向 `database`;存在的 `PCB/template.prj` 不能当作活动工程猜测使用。后续八项被跳过。
|
||||
|
||||
## 修订
|
||||
|
||||
- 只有 PCB 唯一、精确反向引用主 PRJ 时,允许缺少辅助 `pcb.prj`。预检查、Repair 后重新打开、管理来源身份及库引用核对使用一致规则。`template.prj` 保持原样并参与资产哈希。
|
||||
- 显示库会话阻止横幅、管理禁用原因、灰色禁用按钮及首项具体失败阶段。
|
||||
- 集成校验跳过原生明确禁止调用、且已同步的动作;仍要求四项最终全部同步。必需动作被禁止或原生拒绝时继续判失败,不伪造通过。
|
||||
- 识别原生 EDIF 中数字开头的精确标识符,例如 `&1GPHY_8212`;不放松设计内容比较。
|
||||
- 私有桌面上的原生库编辑器若提示其他已确认缺少 PCB 的条目,只确认准确匹配的已知通知。当前目标、未知弹窗或身份不符的窗口不自动确认。
|
||||
- 原生新增共享明确截止时间;父进程超时发出取消信号。阻塞调用返回后,以及所有日志和证据 I/O 完成、提交 OK 之前,重新检查监督进程、取消状态及期限,防止超时后迟到写入。
|
||||
|
||||
## 隔离原生证据及限制
|
||||
|
||||
证据根目录为 `diagnostics/issue2-user-feedback-20261103/`。
|
||||
|
||||
完整现场库副本保留原生地址和所有工程文件,共 38,954 个文件。原用户库始终不参与写入,完整恢复新增结束后 `source-final-recheck.json` 再次确认 25,214 个主要文件与试验前完全一致。
|
||||
|
||||
`d36b6bc` 冻结程序的实际维护按钮已在该副本完成完整备份、官方 Repair、数据库地址释放及同一 PCB 重新打开。随后原生要求选择历史 PCB 数据,应用返回 `PCB_VERSION_CHOICE_REQUIRED`,没有显示修复完成。
|
||||
|
||||
用户选择最后手动保存版本(2026/9/24 15:15)后,在确切所属的隔离会话中继续。SynchCES 和 LoadCES 成功,但原生 BackAnnotate 仍报已验证工程不允许执行。未保存、未达到 READY,失败 PCB 已正常关闭。这段人工续接不算无人值守自动修复通过。
|
||||
|
||||
空隔离库中的重新导入及工程身份核对通过,但自动校验因目标缺少 PartsDB 分区失败,不能算完整校验通过。完整依赖库中的首次同名替换完成原生移除后,新增被其他条目缺少 PCB 的提示阻塞而超时;该部分失败的检查点及完整旧库备份保留在 `diagnostics/full-update-events/`,没有自动重放。
|
||||
|
||||
完整隔离库中 IP101GR 的旧数据库地址通过官方 Repair 释放,证据为 `dependency-ip101gr-native-only/result.json`。这只是依赖数据库的原生修复诊断,没有重新打开或 READY 验收。
|
||||
|
||||
修订后对缺失的 `1GPHY_8212` 显式执行恢复新增,启用自动校验;独立证据目录为 `diagnostics/full-recovery-events/`。结果为 `UPLOADED_VERIFIED`,`safe_to_continue=true`。已知的其他缺 PCB 条目提示被自动准确确认;新增后独立重读库、三种原生逻辑导出及主要资产比较通过。随后自动执行 ForwardAnnotate、SynchCES、LoadCES、BackAnnotate,四项最终均同步,保存、关闭和进程退出确认完成,权威 `IsVerifiedReuseBlock` 返回 `raw=1 / READY`。自动校验链路耗时 126.422 秒(不含完整备份和新增身份检查)。
|
||||
|
||||
最终结果为 `full-recovery-add-result.json`,完整检查点为 `diagnostics/full-recovery-events/management-03a9dbc537f84e0faaea2ad5a2a732c2/checkpoint.json`。此结果证明修订后**重新导入加校验**的恢复路径有效,不能替代直接 ICDB Repair 后仍被原生 BackAnnotate 拒绝的失败结论,也不把用户选择历史数据后的工程称为无损修复。
|
||||
|
||||
## 尚未满足的门槛
|
||||
|
||||
服务器会话失联经实际按钮触发、自动 Repair、重新打开、保存关闭及权威 READY 的完整链路仍需通过。历史数据选择及重新导入均可能改变恢复版本,不能宣称无损恢复。Windows 10 尚未验证;当前实机为 Windows 11 / Mentor EE7.9.5。
|
||||
|
||||
## 自动化验证
|
||||
|
||||
修订代码全量 `python -X utf8 -m pytest -q`:**1095 passed,171.09 秒**。保留一条已有 pywinauto STA COM 线程模式警告。`compileall`、`git diff --check` 通过。取消发生在日志证据 I/O 中的回归先复现错误提交,再验证修复;相关集中测试 108 项通过。独立审查已复核全部代码修订,最后一项取消时序 P2 已解决,没有剩余实质问题。
|
||||
|
||||
候选包按提交归档构建。最终冻结按钮冒烟结果及构建、压缩包校验记录分别保存在证据目录的 `final-frozen-buttons/result.json`、`build-result.json`、`package-result.json`;按钮冒烟只证明界面响应,不等于现场 ICDB 自动修复验收。
|
||||
@@ -1,46 +0,0 @@
|
||||
# 无地址 ICDB 维护及 PCB 版本选择
|
||||
|
||||
沿用 `codex/temp-issue-2-icdb-recovery` 临时分支。依据实际错误日志与公开资料修正入口,用户明确授权在需要时弹窗选择版本。应用自动备份仍取消,操作前保留手动备份提醒;未修改原用户库。
|
||||
|
||||
## 本次行为
|
||||
|
||||
- 明确发起 ICDB 维护时,不再因为没有 `sAddress.adr` 或协调检查点而跳过原生检查。
|
||||
- 无地址时,所选 PCB 必须唯一反向引用主 PRJ,工程内数据库映射必须唯一。多数据库、共享地址、路径身份不符、原生进程/脚本占用及无法独占读取仍停止。
|
||||
- 原生 Repair 成功并确认释放后,沿同一任务重新打开。若原生要求选择历史 PCB 版本,主应用显示实际候选时间和“最后手动保存 / 自动保存 / 取消”。不默认选择任一历史版本。
|
||||
- 用户选择后,私有桌面代理重新核对窗口、进程、候选时间及单选状态,再确认恢复。选择过期、窗口变化或执行失败不重试确认。等待期间应用保持响应;取消停止当前项并保留原生现场。
|
||||
- 最终仍要求集成校验、保存关闭、进程退出及权威 READY。使用了历史 PCB 版本时,即便校验通过,也记录 `RESTORED_REVIEW_REQUIRED`(已恢复,版本待核对),不标记为无损 Repair。
|
||||
- 未提供交互入口的调用保留待选择结果,不自动选版本;普通 Verify 不获得修复后授权。
|
||||
|
||||
## 过程证据
|
||||
|
||||
无地址隔离工程 IP101GR 经实际应用维护按钮完成原生 Repair,地址为空且进程退出。之后严格的修复后授权通过读写确认,继续到 PCB 历史版本选择。证据为 `diagnostics/noaddr-ui/evidence/maintenance-c05e9c4b06b2/result.json`。
|
||||
|
||||
用户此前已选择最后手动保存版本(2026/9/24 23:06)。首次诊断续接沿用该选择,完成校验、保存关闭,`IsVerifiedReuseBlock` 返回 READY/raw=1;记录在 `diagnostics/icdb-addressless-20261103/authorized-last-manual/result.json`。该次还通过诊断操作确认了保存弹窗,不能记为完整自动链路通过,因此继续实现上述应用内选择流程。
|
||||
|
||||
后续应用内选择试验两次在原生修复前被其他脚本占用阻止。进一步日志显示来自另一工具的并行 `run_bridge.vbs` 测试;没有强制结束或忽略该进程。失败记录保留在 `source-choice-button/`、`source-choice-button-retry/`。
|
||||
|
||||
## 验证边界
|
||||
|
||||
集中回归覆盖无地址选目标、地址变化、共享/多个数据库、修复后授权、选择/取消、版本日期改变、重复确认、原生动作失败、错 PID/桌面、真实单选状态复读和历史恢复归类。独立代码审查无剩余实质问题。
|
||||
|
||||
最终全量测试、冻结构建及实际按钮结果统一记录在 `diagnostics/icdb-addressless-20261103/`。本文件不将历史版本恢复视为无损修复,也不将模拟测试或人工续接替代最终冻结链路结果。
|
||||
|
||||
## 最终冻结包结果
|
||||
|
||||
程序源码提交 `de952a6`。全量 **1135 passed,228.63 秒**,一条已有 pywinauto STA COM 线程模式警告;编译、diff 检查及独立审查通过。候选程序从该提交的不可变归档构建。
|
||||
|
||||
最终试验使用原有完整隔离副本。先由官方 Repair 做独立准备,释放旧地址且不打开 PCB;这只用于构造此前真实遇到的无地址状态,不作为验收。启动最终冻结程序前确认:**地址为空、协调阻止检查点不存在**。
|
||||
|
||||
随后通过应用真实维护按钮执行,没有替换原生适配器或直接调用分阶段校验:
|
||||
|
||||
1. 原生检查确认未占用,执行 Repair,记录本轮原生日志并确认退出/释放。
|
||||
2. 同一工程重新打开,应用弹窗显示手动保存和自动保存日期均为 `2026/9/24 23:06`。
|
||||
3. 在应用弹窗选择用户此前已批准的最后手动保存版本。私有桌面代理完成单选复读及原生确认。
|
||||
4. 原有监督器自动处理保存 Reusable Block cell 提示,完成校验、保存、关闭及进程退出,无诊断脚本手动点击原生窗口。
|
||||
5. 权威 `IsVerifiedReuseBlock` 返回 `READY / raw=1`。最终 `PASS / GREEN / safe_to_continue=true`,恢复结果为 `RESTORED_REVIEW_REQUIRED`。
|
||||
|
||||
证据:`frozen-choice-button-retry/result.json`、`version-choice.png`,以及
|
||||
`diagnostics/choice-frozen-ui-retry/evidence/verify-7b0cd3fb8608/result.json`。
|
||||
之前被其他任务脚本阻止的各次试验均保留,没有计入成功。用户授权关闭并行测试时,该测试已经自行退出,因此没有终止 Mentor 进程或外来测试进程。
|
||||
|
||||
该结果证明本机 Windows 11 / EE7.9.5 上 IP101GR 的无地址维护、应用内用户选择和后续完整链路可执行;恢复采用历史手动保存版本,不证明无损保留了该版本之后的修改。未据此合并发布或关闭工单。
|
||||
@@ -1,53 +0,0 @@
|
||||
# 自动备份检查与调整
|
||||
|
||||
按用户 2026-11-03 最新要求:取消应用操作前自动备份,改为弹窗提示手动备份。本要求覆盖早期计划中的“必须完整备份后执行”。仍在 `codex/temp-issue-2-icdb-recovery` 临时分支,未合并或发布。
|
||||
|
||||
## 检查结果与调整范围
|
||||
|
||||
| 操作 | 检查到的旧行为 | 当前调整 |
|
||||
| --- | --- | --- |
|
||||
| 新增 CBB | 每项复制整个中心库,即使没有旧同名工程 | 取消,记录只读内容基线 |
|
||||
| 同名替换 | 每项复制整个中心库,再移除并导入 | 取消,保留逐项阶段及失败记录;失败时使用手动备份恢复 |
|
||||
| 移除 | 每项复制整个中心库 | 取消,原生移除后重新读库确认缺失 |
|
||||
| 普通校验 | 本地工程辅助备份,网络路径跳过 | 统一取消,记录 `manual_backup_policy` |
|
||||
| ICDB 修复 | 应用复制完整工程,原生工具另外备份 | 取消应用复制,保留独占访问、原生自身备份及成功证据要求 |
|
||||
| 从备份恢复 | 整库回退备份,再从中复制验证库;额外保留来源副本 | 去掉回退备份和重复来源副本,直接生成一份隔离验证库 |
|
||||
| 读取、搜索、筛选 | 无自动备份 | 保持只读 |
|
||||
|
||||
## 仍需生成的数据
|
||||
|
||||
- 新增/替换的来源暂存及原生内容导出副本:防止原生工具直接改写用户提供的源工程。
|
||||
- 恢复的隔离验证库:用于在安装前完成实际校验,会占用磁盘并花费复制时间,不能等同于未经修改的整库备份。
|
||||
- 恢复安装时保留旧 Work:仅同卷目录改名,不复制数据,用于安装失败时还原目录交换。
|
||||
- 工程库引用修正前的单个 PRJ 原文、日志、清单及检查点:属于轻量变更证据,不是工程或中心库备份。
|
||||
- Mentor 原生 Repair 自身生成的备份:属于原生修复流程,应用没有绕过。
|
||||
|
||||
独立研究探针中显式创建的实验备份及现存历史备份未删除。桌面生产路径不再触发上述旧的自动工程/整库备份辅助函数。
|
||||
|
||||
## 用户交互和约束
|
||||
|
||||
管理操作沿用原确认窗口,增加“应用不会自动备份,请先手动备份中心库及相关工程”。普通校验、维护、恢复同样在启动前提示;每批一次,取消不启动后台任务。应用不检查也不声称用户已经创建了手动备份。
|
||||
|
||||
取消备份不会取消串行任务、库锁、数据库独占检查、目标变更检查、来源身份核对、重新读库验证或未完成任务检查点。替换仍是移除后重新导入,非原子操作;部分失败必须使用手动备份及检查点恢复,不自动重放。
|
||||
|
||||
直接 ICDB Repair 的现场完整验收缺口仍保留,本次备份策略调整不代表该故障已解决。
|
||||
|
||||
## 隔离原生验证
|
||||
|
||||
在既有独立实验库 `diagnostics/reimport-8212/native-add/fixture/mentor_lib.lmc` 通过正式管理引擎实测:
|
||||
|
||||
- 原生移除 `1GPHY_8212` 后复读确认缺失,结果 `REMOVED`,安全释放,耗时 39.391 秒。
|
||||
- 随后原生重新导入同一独立来源,复读名称/分区、原生逻辑导出及主要资产身份确认通过,结果 `UPLOADED`,安全释放,耗时 101.359 秒。
|
||||
- 两项操作均没有生成 `library-before` 整库备份,来源主要文件清单未变。测试未启用自动校验,不将上传成功解释为 READY。
|
||||
|
||||
证据:`diagnostics/manual-backup-20261103/native-cycle-result.json`、`native-cycle-accepted.json` 和 `diagnostics/mb-events/`。上述耗时包含原生启动、复读和内容检查,不能当作与旧版同环境对照的提速比例。
|
||||
|
||||
开始实测前发现上一版应用在完整隔离库 IP101GR 上保留了“继续以读写方式打开”提示。仅向已核对进程命令和私有桌面的该提示发送“否”,两个 PCB 进程正常退出;没有强杀、保存或删除原生地址。原失败证据与取消记录保留在 `previous-test-cancel.json`。随后通过正式释放检查解除小实验库旧阻止记录,未绕过库锁。
|
||||
|
||||
## 代码验证
|
||||
|
||||
最终全量 Python 回归:**1111 passed,192.49 秒**,一条已有 pywinauto STA COM 线程模式警告。集中回归 297 项通过;占用检查修订后相关 151 项通过。编译及 diff 检查通过,独立复审无剩余实质问题。
|
||||
|
||||
审查发现取消整库复制时一并丢失了全库数据库独占检查,已改为不复制数据的 `build_exclusive_library_manifest`:记录基线和写入前检查均同时持有所有 `.lmc` / `icdb.dat` 的独占读取句柄。回归覆盖主库、共享库、其他 CBB 数据库仍被共享读取句柄占用的情况,确认未进入原生写入。
|
||||
|
||||
候选包从提交归档构建。最终冻结程序手动备份提示及取消测试记录位于 `diagnostics/manual-backup-20261103/frozen-prompts/result.json`,构建和交付信息保存在同一证据目录。
|
||||
@@ -1,77 +0,0 @@
|
||||
# 原生 CBB 增删改查接入与候选包验证
|
||||
|
||||
程序源码提交:`b26e2f2f6232c22a94ee1269bd4449fe0fe06623`。
|
||||
分支:`codex/temp-issue-2-icdb-recovery`。本地候选包,未合并、未发布、未关闭工单。
|
||||
|
||||
## 已接入的操作
|
||||
|
||||
| 操作 | 原生入口与验收条件 |
|
||||
| --- | --- |
|
||||
| 读取 | `LibraryManager.Application.OpenLibrary`、`Partitions(7)`;核对库身份、分区和条目,正常关闭会话。 |
|
||||
| 新增 CBB | `OnReusableBlocksEditor` → Logical-Physical → New;私有桌面 UIA 和有时限的控件消息提交完整 PRJ,确认成功提示后关闭重开库,再核对工程内容。重名拒绝覆盖。 |
|
||||
| 用工程替换已选 CBB | 完整工程及中心库备份 → 原生移除 → 原生重新导入 → 重新读库和内容核对。失败保留恢复证据并停止后续写操作。 |
|
||||
| 移除已选 | 安装脚本确认的 `CleanWGLib.exe <lmc> F4 <list>`,输入为 `REUSE_BLOCK`;先完整备份,要求明确 Removed 输出,再重新读库确认不存在。 |
|
||||
|
||||
“用工程替换已选 CBB…(原生重新导入)”与已有“从备份恢复 CBB…”是不同操作。前者更新中心库注册条目,采用移除后重新导入,**不是原子替换**;后者沿用备份 Work 的副本验证与安装恢复流程。
|
||||
|
||||
新增和替换默认继续自动校验,允许批次开始前取消。结果分别显示上传失败、上传成功但校验失败、上传并校验通过;取消自动校验时明确显示“已上传 / 未自动校验”。
|
||||
|
||||
## 支持范围与保护
|
||||
|
||||
- 已验证本机 Mentor EE7.9.5、DxDesigner、Logical-Physical、ASCII CBB 名称。原生核心组件和三种内容导出程序均核对固定 SHA-256;接口或版本不符时禁用并显示原因。
|
||||
- 所有写操作使用串行任务、共享互斥和上传工具兼容的库锁;暂存来源、完整备份、目标身份、事务随机标识、监督进程及实际独占句柄必须相互匹配。
|
||||
- 不直接修改 LMC 二进制,不依赖独立上传工具安装目录,不退回前台鼠标。遇到中心库升级或流程选择提示拒绝自动迁移。
|
||||
- 原生导入会改写 ICDB 存储字节。内容身份采用官方 ASCII、CSV 和 EDIF 原理图导出,加上 Layout、约束及其他主要资产的 SHA-256。只规范化已实测的报告时间和路径字段;未知工程文件继续参与比较。
|
||||
- 原生复制可能留下不正确的 PCB 库相对引用。仅在本任务导入、会话释放及库锁持有得到确认后校正已导入副本,再复读目录与内容。原始来源不改写。
|
||||
- 导出副本所有权随库检查点持久保存;超时、重启、地址记录仍存在或进程、独占访问无法确认时,不能解除库锁或接续维护。
|
||||
- 完整来源和预计目标路径达到 260 个 UTF-16 单元时,在原生写入前拒绝;同名替换在移除旧条目前检查。保留所有文件,提示缩短操作数据或目标库路径,不宣称已实现原生长路径支持。
|
||||
- 本轮已确认的原生复制失败即时记录。只正常确认本任务进程的已验证错误对话框;未知提示不自动点击,会话释放不明确时保留阻止状态。
|
||||
|
||||
## 实际验证
|
||||
|
||||
环境:Windows 11,版本 `10.0.26200`;Mentor EE7.9.5。
|
||||
|
||||
### 原生完整管理引擎
|
||||
|
||||
真实新建隔离库完成:新增 A、拒绝重复名称、替换为 B、备份后移除、将独立备份工程重新导入。各项会话均安全释放。B 的 Layout 哈希与 A 不同,并与来源 B 一致。原始来源主要文件清单未变。
|
||||
|
||||
证据:`diagnostics/issue2-native-crud-20261103/engine-e2e/cycle-result.json`。
|
||||
|
||||
### 最终冻结程序公开界面
|
||||
|
||||
从应用真实按钮、来源文件选择器和确认清单执行,没有替换原生适配器或绕过能力检查。
|
||||
|
||||
| 试验 | 结果 |
|
||||
| --- | --- |
|
||||
| 275 字符暂存路径 | `UPLOAD_FAILED`,明确 `NATIVE_PATH_TOO_LONG`,`safe_to_continue=true`;未启动内容导出或原生 Add。 |
|
||||
| 正常路径新增 A | `UPLOADED`,重新读库与工程内容核对通过。 |
|
||||
| 同名替换为 B | `UPLOADED`,实际 Layout 匹配 B 且不同于 A。 |
|
||||
| 原生移除 | `REMOVED`,重新读库确认不存在。 |
|
||||
| 最终退出与来源检查 | 原生进程已退出;两份来源的 153/147 个主要文件哈希及 541/506 个文件的大小、修改时间保持一致。 |
|
||||
|
||||
证据位于 `diagnostics/issue2-native-crud-20261103/`:
|
||||
|
||||
- `frozen-public-ui-path-block/result.json`:写入前长路径拒绝。
|
||||
- `frozen-public-ui/result.json`:最终冻结程序完整按钮流程及截图。
|
||||
- `final-source-baselines.json`、`final-acceptance.json`:来源和会话释放证据。
|
||||
- `build-result.json`、`validation.json`、`package-result.json`:源码、测试、构建和包校验记录。
|
||||
|
||||
本轮 CRUD 原生及冻结界面试验均在批次开始前取消自动校验,**上传成功不等于 READY**。这些结果不能代替上传后完整 Verify/Save/Close 或现场 ICDB 失联修复验收。
|
||||
|
||||
### 实测发现并修正的长路径问题
|
||||
|
||||
初版冻结程序在 264 字符暂存文件路径下弹出“系统找不到指定的路径”,日志记录 `Cannot copy iCDB base of Reusable Block project`,旧逻辑只检查成功提示,直到超时才返回。该失败未计入通过。
|
||||
|
||||
对同一文件,旧式 32 位 Win32 CopyFile 复现错误码 3;保持同一冻结程序、测试库、完整来源和空描述,仅缩短暂存路径后,原生新增和内容核对通过。最终修订增加完整路径预检和本轮失败识别,并在新冻结包实测提前拒绝。没有删减长路径中的日志或其他文件来绕过问题。
|
||||
|
||||
保留原始失败、正常关闭及库锁重新核验记录:`frozen-public-ui-longpath-failed/`、`longpath-failure-release/`、`longpath-failure-catalog/`、`path-copy-probe/`、`frozen-public-ui-shortpath-control/`。
|
||||
|
||||
## 自动化验证与交付
|
||||
|
||||
- 全量 `python -m pytest -q`:**1071 passed**,90.98 秒,1 条已有 pywinauto COM 线程模式警告。
|
||||
- `python -m compileall -q src tests`、`git diff --check`:通过。
|
||||
- 独立整体代码审查及长路径修订复审:无未解决的实质问题。
|
||||
- 从提交归档构建冻结程序,启动与退出冒烟测试通过;上述公开界面验收使用同一构建。
|
||||
- 候选包:`dist/issue2-native-crud-20261103-b26e2f2.zip`,旁附 SHA-256;包内含使用说明及验证摘要。
|
||||
|
||||
尚未完成 Windows 10 实机验证,也未将本轮 CRUD 试验视作现场服务器会话失联修复通过。旧版库迁移、其他 Mentor 版本、非 Logical-Physical 分区及原生长路径支持不在已验证范围。原用户库不参与本轮写入试验。
|
||||
@@ -1,29 +0,0 @@
|
||||
# ICDB 维护审查修正(候选)
|
||||
|
||||
替代 `8180a8a` 的诊断实现。该旧候选曾把完整校验当作诊断,且存在缺失证据后直接进入 Repair 的分支,不应继续用于原库。
|
||||
|
||||
## 行为
|
||||
|
||||
- READY 始终不进入维护或默认备份恢复队列,即使被勾选。混合选择只处理可见的、可用的非 READY 项;全部 READY 时没有可执行目标,不回退到处理 READY。
|
||||
- 先取得上传工具兼容的库锁,验证检查点、工程身份、进程和数据库独占访问,再启动诊断。
|
||||
- 独立的 `diagnostic_only` 模式只打开并确认目标,随后通过原生 `Close(False)` 关闭。不执行 Project Integration、保存、原生 LM Verify 菜单、工程库路径改写或 READY 校验。Mentor 启动本身仍可能生成运行日志/地址记录,因此不宣称整个原生过程绝对只读。
|
||||
- 诊断拒绝配置中指向其他中心库的引用,包含缩进/制表符格式。不会为了检查而改写引用。
|
||||
- 原生关闭助手最多调用一次。关闭返回后最多观察 30 秒的进程/地址释放;超时保留现场并停止。
|
||||
- Repair 只接受本次独立证据目录中的结构化 `ICDB_REPAIR_REQUIRED` 记录,要求工程级范围、会话身份和精确匹配的数据库路径。修复前再次确认目标及释放状态。
|
||||
- 删除通过 Python 函数名、模块名判断可信度的逻辑,以及吞掉断言/pytest 失败后直接修复的分支。缺少证据、通用数据库安全错误、其他工程或历史轮次证据均不能授权 Repair。
|
||||
- 诊断通过在报告中单列“启动检查通过、未修复”,不冒充修复完成或 READY。只有修复后完整校验取得权威 GREEN/READY 才算修复验证通过;历史恢复仍需核对版本。
|
||||
|
||||
## 验证范围
|
||||
|
||||
- 最终从 `ef652f3` 导出的固定源码运行完整回归:`python -X utf8 -m pytest -q --tb=short`,**1,151 passed,375.48 秒**;仅既有 pywinauto STA 警告。
|
||||
- 此前的专项覆盖包括库锁、证据缺失/其他工程/历史轮次、无集成保存、关闭失败、路径格式、READY 选择范围和延迟退出。最终源码副本与构建输入哈希已核对。
|
||||
- `compileall` 与 `git diff --check` 通过。
|
||||
- 独立审查发现并修正重复关闭和路径格式遗漏;冻结构建和启动结果另存于 `diagnostics/icdb-review-20261104/`。
|
||||
- 冻结启动/退出检查返回 0;EXE 内 5 个变更模块与固定源码编译结果一致;ZIP CRC 校验通过。
|
||||
- 最终候选:`dist/issue2-icdb-reviewed-ef652f3.zip`,50,871,172 字节;SHA-256:`f4565f1696caf620522d621bd8555817a6d7d5d6ed4193cf87f2b53758a5d8c7`。构建和测试证据对应代码提交 `ef652f3ada0b9b8422e49f2ebc5b18305204d8ab`。
|
||||
|
||||
## 保留的限制
|
||||
|
||||
本轮不在原库执行原生操作,未重新完成现场失联故障的端到端验收。仅有 `sAddress.adr`、历史版本选择提示或一般数据库错误不足以认定 ICDB 损坏;这些情况会停止并保留证据,不自动 Repair。若原生启动后会话未释放,也不会继续修复或处理下一项。
|
||||
|
||||
本候选不推送、不合并发布、不关闭工单。测试中的模拟边界用于验证队列和安全条件,不代替现场 Mentor 验收。
|
||||
@@ -0,0 +1,7 @@
|
||||
# PR #10 comment 309
|
||||
|
||||
Release proof now records the requested CBB, effective BLOCK/LIBRARY proof scope, identities/statuses of archived checkpoints and retained owners, and `reconciled_foreign_blockers`. For example, a BlockA operation which safely reconciles BlockB's historical checkpoint explicitly lists BlockB and the full-library proof. `data_recovery_confirmed` remains false. No extra gate, automatic backup or native action was added.
|
||||
|
||||
Three regressions first failed on missing evidence fields. After the fix, 94 backend/lease/release regressions passed; compileall and git diff --check passed. The tests use real temporary file/lease handles with the process-query boundary replaced; no production library was opened. Full regression is run again at the integrated chain tip. Real Mentor/shared-network acceptance and a rebuilt package remain outstanding.
|
||||
|
||||
Review: https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/pulls/10#issuecomment-309
|
||||
@@ -0,0 +1,38 @@
|
||||
# PR11 review 345 follow-up
|
||||
|
||||
Repeated CBB verification and ICDB check runs replace the previous result dialog
|
||||
for the same operation. Closing a result retires its Qt widgets and action
|
||||
references, while the check task keeps its requests, results, invalidated targets,
|
||||
and recovery context. A result for the other operation stays available.
|
||||
|
||||
During application shutdown, the title and status show that background work and
|
||||
path release are pending. After approximately 120 seconds a second notice says
|
||||
the application is still waiting. This is a notice interval, not a deadline;
|
||||
shutdown still waits for existing workers and never forces native tools to stop.
|
||||
|
||||
The batch CLI accepts an optional positive `--limit`:
|
||||
|
||||
```powershell
|
||||
python -m cbb_refresh_verify --batch-lmc 'Z:\library\library.lmc' --limit 2
|
||||
```
|
||||
|
||||
The limit selects the first requested names in their existing order. With no
|
||||
`--block`, the existing non-READY selection supplies those names; repeated
|
||||
`--block` options retain their explicit order. Omitting `--limit` retains the
|
||||
existing all-requested behavior. `batch_selection` logs selected, total, and
|
||||
remaining counts. On batch exceptions or unconfirmed native release,
|
||||
`batch_drive_retained` identifies the drive, remote share, display library and
|
||||
Mentor path, and directs the operator to the confirmed-release entry. It never
|
||||
disconnects a mapping while a native writer may still be active.
|
||||
|
||||
Management change counts explicitly cover the compared engineering files only.
|
||||
|
||||
Removed from the standalone PR11 head: all five `if False` blocks for the later
|
||||
release flow, and `_reload_after_maintenance` assignments and its unused reload
|
||||
branch. The hidden release control and existing method signatures remain for
|
||||
the later PR12 implementation. When integrating forward, preserve PR12's live
|
||||
release/resume behavior and retire its dialog-owned action references as well.
|
||||
Preserve PR13's asynchronous close and lease guards when adding the wait notice.
|
||||
|
||||
Validation uses the isolated offscreen review wrapper with fake native boundaries;
|
||||
it does not open Mentor, kill native processes, invoke Repair, or back up a library.
|
||||
@@ -0,0 +1,13 @@
|
||||
# 独立审查 1:只读进程探测与原生任务准入队列
|
||||
|
||||
基于 main `a56fd17`,不叠加 PR #3 的历史提交。
|
||||
|
||||
**行为变化:** 增加有界、版本化、只读 owner-probe helper 和可取消的 FIFO 原生任务队列。应用仅新增隐藏的只读 helper 分派;现有 UI、验证和原生写操作保持原来的入口。
|
||||
|
||||
**失败安全:** 查询超时或协议/身份异常返回未确认;暂停或取消的队列票据不会运行其动作,也不阻止后面的可执行任务。不启动或终止 Mentor 进程。
|
||||
|
||||
**回滚方式:** 尚未合入下游时撤销本提交即可;下游接入后须按依赖从上层向下回退。
|
||||
|
||||
完整回归:491 passed,1 条既有 pywinauto STA 提示。编译和 diff 检查通过。
|
||||
|
||||
与原评论建议的差别:`management_transaction` 直接导入管理模型和库锁;`scoped_manifest` 的协调记录与独占快照依赖库锁协议。这两者在后端审查中一起交付,避免构造导入不完整的“纯工具”基线。
|
||||
@@ -0,0 +1,20 @@
|
||||
# Native backend review unit
|
||||
|
||||
Base: codex/review-infrastructure. This unit integrates ICDB open diagnostics, scoped content manifests, native CBB transactions and the library-release protocol; it does not expose the new UI or residual termination action. Verification and ICDB checks remain separate, READY items are excluded from maintenance, and a released single-item failure can continue independent targets.
|
||||
|
||||
Failure safety: no automatic Repair/version choice, no server termination, no direct LMC edits or native lock-file deletion. Native writes are serialized, uncertain ownership retains evidence and mappings, and unfinished writes are shown without replay.
|
||||
|
||||
Dependency rationale: library release imports native engineering identity and retained management workers; engineering identity imports management source models and scoped manifests. Separating these into nominally independent utilities would leave runtime imports unresolved. This PR therefore keeps the backend dependency closure together; UI and user-confirmed termination remain separate later PRs.
|
||||
|
||||
Rollback: before dependents are merged, revert this commit. After merging dependents, revert in reverse order or use the previous candidate package after closing the current app. Code rollback does not undo a native transaction; use a consistent manual backup or explicitly selected native history on an isolated copy.
|
||||
|
||||
Validation: full Python suite 1,376 passed (one existing pywinauto COM-threading warning); compileall and git diff --check passed. Native field recovery, Windows 10 and cross-machine shared-library acceptance remain pending.
|
||||
|
||||
Review comment 344 follow-up (2026-11-09):
|
||||
|
||||
- Production status scans continue to query fresh bridge results. The low-level session now also defaults to fresh scans; explicit checkpoint reuse is documented as a controlled read-only option with no production resume promise.
|
||||
- `library-changes.json` declares `rule_version`, the selected `scope`, excluded directory categories and suffixes, positional runtime rules, runtime filenames/prefixes, and recognized coordination checkpoints. Names, suffixes, prefixes and native database locations come from the same constants used by semantic classification. These are differences in participating engineering files; excluded content is not proven unchanged, and unrelated CBB content is not checked.
|
||||
- Removed the tests-only `pcb_bridge.execution_outcome` helper. Production release safety continues to come from observed release state and remaining clients.
|
||||
- Unlocked primary snapshots hash the copy stream, then independently hash the final source and destination. Source reads decrease from three to two. Rejected the suggestion to remove/threshold the final source hash: size and mtime cannot detect same-size, same-timestamp source edits. Locked LMC/icdb streams and owned lock snapshots retain their existing behavior; no source-rehash skip flag is added.
|
||||
|
||||
Validation for this follow-up: 287 targeted cases passed through the isolated mutex/PYTHONPATH wrapper (`test_batch_status`, `test_batch_status_faults`, `test_review_backend_followup`, `test_scoped_manifest`, `test_pcb_bridge`, `test_management_retry_blockers`, `test_backup_recovery`, `test_library_lock`, `test_management`). AST parsing, `git diff --check`, and original newline-style checks passed. No real Mentor, COM automation, shared library or process control was exercised; no full-suite run was requested.
|
||||
@@ -0,0 +1,9 @@
|
||||
# Application integration review unit
|
||||
|
||||
Base: codex/review-native-backend. Behavior: verification, ICDB batch checking and CBB management have separate tabs; background checks yield between items, keep browsing responsive and let other native tasks queue. READY targets are excluded at execution, status refresh is scoped, and manual version/copy decisions remain explicit.
|
||||
|
||||
Failure safety: a released item failure can continue independent targets; uncertain native ownership retains evidence and mappings. There is no residual-session release backend in this review stage: its button and result actions are hidden, and its callback is inert. The next PR restores the complete release entry together with its tested backend, rather than exposing a button with a missing import. No automatic Repair or native version selection is added.
|
||||
|
||||
Rollback: revert this UI commit before its dependent release PR; after dependents, revert in reverse order or close the current program and use the prior candidate. This does not roll back library writes.
|
||||
|
||||
Validation: 1,545 passed (one existing pywinauto COM-threading warning), compileall and diff checks passed. Release-specific tests are introduced in the dependent PR, never discarded from the final tree. Windows 10, real shared-library concurrency and field ICDB recovery remain pending.
|
||||
@@ -0,0 +1,9 @@
|
||||
# 评论 275:占用复核与变更报告
|
||||
|
||||
校验和管理共用历史释放记录复核:旧 JSON/内存租约触发实际进程、地址、独占文件和导出副本证明,不直接视为真实占用,不结束进程或执行 Repair。确认释放后归档旧记录并继续;失败且本项尚未启动时保留原记录,结果不会把本项标成未释放。校验结果兼容新增 release_proof,管理首次原生调用前保存释放经过;进程释放不等于历史数据已恢复。
|
||||
|
||||
写后仅对原先的目标 Work/Cert、中心库配置和共享依赖范围生成 SHA-256 差分,报告新增、删除、修改路径,并保存写后清单。范围沿用原有 ManifestScope.library,不增加整库备份或其他 CBB 内容哈希,不声称已证明所有其他 CBB 未被波及。已释放的部分失败也保留差分;仍有原生所有者时不为报告读取数据库。报告失败单独标为 UNCONFIRMED 并返回原因,不伪造未完成事务、不制造永久占用。
|
||||
|
||||
PASS 不再重复计入 unconfirmed。未改变实际原生写操作、人工备份政策或服务器保护,也没有恢复自动修复。
|
||||
|
||||
回归覆盖历史记录无占用/真实地址占用、首次原生调用前留证、目标及共享依赖差分、失败后差分、报告保存失败后可继续。完整回归和限制以最终验证记录及 PR 描述为准;真实 Mentor、Win10、跨机器共享库尚未因此取得新验收结论。
|
||||
@@ -0,0 +1,7 @@
|
||||
# 评论 275/283:结果口径接入
|
||||
|
||||
管理进度显示历史占用复核;结果分别呈现已确认的原生动作、变更清单完整性和历史会话释放事实。单项 RECOVERY_REQUIRED 但 safe_to_continue=True 时,不再声称整个队列停止;记录失败不伪装成原生上传/移除失败。
|
||||
|
||||
独立操作回归更新为实际历史记录归档流程:先证明当前占用已释放、保留归档字节,再进行普通验证;不自动 Repair,失败后不遗留新的占用锁。
|
||||
|
||||
本阶段相关 UI/独立操作/后端回归 29 passed。后端完整回归与最终集成回归另见验证记录。没有执行真实 Mentor 写操作;回退按依赖逆序,不代表恢复原生事务。
|
||||
@@ -1,5 +1,7 @@
|
||||
# CBB Batch Status Bridge Implementation Plan
|
||||
|
||||
Current behavior (2026-11-09): production status scans always query the bridge fresh and overwrite checkpoint evidence. `BatchStatusSession.scan` defaults to `resume=False`; `resume=True` remains an explicit low-level option for controlled read-only scans, not an exposed production resume feature. Its lightweight fingerprint cannot detect every native payload/database write, so saved READY/PENDING rows must not authorize production actions.
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Read 180 to 3000 CBB Verify states through one resilient x86 Mentor bridge session with checkpoint recovery and authoritative `READY/PENDING` results.
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
# Issue #2 implementation plan
|
||||
|
||||
Approved by user on 2026-11-02. Continue branch codex/temp-issue-2-icdb-recovery,
|
||||
baseline ec78dd7 (491 tests). Do not merge, publish or close the issue. Preserve
|
||||
untracked review.diff. Python 3.12, PySide6, Mentor EE7.9.5, private desktop by
|
||||
default. No force termination of native database owners, deleting locks,
|
||||
guessing native write interfaces, or editing LMC binary contents.
|
||||
|
||||
Each task uses regression tests, focused validation and a separate commit.
|
||||
Real field lost-session reproduction and Windows 10 validation must be reported
|
||||
as unverified when unavailable; header corruption is not a substitute.
|
||||
|
||||
## Task 1: ICDB failure lifecycle and repair outcomes
|
||||
|
||||
Extend the existing owned-empty-PCB close path to wait for its launcher as well.
|
||||
Cover COM connected without a document, delayed dialogs/addresses/process exit.
|
||||
Native Repair must report missing healthy backup, native repair failure, database
|
||||
busy, unknown dialogs and timeout/unreleased distinctly using this run's native
|
||||
logs and Output. Safely close an idle, conclusively failed native repair tool;
|
||||
never act on unrecognized prompts or active native operations.
|
||||
Preserve original error, original evidence and all repair evidence. Record release
|
||||
state. Repair success in summaries means original native repair succeeded AND
|
||||
same-project reopening, verification and authoritative GREEN succeeded. Historical
|
||||
backup restoration remains RESTORED_REVIEW_REQUIRED. A conclusively failed repair
|
||||
may continue independent CBB items only if all relevant processes and addresses
|
||||
are released and scope is project-local; shared-library/unknown ownership stops.
|
||||
Add sanitized replay of issue2 lost-session/open-failure events with asserted target,
|
||||
stage and invocation order; one automatic repair maximum, no repeated PCB loop.
|
||||
Maintain VerifyRequest/VerifyResult compatibility. Files primarily failed_session,
|
||||
pcb_bridge, mentor_adapter, native_repair[_ui], verify_runner, icdb_maintenance and
|
||||
their tests. Update release evidence. No native live operations without coordinator
|
||||
agreement (only one native operation at a time). Coordinator builds candidate and
|
||||
runs frozen tests after review. Field fault sample is not in the attachment (logs
|
||||
only); do not claim field recovery.
|
||||
|
||||
## Task 2: Search, filtering, selection and non-READY maintenance
|
||||
|
||||
Implement local name/partition keyword search and filters: all, READY, non-READY,
|
||||
PENDING, unknown/read errors, missing project. Non-READY includes unconfirmed states
|
||||
without calling them corrupt. Show visible/READY/error counts; no Mentor rereads on
|
||||
filtering. Management selection permits READY; verify/maintenance/default backup
|
||||
recovery exclude READY. Operations target current visible checked rows; hiding a row
|
||||
clears its checkbox. Provide select visible/clear selection. Maintenance entry,
|
||||
confirmation, progress and report agree on non-READY target set. Existing verify-all
|
||||
means visible eligible rows, maintenance defaults visible eligible rows with checked
|
||||
subset if any. Refresh affected authoritative statuses after operations, retain search
|
||||
and filter. No premature integration of CRUD; expose selected records for Task4.
|
||||
Maintain CbbRecord compatibility and explicit status separate from action result.
|
||||
Tests include mixed READY/PENDING/errors/missing, filtering after state transitions,
|
||||
selection scope and 381/3000 row responsiveness. Files UI main_window, small focused
|
||||
filter helper if useful, backup dialog and maintenance report + tests. Avoid unrelated
|
||||
UI overhaul. Commit and report focused tests plus full suite once.
|
||||
|
||||
## Task 3: Scoped primary-file hashes and verified backups
|
||||
|
||||
Copy and retain complete backup trees. Restrict SHA256 and semantic before/after
|
||||
comparison to primary project/design/database/constraint files and required library
|
||||
dependencies: PRJ/PCB/DXP, icdb.dat, Layout, schematic/logic/symbol assets, CES/config,
|
||||
target LMC and shared database dependencies. Explicitly exclude runtime logs/temp/
|
||||
locks/address records, historical backups, PDF/generated output from content hashes;
|
||||
address files still participate in idle checks. Treat unclassified engineering data
|
||||
conservatively as primary rather than accidentally excluding it. For central-library
|
||||
manifest, only target CBB Work/Cert plus active library configuration/shared library
|
||||
dependency trees; do not hash unrelated CBB projects.
|
||||
During copy validate tree membership and file size/mtime before/after; primary files
|
||||
also source/destination SHA256, including locked database stream bytes. Logs changing
|
||||
after successful snapshot must not invalidate subsequent semantic comparison, while
|
||||
primary changes/additions/deletions must block install. Manifest is versioned and
|
||||
contains relative paths, size, hash and scope; progress gives hashed files/bytes/stage.
|
||||
Keep existing validate-copy -> target conflict check -> retain Work -> install ->
|
||||
reopen verification. Preserve old backups and evidence on failure. Add tests for logs
|
||||
only, all primary categories, changed/deleted sources, target concurrency, copied byte
|
||||
corruption and preserved recovery copies. Files backup_recovery and new focused
|
||||
manifest helper + tests. Reuse helper in management Task4 without changing old public
|
||||
Verify contracts. Document explicit rules/compatibility, commit after tests.
|
||||
|
||||
## Task 4: Native CBB management and delivery
|
||||
|
||||
Integrate add, same-name update, remove in current application. Input complete PRJ/PCB
|
||||
projects, no Packager/PDF/part replacement/rename/partition move. Add conflicts never
|
||||
overwrite. Update matches existing name/partition and backs up complete old project
|
||||
and library recovery snapshot. Remove backs up then uses verified Mentor native
|
||||
operation; reread confirms absence. Never fake removal by deleting directories.
|
||||
Add/update reread identity, default auto-verify optional per batch, distinguish upload
|
||||
failed, uploaded-but-verification-failed, uploaded-and-verified. Preserve source files.
|
||||
Use isolated native adapter: capability detection by installed version/interface plus
|
||||
isolated validation. Prefer proven COM/command; verified private desktop controls only
|
||||
fallback, never foreground input. Unsupported operations disabled with exact reason.
|
||||
Use cbb-upload-795 as research only, no external runtime dependency. Native API research
|
||||
comes from coordinator. No fabricated operation parameters. Snapshot/readback result
|
||||
must correspond to actual library entry and source engineering identity.
|
||||
Requests/results contain operation, library, CBB, partition, source, auto_verify,
|
||||
stage/status, safe_to_continue and evidence path. Serialize all writes with existing
|
||||
verification mutex and a library-level lock compatible with original uploader; apply
|
||||
coordination to verify/recovery too. Stop when native release uncertain. Persist item
|
||||
checkpoints and show unfinished tasks on restart, never replay automatically.
|
||||
Provide safe preview/confirmation for destructive operations; backups outside target.
|
||||
Test isolated add/conflict/update/remove/reimport, cancellation, timeout/network errors,
|
||||
partial successes, no-op/lying native response, busy library, restart checkpoints.
|
||||
Implement capabilities conservatively: if actual native operation cannot be proven,
|
||||
its UI remains disabled with actionable explanation and validation gap is explicit.
|
||||
Full Python/compile/diff checks, candidate frozen smoke, Windows11 native scenario;
|
||||
Windows10 and real field sample explicitly unverified if inaccessible. Coordinator
|
||||
provides final review and source/frozen deliverables without merging/publishing.
|
||||
@@ -1,12 +0,0 @@
|
||||
# 无地址 ICDB 维护与 PCB 版本选择
|
||||
|
||||
用户要求按已确认的入口分析修复,并明确允许需要时弹窗让用户选择。沿用临时分支,不恢复应用自动备份,不改原库。
|
||||
|
||||
- [x] 无地址记录的明确维护也进入原生 Repair;仅允许唯一数据库与 PCB/PRJ 反向引用绑定,保留全库独占检查。新增回归先失败,集中 250 项通过,独立审查通过。
|
||||
- [x] 实际应用按钮在无地址 IP101GR 副本完成原生 Repair,随后需要 PCB 版本选择;沿用用户此前确认的手动保存版本,诊断续接已保存关闭并读取 READY。人工续接不算完整自动链路验收。
|
||||
- [x] 在主应用显示候选时间和手动保存/自动保存/取消按钮。没有 UI 选择入口的调用保持待选择,不自动选版本;每个原生窗口只问一次,等待期间继续观察会话。
|
||||
- [x] 原生动作仍由私有桌面代理执行,核对修复证明、进程、窗口和候选版本;先选择单选项并复读,再确认 OK;取消或窗口变化不确认恢复。
|
||||
- [x] 用户选择后沿原校验链路继续,原生保存提示仍由已有监督器处理。最终 READY 保持原有门槛;使用历史 PCB 版本记录“已恢复,版本待核对”,不标记无损修复。
|
||||
- [x] 测试 UI 取消、手动/自动选择、选择失效、重复弹窗、错 PID/桌面、原生失败和 READY 区分;独立审查、全量回归、冻结实际按钮验证并交付候选。1135 项通过;de952a6 冻结实际按钮达到 PASS/GREEN/READY,历史版本仍标记待核对。
|
||||
|
||||
采用独立版本选择控制器与 Qt 对话框,复用原生代理及现有进度信号;不引入前台鼠标或自动重导入。界面只要求选择已有候选版本,不替用户推断应采用哪个版本。
|
||||
@@ -1,36 +0,0 @@
|
||||
# Manual Backup Implementation Plan
|
||||
|
||||
**Goal:** 按用户最新要求取消应用操作前的自动备份,改为提示手动备份,减少整库复制和重复哈希耗时。
|
||||
|
||||
**Architecture:** 管理操作使用只读内容基线、暂存来源、原生身份核对和现有库锁。备份责任转为用户;应用不验证或声称手动备份已存在。恢复操作只创建用于隔离校验的库副本,不再额外复制完整回退库。原生 Repair 自身备份保持原生行为。
|
||||
|
||||
**Tech Stack:** Python 3.12 / PySide6 / Mentor EE7.9.5。
|
||||
|
||||
用户已明确指定取消自动备份并提示手动备份,本计划直接执行。沿用临时分支,不合并发布、不修改原用户库。保留既有 `review.diff`。
|
||||
|
||||
## 范围与检查结果
|
||||
|
||||
| 操作 | 旧行为 | 新行为 |
|
||||
| --- | --- | --- |
|
||||
| 新增、替换、移除 | 每项完整中心库备份 | 手动备份提示;只读基线、检查点及来源暂存 |
|
||||
| 普通校验 | 本地 CBB 辅助备份,网络跳过 | 所有路径统一取消应用辅助备份 |
|
||||
| ICDB Repair | 应用完整工程备份,加原生自身备份 | 取消应用复制,保留独占读取/身份检查及原生自身行为 |
|
||||
| 从备份恢复 | 整库回退备份再复制验证库;额外来源副本 | 直接复制一次隔离验证库,来源直接暂存到验证工程 |
|
||||
| 读取/搜索/筛选 | 无备份 | 保持只读 |
|
||||
|
||||
验证工程副本和来源暂存是任务输入,不能删除后直接改原始来源。恢复安装中的旧 Work 改名保留是目录交换保护,不复制数据,继续保留。历史证据与备份不清理。独立研究工具的显式备份不属于桌面自动操作。
|
||||
|
||||
## Tasks
|
||||
|
||||
- [ ] 管理:先增加不复制整库及基线变化阻止写入的回归;移除事务授权对备份目录的依赖,绑定基线清单,保留身份、监督进程、活跃库锁和检查点验证;更新对应测试。
|
||||
- [ ] 校验/Repair/恢复:先写不调用自动备份、保持独占检查及单一验证库副本的回归;改调用路径和进度说明,测试取消/占用/来源及目标变化继续阻止操作。
|
||||
- [ ] 界面:将手动备份提示加入管理、校验、维护、恢复执行确认;取消不启动任务,每批一次,不伪称备份已完成。移除自动备份承诺。
|
||||
- [ ] 验证:集中测试、全量 Python 测试、编译与 diff 检查、独立代码审查;隔离原生移除验证不创建整库备份;新冻结包验证提示和取消反馈。更新验证记录,提交并构建候选。
|
||||
|
||||
## Review Focus
|
||||
|
||||
- 没有备份目录仍能通过真实管理事务校验;错库、过期锁、来源变化、基线记录篡改仍拒绝。
|
||||
- 替换移除成功但新增失败必须保留部分失败检查点,明确使用用户手动备份恢复。
|
||||
- 删除备份调用不能同时删掉数据库独占和取消检查。
|
||||
- 恢复仍隔离验证,并保留来源/目标变更检查与失败安装回退。
|
||||
- UI 取消确认无写入;逐项自动校验不重复弹窗;没有目标时不弹无意义提示。
|
||||
@@ -1,32 +0,0 @@
|
||||
# 原生 CBB 管理接入续作
|
||||
|
||||
沿用用户已批准的工单 #2 管理范围与临时分支。此次用户要求找到并尝试接入库的增删改查原生接口。
|
||||
不直接修改 LMC 二进制,不采用前台鼠标,不强制结束持有数据库的原生进程;原用户库不参与写入试验。
|
||||
|
||||
## 已确认接口
|
||||
|
||||
- 查询:LibraryManager.Application.OpenLibrary → Partitions(7) → 名称、分区,核对库身份并正常退出。
|
||||
- 新增:OnReusableBlocksEditor → 原生 Logical-Physical 页签 → New → 源 PRJ、名称、顶层块,提交原生对话框。字段使用有时限的窗口消息复读,提交后确认成功消息,再关闭重开目录。
|
||||
- 移除:安装脚本确认的 CleanWGLib/F4/REUSE_BLOCK,必须完整备份且重新读库确认缺失。
|
||||
- 同名替换:复用经过验证的移除与新增;它不是原子更新,删除后导入失败时保留恢复检查点并停止队列。与仅替换 Work 的“从备份恢复”明确区分。
|
||||
|
||||
## 接入步骤
|
||||
|
||||
1. 共享原生新增适配层,保留私有桌面、二进制版本、同库租约、监督进程、来源暂存及完整备份的验证。生产能力未通过时只有带隔离库所有权证据的研究入口可写。
|
||||
2. 原生 ICDB 导入会重写存储。用安装版本锁定的 ASCII、CSV 和 EDIF 原理图导出建立内容指纹,并保留布局及其他工程资产的字节哈希。不能把注册成功或名称相同等同于工程内容一致。
|
||||
3. 导出仅使用新建的完整工程副本。严格确认退出、有效输出与原生完成标记;仅规范化已经实际证明会变化的报告时间/路径字段。布局、坐标、连接、属性及未知工程文件变化一律阻止接受。
|
||||
4. 新增后原生程序可能未正确重定位 PCB 配置的 CentralLibrary。仅在本任务注册成功、原生释放和租约持有时修正该已导入工程的库引用,再重新打开核对目录与内容。原始输入工程不改动。
|
||||
5. 在实际新建隔离库运行新增、同名冲突、不同版本同名替换、备份后移除、从备份重新导入;逐项保存证据,验证源文件未变。随后才提升对应生产能力。
|
||||
6. 运行相关回归、独立审查、全量测试与冻结包实际管理入口验证。缺少原生证据的能力继续禁用并准确说明原因。
|
||||
|
||||
## 已完成的内容指纹取证
|
||||
|
||||
`diagnostics/issue2-native-crud-20261103/` 保存真实导出对照:
|
||||
|
||||
- ASCII:层次与展开连接、组件、端口和属性,3,531 行;只差生成时间和数据库目录三行报告元数据。
|
||||
- CSV:14 个表格文件;只差信息表的 System_Date 字段。
|
||||
- EDIF `-schematic`:约 580 KB,包含坐标、图形、连线、旋转、文本位置及属性;只差根级 status/written/timestamp。
|
||||
- 139 个主要工程资产一致;其余变化为 ICDB 数据文件、其运行时记录及两处 PCB CentralLibrary 引用。
|
||||
|
||||
以上为已验证格式的内容身份合同,不声称任意未知版本、任意外部工具私有元数据都可无差别转换。
|
||||
导出格式、安装版本、必需文件或引用不符合时拒绝操作。
|
||||
@@ -0,0 +1,25 @@
|
||||
# Latest reviews for PR #10/#11/#12
|
||||
|
||||
Scope: user selected only the 2026-11-09 comments #309/#310/#313. Earlier deep-review backlog stays out of scope. Preserve ICDB automatic Repair OFF, serial writes, current icon and independent-library admission. No merge to main, issue closure or release.
|
||||
|
||||
## PR #10
|
||||
|
||||
- [ ] Reproduce BlockA releasing historical BlockB checkpoints and retained owners without naming BlockB in proof.
|
||||
- [ ] Record requested block, actual proof scope, checkpoint identities and foreign names in existing release proof. Preserve original checkpoint bytes and data_recovery_confirmed=False; no new blocking gate.
|
||||
- [ ] Run backend/lease regressions, compile/diff checks, commit on codex/review-native-backend.
|
||||
|
||||
## PR #11/#12
|
||||
|
||||
- [ ] Forward-merge backend into UI, then UI into residual branch; no history rewriting.
|
||||
- [ ] Test one unreadable process/thread not affecting another, without fabricated modal windows; cover preview and action-time rechecks.
|
||||
- [ ] Enumerate only target-process threads/windows, store incomplete-read metadata per PID. Keep unknown/active writers protected rather than adding a blind force override.
|
||||
- [ ] Persist window identities and at most a 4 KiB output excerpt, preserve full preview in memory, stop duplicating activity output.
|
||||
- [ ] Carry exact preview block scope into native Cancel and recheck identity/scope before clicking.
|
||||
- [ ] Run residual/UI regressions, compile/diff checks, commit on residual branch.
|
||||
|
||||
## Chain tip
|
||||
|
||||
- [ ] Merge residual fixes into PR #13, preserving ca39fb3 and icon.
|
||||
- [ ] Address #11's line-ending note once at the tip: application.py to LF; pin it and main_window.py in EditorConfig. Preserve all other file endings and the global * -text rule.
|
||||
- [ ] Independent review, integrated full suite, compile/diff checks, validation records and fast-forward pushes to existing PR branches.
|
||||
- [ ] Update PR descriptions with precise results and no new package/native acceptance. Leave #3 as historical umbrella, without merging or closing it.
|
||||
@@ -1,5 +1,7 @@
|
||||
# CBB 批量状态桥设计
|
||||
|
||||
Current behavior (2026-11-09): production status scans always query the bridge fresh and overwrite checkpoint evidence. `BatchStatusSession.scan` defaults to `resume=False`; `resume=True` remains an explicit low-level option for controlled read-only scans, not an exposed production resume feature. Its lightweight fingerprint cannot detect every native payload/database write, so saved READY/PENDING rows must not authorize production actions.
|
||||
|
||||
## 目标
|
||||
|
||||
支持对 180 到 3000 个 CBB 进行 Mentor authoritative Verify 状态读取,要求单条失败隔离、过程可恢复、结果可审计,并避免现有“一条 CBB 启动一个桥进程”的启动开销。
|
||||
|
||||
@@ -1,8 +1,23 @@
|
||||
from pathlib import Path
|
||||
import os
|
||||
import struct
|
||||
project_root = Path(SPECPATH).parent
|
||||
assets_root = project_root / 'src' / 'cbb_refresh_verify' / 'assets'
|
||||
bridge_path = project_root / 'tools' / 'status_bridge' / 'bin' / 'CbbStatusBridge32.exe'
|
||||
verify_probe_path = project_root / 'tools' / 'status_bridge' / 'bin' / 'VerifyProbe32.exe'
|
||||
# App-local x86 runtime belongs beside the x86 bridge, separate from Qt/Python.
|
||||
bridge_runtime = []
|
||||
if bridge_path.is_file():
|
||||
runtime_root = Path(os.environ.get('WINDIR', r'C:\Windows')) / 'SysWOW64'
|
||||
for name in ('mfc140.dll', 'msvcp140.dll', 'vcruntime140.dll', 'concrt140.dll'):
|
||||
runtime = runtime_root / name
|
||||
if not runtime.is_file():
|
||||
raise RuntimeError(f'Install the Microsoft VC++ 2015-2022 x86 runtime before packaging: {runtime}')
|
||||
data = runtime.read_bytes()
|
||||
pe_offset = struct.unpack_from('<I', data, 0x3c)[0]
|
||||
if data[pe_offset:pe_offset+4] != b'PE\x00\x00' or struct.unpack_from('<H', data, pe_offset+4)[0] != 0x14c:
|
||||
raise RuntimeError(f'Expected an x86 bridge runtime: {runtime}')
|
||||
bridge_runtime.append((str(runtime), 'tools/status_bridge/bin'))
|
||||
a = Analysis(
|
||||
[str(project_root / 'src' / 'cbb_refresh_verify' / '__main__.py')],
|
||||
pathex=[str(project_root / 'src'), r'F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\src'],
|
||||
@@ -12,7 +27,7 @@ a = Analysis(
|
||||
[(str(verify_probe_path), 'tools/status_bridge/bin')]
|
||||
if verify_probe_path.is_file() else []
|
||||
),
|
||||
datas=[(str(project_root / 'src' / 'cbb_refresh_verify' / 'save_verified_block.vbs'), 'cbb_refresh_verify'),
|
||||
datas=bridge_runtime + [(str(project_root / 'src' / 'cbb_refresh_verify' / 'save_verified_block.vbs'), 'cbb_refresh_verify'),
|
||||
(str(project_root / 'src' / 'cbb_refresh_verify' / 'close_failed_block.vbs'), 'cbb_refresh_verify'),
|
||||
(str(assets_root / 'cbb_refresh_verify.ico'), 'cbb_refresh_verify/assets'),
|
||||
(str(assets_root / 'cbb_refresh_verify.png'), 'cbb_refresh_verify/assets'),
|
||||
|
||||
@@ -46,20 +46,39 @@ def resolve_data_root(cli_value: Path | None) -> Path:
|
||||
local = os.environ.get("LOCALAPPDATA")
|
||||
return (Path(local) / "CbbRefreshVerify" if local else Path.home() / "AppData" / "Local" / "CbbRefreshVerify").resolve()
|
||||
|
||||
def _positive_int(value):
|
||||
try:
|
||||
number = int(value)
|
||||
except ValueError:
|
||||
raise argparse.ArgumentTypeError('must be a positive integer') from None
|
||||
if number <= 0:
|
||||
raise argparse.ArgumentTypeError('must be a positive integer')
|
||||
return number
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(prog="CbbRefreshVerify")
|
||||
parser.add_argument('--verify-worker', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--repair-worker', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--owner-probe', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--native-backup-worker', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--management-worker', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--dialog-agent', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--batch-lmc', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--block', action='append', default=[], help=argparse.SUPPRESS)
|
||||
parser.add_argument('--limit', type=_positive_int, help='Maximum requested CBB names for --batch-lmc (default: all)')
|
||||
parser.add_argument('--libspec', default='', help=argparse.SUPPRESS)
|
||||
parser.add_argument('--dms-login-config', default='', help=argparse.SUPPRESS)
|
||||
parser.add_argument('--mentor-bin', default='', help=argparse.SUPPRESS)
|
||||
parser.add_argument("--smoke-test", action="store_true", help=argparse.SUPPRESS); parser.add_argument("--data-root", type=Path, help=argparse.SUPPRESS)
|
||||
args = parser.parse_args(list(argv) if argv is not None else None)
|
||||
if args.owner_probe:
|
||||
from .owner_probe import owner_probe_main
|
||||
return owner_probe_main(args.owner_probe)
|
||||
if args.native_backup_worker:
|
||||
from .native_backup import native_backup_worker_main
|
||||
return native_backup_worker_main(args.native_backup_worker)
|
||||
if args.management_worker:
|
||||
from .native_management import management_worker_main
|
||||
return management_worker_main(args.management_worker)
|
||||
@@ -102,6 +121,11 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
if library.error: raise RuntimeError(library.error)
|
||||
names = [record.name for record in library.records if record.status != 'READY']
|
||||
if not names: raise RuntimeError('中心库未读取到需要校验的 CBB')
|
||||
total = len(names)
|
||||
if args.limit is not None:
|
||||
names = names[:args.limit]
|
||||
logger.info('batch_selection selected=%s total=%s remaining=%s limit=%s',
|
||||
len(names), total, total - len(names), args.limit or 'all')
|
||||
requests = [VerifyRequest(mentor_path, name, context.root/'evidence',
|
||||
libspec=args.libspec, dms_login_config=args.dms_login_config,
|
||||
mentor_bin=args.mentor_bin, logging_context=context,
|
||||
@@ -109,13 +133,21 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
mapped_remote_root=lease.remote_root,
|
||||
native_lm_verify=native_lm_verify_enabled())
|
||||
for name in names]
|
||||
def retain_mapping(reason):
|
||||
lease.retain_for_recovery()
|
||||
logger.warning(
|
||||
'batch_drive_retained drive=%s remote=%s display=%s mentor=%s reason=%s '
|
||||
'guidance=请打开此中心库的“释放残留会话…”入口,确认原生会话安全释放后再释放映射;'
|
||||
'原生写入仍可能运行时请保留映射。',
|
||||
lease.drive or '-', lease.remote_root or '-', lease.display_path,
|
||||
mentor_path, reason)
|
||||
try:
|
||||
results = run_batch(requests)
|
||||
except Exception:
|
||||
lease.retain_for_recovery()
|
||||
retain_mapping('batch_exception')
|
||||
raise
|
||||
if any(not result.safe_to_continue for result in results):
|
||||
lease.retain_for_recovery()
|
||||
retain_mapping('native_release_unconfirmed')
|
||||
report = write_batch_report(requests, results, context.root/'reports')
|
||||
logger.info('batch_report path=%s', report)
|
||||
logger.info('failure_report path=%s', failure_report_path(report))
|
||||
|
||||
@@ -29,14 +29,55 @@ def _paths(root):
|
||||
|
||||
|
||||
def _idle_check(library, project, pcb):
|
||||
from .mentor_adapter import pcb_processes, _process_details
|
||||
from .icdb_ownership import unreleased_addresses
|
||||
if pcb_processes() or any(_process_details(name) for name in (
|
||||
'LibraryManager.exe', 'viewdraw.exe')):
|
||||
raise ValueError('请先正常关闭 PCB、Library Manager 和原理图编辑器,再恢复备份。')
|
||||
from .mentor_adapter import _process_details
|
||||
from .icdb_ownership import database_directories, unreleased_addresses
|
||||
from contextlib import ExitStack
|
||||
import win32con, win32file
|
||||
directories = database_directories(library, project, pcb)
|
||||
scope = (Path(project).parent, *directories)
|
||||
for name in ('ExpeditionPCB.exe', 'LibraryManager.exe', 'viewdraw.exe',
|
||||
'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe'):
|
||||
for pid, executable, command, parent in _process_details(name):
|
||||
match = _native_scope_match(command, roots=scope, files=(library, project, pcb))
|
||||
if match is True:
|
||||
raise ValueError(f'TARGET_NATIVE_OWNER_ACTIVE: 目标工程或共享库有原生会话,PID={pid}')
|
||||
if match is None:
|
||||
raise ValueError(f'TARGET_NATIVE_OWNER_UNCONFIRMED: 无法确认原生会话所属工程,PID={pid}')
|
||||
addresses = unreleased_addresses(library, project, pcb)
|
||||
if addresses:
|
||||
raise ValueError(f'数据库会话尚未释放,停止恢复:{addresses}')
|
||||
raise ValueError(f'TARGET_DATABASE_ADDRESS_UNCONFIRMED: 地址记录需原生确认;未据此判定正在占用:{addresses}')
|
||||
with ExitStack() as stack:
|
||||
paths = [Path(library), Path(pcb).parent/'Layout/LayoutDB.lyt',
|
||||
*(directory/'icdb.dat' for directory in directories)]
|
||||
for path in dict.fromkeys(paths):
|
||||
if path.is_file():
|
||||
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
|
||||
win32con.OPEN_EXISTING, 0, None)
|
||||
stack.callback(handle.Close)
|
||||
|
||||
|
||||
def _native_scope_match(command, *, roots=(), files=()):
|
||||
"""Match complete native path arguments; a missing identity remains unknown."""
|
||||
from .failed_session import _command_args
|
||||
if not command:
|
||||
return None
|
||||
expected_files = {Path(path).resolve() for path in files}
|
||||
expected_roots = tuple(Path(path).resolve() for path in roots)
|
||||
identities = []
|
||||
for arg in _command_args(command)[1:]:
|
||||
value = arg.split('=', 1)[-1].strip('"')
|
||||
path = Path(value)
|
||||
if not path.is_absolute():
|
||||
continue
|
||||
key = arg.split('=', 1)[0].lstrip('-/').casefold() if '=' in arg else ''
|
||||
if (path.suffix.casefold() in ('.prj', '.pcb', '.lmc')
|
||||
or path.name.casefold() in ('database', '__reusableblockssymb', 'icdb.dat')
|
||||
or key in ('project', 'icdb', 'database', 'db', 'lmc', 'prj', 'pcb')):
|
||||
identities.append(path.resolve())
|
||||
if not identities:
|
||||
return None
|
||||
return any(path in expected_files or any(path == root or path.is_relative_to(root)
|
||||
for root in expected_roots) for path in identities)
|
||||
|
||||
|
||||
def _project_text(path):
|
||||
@@ -140,9 +181,12 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
|
||||
return report
|
||||
def save(result):
|
||||
record.update({'installed': installed, 'result': asdict(result)})
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
report = root/'recovery-result.json'
|
||||
report.write_text(json.dumps(record, ensure_ascii=False, default=str, indent=2), encoding='utf-8')
|
||||
try:
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
report.write_text(json.dumps(record, ensure_ascii=False, default=str, indent=2), encoding='utf-8')
|
||||
except OSError as error:
|
||||
return replace(result, stderr=(result.stderr+'\n恢复报告写入失败:'+str(error)).strip())
|
||||
return replace(result, evidence_path=report)
|
||||
from .com_runtime import initialize_com, uninitialize_com
|
||||
initialized = initialize_com()
|
||||
@@ -239,7 +283,7 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
|
||||
return save(final)
|
||||
except Exception as error:
|
||||
return save(VerifyResult('FAIL' if installed else 'BLOCKED', stderr=str(error),
|
||||
safe_to_continue=False))
|
||||
safe_to_continue=release_confirmed))
|
||||
finally:
|
||||
try:
|
||||
if library_lock is not None:
|
||||
|
||||
@@ -48,6 +48,7 @@ class BatchStatusRecord:
|
||||
detail: str = ""
|
||||
fingerprint: str = ""
|
||||
timestamp: str = ""
|
||||
block_type: str = "RULP"
|
||||
|
||||
@property
|
||||
def completed(self) -> bool:
|
||||
@@ -106,9 +107,11 @@ def fingerprint_library(lmc: Path) -> LmcFingerprint:
|
||||
# Metadata alone is not a safe checkpoint key: on network shares and on
|
||||
# file systems with coarse timestamp resolution, two different LMC
|
||||
# contents can have the same size and mtime. Include the actual file
|
||||
# digest so a changed central library can never reuse an old status row.
|
||||
# digest to invalidate changed LMC bytes; payload edits remain outside this key.
|
||||
content_sha256 = _sha256_file(path)
|
||||
combined = hashlib.sha256()
|
||||
combined.update(str(path).casefold().encode('utf-8', errors='surrogatepass'))
|
||||
combined.update(b'\0')
|
||||
combined.update(content_sha256.encode("ascii"))
|
||||
combined.update(b"\0" + str(stat.st_size).encode("ascii"))
|
||||
combined.update(b"\0" + str(stat.st_mtime_ns).encode("ascii") + b"\0")
|
||||
@@ -165,6 +168,7 @@ class BatchCheckpoint:
|
||||
detail=str(payload.get("detail") or ""),
|
||||
fingerprint=str(payload.get("fingerprint") or ""),
|
||||
timestamp=str(payload.get("timestamp") or ""),
|
||||
block_type=str(payload.get("block_type") or "RULP"),
|
||||
)
|
||||
return cls(records)
|
||||
|
||||
@@ -182,7 +186,12 @@ def _now() -> str:
|
||||
|
||||
|
||||
class BatchStatusSession:
|
||||
"""Supervised serial bridge session with checkpoint recovery."""
|
||||
"""Supervised serial bridge session; fresh status queries by default.
|
||||
|
||||
Checkpoints record scan evidence. Explicit ``resume=True`` is a low-level
|
||||
opt-in for controlled read-only scans, not a production freshness proof:
|
||||
the lightweight fingerprint does not cover native payload/database edits.
|
||||
"""
|
||||
|
||||
def __init__(self, bridge: StatusBridgeClient, *, timeout_seconds: float = 10.0,
|
||||
rotate_every: int = 500) -> None:
|
||||
@@ -192,7 +201,7 @@ class BatchStatusSession:
|
||||
self.restart_count = 0
|
||||
|
||||
def scan(self, names: Iterable[str], lmc_file: Path, checkpoint_path: Path,
|
||||
*, block_type: str = "RULP", resume: bool = True) -> list[BatchStatusRecord]:
|
||||
*, block_type: str = "RULP", resume: bool = False) -> list[BatchStatusRecord]:
|
||||
fingerprint = fingerprint_library(Path(lmc_file))
|
||||
if resume:
|
||||
checkpoint = BatchCheckpoint.load(checkpoint_path)
|
||||
@@ -211,7 +220,8 @@ class BatchStatusSession:
|
||||
queried = 0
|
||||
for index, name in enumerate(names):
|
||||
previous = checkpoint.get(name)
|
||||
if previous and previous.fingerprint == fingerprint.sha256:
|
||||
if (previous and previous.status in {'READY', 'PENDING'}
|
||||
and previous.fingerprint == fingerprint.sha256 and previous.block_type == block_type):
|
||||
results.append(previous)
|
||||
continue
|
||||
try:
|
||||
@@ -223,15 +233,18 @@ class BatchStatusSession:
|
||||
block_name=name, status=result.status, source=result.source,
|
||||
raw_status=result.raw_status, detail=result.detail,
|
||||
fingerprint=fingerprint.sha256, timestamp=_now(),
|
||||
block_type=block_type,
|
||||
)
|
||||
except BridgeUnavailable as error:
|
||||
record = BatchStatusRecord(block_name=name, status="UNAVAILABLE",
|
||||
detail=str(error), fingerprint=fingerprint.sha256,
|
||||
timestamp=_now())
|
||||
timestamp=_now(), block_type=block_type)
|
||||
except BridgeResponseError as error:
|
||||
message = str(error)
|
||||
lower_message = message.casefold()
|
||||
unavailable = any(marker in message for marker in ("LMCDLL70", "私有 MFC", "未找到可用"))
|
||||
unavailable = any(marker in message for marker in ("LMCDLL70", "私有 MFC", "未找到可用")) or any(
|
||||
code in lower_message for code in ('0xc0000135', '-1073741515', '3221225781',
|
||||
'0xc000007b', '-1073741701', '3221225595'))
|
||||
malformed = (any(marker in message for marker in (
|
||||
"路径不匹配", "请求标识不匹配", "CBB 标识不匹配",
|
||||
)) or "mismatch" in lower_message)
|
||||
@@ -239,15 +252,15 @@ class BatchStatusSession:
|
||||
else "UNAVAILABLE" if unavailable
|
||||
else "MALFORMED" if malformed else "ERROR")
|
||||
record = BatchStatusRecord(block_name=name, status=status, detail=message,
|
||||
fingerprint=fingerprint.sha256, timestamp=_now())
|
||||
if server is not None and status not in {"UNAVAILABLE", "MALFORMED"}:
|
||||
fingerprint=fingerprint.sha256, timestamp=_now(), block_type=block_type)
|
||||
if server is not None and status != "UNAVAILABLE":
|
||||
try:
|
||||
server.restart()
|
||||
except BridgeUnavailable:
|
||||
pass
|
||||
except Exception as error: # bridge failures isolate one CBB
|
||||
record = BatchStatusRecord(block_name=name, status="ERROR", detail=str(error),
|
||||
fingerprint=fingerprint.sha256, timestamp=_now())
|
||||
fingerprint=fingerprint.sha256, timestamp=_now(), block_type=block_type)
|
||||
if server is not None:
|
||||
try:
|
||||
server.restart()
|
||||
@@ -255,7 +268,7 @@ class BatchStatusSession:
|
||||
pass
|
||||
checkpoint.append(checkpoint_path, record)
|
||||
results.append(record)
|
||||
if record.status in {"UNAVAILABLE", "MALFORMED"} and index + 1 < len(names):
|
||||
if record.status == "UNAVAILABLE" and index + 1 < len(names):
|
||||
# Startup/protocol failures cannot be repaired by retrying
|
||||
# the same request contract for every CBB.
|
||||
# Preserve a terminal record for each remaining name so a
|
||||
@@ -264,6 +277,7 @@ class BatchStatusSession:
|
||||
unavailable_record = BatchStatusRecord(
|
||||
block_name=remaining, status=record.status, detail=record.detail,
|
||||
fingerprint=fingerprint.sha256, timestamp=_now(),
|
||||
block_type=block_type,
|
||||
)
|
||||
checkpoint.append(checkpoint_path, unavailable_record)
|
||||
results.append(unavailable_record)
|
||||
@@ -282,6 +296,8 @@ def authoritative_status_map(names: Iterable[str], lmc_file: Path, checkpoint_pa
|
||||
timeout_seconds: float = 10.0) -> dict[str, str]:
|
||||
"""Return only bridge-backed statuses for an optional UI integration.
|
||||
|
||||
Production always queries fresh statuses, including after native writes;
|
||||
saved READY/PENDING rows are never reused here.
|
||||
A missing bridge is represented as ``UNAVAILABLE``/``UNKNOWN`` by callers;
|
||||
it is never promoted to ``READY``.
|
||||
"""
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
"""Shared execution defaults for GUI, batch requests and integration."""
|
||||
|
||||
DEFAULT_TIMEOUT_SECONDS = 600
|
||||
DIALOG_AGENT_STARTUP_TIMEOUT_SECONDS = 30
|
||||
WORKER_START_GATE_TIMEOUT_SECONDS = DIALOG_AGENT_STARTUP_TIMEOUT_SECONDS + 15
|
||||
@@ -22,7 +22,7 @@ def launch_save_helper(command, **kwargs):
|
||||
return helper
|
||||
|
||||
|
||||
def start_supervisor_watchdog(supervisor_pid, *, cancel_path=None):
|
||||
def start_supervisor_watchdog(supervisor_pid, *, cancel_path=None, stop_clients=False):
|
||||
"""A crashed supervisor must not leave unsupervised automation writing.
|
||||
|
||||
Stop only this Python worker and its registered automation clients. Native
|
||||
@@ -38,7 +38,9 @@ def start_supervisor_watchdog(supervisor_pid, *, cancel_path=None):
|
||||
# Let native calls finish before the worker closes its exact
|
||||
# document. Killing a pending automation client can abandon it.
|
||||
Path(cancel_path).touch()
|
||||
return
|
||||
if not stop_clients:
|
||||
return
|
||||
threading.Event().wait(5)
|
||||
with _automation_clients_lock:
|
||||
for helper in _automation_clients:
|
||||
try:
|
||||
@@ -48,7 +50,7 @@ def start_supervisor_watchdog(supervisor_pid, *, cancel_path=None):
|
||||
pass
|
||||
finally:
|
||||
parent.Close()
|
||||
if cancel_path is None:
|
||||
if cancel_path is None or stop_clients:
|
||||
os._exit(75)
|
||||
|
||||
thread = threading.Thread(target=watch, name='supervisor-watchdog', daemon=True)
|
||||
@@ -72,27 +74,58 @@ class DesktopWorker:
|
||||
def __init__(self, command, name, *, interactive_input=False):
|
||||
self.name = name
|
||||
self.interactive_input = bool(interactive_input)
|
||||
self.desktop = None if self.interactive_input else win32service.CreateDesktop(
|
||||
name, 0, win32con.GENERIC_ALL, None)
|
||||
# Track the session, but never use kill-on-close: PCB descendants can
|
||||
# still own a database transaction when the Python supervisor exits.
|
||||
self.job = win32job.CreateJobObject(None, '')
|
||||
self.job_bound = False
|
||||
self.desktop = None
|
||||
self.job = None
|
||||
self.handle = None
|
||||
self.companions = []
|
||||
self.companion_pids = []
|
||||
startup = win32process.STARTUPINFO()
|
||||
# subprocess.STARTUPINFO does NOT pass lpDesktop to CreateProcess.
|
||||
startup.lpDesktop = startup_desktop_name(name, interactive_input=self.interactive_input)
|
||||
self.handle, thread, self.pid, _ = win32process.CreateProcess(
|
||||
command[0], subprocess.list2cmdline(command), None, None, False,
|
||||
win32con.CREATE_NO_WINDOW, None, None, startup)
|
||||
thread.Close()
|
||||
self.job_bound = False
|
||||
# Track the session, but never use kill-on-close: PCB descendants can
|
||||
# still own a database transaction when the Python supervisor exits.
|
||||
try:
|
||||
win32job.AssignProcessToJobObject(self.job, self.handle)
|
||||
self.job_bound = True
|
||||
except Exception:
|
||||
# Kill-through-job is a cleanup guarantee, not a launch requirement.
|
||||
self.job_bound = False
|
||||
self.desktop = None if self.interactive_input else win32service.CreateDesktop(
|
||||
name, 0, win32con.GENERIC_ALL, None)
|
||||
self.job = win32job.CreateJobObject(None, '')
|
||||
startup = win32process.STARTUPINFO()
|
||||
# subprocess.STARTUPINFO does NOT pass lpDesktop to CreateProcess.
|
||||
startup.lpDesktop = startup_desktop_name(name, interactive_input=self.interactive_input)
|
||||
self.handle, thread, self.pid, _ = win32process.CreateProcess(
|
||||
command[0], subprocess.list2cmdline(command), None, None, False,
|
||||
win32con.CREATE_NO_WINDOW, None, None, startup)
|
||||
thread.Close()
|
||||
try:
|
||||
win32job.AssignProcessToJobObject(self.job, self.handle)
|
||||
self.job_bound = True
|
||||
except Exception:
|
||||
# Kill-through-job is a cleanup guarantee, not a launch requirement.
|
||||
self.job_bound = False
|
||||
except Exception as error:
|
||||
# No worker means no native descendants; a partial launch is uncertain.
|
||||
error.worker_launch_release = {
|
||||
'process_created': self.handle is not None,
|
||||
'safe_to_continue': self.handle is None,
|
||||
'worker_exited': self.handle is None,
|
||||
'remaining_pids': [self.pid] if self.handle is not None else []}
|
||||
if self.handle is not None:
|
||||
try:
|
||||
win32process.TerminateProcess(self.handle, 1)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
self.handle.Close()
|
||||
except Exception:
|
||||
pass
|
||||
if self.job is not None:
|
||||
try:
|
||||
self.job.Close()
|
||||
except Exception:
|
||||
pass
|
||||
if self.desktop is not None:
|
||||
try:
|
||||
self.desktop.CloseDesktop()
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
|
||||
def start_companion(self, command):
|
||||
startup = win32process.STARTUPINFO()
|
||||
@@ -118,9 +151,39 @@ class DesktopWorker:
|
||||
return int(pid)
|
||||
|
||||
def poll(self):
|
||||
if getattr(self, '_closed', False):
|
||||
return self._exit_code
|
||||
code = win32process.GetExitCodeProcess(self.handle)
|
||||
return None if code == 259 else code
|
||||
|
||||
def _save_clients(self):
|
||||
from .owner_probe import query_owners
|
||||
from .failed_session import _command_args
|
||||
expected = {Path(__file__).with_name(name).resolve()
|
||||
for name in ('save_verified_block.vbs', 'close_failed_block.vbs')}
|
||||
clients = []
|
||||
# Interpreter + COM startup measures ~4.75s on the field machine.
|
||||
for row in query_owners(('cscript.exe',), timeout_seconds=10):
|
||||
if row.get('parent') != self.pid:
|
||||
continue
|
||||
args = _command_args(row['command'])
|
||||
if any(Path(arg).resolve() in expected for arg in args[1:] if arg.casefold().endswith('.vbs')):
|
||||
clients.append(row['pid'])
|
||||
return clients
|
||||
|
||||
def automation_release_state(self):
|
||||
try:
|
||||
remaining = self._save_clients()
|
||||
return {'safe_to_continue': self.poll() is not None and not remaining,
|
||||
'remaining_pids': remaining}
|
||||
except Exception as error:
|
||||
return {'safe_to_continue': False, 'remaining_pids': [], 'error': str(error)}
|
||||
|
||||
def stop_automation_clients(self):
|
||||
from .mentor_adapter import _terminate_pid
|
||||
for pid in self._save_clients():
|
||||
_terminate_pid(pid)
|
||||
|
||||
@property
|
||||
def returncode(self):
|
||||
return self.poll()
|
||||
@@ -132,12 +195,9 @@ class DesktopWorker:
|
||||
except Exception:
|
||||
pass
|
||||
# The worker is now stopped and cannot spawn another save helper.
|
||||
from .mentor_adapter import _process_details, _terminate_pid
|
||||
try:
|
||||
for pid, _exe, command, parent in _process_details('cscript.exe'):
|
||||
if (int(parent or 0) == self.pid
|
||||
and 'save_verified_block.vbs' in str(command).casefold()):
|
||||
_terminate_pid(pid) # single automation process, no /T
|
||||
self.wait(timeout=5)
|
||||
self.stop_automation_clients()
|
||||
except Exception:
|
||||
pass
|
||||
for companion in self.companions:
|
||||
@@ -162,6 +222,8 @@ class DesktopWorker:
|
||||
return self.poll()
|
||||
|
||||
def close(self):
|
||||
if getattr(self, '_closed', False):
|
||||
return
|
||||
# Releasing Python resources must not kill native database owners.
|
||||
try:
|
||||
if self.poll() is None:
|
||||
@@ -177,7 +239,9 @@ class DesktopWorker:
|
||||
pass
|
||||
self.companions.clear()
|
||||
self.companion_pids.clear()
|
||||
self._exit_code = self.poll()
|
||||
self.handle.Close()
|
||||
self._closed = True
|
||||
# Native processes keep their desktop alive if manual recovery is needed.
|
||||
self.job.Close()
|
||||
if self.desktop is not None:
|
||||
|
||||
@@ -0,0 +1,377 @@
|
||||
"""Process-bound native opening check. This module never acquires PCB COM.
|
||||
|
||||
The caller must bind the newly launched PCB command/PID before entering here.
|
||||
The check runs in that worker's private desktop and closes only that session.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
import heapq
|
||||
import hashlib
|
||||
import ntpath
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import time
|
||||
|
||||
from .dialog_probe import _bounded_call
|
||||
from .icdb_recovery import LOG_LIMIT, _read_log_delta, decode_log, snapshot_log
|
||||
|
||||
_MAX_WINDOWS = 128
|
||||
_MAX_CHILDREN = 512
|
||||
|
||||
|
||||
def _normal(path):
|
||||
return ntpath.normcase(ntpath.normpath(str(path).strip()))
|
||||
|
||||
|
||||
def _log_paths(job):
|
||||
project = Path(job['project']).parent
|
||||
pcb_logs = Path(job['pcb']).parent / 'LogFiles'
|
||||
paths = [pcb_logs / 'PCBAutoSave.txt', pcb_logs / 'PCBLogFile.txt']
|
||||
directory = project / 'database/cdbsvr/log'
|
||||
directories = []
|
||||
if directory.is_dir():
|
||||
with os.scandir(directory) as entries:
|
||||
directories = [entry.name for entry in entries if entry.is_dir(follow_symlinks=False)]
|
||||
# Native names start with sortable YYYY-MM-DD HH.MM.SS. Only the
|
||||
# newest candidates can describe this launch; history is never read.
|
||||
for name in heapq.nlargest(8, directories):
|
||||
with os.scandir(directory / name) as entries:
|
||||
logs = heapq.nlargest(2, (entry.name for entry in entries
|
||||
if entry.is_file(follow_symlinks=False) and entry.name.casefold().endswith('.txt')))
|
||||
paths.extend(directory / name / log for log in logs)
|
||||
return paths, directories
|
||||
|
||||
|
||||
def _read_logs(job):
|
||||
result = {}
|
||||
paths, directories = _log_paths(job)
|
||||
for path in paths:
|
||||
try:
|
||||
record = snapshot_log(path)
|
||||
record['mtime_ns'] = path.stat().st_mtime_ns
|
||||
result[str(path)] = record
|
||||
except FileNotFoundError:
|
||||
result[str(path)] = snapshot_log(path)
|
||||
return {'files': result, 'server_directories': directories}
|
||||
|
||||
|
||||
def _read_bounded(function):
|
||||
try:
|
||||
return _bounded_call(function, 2)
|
||||
except TimeoutError as error:
|
||||
# Abort this check, rather than spawning another reader while a slow
|
||||
# share still owns the previous read. The daemon performs reads only.
|
||||
raise RuntimeError('DIAGNOSTIC_LOG_READ_TIMEOUT: native evidence unavailable') from error
|
||||
|
||||
|
||||
def snapshot_diagnostic_logs(job) -> dict:
|
||||
"""Capture pre-launch content, so copied/stale successes cannot pass.
|
||||
|
||||
Store the returned JSON-compatible value at job['diagnostic_log_baseline'].
|
||||
File count, content size and the entire read are bounded; failure is closed.
|
||||
"""
|
||||
started = time.time_ns()
|
||||
return {'started_ns': started, **_read_bounded(lambda: _read_logs(job))}
|
||||
|
||||
|
||||
def _fresh_logs_read(job, baseline):
|
||||
paths, _ = _log_paths(job)
|
||||
fresh = {}
|
||||
for path in paths:
|
||||
try:
|
||||
stat = path.stat()
|
||||
old = baseline['files'].get(str(path))
|
||||
if stat.st_mtime_ns < baseline['started_ns']:
|
||||
continue
|
||||
if old is None:
|
||||
if path.parent.name in baseline.get('server_directories', ()):
|
||||
continue # An unobserved historical file cannot prove freshness.
|
||||
old = {'size': 0, 'tail_sha256': hashlib.sha256(b'').hexdigest()}
|
||||
if 'error' in old or (old.get('mtime_ns') == stat.st_mtime_ns and old['size'] == stat.st_size):
|
||||
continue
|
||||
content, appended = _read_log_delta(path, old)
|
||||
if not content and stat.st_mtime_ns != old.get('mtime_ns') and stat.st_size == old['size']:
|
||||
# Native PCBLog is overwritten with the same successful text.
|
||||
content, _ = _read_log_delta(path, {'size': 0, 'tail_sha256': ''})
|
||||
if not appended and old.get('truncated') and stat.st_size > LOG_LIMIT:
|
||||
continue
|
||||
fresh[str(path)] = decode_log(content)
|
||||
except FileNotFoundError:
|
||||
continue
|
||||
return fresh
|
||||
|
||||
|
||||
def _fresh_logs(job, baseline):
|
||||
return _read_bounded(lambda: _fresh_logs_read(job, baseline))
|
||||
|
||||
|
||||
def _load_evidence(job, pcb_pid, baseline, *, require_autosave=True):
|
||||
logs = _fresh_logs(job, baseline)
|
||||
project = Path(job['project']).parent
|
||||
pcb = str(Path(job['pcb']))
|
||||
auto_path = str(Path(job['pcb']).parent / 'LogFiles/PCBAutoSave.txt')
|
||||
read_path = str(Path(job['pcb']).parent / 'LogFiles/PCBLogFile.txt')
|
||||
names = re.findall(r'^Job Name:\s*(.*?)\s*$', logs.get(auto_path, ''), re.M | re.I)
|
||||
if names and any(_normal(name) != _normal(pcb) for name in names):
|
||||
return None
|
||||
if require_autosave and not names:
|
||||
return None
|
||||
if 'Successfully read the design.' not in logs.get(read_path, ''):
|
||||
return None
|
||||
database = _normal(project / 'database')
|
||||
project_file = _normal(job['project'])
|
||||
for path, text in logs.items():
|
||||
if path in (auto_path, read_path):
|
||||
continue
|
||||
db_paths = re.findall(r'S: Project path \[(.*?)\]', text)
|
||||
prj_paths = re.findall(r'S: Project file \(\.prj\) path \[(.*?)\]', text)
|
||||
startup = re.search(r'S: Started up automatically by iCDB Client: [^\r\n]*:' + str(pcb_pid) + r'\s*$', text, re.M)
|
||||
client = re.search(r'Registered sub-client \[Expedition PCB[^\r\n]*process ID \[' + str(pcb_pid) + r'\]', text)
|
||||
if (db_paths and all(_normal(value) == database for value in db_paths)
|
||||
and prj_paths and all(_normal(value) == project_file for value in prj_paths)
|
||||
and startup and client and 'S: iCDB database loaded' in text):
|
||||
return {'pcb': pcb, 'pcb_pid': pcb_pid,
|
||||
'logs': [auto_path, read_path, path], 'document_identity': 'native_path_pid_logs'}
|
||||
return None
|
||||
|
||||
|
||||
def _target_frame(windows, name):
|
||||
matches = []
|
||||
for window in windows:
|
||||
if not window['class'].casefold().startswith('afx:') or not window.get('enabled', True):
|
||||
continue
|
||||
if not window['text'].casefold().startswith('expedition pcb') or f'[{name}]'.casefold() not in window['text'].casefold():
|
||||
continue
|
||||
mdi = {child['hwnd'] for child in window['children'] if child['class'].casefold() == 'mdiclient'}
|
||||
if any(child.get('parent') in mdi and child['text'].casefold() == name.casefold()
|
||||
and child['class'].casefold().startswith('afx:') for child in window['children']):
|
||||
matches.append(window)
|
||||
return matches[0] if len(matches) == 1 else None
|
||||
|
||||
|
||||
def _windows(pid):
|
||||
"""Read only this PID on the current desktop; cap text and enumeration work."""
|
||||
import win32api
|
||||
import win32gui
|
||||
import win32process
|
||||
user = ctypes.WinDLL('user32', use_last_error=True)
|
||||
user.GetWindowTextW.argtypes = [wintypes.HWND, wintypes.LPWSTR, ctypes.c_int]
|
||||
user.GetWindowTextW.restype = ctypes.c_int
|
||||
deadline = time.monotonic() + .2
|
||||
def text(hwnd):
|
||||
if time.monotonic() >= deadline:
|
||||
raise RuntimeError('DIAGNOSTIC_WINDOW_LIMIT: window scan exceeded 0.2s')
|
||||
buffer = ctypes.create_unicode_buffer(4096)
|
||||
# All handles belong to the external PCB PID: GetWindowText reads
|
||||
# Windows' cached caption without sending a message to its UI thread.
|
||||
# Custom controls may have no cached text; missing evidence fails closed.
|
||||
user.GetWindowTextW(hwnd, buffer, len(buffer))
|
||||
return buffer.value
|
||||
result = []
|
||||
seen = 0
|
||||
def collect(hwnd, _):
|
||||
nonlocal seen
|
||||
if win32process.GetWindowThreadProcessId(hwnd)[1] != pid or not win32gui.IsWindowVisible(hwnd):
|
||||
return True
|
||||
seen += 1
|
||||
if seen > _MAX_WINDOWS:
|
||||
raise RuntimeError('DIAGNOSTIC_WINDOW_LIMIT: too many windows')
|
||||
cls = win32gui.GetClassName(hwnd)
|
||||
if cls.casefold() in {'uac_inputindicatoroverlaywnd', 'uac input indicator'}:
|
||||
return True
|
||||
children = []
|
||||
count = 0
|
||||
def child(ch, _):
|
||||
nonlocal count
|
||||
count += 1
|
||||
if count > _MAX_CHILDREN:
|
||||
raise RuntimeError('DIAGNOSTIC_WINDOW_LIMIT: too many controls')
|
||||
child_cls = win32gui.GetClassName(ch)
|
||||
if (cls == '#32770' or cls.casefold() == 'internet explorer_hidden'
|
||||
or child_cls.casefold() == 'mdiclient' or child_cls.casefold().startswith('afx:')):
|
||||
children.append({'hwnd': ch, 'class': child_cls, 'text': text(ch),
|
||||
'id': win32gui.GetDlgCtrlID(ch), 'parent': win32gui.GetParent(ch),
|
||||
'enabled': bool(win32gui.IsWindowEnabled(ch))})
|
||||
return True
|
||||
if cls == '#32770' or cls.casefold().startswith('afx:') or cls.casefold() == 'internet explorer_hidden':
|
||||
win32gui.EnumChildWindows(hwnd, child, None)
|
||||
caption = text(hwnd)
|
||||
if cls.casefold() == 'internet explorer_hidden' and not caption and not children:
|
||||
left, top, right, bottom = win32gui.GetWindowRect(hwnd)
|
||||
if left == right and top == bottom:
|
||||
return True
|
||||
result.append({'hwnd': hwnd, 'pid': pid, 'class': cls, 'text': caption,
|
||||
'enabled': bool(win32gui.IsWindowEnabled(hwnd)), 'children': children,
|
||||
'owner': int(win32gui.GetWindow(hwnd, 4) or 0)})
|
||||
return True
|
||||
win32api.SetLastError(0)
|
||||
try:
|
||||
win32gui.EnumWindows(collect, None)
|
||||
except Exception as error:
|
||||
if getattr(error, 'winerror', None) not in (0, 2) or result:
|
||||
raise
|
||||
return result
|
||||
|
||||
|
||||
class _NativeSession:
|
||||
def __init__(self, job, pid, launcher):
|
||||
if launcher is None or not callable(getattr(launcher, 'poll', None)):
|
||||
raise RuntimeError('DIAGNOSTIC_LAUNCHER_REQUIRED: retain the exact launch process handle')
|
||||
import win32api
|
||||
import win32service
|
||||
import win32con
|
||||
import win32event
|
||||
import win32gui
|
||||
self.handles = []
|
||||
self.pid = int(pid)
|
||||
self.launcher = launcher
|
||||
self.gui = win32gui
|
||||
self.event = win32event
|
||||
desktop = win32service.GetThreadDesktop(win32api.GetCurrentThreadId())
|
||||
actual = win32service.GetUserObjectInformation(desktop, 2)
|
||||
expected = str(job.get('desktop', '')).split('\\')[-1]
|
||||
if not expected or expected.casefold() in {'default', 'winlogon', 'disconnect'} or actual.casefold() != expected.casefold():
|
||||
raise RuntimeError('DIAGNOSTIC_DESKTOP_MISMATCH')
|
||||
self.pcb = win32api.OpenProcess(win32con.SYNCHRONIZE, False, int(pid))
|
||||
self.handles.append(self.pcb)
|
||||
|
||||
def pcb_alive(self):
|
||||
return self.event.WaitForSingleObject(self.pcb, 0) != 0
|
||||
|
||||
def launcher_alive(self):
|
||||
return self.launcher.poll() is None
|
||||
|
||||
def post(self, hwnd, message):
|
||||
import win32process
|
||||
if not self.pcb_alive() or win32process.GetWindowThreadProcessId(hwnd)[1] != self.pid:
|
||||
raise RuntimeError('DIAGNOSTIC_STALE_WINDOW: target window identity changed')
|
||||
self.gui.PostMessage(hwnd, message, 0, 0)
|
||||
|
||||
def close(self):
|
||||
for handle in self.handles:
|
||||
handle.Close()
|
||||
self.handles.clear()
|
||||
|
||||
|
||||
def _cancel(job):
|
||||
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
|
||||
raise RuntimeError('VERIFY_CANCELLED: native opening check cancelled')
|
||||
|
||||
|
||||
def _pending_prompt(windows, *, closing=False, frame=None, session=None, clicked=None, pcb_name=''):
|
||||
for window in windows:
|
||||
known_titles = {'expedition pcb', 'expedition pcb - reusable block'}
|
||||
if (window['class'].casefold().startswith('afx:') and not window.get('owner')
|
||||
and (window['text'].casefold() in known_titles
|
||||
or frame is not None and window['hwnd'] == frame['hwnd'])):
|
||||
continue
|
||||
text = ' '.join([window['text'], *(child['text'] for child in window['children'])]).casefold()
|
||||
if not closing and ('select the desired product license' in text or window['text'] == 'Tip of the Day'):
|
||||
return True # The caller's PID-scoped DialogAgent owns startup choices.
|
||||
standard_save = (pcb_name and window['class'] == '#32770' and window['text'] == 'Expedition PCB'
|
||||
and any(child['class'].casefold() == 'static'
|
||||
and child['text'].strip().casefold() == f'Save changes to {pcb_name}?'.casefold()
|
||||
for child in window['children'])
|
||||
and {child.get('id') for child in window['children'] if child['class'].casefold() == 'button'} == {2, 6, 7})
|
||||
if closing and window.get('owner') == frame['hwnd'] and (standard_save or 'do you want to save the reusable block cell' in text):
|
||||
targets = [child for child in window['children'] if child['class'].casefold() == 'button'
|
||||
and child.get('id') == 7 and child['text'].replace('&', '').strip().casefold() in {'no', '否(n)', '否'}
|
||||
and child.get('enabled', True)]
|
||||
if len(targets) == 1:
|
||||
if window['hwnd'] not in clicked:
|
||||
session.post(targets[0]['hwnd'], 0xF5)
|
||||
clicked.add(window['hwnd'])
|
||||
continue
|
||||
raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: unknown native prompt preserved; '
|
||||
f"pid={window['pid']} hwnd={window['hwnd']} class={window['class']!r} "
|
||||
f"title={window['text']!r}")
|
||||
return False
|
||||
|
||||
|
||||
def check_target_window(job, pcb_pid, *, emit, error_reader, launcher_process=None) -> dict:
|
||||
"""Prove this launch opened its native document, close it, and prove exit.
|
||||
|
||||
PASS describes opening only; it does not imply refresh READY or unoccupied
|
||||
shared library data. Unknown prompts are preserved for existing recovery.
|
||||
"""
|
||||
baseline = job.get('diagnostic_log_baseline')
|
||||
if not isinstance(baseline, dict) or 'started_ns' not in baseline or 'files' not in baseline:
|
||||
raise RuntimeError('DIAGNOSTIC_BASELINE_REQUIRED: snapshot before native launch')
|
||||
session = _NativeSession(job, int(pcb_pid), launcher_process)
|
||||
try:
|
||||
deadline = time.monotonic() + max(.01, float(job['timeout']))
|
||||
while True:
|
||||
_cancel(job)
|
||||
error = _read_bounded(error_reader) if error_reader else None
|
||||
if error:
|
||||
raise RuntimeError(str(error))
|
||||
if not session.pcb_alive():
|
||||
raise RuntimeError('DIAGNOSTIC_OPEN_UNCONFIRMED: target PCB exited before loaded evidence')
|
||||
windows = _windows(int(pcb_pid))
|
||||
if any(window['pid'] != int(pcb_pid) for window in windows):
|
||||
raise RuntimeError('DIAGNOSTIC_PID_MISMATCH')
|
||||
frame = _target_frame(windows, Path(job['pcb']).stem)
|
||||
# Startup splash/control windows are transient. Unknown windows
|
||||
# veto closing only once the target actually has loaded evidence.
|
||||
pending = (_pending_prompt(windows, frame=frame, pcb_name=Path(job['pcb']).name)
|
||||
if frame is not None else True)
|
||||
evidence = (_load_evidence(job, int(pcb_pid), baseline, require_autosave=False)
|
||||
if frame is not None and not pending else None)
|
||||
if evidence is not None:
|
||||
emit(stage='diagnostic_native_loaded_candidate', **evidence)
|
||||
break
|
||||
if time.monotonic() >= deadline:
|
||||
raise RuntimeError('DIAGNOSTIC_OPEN_UNCONFIRMED: current target MDI/path/PID logs missing')
|
||||
time.sleep(.1)
|
||||
# Re-read the exact PID/frame before the sole close request.
|
||||
_cancel(job)
|
||||
windows = _windows(int(pcb_pid))
|
||||
_pending_prompt(windows, frame=frame, pcb_name=Path(job['pcb']).name)
|
||||
current = _target_frame(windows, Path(job['pcb']).stem)
|
||||
if current is None or current['hwnd'] != frame['hwnd']:
|
||||
raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: target frame changed')
|
||||
session.post(frame['hwnd'], 0x10)
|
||||
emit(stage='diagnostic_wm_close', pcb_pid=int(pcb_pid), hwnd=frame['hwnd'])
|
||||
close_deadline = time.monotonic() + 30
|
||||
clicked = set()
|
||||
last_pending = ''
|
||||
while session.pcb_alive() or session.launcher_alive():
|
||||
# Cancellation stops future work; an accepted normal close must
|
||||
# still finish before its queue slot can be safely released.
|
||||
windows = _windows(int(pcb_pid)) if session.pcb_alive() else []
|
||||
previous_clicks = set(clicked)
|
||||
pending_error = None
|
||||
try:
|
||||
_pending_prompt(windows, closing=True, frame=frame, session=session, clicked=clicked,
|
||||
pcb_name=Path(job['pcb']).name)
|
||||
except RuntimeError as error:
|
||||
if not str(error).startswith('DIAGNOSTIC_CLOSE_UNCONFIRMED: unknown native prompt'):
|
||||
raise
|
||||
# WM_CLOSE creates and destroys native windows asynchronously;
|
||||
# preserve them and wait for populated controls or process exit.
|
||||
pending_error = error
|
||||
if str(error) != last_pending:
|
||||
last_pending = str(error)
|
||||
emit(stage='diagnostic_close_pending', detail=last_pending)
|
||||
for hwnd in clicked - previous_clicks:
|
||||
emit(stage='diagnostic_save_no', pcb_pid=int(pcb_pid), hwnd=hwnd)
|
||||
if time.monotonic() >= close_deadline:
|
||||
if pending_error is not None:
|
||||
raise pending_error
|
||||
raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: target PCB/launcher still running')
|
||||
time.sleep(.1)
|
||||
# EE7.9 buffers PCBAutoSave's complete Job Name until normal close.
|
||||
# The candidate permits closing only; PASS still needs that exact path.
|
||||
evidence = _load_evidence(job, int(pcb_pid), baseline)
|
||||
if evidence is None:
|
||||
raise RuntimeError('DIAGNOSTIC_OPEN_UNCONFIRMED: fresh full PCB path not confirmed after close')
|
||||
emit(stage='diagnostic_native_open_confirmed', **evidence)
|
||||
return {'status': 'PASS', 'check': 'native_open_only', 'native_processes_exited': True,
|
||||
'library_ownership': 'NOT_ASSESSED', 'pcb_pid': int(pcb_pid),
|
||||
'launcher_pid': getattr(launcher_process, 'pid', None), 'evidence': evidence,
|
||||
'detail': 'Native target opened and its PCB/launcher exited; refresh readiness and shared library ownership not assessed.'}
|
||||
finally:
|
||||
session.close()
|
||||
@@ -324,6 +324,7 @@ class DialogAgentServer:
|
||||
self.channel = JsonChannel(connection)
|
||||
self.channel.send({"token": paths.token}, timeout_seconds=10)
|
||||
self.observed_snapshots = {}
|
||||
self.observed_pids = None
|
||||
|
||||
@classmethod
|
||||
def from_config(cls, config_path: Path, *, probe, executor=None):
|
||||
@@ -348,7 +349,15 @@ class DialogAgentServer:
|
||||
try:
|
||||
phase = DialogPhase(request["phase"])
|
||||
if request.get("op") == "observe":
|
||||
snapshots = self.probe.capture(phase)
|
||||
pids = request.get('pids')
|
||||
if pids is not None and (not isinstance(pids, list)
|
||||
or any(type(pid) is not int or pid <= 0 for pid in pids)):
|
||||
raise ValueError('DIALOG_PID_SCOPE_INVALID')
|
||||
self.observed_pids = set(pids) if pids is not None else None
|
||||
snapshots = (self.probe.capture(phase, pids=self.observed_pids) if pids is not None
|
||||
else self.probe.capture(phase))
|
||||
if pids is not None:
|
||||
snapshots = tuple(w for w in snapshots if w.pid in self.observed_pids)
|
||||
self.observed_snapshots.clear()
|
||||
for snapshot in snapshots:
|
||||
self.observed_snapshots[stable_fingerprint(snapshot)] = snapshot
|
||||
@@ -356,7 +365,9 @@ class DialogAgentServer:
|
||||
return
|
||||
if request.get("op") == "perform":
|
||||
expected = self.observed_snapshots.get(request.get("fingerprint"))
|
||||
if expected is None:
|
||||
if (expected is None or int(request.get('hwnd', 0)) != expected.hwnd
|
||||
or self.observed_pids is not None and (expected.pid not in self.observed_pids
|
||||
or not self.probe.matches_identity(expected))):
|
||||
self._response(request, result=ActionResult(
|
||||
error_code="STALE_DIALOG",
|
||||
detail="窗口已消失或指纹已变化",
|
||||
@@ -422,27 +433,45 @@ class DialogAgentClient:
|
||||
raise
|
||||
|
||||
@classmethod
|
||||
def start(cls, worker, root: Path, *, timeout_seconds: float = 2.0):
|
||||
def start(cls, worker, root: Path, *, timeout_seconds: float = 2.0, stop=None):
|
||||
client = cls.prepare(root, desktop_name=worker.name, timeout_seconds=timeout_seconds)
|
||||
try:
|
||||
from .defaults import DIALOG_AGENT_STARTUP_TIMEOUT_SECONDS
|
||||
worker.start_companion(dialog_agent_command(client.paths.config))
|
||||
client._accept(timeout_seconds=10.0)
|
||||
# Frozen imports can exceed ten seconds; PCB remains behind its gate.
|
||||
client._accept(timeout_seconds=DIALOG_AGENT_STARTUP_TIMEOUT_SECONDS, stop=stop)
|
||||
return client
|
||||
except Exception:
|
||||
client.close()
|
||||
raise
|
||||
|
||||
def _accept(self, timeout_seconds):
|
||||
def _accept(self, timeout_seconds, *, stop=None):
|
||||
if self.channel is not None:
|
||||
return
|
||||
self.listener.settimeout(timeout_seconds)
|
||||
connection, _address = self.listener.accept()
|
||||
deadline = time.monotonic() + timeout_seconds
|
||||
while True:
|
||||
if stop is not None and stop.is_set():
|
||||
raise InterruptedError('VERIFY_CANCELLED: 弹窗代理启动已取消,未启动 PCB')
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError('dialog-agent startup timed out')
|
||||
self.listener.settimeout(min(.2, remaining))
|
||||
try:
|
||||
connection, _address = self.listener.accept()
|
||||
break
|
||||
except socket.timeout:
|
||||
continue
|
||||
channel = JsonChannel(connection)
|
||||
try:
|
||||
connection.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
||||
hello = channel.receive(timeout_seconds)
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError('dialog-agent handshake timed out')
|
||||
hello = channel.receive(min(self.timeout_seconds, remaining))
|
||||
if hello.get("token") != self.paths.token:
|
||||
raise DialogAgentProtocolError("dialog-agent authentication failed")
|
||||
if stop is not None and stop.is_set():
|
||||
raise InterruptedError('VERIFY_CANCELLED: 弹窗代理启动已取消,未启动 PCB')
|
||||
self.channel = channel
|
||||
except Exception:
|
||||
channel.close()
|
||||
@@ -473,8 +502,8 @@ class DialogAgentClient:
|
||||
raise DialogAgentProtocolError(f"{response['error_code']}: {response.get('detail', '')}")
|
||||
return response.get("result")
|
||||
|
||||
def observe(self, phase: DialogPhase) -> tuple[WindowSnapshot, ...]:
|
||||
result = self._request("observe", phase)
|
||||
def observe(self, phase: DialogPhase, *, pids=None) -> tuple[WindowSnapshot, ...]:
|
||||
result = self._request("observe", phase, **({'pids': sorted(pids)} if pids is not None else {}))
|
||||
return tuple(WindowSnapshot.from_record(item) for item in (result or ()))
|
||||
|
||||
def perform(self, *, hwnd: int, fingerprint: str, action: dict,
|
||||
|
||||
@@ -265,9 +265,23 @@ class WindowProbe:
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def capture(self, phase: DialogPhase) -> tuple[WindowSnapshot, ...]:
|
||||
def matches_identity(self, snapshot):
|
||||
try:
|
||||
return (self.win32gui.IsWindowVisible(snapshot.hwnd)
|
||||
and self.win32process.GetWindowThreadProcessId(snapshot.hwnd)[1] == snapshot.pid
|
||||
and self.win32gui.GetClassName(snapshot.hwnd) == snapshot.window_class)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def capture(self, phase: DialogPhase, *, pids=None) -> tuple[WindowSnapshot, ...]:
|
||||
snapshots = []
|
||||
for hwnd in self._handles():
|
||||
if pids is not None:
|
||||
try:
|
||||
if self.win32process.GetWindowThreadProcessId(hwnd)[1] not in pids:
|
||||
continue
|
||||
except Exception:
|
||||
continue
|
||||
try:
|
||||
window_class = str(self.win32gui.GetClassName(hwnd) or "")
|
||||
except Exception:
|
||||
|
||||
@@ -100,11 +100,15 @@ class DialogBackend(Protocol):
|
||||
class AgentDialogBackend:
|
||||
"""Adapt the private-desktop JSONL client to the supervisor backend."""
|
||||
|
||||
def __init__(self, client) -> None:
|
||||
def __init__(self, client, *, pids=None) -> None:
|
||||
self.client = client
|
||||
self.pids = pids
|
||||
|
||||
def observe(self, phase: DialogPhase):
|
||||
return self.client.observe(phase)
|
||||
if self.pids is None:
|
||||
return self.client.observe(phase)
|
||||
pids = set(self.pids())
|
||||
return tuple(w for w in self.client.observe(phase, pids=pids) if w.pid in pids)
|
||||
|
||||
def perform(self, snapshot: WindowSnapshot, action: dict, phase: DialogPhase) -> ActionResult:
|
||||
return self.client.perform(
|
||||
|
||||
@@ -24,15 +24,44 @@ def _command_args(command):
|
||||
kernel.LocalFree(ctypes.cast(args, wintypes.HLOCAL))
|
||||
|
||||
|
||||
def _startup_snapshot(hwnd, pcb_pid):
|
||||
import win32gui, win32process
|
||||
from .dialog_models import ControlSnapshot, DialogPhase, WindowSnapshot
|
||||
if win32process.GetWindowThreadProcessId(hwnd)[1] != pcb_pid:
|
||||
raise ValueError('STARTUP_WINDOW_OWNER_CHANGED')
|
||||
children = []
|
||||
win32gui.EnumChildWindows(hwnd, lambda child, _: children.append(child), None)
|
||||
controls = tuple(ControlSnapshot(child, win32gui.GetDlgCtrlID(child) & 0xffff,
|
||||
win32gui.GetClassName(child), win32gui.GetWindowText(child),
|
||||
enabled=bool(win32gui.IsWindowEnabled(child))) for child in children)
|
||||
return WindowSnapshot(hwnd, pcb_pid, 'ExpeditionPCB.exe', 'pcb',
|
||||
win32gui.GetClassName(hwnd), win32gui.GetWindowText(hwnd), DialogPhase.PCB_STARTING, controls)
|
||||
|
||||
|
||||
def _cancel_target(snapshot):
|
||||
from .post_repair_consent import exact_prompt
|
||||
from .dialog_rules import pcb_version_choice
|
||||
if exact_prompt(snapshot):
|
||||
return 'read_write_access', next(c for c in snapshot.controls if c.control_id == 7)
|
||||
if pcb_version_choice(snapshot) is not None:
|
||||
buttons = [c for c in snapshot.controls if c.class_name == 'Button']
|
||||
cancel = [c for c in buttons if c.control_id == 2 and c.name == 'Cancel' and c.enabled]
|
||||
if (len(cancel) == 1 and {c.control_id for c in buttons} == {6212, 6213, 6206, 1, 2}
|
||||
and any(c.control_id == 6211 and c.name == '* Cancelling will load no design.'
|
||||
for c in snapshot.controls)):
|
||||
return 'pcb_version_choice', cancel[0]
|
||||
return None
|
||||
|
||||
|
||||
def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event: None,
|
||||
timeout_seconds=20, launcher_process=None):
|
||||
"""Normally close our empty PCB after a diagnosed database startup failure.
|
||||
|
||||
No COM attach: there is no document, and the global ROT can name another
|
||||
session. Unknown windows, live database addresses and other desktops are
|
||||
retained. WM_CLOSE is cooperative; no save prompt is accepted or killed.
|
||||
No COM attach: the global ROT can name another session. Only the exact
|
||||
read/write question is declined; no ownership is taken or version restored.
|
||||
Unknown windows and documents are retained. WM_CLOSE is cooperative.
|
||||
"""
|
||||
import win32con, win32gui, win32process
|
||||
import win32api, win32con, win32gui, win32process
|
||||
from .mentor_adapter import _process_details
|
||||
from .native_repair_ui import _current_desktop_name
|
||||
from .icdb_ownership import unreleased_addresses
|
||||
@@ -43,23 +72,6 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
if launcher_process is not None:
|
||||
result['launcher_pid'] = launcher_process.pid
|
||||
try:
|
||||
diagnosed = False
|
||||
diagnosis_path = root/'diagnostics/icdb-recovery.json'
|
||||
if diagnosis_path.is_file():
|
||||
diagnosis = json.loads(diagnosis_path.read_text('utf-8'))
|
||||
diagnosed = diagnosis.get('error_code') == 'ICDB_REPAIR_REQUIRED'
|
||||
dialogs_path = root/'dialogs.jsonl'
|
||||
if not diagnosed and dialogs_path.is_file():
|
||||
for line in dialogs_path.read_text('utf-8').splitlines():
|
||||
try:
|
||||
dialog = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if (dialog.get('pid') == pcb_pid and dialog.get('phase') == 'PCB_STARTING'
|
||||
and dialog.get('error_code') == 'MENTOR_DATABASE_LOAD_FAILED'):
|
||||
diagnosed = True
|
||||
if not diagnosed:
|
||||
raise ValueError('STARTUP_FAILURE_UNCONFIRMED')
|
||||
desktop = job.get('desktop', '')
|
||||
if (job.get('interactive_input') or not desktop.startswith('CbbVerify_')
|
||||
or _current_desktop_name() != desktop):
|
||||
@@ -69,14 +81,20 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
expected = os.path.normcase(os.path.abspath(job['pcb']))
|
||||
deadline = time.monotonic() + max(0, timeout_seconds)
|
||||
sent = False
|
||||
declined_hwnd = None
|
||||
declined_kind = None
|
||||
cancelled_open = False
|
||||
while True:
|
||||
records = [r for r in _process_details('ExpeditionPCB.exe') if r[0] == pcb_pid]
|
||||
if not records:
|
||||
if declined_hwnd is not None:
|
||||
cancelled_open = True
|
||||
result['cancelled_prompt'] = declined_kind
|
||||
addresses = unreleased_addresses(job['lmc_file'], job['project'], job['pcb'])
|
||||
launcher_exited = launcher_process is None or launcher_process.poll() is not None
|
||||
result['release'] = {'pcb_exited': True, 'launcher_exited': launcher_exited,
|
||||
'addresses': addresses,
|
||||
'safe_to_continue': launcher_exited and not addresses}
|
||||
'safe_to_continue': launcher_exited and (cancelled_open or not addresses)}
|
||||
if result['release']['safe_to_continue']:
|
||||
result['status'] = 'CLOSED'
|
||||
result.pop('detail', None)
|
||||
@@ -86,19 +104,43 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
break
|
||||
time.sleep(.2)
|
||||
continue
|
||||
_, executable, command, _ = records[0]
|
||||
args = _command_args(command)
|
||||
if (Path(executable).name.casefold() != 'expeditionpcb.exe'
|
||||
or '-reusablecircuit' not in [a.casefold() for a in args]
|
||||
or expected not in [os.path.normcase(os.path.abspath(a)) for a in args[1:]]):
|
||||
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
|
||||
if not sent:
|
||||
_, executable, command, _ = records[0]
|
||||
args = _command_args(command)
|
||||
if (Path(executable).name.casefold() != 'expeditionpcb.exe'
|
||||
or '-reusablecircuit' not in [a.casefold() for a in args]
|
||||
or expected not in [os.path.normcase(os.path.abspath(a)) for a in args[1:]]):
|
||||
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
|
||||
windows = []
|
||||
def observe(hwnd, _):
|
||||
if (win32process.GetWindowThreadProcessId(hwnd)[1] == pcb_pid
|
||||
and win32gui.IsWindowVisible(hwnd)):
|
||||
windows.append(hwnd)
|
||||
win32api.SetLastError(0)
|
||||
win32gui.EnumWindows(observe, None)
|
||||
if declined_hwnd is not None and declined_hwnd not in windows:
|
||||
cancelled_open = True
|
||||
result['cancelled_prompt'] = declined_kind
|
||||
if declined_hwnd is None:
|
||||
for hwnd in windows:
|
||||
if win32gui.GetClassName(hwnd) != '#32770':
|
||||
continue
|
||||
snapshot = _startup_snapshot(hwnd, pcb_pid)
|
||||
target = _cancel_target(snapshot)
|
||||
if target is None:
|
||||
continue
|
||||
# Re-read immediately before declining; never select a version.
|
||||
current = _startup_snapshot(hwnd, pcb_pid)
|
||||
if _cancel_target(current) != target or current != snapshot:
|
||||
raise ValueError('STARTUP_CANCEL_PROMPT_CHANGED')
|
||||
declined_kind, cancel = target
|
||||
win32gui.PostMessage(cancel.handle, win32con.BM_CLICK, 0, 0)
|
||||
declined_hwnd = hwnd
|
||||
emit(stage='startup_open_declined', pcb_pid=pcb_pid, hwnd=hwnd,
|
||||
control_id=cancel.control_id, prompt=declined_kind)
|
||||
break
|
||||
if declined_hwnd is not None:
|
||||
continue
|
||||
main = [w for w in windows if win32gui.GetClassName(w).startswith('Afx:')
|
||||
and win32gui.GetWindowText(w).strip() in (
|
||||
'Expedition PCB', 'Expedition PCB - Reusable Block')
|
||||
@@ -112,6 +154,7 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
if window['class'] == 'Internet Explorer_Hidden' and window['title'] == '':
|
||||
window['rect'] = list(win32gui.GetWindowRect(window['hwnd']))
|
||||
window['children'] = []
|
||||
win32api.SetLastError(0)
|
||||
win32gui.EnumChildWindows(window['hwnd'],
|
||||
lambda hwnd, _: window['children'].append(int(hwnd)), None)
|
||||
left, top, right, bottom = window['rect']
|
||||
@@ -126,15 +169,19 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
and win32gui.GetWindow(hwnd, win32con.GW_CHILD)):
|
||||
documents.append(hwnd)
|
||||
if len(main) == 1:
|
||||
win32api.SetLastError(0)
|
||||
win32gui.EnumChildWindows(main[0], child, None)
|
||||
addresses = unreleased_addresses(job['lmc_file'], job['project'], job['pcb'])
|
||||
if len(main) == 1 and not unknown and not documents and not addresses:
|
||||
if len(main) == 1 and not unknown and not documents and (cancelled_open or not addresses):
|
||||
win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0)
|
||||
sent = True
|
||||
emit(stage='startup_close_requested', pcb_pid=pcb_pid, hwnd=main[0])
|
||||
# Observe exit even when the caller requested no extra wait.
|
||||
continue
|
||||
result['detail'] = 'STARTUP_IDLE_UNCONFIRMED: 等待空闲窗口和数据库释放'
|
||||
# After the single owned WM_CLOSE, WMI may lose the executable/
|
||||
# command fields before removing the PID. Only observe exit here;
|
||||
# never issue another close or treat missing fields as release.
|
||||
if time.monotonic() >= deadline:
|
||||
if sent:
|
||||
result['detail'] = 'STARTUP_EXIT_UNCONFIRMED: 已请求正常关闭,但 PCB 尚未退出'
|
||||
|
||||
@@ -15,17 +15,25 @@ def maintenance_counts(results):
|
||||
version_choice = sum(attempt.get('status') == 'PCB_VERSION_CHOICE_REQUIRED'
|
||||
and attempt.get('native_status') == 'REPAIRED'
|
||||
and attempt.get('validation_passed') is False for attempt in attempts)
|
||||
pending = sum(attempt.get('status') == 'REPAIRED_UNVERIFIED'
|
||||
and attempt.get('native_status') == 'REPAIRED' for attempt in attempts)
|
||||
return {'total': len(results), 'passed': sum(r.status == 'PASS' for r in results),
|
||||
'checked_without_repair': sum(r.status == 'PASS' and not r.recovery_attempts for r in results),
|
||||
'checked_without_repair': sum(r.status == 'CHECKED' for r in results),
|
||||
'issues_found': sum(r.error_category == 'ICDB_REPAIR_REQUIRED' for r in results),
|
||||
'in_use': sum(r.error_category == 'ICDB_DATABASE_IN_USE' for r in results),
|
||||
'unconfirmed': sum(r.status not in ('PASS', 'CHECKED', 'SKIPPED', 'CANCELLED')
|
||||
and r.error_category not in ('ICDB_REPAIR_REQUIRED', 'ICDB_DATABASE_IN_USE') for r in results),
|
||||
'cancelled': sum(r.status == 'CANCELLED' for r in results),
|
||||
'skipped': sum(r.status == 'SKIPPED' for r in results),
|
||||
'repaired': repaired, 'review_required': review,
|
||||
'version_choice_required': version_choice,
|
||||
'repair_unconfirmed': len(attempts)-repaired-review-version_choice}
|
||||
'repaired_unverified': pending,
|
||||
'repair_unconfirmed': len(attempts)-repaired-review-version_choice-pending}
|
||||
|
||||
|
||||
def write_maintenance_report(requests, results, batch_report, skipped_names):
|
||||
path = batch_report.with_name(batch_report.name.replace('batch-', 'icdb-', 1)).with_suffix('.json')
|
||||
record = {'operation': 'visible_non_ready_icdb_check_and_repair',
|
||||
record = {'operation': 'visible_non_ready_icdb_batch_check', 'automatic_repair': False,
|
||||
'library': str(requests[0].lmc_file), 'includes_ready': False,
|
||||
'target_names': [request.block_name for request in requests],
|
||||
'shared_database_repair_supported': False,
|
||||
|
||||
@@ -17,6 +17,37 @@ _SESSION_LOSS = re.compile(
|
||||
r'\bthe\s+last\s+server\s+session\s+on\s+different\s+server\s+machine\s+'
|
||||
r'lost\s+the\s+connection\s+to\s+the\s+database\b', re.IGNORECASE)
|
||||
|
||||
_ICDB_MESSAGE = re.compile(r'(?<![A-Za-z0-9_])icdb(?![A-Za-z0-9_.\\/])', re.I)
|
||||
_FAILURE_MESSAGE = re.compile(
|
||||
r'\b(?:error|failed|failure|unable|cannot|could\s+not|lost|corrupt(?:ed|ion)?|'
|
||||
r'inconsistent|unsupported|refused|denied)\b|失败|错误|异常|无法|损坏|失联|拒绝|未完成', re.I)
|
||||
|
||||
|
||||
def _icdb_error_paragraphs(text, *, error_message=False):
|
||||
text = str(text or '').replace('\r', '')
|
||||
for record in _session_losses(text):
|
||||
yield record['native_message'].strip()
|
||||
for paragraph in text.splitlines():
|
||||
# A pathname or our own category label is not native error content.
|
||||
message = re.sub(r'\[[^\]\n]*[\\/][^\]\n]*\]', '', paragraph)
|
||||
if _ICDB_MESSAGE.search(message) and (error_message or _FAILURE_MESSAGE.search(message)):
|
||||
yield paragraph.strip()
|
||||
|
||||
|
||||
def icdb_error_content(text, *, error_message=False):
|
||||
"""Extract failure paragraphs mentioning iCDB; codes/healthy text do not qualify."""
|
||||
return '\n\n'.join(dict.fromkeys(_icdb_error_paragraphs(text, error_message=error_message)))
|
||||
|
||||
|
||||
def read_icdb_error(path, baseline):
|
||||
"""Retain only new native error content, with the same bounded freshness rules."""
|
||||
data, appended = _read_log_delta(path, baseline)
|
||||
if not appended and (not baseline or baseline.get('truncated') or 'icdb_errors' not in baseline):
|
||||
return ''
|
||||
previous = baseline.get('icdb_errors', [])
|
||||
return '\n\n'.join(message for message in _icdb_error_paragraphs(decode_log(data))
|
||||
if appended or ' '.join(message.split()) not in previous)
|
||||
|
||||
|
||||
def parse_session_loss(text):
|
||||
"""Keep the native target verbatim; never infer a local repair target."""
|
||||
@@ -68,9 +99,10 @@ def snapshot_log(path):
|
||||
losses = [_session_identity(record) for record in _session_losses(decode_log(tail))]
|
||||
return {'size': size, 'tail_sha256': hashlib.sha256(tail).hexdigest(),
|
||||
'truncated': size > LOG_LIMIT,
|
||||
'icdb_errors': [' '.join(message.split()) for message in _icdb_error_paragraphs(decode_log(tail))],
|
||||
'session_losses': losses}
|
||||
except FileNotFoundError:
|
||||
return {'size': 0, 'tail_sha256': hashlib.sha256(b'').hexdigest()}
|
||||
return {'size': 0, 'tail_sha256': hashlib.sha256(b'').hexdigest(), 'icdb_errors': []}
|
||||
except OSError as error:
|
||||
return {'error': str(error)}
|
||||
|
||||
|
||||
@@ -17,6 +17,16 @@ class LibraryBusy(OSError):
|
||||
pass
|
||||
|
||||
|
||||
def inspect_residual_sessions(library, *, block_names=()):
|
||||
from .residual_sessions import inspect_residual_sessions as inspect
|
||||
return inspect(library, block_names=block_names)
|
||||
|
||||
|
||||
def release_residual_sessions(plan, evidence_dir, *, stop=None, force=False):
|
||||
from .residual_sessions import release_residual_sessions as release
|
||||
return release(plan, evidence_dir, stop=stop, force=force)
|
||||
|
||||
|
||||
def _key(path):
|
||||
return str(Path(path).resolve()).casefold()
|
||||
|
||||
@@ -53,38 +63,78 @@ def checkpoint_record(path):
|
||||
|
||||
def has_blocker(library):
|
||||
path = blocker_path(library)
|
||||
if path.with_suffix('.pending').exists():
|
||||
return True
|
||||
if not path.exists():
|
||||
return False
|
||||
record = checkpoint_record(path)
|
||||
# Complete snapshots retain every file, including their source lease
|
||||
# checkpoint. Only a valid relocated snapshot record can be ignored.
|
||||
return record is None or _key(record['library']) == _key(library)
|
||||
for marker in (path, path.with_suffix('.pending')):
|
||||
if marker.exists():
|
||||
record = checkpoint_record(marker)
|
||||
if record is None or _key(record['library']) == _key(library):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _persist_blocker(library, status='OWNER_RELEASE_UNCONFIRMED', *, lease_id):
|
||||
def has_retained_library(library):
|
||||
"""Include leases retained without a JSON checkpoint, such as PCB checks."""
|
||||
path = Path(library).resolve()
|
||||
key = _key(path.with_name('.' + path.stem + '.cbb-upload.lock'))
|
||||
with _guard:
|
||||
owner = _owners.get(key)
|
||||
return bool(owner and owner['retained'])
|
||||
|
||||
|
||||
def recheck_previous_release(library, evidence_dir, *, block_name=None, required=False, progress=None):
|
||||
"""Historical records trigger fresh proof, never process termination or repair."""
|
||||
if not (required or has_blocker(library) or has_retained_library(library)):
|
||||
return None
|
||||
def notify(stage, **details):
|
||||
if progress is not None:
|
||||
try:
|
||||
progress({'stage': stage, 'block': block_name or '', **details})
|
||||
except Exception:
|
||||
import logging
|
||||
logging.getLogger(__name__).warning('Release progress observer failed', exc_info=True)
|
||||
notify('previous_release_check', detail='正在复核历史记录对应的实际占用')
|
||||
try:
|
||||
proof = release_retained_library(library, evidence_dir, block_name=block_name)
|
||||
except Exception as error:
|
||||
notify('previous_release_unconfirmed', detail=str(error))
|
||||
raise
|
||||
notify('previous_release_confirmed', release_proof=proof,
|
||||
detail='已确认会话释放并归档历史记录;这不表示历史数据已恢复')
|
||||
return proof
|
||||
|
||||
|
||||
def _persist_blocker(library, status='OWNER_RELEASE_UNCONFIRMED', *, lease_id, block_name=None):
|
||||
import win32api, win32process
|
||||
path = blocker_path(library)
|
||||
pending = path.with_suffix('.pending')
|
||||
previous = checkpoint_record(path)
|
||||
export_record = ({'export_analysis': previous['export_analysis']}
|
||||
if previous and previous['lease_id'] == lease_id and 'export_analysis' in previous else {})
|
||||
if block_name is not None:
|
||||
export_record['block_name'] = block_name
|
||||
elif previous and previous['lease_id'] == lease_id and 'block_name' in previous:
|
||||
export_record['block_name'] = previous['block_name']
|
||||
with pending.open('w', encoding='utf-8') as stream:
|
||||
json.dump({**export_record, 'protocol': 'cbb-refresh-verify-library-lease', 'version': 1,
|
||||
'lease_id': lease_id, 'library': str(library), 'status': status,
|
||||
'machine': socket.gethostname(),
|
||||
'supervisor_created': win32process.GetProcessTimes(win32api.GetCurrentProcess())['CreationTime'].isoformat(),
|
||||
'pid': os.getpid(), 'time': datetime.now(timezone.utc).isoformat()}, stream)
|
||||
stream.flush(); os.fsync(stream.fileno())
|
||||
pending.replace(path)
|
||||
|
||||
|
||||
class LibraryLock:
|
||||
def __init__(self, library, *, safe_to_release=None):
|
||||
def __init__(self, library, *, safe_to_release=None, checkpoint=True, block_name=None):
|
||||
library = Path(library).resolve()
|
||||
self.library = library
|
||||
self.path = library.with_name('.' + library.stem + '.cbb-upload.lock')
|
||||
self.key = _key(self.path)
|
||||
self.entered = False
|
||||
self.safe_to_release = safe_to_release
|
||||
self.checkpoint = checkpoint
|
||||
self.block_name = block_name
|
||||
self.maintenance_guard = None
|
||||
self.maintenance_mutex = None
|
||||
|
||||
@@ -96,6 +146,24 @@ class LibraryLock:
|
||||
return lease
|
||||
|
||||
def __enter__(self):
|
||||
with _guard:
|
||||
owner = _owners.get(self.key)
|
||||
if owner and owner['retained'] and owner['depth'] == 0 and owner.get('release_probe'):
|
||||
try:
|
||||
released = owner['release_probe']() is True
|
||||
except Exception:
|
||||
released = False
|
||||
if released:
|
||||
if owner.get('checkpoint', True):
|
||||
marker = blocker_path(self.library)
|
||||
record = checkpoint_record(marker)
|
||||
if (record is None or record['lease_id'] != owner['lease_id']
|
||||
or 'export_analysis' in record or marker.with_suffix('.pending').exists()):
|
||||
raise LibraryBusy('协调检查点身份或导出会话尚未确认,保持库锁。')
|
||||
marker.unlink()
|
||||
owner['handle'].Close()
|
||||
del _owners[self.key]
|
||||
owner = None
|
||||
if self.maintenance_guard is not None:
|
||||
return _enter_maintenance(self)
|
||||
import win32con, win32file
|
||||
@@ -106,7 +174,7 @@ class LibraryLock:
|
||||
raise LibraryBusy(f'中心库被其他任务占用:{self.path}')
|
||||
owner['depth'] += 1
|
||||
else:
|
||||
if has_blocker(self.library):
|
||||
if self.checkpoint and has_blocker(self.library):
|
||||
raise LibraryBusy(f'中心库存在未解除的会话阻止记录,请先执行释放检查:{blocker_path(self.library)}')
|
||||
try:
|
||||
lease_id = uuid4().hex
|
||||
@@ -114,6 +182,8 @@ class LibraryLock:
|
||||
win32con.GENERIC_READ | win32con.GENERIC_WRITE, 0, None,
|
||||
win32con.OPEN_ALWAYS, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
||||
except Exception as error:
|
||||
if getattr(error, 'winerror', None) not in (32, 33):
|
||||
raise
|
||||
raise LibraryBusy(f'中心库已锁定或无法创建协调锁:{self.path}: {error}') from error
|
||||
try:
|
||||
data = (f'machine={socket.gethostname()}; pid={os.getpid()}; '
|
||||
@@ -127,12 +197,17 @@ class LibraryLock:
|
||||
# it explicitly before complete-copy metadata is captured.
|
||||
import pywintypes
|
||||
win32file.SetFileTime(handle, None, None, pywintypes.Time(datetime.now()))
|
||||
_persist_blocker(self.library, 'OPERATION_IN_PROGRESS', lease_id=lease_id)
|
||||
if self.checkpoint:
|
||||
_persist_blocker(self.library, 'OPERATION_IN_PROGRESS', lease_id=lease_id,
|
||||
block_name=self.block_name)
|
||||
except Exception:
|
||||
handle.Close()
|
||||
raise
|
||||
_owners[self.key] = {'thread': threading.get_ident(), 'depth': 1,
|
||||
'handle': handle, 'retained': False, 'lease_id': lease_id}
|
||||
'handle': handle, 'retained': False, 'lease_id': lease_id,
|
||||
'checkpoint': self.checkpoint,
|
||||
'block_name': self.block_name,
|
||||
'release_probe': self.safe_to_release}
|
||||
self.entered = True
|
||||
return self
|
||||
|
||||
@@ -162,6 +237,20 @@ class LibraryLock:
|
||||
if not self.entered:
|
||||
return
|
||||
owner = _owners[self.key]
|
||||
if not owner.get('checkpoint', True):
|
||||
if self.safe_to_release is not None:
|
||||
try:
|
||||
released = self.safe_to_release() is True
|
||||
except Exception:
|
||||
released = False
|
||||
if not released:
|
||||
owner['retained'] = True
|
||||
owner['depth'] -= 1
|
||||
self.entered = False
|
||||
if owner['depth'] == 0 and not owner['retained']:
|
||||
owner['handle'].Close()
|
||||
del _owners[self.key]
|
||||
return
|
||||
checkpoint = checkpoint_record(blocker_path(self.library))
|
||||
if checkpoint is not None and 'export_analysis' in checkpoint:
|
||||
owner['retained'] = True
|
||||
@@ -212,6 +301,67 @@ def _supervisor_alive(pid):
|
||||
handle.Close()
|
||||
|
||||
|
||||
def _recorded_supervisor_alive(record):
|
||||
"""None means legacy/unknown identity; the native/file guard still applies."""
|
||||
if record.get('machine') != socket.gethostname() or not record.get('supervisor_created'):
|
||||
return None
|
||||
import pywintypes, win32api, win32con, win32process
|
||||
try:
|
||||
handle = win32api.OpenProcess(win32con.SYNCHRONIZE | 0x1000, False, record['pid'])
|
||||
except pywintypes.error as error:
|
||||
return False if error.winerror == 87 else None
|
||||
try:
|
||||
return (win32process.GetProcessTimes(handle)['CreationTime'].isoformat() == record['supervisor_created']
|
||||
and _supervisor_alive(record['pid']))
|
||||
finally:
|
||||
handle.Close()
|
||||
|
||||
|
||||
def _owner_matches_scope(item, library, roots):
|
||||
"""False requires an explicit other project; a missing path stays unknown."""
|
||||
import ntpath
|
||||
from .failed_session import _command_args
|
||||
command = str(item.get('command') or '')
|
||||
if not command:
|
||||
return None
|
||||
try:
|
||||
args = _command_args(command)
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
candidates = []
|
||||
worker_flags = {'--verify-worker', '--repair-worker', '--management-worker', '--native-backup-worker'}
|
||||
for index, arg in enumerate(args[1:], 1):
|
||||
if arg.casefold() in worker_flags and index + 1 < len(args):
|
||||
try:
|
||||
request = Path(args[index + 1])
|
||||
if request.stat().st_size > 1024 * 1024:
|
||||
return None
|
||||
record = json.loads(request.read_text(encoding='utf-8'))
|
||||
for key in ('library', 'lmc_file', 'project', 'database'):
|
||||
if isinstance(record.get(key), str):
|
||||
candidates.append(record[key])
|
||||
except (OSError, ValueError, TypeError, AttributeError):
|
||||
return None
|
||||
value = arg.split('=', 1)[1] if arg.startswith('-') and '=' in arg else arg
|
||||
if (ntpath.isabs(value) and (ntpath.splitext(value)[1].casefold() in ('.prj', '.pcb', '.lmc')
|
||||
or arg.casefold().startswith(('-project=', '-icdb='))
|
||||
or args[index - 1].casefold() in ('-icdb', '-project', '-p'))):
|
||||
candidates.append(value)
|
||||
normalized_roots = [ntpath.normcase(ntpath.normpath(str(root))) for root in roots]
|
||||
expected_library = ntpath.normcase(ntpath.normpath(str(library)))
|
||||
for candidate in candidates:
|
||||
path = ntpath.normcase(ntpath.normpath(candidate))
|
||||
if path == expected_library:
|
||||
return True
|
||||
for root in normalized_roots:
|
||||
try:
|
||||
if ntpath.commonpath((path, root)) == root:
|
||||
return True
|
||||
except ValueError:
|
||||
pass
|
||||
return False if candidates else None
|
||||
|
||||
|
||||
def _enter_maintenance(lease):
|
||||
"""Transfer only a valid known lease, after project admission under lock."""
|
||||
import win32con, win32event, win32file
|
||||
@@ -237,13 +387,16 @@ def _enter_maintenance(lease):
|
||||
raise LibraryBusy('本进程库锁仍在使用或检查点身份不符')
|
||||
handle = existing['handle']
|
||||
else:
|
||||
if record is not None and _supervisor_alive(record['pid']):
|
||||
if record is not None and record['pid'] != os.getpid() and _recorded_supervisor_alive(record) is True:
|
||||
raise LibraryBusy('原监督进程仍存在,不能接续其库锁')
|
||||
handle = win32file.CreateFile(str(lease.path), win32con.GENERIC_READ | win32con.GENERIC_WRITE,
|
||||
0, None, win32con.OPEN_ALWAYS, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
||||
# All target/process/address/exclusive-file checks finish BEFORE
|
||||
# any old checkpoint replacement. Keep the exact sidecar open.
|
||||
from .native_export_guard import prove_export_copies_released
|
||||
if record is not None and _recorded_supervisor_alive(record) is None:
|
||||
from .maintenance_entry import assert_native_idle
|
||||
assert_native_idle()
|
||||
with prove_export_copies_released(lease.library), lease.maintenance_guard() as proof:
|
||||
if (marker.read_bytes() if marker.exists() else None) != old:
|
||||
raise LibraryBusy('维护检查期间检查点变化')
|
||||
@@ -256,7 +409,8 @@ def _enter_maintenance(lease):
|
||||
lease_id = uuid4().hex
|
||||
_persist_blocker(lease.library, 'OPERATION_IN_PROGRESS', lease_id=lease_id)
|
||||
_owners[lease.key] = {'thread': threading.get_ident(), 'depth': 1, 'handle': handle,
|
||||
'retained': False, 'lease_id': lease_id}
|
||||
'retained': False, 'lease_id': lease_id, 'checkpoint': True,
|
||||
'release_probe': lease.safe_to_release, 'block_name': None}
|
||||
lease.maintenance_proof = proof
|
||||
lease.entered = True
|
||||
lease.maintenance_mutex = mutex
|
||||
@@ -286,50 +440,88 @@ def owned_snapshot(path):
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _prove_library_released(library):
|
||||
def _prove_library_released(library, block_name=None, *, allow_unknown_checkpoint=False):
|
||||
"""Hold all native database read handles during explicit lease release."""
|
||||
import pythoncom, win32com.client, win32con, win32file
|
||||
import stat
|
||||
import win32con, win32file
|
||||
from .owner_probe import query_owners
|
||||
from .scoped_manifest import scan_tree
|
||||
from .native_management import _retained_workers
|
||||
from .native_export_guard import assert_retained_exports_idle, prove_export_copies_released
|
||||
from .native_engineering_identity import _OWNER_NAMES
|
||||
assert_retained_exports_idle()
|
||||
if any(worker.poll() is None for worker in _retained_workers):
|
||||
library = Path(library).resolve()
|
||||
assert_retained_exports_idle(library)
|
||||
if any(worker.poll() is None and (allow_unknown_checkpoint
|
||||
or not getattr(worker, 'cbb_library', None) or _key(worker.cbb_library) == _key(library))
|
||||
for worker in _retained_workers):
|
||||
raise LibraryBusy('原生管理工作进程尚未返回,不能解除协调阻止。')
|
||||
from .com_runtime import initialize_com, uninitialize_com
|
||||
initialized = initialize_com()
|
||||
try:
|
||||
service = win32com.client.GetObject('winmgmts:')
|
||||
names = ('LibraryManager.exe', 'ExpeditionPCB.exe', 'viewdraw.exe',
|
||||
'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe', 'CleanWGLib.exe', *sorted(_OWNER_NAMES))
|
||||
query = 'SELECT ProcessId, Name FROM Win32_Process WHERE ' + ' OR '.join(
|
||||
f"Name='{name}'" for name in names)
|
||||
owners = [{'pid': int(item.ProcessId), 'name': str(item.Name)} for item in service.ExecQuery(query)]
|
||||
service = None
|
||||
if owners:
|
||||
raise LibraryBusy(f'原生进程仍存在,不能解除协调阻止:{owners}')
|
||||
entries = scan_tree(Path(library).parent)
|
||||
addresses = [str(path) for path in entries if path.name.casefold() == 'saddress.adr']
|
||||
'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe', 'CleanWGLib.exe',
|
||||
'cscript.exe', 'wscript.exe', 'python.exe', 'pythonw.exe',
|
||||
'CbbRefreshVerify.exe', *sorted(_OWNER_NAMES))
|
||||
scope_root = (Path(library).resolve().parent/'ReusableBlocksLP'/block_name/'Work').resolve() if block_name else None
|
||||
shared_root = Path(library).resolve().parent/'SymbolLibs'
|
||||
if allow_unknown_checkpoint and scope_root is not None:
|
||||
raise LibraryBusy('未知检查点必须执行完整库释放证明。')
|
||||
def check_owners():
|
||||
owners = []
|
||||
for item in query_owners(names):
|
||||
if item['pid'] == os.getpid():
|
||||
continue
|
||||
if not allow_unknown_checkpoint:
|
||||
roots = (scope_root, shared_root) if scope_root is not None else (Path(library).parent,)
|
||||
if _owner_matches_scope(item, library, roots) is False:
|
||||
continue
|
||||
automation = item['name'].casefold() in ('python.exe', 'pythonw.exe', 'cbbrefreshverify.exe')
|
||||
command = item['command'].casefold()
|
||||
if not automation or not command or any(flag in command for flag in (
|
||||
'--verify-worker', '--repair-worker', '--management-worker', '--native-backup-worker')):
|
||||
owners.append(item)
|
||||
if owners:
|
||||
raise LibraryBusy(f'原生进程仍存在,不能解除协调阻止:{owners}')
|
||||
return owners
|
||||
check_owners()
|
||||
if scope_root is None:
|
||||
entries = scan_tree(Path(library).parent)
|
||||
else:
|
||||
entries = {Path(library): Path(library).lstat()}
|
||||
for root in (scope_root, shared_root):
|
||||
if root.exists():
|
||||
entries.update(scan_tree(root))
|
||||
addresses = [str(path) for path in entries if path.name.casefold() == 'saddress.adr'
|
||||
and (scope_root is None or path.is_relative_to(scope_root)
|
||||
or path.is_relative_to(shared_root))]
|
||||
if addresses:
|
||||
raise LibraryBusy(f'库中仍有数据库地址记录,不能自动解除:{addresses}')
|
||||
native = [path for path in entries if path.is_file()
|
||||
and (path.suffix.casefold() == '.lmc' or path.name.casefold() in ('icdb.dat', 'layoutdb.lyt'))]
|
||||
if Path(library).resolve() not in native:
|
||||
# scan_tree already rejects links; only native candidates need file opens.
|
||||
native = [path for path, metadata in entries.items() if stat.S_ISREG(metadata.st_mode) and (
|
||||
path == library
|
||||
or (path.name.casefold() in ('icdb.dat', 'layoutdb.lyt')
|
||||
and (scope_root is None or path.is_relative_to(scope_root)
|
||||
or path.is_relative_to(shared_root))))]
|
||||
if library not in native:
|
||||
raise LibraryBusy('目标库身份缺失,不能解除协调阻止。')
|
||||
with ExitStack() as stack:
|
||||
export_copies = stack.enter_context(prove_export_copies_released(library))
|
||||
export_proof = (prove_export_copies_released(library, allow_unknown_checkpoint=True)
|
||||
if allow_unknown_checkpoint else prove_export_copies_released(library))
|
||||
export_copies = stack.enter_context(export_proof)
|
||||
for path in native:
|
||||
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
|
||||
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
||||
stack.callback(handle.Close)
|
||||
owners = check_owners()
|
||||
yield {'native_owners': owners, 'addresses': addresses, 'export_copies': export_copies,
|
||||
'unknown_checkpoint_recovery': allow_unknown_checkpoint,
|
||||
'exclusive_files': [str(path) for path in native]}
|
||||
finally:
|
||||
uninitialize_com(initialized)
|
||||
|
||||
|
||||
def release_retained_library(library, evidence_dir):
|
||||
"""Explicit user-requested release, after fresh owner/address/access proof.
|
||||
def release_retained_library(library, evidence_dir, *, block_name=None):
|
||||
"""Reconcile historical leases after fresh owner/address/access proof.
|
||||
|
||||
The upload sidecar is never deleted. This acknowledges process release,
|
||||
not the correctness of a partially changed library or its recovery state.
|
||||
@@ -357,15 +549,41 @@ def release_retained_library(library, evidence_dir):
|
||||
win32con.GENERIC_READ | win32con.GENERIC_WRITE, 0, None,
|
||||
win32con.OPEN_ALWAYS, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
||||
except Exception as error:
|
||||
if getattr(error, 'winerror', None) not in (32, 33):
|
||||
raise
|
||||
raise LibraryBusy('其他进程仍持有库锁,不能解除。') from error
|
||||
with _prove_library_released(library) as proof:
|
||||
marker = blocker_path(library)
|
||||
checkpoints = (marker, marker.with_suffix('.pending'))
|
||||
if any(path.exists() and checkpoint_record(path) is None for path in checkpoints):
|
||||
raise LibraryBusy('协调检查点格式不明或已损坏,保留原文件供人工审查。')
|
||||
marker = blocker_path(library)
|
||||
checkpoints = (marker, marker.with_suffix('.pending'))
|
||||
before = {path: path.read_bytes() if path.exists() else None for path in checkpoints}
|
||||
unknown = any(data is not None and checkpoint_record(path) is None for path, data in before.items())
|
||||
records = [checkpoint_record(path) for path, data in before.items() if data is not None]
|
||||
scoped = (block_name if block_name and all(record and record.get('block_name') == block_name
|
||||
for record in records) and (owner is None or owner.get('block_name') == block_name) else None)
|
||||
reconciled = [{'kind': 'checkpoint', 'path': str(path), 'recognized': metadata is not None,
|
||||
**{key: (metadata or {}).get(key) for key in ('block_name', 'lease_id', 'pid', 'status', 'time')}}
|
||||
for path, data in before.items() if data is not None
|
||||
for metadata in (checkpoint_record(path),)]
|
||||
if owner:
|
||||
reconciled.append({'kind': 'retained_owner', 'path': str(lease.path),
|
||||
'block_name': owner.get('block_name'), 'lease_id': owner['lease_id'],
|
||||
'status': 'OWNER_RELEASE_UNCONFIRMED'})
|
||||
foreign = sorted({item['block_name'] for item in reconciled
|
||||
if block_name and item.get('block_name') and item['block_name'] != block_name})
|
||||
proof_context = (_prove_library_released(library, allow_unknown_checkpoint=True) if unknown else
|
||||
_prove_library_released(library, block_name=scoped)
|
||||
if scoped else _prove_library_released(library))
|
||||
with proof_context as proof:
|
||||
if unknown and proof.get('unknown_checkpoint_recovery') is not True:
|
||||
raise LibraryBusy('未知检查点缺少完整库释放证明,保留原文件。')
|
||||
if any((path.read_bytes() if path.exists() else None) != data for path, data in before.items()):
|
||||
raise LibraryBusy('释放检查期间协调检查点变化,保留原文件。')
|
||||
root = evidence/('release-' + uuid4().hex)
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
record = {'library': str(library), 'status': 'RELEASE_CONFIRMED', **proof,
|
||||
'requested_block_name': block_name, 'proof_scope': 'BLOCK' if scoped else 'LIBRARY',
|
||||
'proof_block_name': scoped, 'reconciled_checkpoints': reconciled,
|
||||
'reconciled_foreign_blockers': foreign,
|
||||
'unknown_checkpoint_archived': unknown,
|
||||
'data_recovery_confirmed': False, 'evidence_path': str(root/'release.json')}
|
||||
(root/'release.json').write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
for index, checkpoint in enumerate(checkpoints):
|
||||
|
||||
@@ -9,37 +9,62 @@ import json
|
||||
import os
|
||||
from pathlib import Path, PureWindowsPath
|
||||
import re
|
||||
import stat
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
def assert_native_idle():
|
||||
import win32com.client
|
||||
def assert_native_idle(target=None):
|
||||
from .owner_probe import query_owners
|
||||
from .native_management import _retained_workers
|
||||
from .native_export_guard import assert_retained_exports_idle
|
||||
from .native_engineering_identity import _OWNER_NAMES
|
||||
assert_retained_exports_idle()
|
||||
if any(worker.poll() is None for worker in _retained_workers):
|
||||
from .library_lock import _key, _owner_matches_scope
|
||||
library = None
|
||||
roots = ()
|
||||
if target is not None:
|
||||
from .backup_recovery import _project_text
|
||||
roots = (Path(target.project).parent, Path(target.database))
|
||||
try:
|
||||
lines = re.findall(r'^KEY CentralLibrary\b[^\r\n]*', _project_text(target.project), re.M)
|
||||
references = [re.fullmatch(r'KEY CentralLibrary "([^"\r\n]+)"\s*', line) for line in lines]
|
||||
if not references or any(match is None for match in references):
|
||||
raise ValueError('CentralLibrary references are missing or invalid.')
|
||||
libraries = {(Path(target.project).parent/match[1]).resolve(strict=True) for match in references}
|
||||
if len(libraries) == 1 and all(path.suffix.casefold() == '.lmc' and path.is_file() for path in libraries):
|
||||
library = libraries.pop()
|
||||
roots += (library.parent/'SymbolLibs',)
|
||||
except (OSError, ValueError):
|
||||
pass # Missing/ambiguous original references cannot narrow retained ownership.
|
||||
assert_retained_exports_idle(library)
|
||||
if any(worker.poll() is None and (library is None or not getattr(worker, 'cbb_library', None)
|
||||
or _key(worker.cbb_library) == _key(library)) for worker in _retained_workers):
|
||||
raise ValueError('MAINTENANCE_OWNER_ACTIVE: 管理工作进程尚未返回')
|
||||
names = ('ExpeditionPCB.exe', 'LibraryManager.exe', 'viewdraw.exe', 'iCDBProjectBackup.exe',
|
||||
'ReuseBlockImporter.exe', 'CleanWGLib.exe', 'cscript.exe', 'wscript.exe',
|
||||
'python.exe', 'pythonw.exe', 'CbbRefreshVerify.exe', *sorted(_OWNER_NAMES))
|
||||
service = win32com.client.GetObject('winmgmts:')
|
||||
query = 'SELECT ProcessId, Name, CommandLine FROM Win32_Process WHERE ' + ' OR '.join(
|
||||
f"Name='{name}'" for name in names)
|
||||
owners = []
|
||||
for item in service.ExecQuery(query):
|
||||
if int(item.ProcessId) == os.getpid():
|
||||
for item in query_owners(names):
|
||||
if item['pid'] == os.getpid():
|
||||
continue
|
||||
name, command = str(item.Name).casefold(), str(item.CommandLine or '').casefold()
|
||||
name, command = item['name'].casefold(), item['command'].casefold()
|
||||
automation = name in ('python.exe', 'pythonw.exe', 'cbbrefreshverify.exe')
|
||||
if not automation or not command or any(flag in command for flag in (
|
||||
'--verify-worker', '--repair-worker', '--management-worker')):
|
||||
owners.append({'pid': int(item.ProcessId), 'name': str(item.Name),
|
||||
'command': str(item.CommandLine or '')})
|
||||
'--verify-worker', '--repair-worker', '--management-worker', '--native-backup-worker')):
|
||||
owners.append(item)
|
||||
if target is not None:
|
||||
owners = [item for item in owners if _owner_matches_scope(item, library, roots) is not False]
|
||||
if owners:
|
||||
raise ValueError(f'MAINTENANCE_OWNER_ACTIVE: 请正常关闭原生程序/操作助手:{owners}')
|
||||
|
||||
|
||||
def _assert_native_idle_for(target):
|
||||
"""Keep test/third-party zero-argument idle probes compatible."""
|
||||
import inspect
|
||||
if not inspect.signature(assert_native_idle).parameters:
|
||||
return assert_native_idle()
|
||||
return assert_native_idle(target)
|
||||
|
||||
|
||||
def address_snapshot(paths):
|
||||
from .scoped_manifest import hash_file
|
||||
return {str(path.resolve()): {'sha256': hash_file(path), 'size': path.stat().st_size,
|
||||
@@ -47,11 +72,32 @@ def address_snapshot(paths):
|
||||
for path in paths}
|
||||
|
||||
|
||||
def _scoped_addresses(request):
|
||||
def maintenance_entries(request, *, check=None):
|
||||
from .verify_runner import preflight
|
||||
from .scoped_manifest import scan_tree
|
||||
project, _ = preflight(request)
|
||||
root = Path(request.lmc_file).parent
|
||||
entries = scan_tree(project.parent, check=check)
|
||||
shared = root/'SymbolLibs/__ReusableBlocksSymb'
|
||||
if shared.exists():
|
||||
entries.update(scan_tree(shared, check=check))
|
||||
for library in root.glob('*.lmc'):
|
||||
info = library.lstat()
|
||||
if (info.st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT
|
||||
or not stat.S_ISREG(info.st_mode)):
|
||||
raise ValueError(f'不支持通过文件链接维护:{library}')
|
||||
entries[library] = info
|
||||
return entries
|
||||
|
||||
|
||||
def _scoped_addresses(request, *, check=None, entries=None):
|
||||
from .scoped_manifest import scan_tree
|
||||
root = Path(request.lmc_file).parent
|
||||
addresses = []
|
||||
for path in scan_tree(root):
|
||||
if entries is None:
|
||||
entries = maintenance_entries(request, check=check)
|
||||
if check is not None: check()
|
||||
for path in entries:
|
||||
if path.name.casefold() != 'saddress.adr':
|
||||
continue
|
||||
parts = tuple(part.casefold() for part in path.relative_to(root).parts)
|
||||
@@ -85,7 +131,7 @@ def maintenance_project_files(project, pcb):
|
||||
return (project,)
|
||||
|
||||
|
||||
def select_maintenance_target(request):
|
||||
def select_maintenance_target(request, *, check=None, entries=None):
|
||||
from .verify_runner import preflight
|
||||
from .backup_recovery import _project_text
|
||||
from .native_repair import RepairTarget
|
||||
@@ -93,7 +139,8 @@ def select_maintenance_target(request):
|
||||
if request.maintenance is not True:
|
||||
raise ValueError('MAINTENANCE_INTENT_REQUIRED')
|
||||
project, pcb = preflight(request)
|
||||
scan_tree(project.parent)
|
||||
if entries is None:
|
||||
entries = maintenance_entries(request, check=check)
|
||||
candidates = []
|
||||
for candidate in maintenance_project_files(project, pcb):
|
||||
if not candidate.is_file():
|
||||
@@ -113,7 +160,7 @@ def select_maintenance_target(request):
|
||||
if not (database/'icdb.dat').is_file():
|
||||
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED: 缺少 icdb.dat')
|
||||
candidates.append(RepairTarget(candidate, candidate.parent/'database'))
|
||||
addresses = _scoped_addresses(request)
|
||||
addresses = _scoped_addresses(request, check=check, entries=entries)
|
||||
if not addresses:
|
||||
# A crashed project may retain its internal open state after the server
|
||||
# advertisement disappears. Explicit maintenance must still inspect it.
|
||||
@@ -133,11 +180,19 @@ def select_maintenance_target(request):
|
||||
|
||||
|
||||
@contextmanager
|
||||
def maintenance_target_guard(request, expected=None):
|
||||
def maintenance_target_guard(request, expected=None, *, stop=None):
|
||||
"""Simultaneously hold native database files, preserving every address."""
|
||||
import win32con, win32file
|
||||
from .scoped_manifest import scan_tree, hash_file
|
||||
target, project, pcb, addresses = select_maintenance_target(request)
|
||||
def check():
|
||||
if stop is not None and stop.is_set():
|
||||
raise ValueError('MAINTENANCE_CANCELLED: 已取消占用检查')
|
||||
check()
|
||||
library_root = Path(request.lmc_file).parent
|
||||
# Share one complete snapshot for target/address selection and file locks.
|
||||
# Refresh it again while the handles are held; do not reuse across guards.
|
||||
entries = maintenance_entries(request, check=check)
|
||||
target, project, pcb, addresses = select_maintenance_target(request, check=check, entries=entries)
|
||||
baseline = address_snapshot(addresses)
|
||||
context = {'library': str(Path(request.lmc_file).resolve()), 'block': request.block_name,
|
||||
'project': str(target.project.resolve()), 'database': str(target.database.resolve()),
|
||||
@@ -146,40 +201,147 @@ def maintenance_target_guard(request, expected=None):
|
||||
for p in (pcb, *maintenance_project_files(project, pcb))}}
|
||||
if expected is not None and context != expected:
|
||||
raise ValueError('MAINTENANCE_SOURCE_CHANGED: 目标或地址记录在检查后变化')
|
||||
assert_native_idle()
|
||||
entries = scan_tree(Path(request.lmc_file).parent)
|
||||
files = [path for path in entries if path.is_file() and (
|
||||
path.suffix.casefold() == '.lmc' or path.name.casefold() in ('icdb.dat', 'layoutdb.lyt'))]
|
||||
_assert_native_idle_for(target)
|
||||
check()
|
||||
def native_files(snapshot):
|
||||
return {path for path, info in snapshot.items() if stat.S_ISREG(info.st_mode) and (
|
||||
path.suffix.casefold() == '.lmc' or path.name.casefold() in ('icdb.dat', 'layoutdb.lyt'))}
|
||||
files = native_files(entries)
|
||||
with ExitStack() as stack:
|
||||
for path in files:
|
||||
for path in sorted(files):
|
||||
check()
|
||||
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
|
||||
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
||||
stack.callback(handle.Close)
|
||||
assert_native_idle()
|
||||
current_addresses = _scoped_addresses(request)
|
||||
_assert_native_idle_for(target)
|
||||
current = maintenance_entries(request, check=check)
|
||||
if native_files(current) != files:
|
||||
raise ValueError('MAINTENANCE_SOURCE_CHANGED: 检查期间库文件集合发生变化')
|
||||
current_addresses = _scoped_addresses(request, check=check, entries=current)
|
||||
if address_snapshot(current_addresses) != baseline:
|
||||
raise ValueError('MAINTENANCE_SOURCE_CHANGED: 地址记录在检查期间变化')
|
||||
yield {'target': target, 'context': context, 'project': project, 'pcb': pcb}
|
||||
|
||||
|
||||
def maintenance_needed(request):
|
||||
# An explicit maintenance request must reach native inspection even when
|
||||
# no address/checkpoint remains. Selection and ownership are guarded later.
|
||||
if request.maintenance is True:
|
||||
return True
|
||||
from .library_lock import has_blocker
|
||||
from .icdb_ownership import unreleased_addresses
|
||||
from .verify_runner import preflight
|
||||
if has_blocker(request.lmc_file):
|
||||
return True
|
||||
project, pcb = preflight(request)
|
||||
return bool(unreleased_addresses(request.lmc_file, project, pcb))
|
||||
def run_icdb_check(request, *, progress=None, stop=None):
|
||||
"""Open PCB diagnostically and classify this attempt's native error content."""
|
||||
from .verify_runner import VerifyResult, run_verify
|
||||
from .icdb_recovery import icdb_error_content
|
||||
root = Path(request.evidence_dir).resolve()/('icdb-check-'+uuid4().hex[:12])
|
||||
library_root = Path(request.lmc_file).resolve().parent
|
||||
if root.is_relative_to(library_root) or library_root.is_relative_to(root):
|
||||
return VerifyResult('FAIL', error_category='ICDB_INSPECTION_UNCONFIRMED',
|
||||
stderr='检查记录目录需位于中心库之外。')
|
||||
record = {'operation': 'icdb_batch_check', 'automatic_repair': False,
|
||||
'library': str(request.lmc_file), 'block': request.block_name}
|
||||
started = False
|
||||
def save(result):
|
||||
report = root/'result.json'
|
||||
recorded = replace(result, evidence_path=report)
|
||||
try:
|
||||
report.write_text(json.dumps({**record, 'result': asdict(recorded)},
|
||||
ensure_ascii=False, default=str, indent=2), encoding='utf-8')
|
||||
except OSError as error:
|
||||
import logging
|
||||
logging.getLogger(__name__).warning('icdb_check_report_unavailable path=%s error=%s', report, error)
|
||||
return result
|
||||
return recorded
|
||||
try:
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
if stop is not None and stop.is_set():
|
||||
return save(VerifyResult('CANCELLED', stderr='已取消 ICDB 检查。'))
|
||||
if progress:
|
||||
progress({'stage': 'icdb_startup_check', 'block': request.block_name,
|
||||
'detail': '正在打开工程并检查本次错误信息'})
|
||||
started = True
|
||||
startup = run_verify(replace(request, maintenance=False, auto_repair=False,
|
||||
diagnostic_only=True, native_lm_verify=False, post_repair_proof=None,
|
||||
evidence_dir=root/'pcb-open'), progress=progress, stop=stop)
|
||||
record['native_open'] = asdict(startup)
|
||||
if startup.status == 'CANCELLED' or stop is not None and stop.is_set():
|
||||
return save(replace(startup, status='CANCELLED', recovery_attempts=()))
|
||||
if startup.status == 'PASS' and startup.safe_to_continue:
|
||||
return save(replace(startup, status='CHECKED', library_flag='UNKNOWN',
|
||||
stdout='工程打开正常,未发现 ICDB 错误;未执行 CBB 校验。', recovery_attempts=()))
|
||||
content = icdb_error_content(startup.stderr, error_message=True)
|
||||
if (startup.evidence_path
|
||||
and startup.evidence_path.resolve().is_relative_to(root/'pcb-open')):
|
||||
try:
|
||||
saved = json.loads(startup.evidence_path.with_name('diagnostics').joinpath(
|
||||
'icdb-error-content.json').read_text('utf-8'))
|
||||
native = icdb_error_content(saved.get('native_message', ''))
|
||||
if native:
|
||||
content = '\n'.join(dict.fromkeys(filter(None, (content, native))))
|
||||
record['native_error'] = saved
|
||||
except (OSError, ValueError, AttributeError):
|
||||
pass
|
||||
if content:
|
||||
return save(replace(startup, status='FAIL', library_flag='UNKNOWN',
|
||||
error_category='ICDB_REPAIR_REQUIRED',
|
||||
stderr='发现 ICDB 错误,未执行修复。\n'+content, recovery_attempts=()))
|
||||
category = startup.error_category
|
||||
if not category or category.startswith('ICDB_'):
|
||||
category = 'ICDB_INSPECTION_UNCONFIRMED'
|
||||
return save(replace(startup, status='FAIL' if startup.status=='PASS' else startup.status,
|
||||
error_category=category, library_flag='UNKNOWN', recovery_attempts=(),
|
||||
stderr=startup.stderr or '工程打开或释放未完成,尚无法确认 ICDB 状态。'))
|
||||
except Exception as error:
|
||||
return save(VerifyResult('FAIL', safe_to_continue=not started,
|
||||
error_category='ICDB_INSPECTION_UNCONFIRMED', stderr=f'无法确认 ICDB 状态:{error}'))
|
||||
|
||||
|
||||
def run_existing_address_maintenance(request, *, verify, progress=None):
|
||||
def run_diagnosed_maintenance(request, *, diagnose, progress=None, stop=None):
|
||||
"""Open PCB once; only a current matching native fault admits maintenance."""
|
||||
from .verify_runner import VerifyResult
|
||||
from .icdb_recovery import parse_session_loss
|
||||
from .native_repair import select_repair_target
|
||||
if stop is not None and stop.is_set():
|
||||
return VerifyResult('CANCELLED', stderr='已取消,未打开工程或请求修复。')
|
||||
if progress:
|
||||
progress({'stage': 'icdb_startup_check', 'block': request.block_name,
|
||||
'detail': '尝试打开工程,依据本次原生报错判断是否需要 ICDB 维护'})
|
||||
startup = diagnose(replace(request, maintenance=False, auto_repair=False,
|
||||
diagnostic_only=True, native_lm_verify=False, post_repair_proof=None))
|
||||
def finish(result):
|
||||
if startup.evidence_path:
|
||||
report = startup.evidence_path.with_name('maintenance-result.json')
|
||||
recorded = replace(result, evidence_path=report)
|
||||
try:
|
||||
report.write_text(json.dumps({'block_name': request.block_name,
|
||||
'startup_evidence': str(startup.evidence_path), **asdict(recorded)},
|
||||
ensure_ascii=False, default=str, indent=2), encoding='utf-8')
|
||||
except OSError as error:
|
||||
import logging
|
||||
logging.getLogger(__name__).warning('maintenance_result_write_failed path=%s error=%s', report, error)
|
||||
else:
|
||||
result = recorded
|
||||
return result
|
||||
if startup.status == 'PASS' and startup.safe_to_continue:
|
||||
return finish(replace(startup, status='CHECKED', library_flag='UNKNOWN',
|
||||
stdout='工程打开正常,无需 ICDB 修复;未执行 CBB 校验。'))
|
||||
if startup.status == 'PASS':
|
||||
return finish(replace(startup, status='FAIL', stderr='工程打开后未确认会话释放,未请求 ICDB 修复。'))
|
||||
if startup.status != 'FAIL' or not startup.safe_to_continue:
|
||||
return startup
|
||||
# Do not search prior evidence directories or treat an error-code label,
|
||||
# address/checkpoint file, timeout or generic server error as a diagnosis.
|
||||
diagnosis = parse_session_loss(startup.stderr)
|
||||
if diagnosis is None:
|
||||
return startup
|
||||
try:
|
||||
target = select_repair_target(request, diagnosis)
|
||||
except (ValueError, OSError) as error:
|
||||
return finish(replace(startup, stderr=f'{startup.stderr}\n{error}',
|
||||
error_stage='icdb_target_check'))
|
||||
if stop is not None and stop.is_set():
|
||||
return finish(replace(startup, status='CANCELLED', stderr='已取消,未请求 ICDB 修复。'))
|
||||
return run_existing_address_maintenance(request, diagnosed_target=target, startup_result=startup,
|
||||
progress=progress, stop=stop)
|
||||
|
||||
|
||||
def run_existing_address_maintenance(request, *, diagnosed_target, startup_result, progress=None, stop=None):
|
||||
from .library_lock import LibraryLock
|
||||
from .native_repair import (run_native_repair, native_success_confirmed, repair_release_state,
|
||||
_native_identity_and_exit_confirmed)
|
||||
from .native_repair import run_native_repair, native_success_confirmed, repair_release_state
|
||||
from .verify_runner import VerifyResult
|
||||
root = Path(request.evidence_dir).resolve()/('maintenance-' + uuid4().hex[:12])
|
||||
library_root = Path(request.lmc_file).resolve().parent
|
||||
@@ -187,7 +349,8 @@ def run_existing_address_maintenance(request, *, verify, progress=None):
|
||||
return VerifyResult('BLOCKED', stderr='维护证据必须位于目标库之外', safe_to_continue=False)
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
record = {'operation': 'explicit_project_maintenance', 'library': str(request.lmc_file),
|
||||
'block': request.block_name, 'stage': 'preflight'}
|
||||
'block': request.block_name, 'stage': 'preflight',
|
||||
'startup_diagnosis': asdict(startup_result)}
|
||||
report = root/'result.json'
|
||||
owner_safe = False
|
||||
recovery = None
|
||||
@@ -199,45 +362,58 @@ def run_existing_address_maintenance(request, *, verify, progress=None):
|
||||
record['result'] = asdict(result)
|
||||
report.write_text(json.dumps(record, ensure_ascii=False, default=str, indent=2), encoding='utf-8')
|
||||
return result
|
||||
def native_event(event):
|
||||
emit(event['stage'], **{key: value for key, value in event.items() if key != 'stage'})
|
||||
try:
|
||||
if stop is not None and stop.is_set():
|
||||
return save(VerifyResult('CANCELLED', stderr='维护已取消,未启动原生操作'))
|
||||
emit('preflight', detail='正在核对工程、库文件和进程占用;可请求取消')
|
||||
lease = LibraryLock.for_maintenance(request.lmc_file, root/'takeover',
|
||||
lambda: maintenance_target_guard(request), safe_to_release=lambda: owner_safe)
|
||||
lambda: maintenance_target_guard(request, stop=stop), safe_to_release=lambda: owner_safe)
|
||||
with lease:
|
||||
owner_safe = True # Admission completed; no native client exists yet.
|
||||
checked = lease.maintenance_proof
|
||||
target, context = checked['target'], checked['context']
|
||||
record['maintenance_context'] = context
|
||||
emit('icdb_diagnosis_start', detail='已取得库锁,检查原生启动;不执行集成或保存')
|
||||
diagnostic_request = replace(request, maintenance=False, auto_repair=False,
|
||||
diagnostic_only=True, post_repair_proof=None, native_lm_verify=False,
|
||||
interactive_input=False, libspec='', dms_login_config='', evidence_dir=root/'diagnosis')
|
||||
diagnosis = verify(diagnostic_request)
|
||||
record['preflight_diagnosis'] = asdict(diagnosis)
|
||||
evidence = diagnosis.evidence_path
|
||||
if (evidence is None or not Path(evidence).is_file()
|
||||
or not Path(evidence).resolve().is_relative_to((root/'diagnosis').resolve())):
|
||||
raise ValueError('ICDB_DIAGNOSIS_UNCONFIRMED: 缺少本轮诊断证据,未调用 Repair')
|
||||
owner_safe = diagnosis.safe_to_continue
|
||||
if diagnosis.status == 'PASS' and owner_safe:
|
||||
emit('icdb_diagnosis_complete', detail='本轮启动未发现 ICDB 故障,未调用 Repair')
|
||||
return save(replace(diagnosis, library_flag='UNKNOWN', library_flag_detail='',
|
||||
stdout='ICDB 启动检查通过;未执行集成、保存或原生 Repair。', recovery_attempts=()))
|
||||
if diagnosis.error_category != 'ICDB_REPAIR_REQUIRED' or diagnosis.status in ('BLOCKED', 'TIMEOUT'):
|
||||
return save(replace(diagnosis, status='BLOCKED' if diagnosis.status == 'PASS' else diagnosis.status,
|
||||
stderr=(diagnosis.stderr + '\n未确认 ICDB 故障,未调用原生 Repair。').strip(),
|
||||
recovery_attempts=()))
|
||||
# Only this run's structured native lost-session diagnosis may
|
||||
# authorize Repair, and it must identify this exact database.
|
||||
fault = json.loads((Path(evidence).parent/'diagnostics/icdb-recovery.json').read_text('utf-8'))
|
||||
if (fault.get('error_code') != 'ICDB_REPAIR_REQUIRED' or fault.get('scope') != 'project'
|
||||
or not fault.get('session') or not fault.get('database_path')
|
||||
or Path(fault['database_path']).resolve() != target.database.resolve()):
|
||||
raise ValueError('ICDB_DIAGNOSIS_UNCONFIRMED: 故障证据未绑定当前数据库')
|
||||
record['confirmed_fault'] = fault
|
||||
# A diagnostic worker may have failed to release its native owner.
|
||||
# Recheck every owner and the exact target before dispatch.
|
||||
with maintenance_target_guard(request, context): pass
|
||||
if (target.project.resolve() != diagnosed_target.project.resolve()
|
||||
or target.database.resolve() != diagnosed_target.database.resolve()):
|
||||
return save(VerifyResult('FAIL', safe_to_continue=owner_safe,
|
||||
error_category='ICDB_TARGET_MISMATCH', error_stage='preflight',
|
||||
stderr='本次打开报错的数据库与维护目标不一致,未请求 ICDB 修复。'))
|
||||
if stop is not None and stop.is_set():
|
||||
raise ValueError('MAINTENANCE_CANCELLED: 已取消,未启动原生检查')
|
||||
emit('icdb_ownership_check', detail='调用原生 Project Backup 检查占用及恢复要求,不执行 Repair')
|
||||
owner_safe = False
|
||||
emit('icdb_diagnosis_confirmed', detail='本轮原生日志已确认目标数据库失联,进入 Repair')
|
||||
inspection = run_native_repair(target, root/'native-inspection',
|
||||
mentor_bin=request.mentor_bin, timeout_seconds=min(30, request.timeout_seconds),
|
||||
progress=native_event, maintenance_context=context, inspection_only=True, stop=stop)
|
||||
record['native_inspection'] = inspection
|
||||
owner_safe = (inspection.get('release', {}).get('native_exited') is True
|
||||
or inspection.get('native_pid') is None and inspection.get('worker_pid') is None)
|
||||
from .native_occupancy import confirmed_inspection
|
||||
if not confirmed_inspection(target, inspection):
|
||||
return save(VerifyResult('BLOCKED', safe_to_continue=owner_safe,
|
||||
error_category='ICDB_INSPECTION_UNCONFIRMED',
|
||||
stderr='原生占用检查未确认或已取消,未请求 Repair。' + str(inspection.get('detail', inspection.get('status')))))
|
||||
if inspection['status'] == 'IN_USE':
|
||||
return save(VerifyResult('BLOCKED', safe_to_continue=owner_safe,
|
||||
error_category='ICDB_DATABASE_IN_USE', stderr='原生工具确认工程正在使用,未请求 Repair。'))
|
||||
# Native loading may retire an old address itself. Permit only
|
||||
# disappearance, never a new/changed advertisement or project.
|
||||
with maintenance_target_guard(request, stop=stop) as refreshed:
|
||||
updated = refreshed['context']
|
||||
if ({k: v for k, v in context.items() if k != 'addresses'}
|
||||
!= {k: v for k, v in updated.items() if k != 'addresses'}
|
||||
or any(context['addresses'].get(k) != v for k, v in updated['addresses'].items())):
|
||||
raise ValueError('MAINTENANCE_SOURCE_CHANGED: 原生检查后工程或地址身份变化')
|
||||
context = updated
|
||||
record['post_inspection_context'] = context
|
||||
if not inspection['repair_required']:
|
||||
return save(VerifyResult('CHECKED', safe_to_continue=owner_safe,
|
||||
stdout='检查完成,无需修复。'))
|
||||
if stop is not None and stop.is_set():
|
||||
raise ValueError('MAINTENANCE_CANCELLED: 已取消,未开始 Repair')
|
||||
emit('icdb_diagnosis_confirmed', detail='本轮原生检查明确要求修复当前数据库,且确认未占用')
|
||||
native_root = root/'native-repair'; native_root.mkdir()
|
||||
attempt = native_root/'attempt.json'
|
||||
with attempt.open('x', encoding='utf-8') as stream:
|
||||
@@ -246,53 +422,25 @@ def run_existing_address_maintenance(request, *, verify, progress=None):
|
||||
emit('native_repair_start', detail='核对占用后由官方工具检查/修复;应用不自动备份')
|
||||
# Repeat immediately before dispatch; the worker repeats before
|
||||
# launching the native process as well.
|
||||
with maintenance_target_guard(request, context): pass
|
||||
with maintenance_target_guard(request, context, stop=stop): pass
|
||||
owner_safe = False
|
||||
recovery = run_native_repair(target, native_root, mentor_bin=request.mentor_bin,
|
||||
timeout_seconds=max(60, request.timeout_seconds), progress=progress,
|
||||
maintenance_context=context)
|
||||
assert_native_idle()
|
||||
timeout_seconds=max(60, request.timeout_seconds), progress=native_event,
|
||||
maintenance_context=context, stop=stop)
|
||||
_assert_native_idle_for(target)
|
||||
recovery = {**recovery, 'native_status': recovery.get('status'), 'validation_passed': False}
|
||||
recovery['release'] = repair_release_state(request, target, recovery)
|
||||
safe = recovery['release'].get('safe_to_continue') is True
|
||||
confirmed = recovery.get('status') == 'REPAIRED' and safe and native_success_confirmed(target, recovery)
|
||||
evidence = recovery.get('evidence')
|
||||
completed_failure = (recovery.get('status') in ('MISSING_HEALTHY_BACKUP', 'NATIVE_REPAIR_FAILED')
|
||||
and isinstance(evidence, dict) and evidence.get('failure_complete') is True
|
||||
and _native_identity_and_exit_confirmed(target, recovery))
|
||||
# Physical release is necessary, but does not approve historical
|
||||
# restoration/unknown/busy outcomes or an incomplete failure report.
|
||||
owner_safe = safe and (confirmed or completed_failure)
|
||||
# Release follows actual clients, not the repair/content verdict.
|
||||
owner_safe = safe or (recovery['release'].get('native_exited') is True
|
||||
and recovery['release'].get('database_exclusive') is True
|
||||
and recovery['release'].get('remaining_pids') == [])
|
||||
if confirmed:
|
||||
emit('repair_verify', detail='原生修复及释放已确认,重新打开同一工程校验')
|
||||
from .post_repair_consent import PostRepairProof
|
||||
owner_safe = False
|
||||
proof = PostRepairProof.create(request, target, recovery)
|
||||
verified = verify(replace(request, maintenance=False, auto_repair=False,
|
||||
diagnostic_only=False, post_repair_proof=proof,
|
||||
interactive_input=False, native_lm_verify=False))
|
||||
owner_safe = verified.safe_to_continue
|
||||
good = verified.status == 'PASS' and verified.library_flag == 'GREEN' and owner_safe
|
||||
recovery.update(status='REPAIRED' if good else 'REPAIR_VALIDATION_FAILED',
|
||||
validation_passed=good, validation_evidence=str(verified.evidence_path or ''))
|
||||
if good and verified.evidence_path:
|
||||
restored = Path(verified.evidence_path).parent/'pcb-version-restoration.json'
|
||||
if restored.exists():
|
||||
version = json.loads(restored.read_text(encoding='utf-8'))
|
||||
if (version.get('confirm_sent') is not True or version.get('historical_restore') is not True
|
||||
or Path(version['project']).resolve() != checked['project'].resolve()
|
||||
or version.get('choice') not in ('last_user_saved', 'autosave')):
|
||||
raise ValueError('PCB_VERSION_RESTORATION_EVIDENCE_INVALID')
|
||||
recovery.update(status='RESTORED_REVIEW_REQUIRED', pcb_version=version)
|
||||
verified = replace(verified, stdout=verified.stdout +
|
||||
f'\n已按用户选择恢复 PCB({version["date"]})并通过校验;版本待核对。')
|
||||
if verified.error_category == 'PCB_VERSION_CHOICE_REQUIRED':
|
||||
owner_safe = False
|
||||
good = False
|
||||
recovery.update(status='PCB_VERSION_CHOICE_REQUIRED', validation_passed=False)
|
||||
verified = replace(verified, safe_to_continue=False,
|
||||
stderr='ICDB原生修复已完成;PCB需选择恢复版本,尚未校验通过。\n' + verified.stderr)
|
||||
return save(replace(verified, status='PASS' if good else 'FAIL',
|
||||
recovery_attempts=(recovery,)))
|
||||
emit('native_repair_complete', detail='原生 ICDB 修复完成,CBB 待单独校验')
|
||||
recovery['status'] = 'REPAIRED_UNVERIFIED'
|
||||
return save(VerifyResult('REPAIRED', safe_to_continue=owner_safe,
|
||||
stdout='原生 ICDB 修复完成,CBB 待单独校验。', recovery_attempts=(recovery,)))
|
||||
if recovery.get('status') == 'REPAIRED':
|
||||
recovery['status'] = 'UNCONFIRMED'; owner_safe = False
|
||||
return save(VerifyResult('FAIL', stderr=f'{recovery["status"]}: {recovery.get("detail", "原生维护未确认修复")}',
|
||||
|
||||
@@ -8,7 +8,7 @@ from uuid import uuid4
|
||||
|
||||
from .library_lock import LibraryLock, LibraryBusy
|
||||
from .scoped_manifest import (ManifestScope, build_manifest, build_exclusive_library_manifest,
|
||||
copy_verified, hash_file, scan_tree)
|
||||
comparison_rules, copy_verified, hash_file, scan_tree)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -31,6 +31,7 @@ class ManagementRequest:
|
||||
mapped_drive: str = ''
|
||||
mapped_remote_root: str = ''
|
||||
transaction_token: str = ''
|
||||
check_previous_release: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -71,6 +72,8 @@ class ManagementResult:
|
||||
safe_to_continue: bool
|
||||
detail: str = ''
|
||||
evidence_path: Path | None = None
|
||||
release_proof: dict | None = None
|
||||
change_report: dict | None = None
|
||||
|
||||
|
||||
def validate_name(value):
|
||||
@@ -150,13 +153,22 @@ def unfinished_operations(root):
|
||||
for path in sorted(Path(root).glob('*/checkpoint.json')):
|
||||
try:
|
||||
record = json.loads(path.read_text(encoding='utf-8'))
|
||||
if record.get('stage') != 'complete' or record.get('safe_to_continue') is False:
|
||||
if (record.get('stage') != 'complete' or record.get('safe_to_continue') is False
|
||||
or record.get('status') == 'RECOVERY_REQUIRED'):
|
||||
results.append({**record, 'evidence_path': str(path)})
|
||||
except (OSError, ValueError):
|
||||
results.append({'status': 'CHECKPOINT_UNREADABLE', 'evidence_path': str(path)})
|
||||
return results
|
||||
|
||||
|
||||
def _may_have_mutated(record):
|
||||
prewrite = {'preflight', 'release_check', 'catalog_before', 'baseline', 'stage_source', 'prepare_identity'}
|
||||
history = record.get('history')
|
||||
return (record.get('stage') not in prewrite | {'complete'} or record.get('status') == 'RECOVERY_REQUIRED'
|
||||
or not isinstance(history, list) or not history
|
||||
or any(not isinstance(item, dict) or item.get('stage') not in prewrite for item in history))
|
||||
|
||||
|
||||
def run_management(request, *, adapter=None, verifier=None, idle_check=None, progress=None):
|
||||
from .verify_runner import VerifyRequest, run_verify
|
||||
from .backup_recovery import _idle_check
|
||||
@@ -174,6 +186,19 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
owner_safe = True
|
||||
mutex = None
|
||||
acquired = False
|
||||
release_proof = None
|
||||
original = None
|
||||
change_report = None
|
||||
def invoke(callback, *args):
|
||||
nonlocal owner_safe
|
||||
owner_safe = False
|
||||
try:
|
||||
result = callback(*args)
|
||||
except Exception as error:
|
||||
owner_safe = getattr(error, 'safe_to_continue', False) is True
|
||||
raise
|
||||
owner_safe = result.safe_to_continue
|
||||
return result
|
||||
def checkpoint(next_stage, **details):
|
||||
nonlocal stage
|
||||
stage = next_stage
|
||||
@@ -184,10 +209,38 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
if progress:
|
||||
progress({'stage': stage, 'block': request.name, 'operation': request.operation, **details})
|
||||
def finish(status, detail='', safe=True):
|
||||
nonlocal change_report
|
||||
if mutated and original is not None and change_report is None:
|
||||
change_report = {'status': 'UNCONFIRMED', 'scope': original['scope'],
|
||||
**comparison_rules(scope),
|
||||
'unrelated_cbb_content_checked': False,
|
||||
'detail': '原生会话尚未释放,未读取写后内容'}
|
||||
if safe:
|
||||
try:
|
||||
after = build_exclusive_library_manifest(library_root, scope=scope, progress=progress)
|
||||
_write_json(root/'library-after-manifest.json', after)
|
||||
before_files, after_files = original['files'], after['files']
|
||||
change_report.update(status='RECORDED', detail='目标工程及共享依赖的内容差分',
|
||||
added=sorted(after_files.keys()-before_files.keys()),
|
||||
deleted=sorted(before_files.keys()-after_files.keys()),
|
||||
modified=sorted(path for path in before_files.keys() & after_files.keys()
|
||||
if before_files[path] != after_files[path]))
|
||||
except Exception as error:
|
||||
change_report['detail'] = f'写后内容未确认:{error}'
|
||||
try:
|
||||
_write_json(root/'library-changes.json', change_report)
|
||||
except OSError as error:
|
||||
change_report.update(status='UNCONFIRMED', evidence_error=str(error),
|
||||
detail=f'变更记录保存失败:{error}')
|
||||
if change_report['status'] != 'RECORDED':
|
||||
detail = (detail+'\n'+change_report['detail']).strip()
|
||||
result = ManagementResult(request.operation, request.library, request.name, request.partition,
|
||||
request.source, request.auto_verify, 'complete', status, safe, detail, report)
|
||||
request.source, request.auto_verify, 'complete', status, safe, detail, report, release_proof, change_report)
|
||||
if report:
|
||||
_write_json(report, {**asdict(result), 'history': history, 'backup_policy': 'manual'})
|
||||
try:
|
||||
_write_json(report, {**asdict(result), 'history': history, 'backup_policy': 'manual'})
|
||||
except OSError as error:
|
||||
result = replace(result, detail=f'{detail}\n操作记录写入失败:{error}'.strip())
|
||||
return result
|
||||
from .com_runtime import initialize_com, uninitialize_com
|
||||
initialized = initialize_com()
|
||||
@@ -207,9 +260,13 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
capability = adapter.capabilities().get(request.operation, Capability(False, '未验证的原生接口'))
|
||||
if not capability.supported:
|
||||
return finish('UNSUPPORTED', capability.reason)
|
||||
unfinished_target = None
|
||||
for unfinished in unfinished_operations(evidence):
|
||||
if unfinished.get('library') and Path(unfinished['library']).resolve() == canonical_library:
|
||||
return finish('BLOCKED', f'存在未完成/需恢复任务,禁止自动重放:{unfinished["evidence_path"]}', False)
|
||||
if (unfinished.get('library') and Path(unfinished['library']).resolve() == canonical_library
|
||||
and _may_have_mutated(unfinished) and (not unfinished.get('name')
|
||||
or str(unfinished['name']).casefold() == request.name.casefold())):
|
||||
unfinished_target = unfinished
|
||||
break
|
||||
source = pcb = None
|
||||
if request.operation in ('add', 'update'):
|
||||
if request.source is None:
|
||||
@@ -219,16 +276,26 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
or evidence.is_relative_to(source.parent)
|
||||
or source.parent.is_relative_to(evidence)):
|
||||
raise ValueError('来源工程、目标库与操作证据必须使用独立目录。')
|
||||
root = evidence/('management-' + uuid4().hex)
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
report = root/'checkpoint.json'
|
||||
checkpoint('release_check')
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
||||
if not acquired:
|
||||
return finish('BLOCKED', '已有 CBB 校验/管理/恢复任务运行。', False)
|
||||
return finish('BLOCKED', '已有 CBB 校验/管理/恢复任务运行;本次未启动。')
|
||||
from .library_lock import recheck_previous_release
|
||||
release_proof = recheck_previous_release(library, root/'previous-release', block_name=request.name,
|
||||
required=request.check_previous_release or bool(unfinished_target
|
||||
and unfinished_target.get('safe_to_continue') is not True), progress=progress)
|
||||
if release_proof is not None:
|
||||
checkpoint('release_check', release_proof=release_proof)
|
||||
if unfinished_target:
|
||||
return finish('BLOCKED', f'存在未完成/需恢复任务,禁止自动重放:{unfinished_target["evidence_path"]}')
|
||||
if hasattr(adapter, 'bind_library_mapping'):
|
||||
adapter.bind_library_mapping(request.mapped_drive, request.mapped_remote_root)
|
||||
with LibraryLock(library, safe_to_release=lambda: owner_safe):
|
||||
root = evidence/('management-' + uuid4().hex)
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
report = root/'checkpoint.json'
|
||||
with LibraryLock(library, block_name=request.name, safe_to_release=lambda: owner_safe or (
|
||||
callable(getattr(adapter, 'release_confirmed', None)) and adapter.release_confirmed(library))):
|
||||
work = library.parent/'ReusableBlocksLP'/request.name/'Work'
|
||||
target_project, target_pcb = work/(request.name+'.prj'), work/'PCB/pcb.pcb'
|
||||
if request.operation != 'add':
|
||||
@@ -244,7 +311,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
idle_check(library, source, pcb)
|
||||
checkpoint('catalog_before')
|
||||
owner_safe = False
|
||||
before = adapter.catalog(library, root/'before')
|
||||
before = invoke(adapter.catalog, library, root/'before')
|
||||
owner_safe = before.safe_to_continue
|
||||
if not owner_safe or Path(before.library).resolve() != canonical_library or before.flow != 1:
|
||||
return finish('BLOCKED', '原生目录身份/流程或所有者释放未确认。仅支持已验证 DxDesigner 流程。', owner_safe)
|
||||
@@ -285,32 +352,29 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
if request.operation in ('remove', 'update'):
|
||||
checkpoint('native_remove')
|
||||
mutated = True; owner_safe = False
|
||||
native = adapter.remove(request, root/'remove')
|
||||
native = invoke(adapter.remove, request, root/'remove')
|
||||
owner_safe = native.safe_to_continue
|
||||
if not owner_safe or not native.success:
|
||||
return finish('RECOVERY_REQUIRED', native.detail, False)
|
||||
owner_safe = False
|
||||
return finish('RECOVERY_REQUIRED', native.detail, owner_safe)
|
||||
idle_check(library, target_project, target_pcb)
|
||||
owner_safe = False
|
||||
after = adapter.catalog(library, root/'after-remove')
|
||||
after = invoke(adapter.catalog, library, root/'after-remove')
|
||||
owner_safe = after.safe_to_continue
|
||||
if (not owner_safe or Path(after.library).resolve() != canonical_library or after.flow != 1
|
||||
or any(e.name == request.name and e.partition == request.partition for e in after.entries)):
|
||||
return finish('RECOVERY_REQUIRED', '原生移除后目录未确认目标缺失。', False)
|
||||
return finish('RECOVERY_REQUIRED', '原生移除后目录未确认目标缺失。', owner_safe)
|
||||
removed = True
|
||||
checkpoint('removed')
|
||||
if request.operation == 'remove':
|
||||
return finish('REMOVED', '已由原生操作移除,重新读取目录确认不存在;应用未创建备份。')
|
||||
checkpoint('native_add')
|
||||
mutated = True; owner_safe = False
|
||||
native = adapter.add(staged, root/'add')
|
||||
native = invoke(adapter.add, staged, root/'add')
|
||||
owner_safe = native.safe_to_continue
|
||||
if not owner_safe or not native.success:
|
||||
return finish('RECOVERY_REQUIRED' if removed or not owner_safe else 'UPLOAD_FAILED',
|
||||
native.detail, owner_safe and not removed)
|
||||
owner_safe = False
|
||||
native.detail, owner_safe)
|
||||
idle_check(library, target_project, target_pcb)
|
||||
after = adapter.catalog(library, root/'after-add')
|
||||
after = invoke(adapter.catalog, library, root/'after-add')
|
||||
owner_safe = after.safe_to_continue
|
||||
matches = [entry for entry in after.entries if entry.name == request.name
|
||||
and entry.partition == request.partition]
|
||||
@@ -319,7 +383,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
len(matches) == 1 and matches[0].engineering_identity == identity)
|
||||
if (not owner_safe or Path(after.library).resolve() != canonical_library or after.flow != 1
|
||||
or len(matches) != 1 or not proof_matches):
|
||||
return finish('RECOVERY_REQUIRED', '原生新增后名称、分区或来源工程内容未确认一致。', False)
|
||||
return finish('RECOVERY_REQUIRED', '原生新增后名称、分区或来源工程内容未确认一致。', owner_safe)
|
||||
uploaded = True
|
||||
checkpoint('uploaded')
|
||||
if not request.auto_verify:
|
||||
@@ -336,12 +400,14 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
verified.stderr or verified.library_flag_detail, owner_safe)
|
||||
except Exception as error:
|
||||
if uploaded:
|
||||
return finish('UPLOADED_VERIFY_FAILED', str(error), False)
|
||||
return finish('UPLOADED_VERIFY_FAILED', str(error), owner_safe)
|
||||
status = 'RECOVERY_REQUIRED' if mutated else ('UPLOAD_FAILED' if request.operation in ('add', 'update') else 'BLOCKED')
|
||||
# Bad input is never described as a native upload attempt.
|
||||
if root is None and isinstance(error, ValueError):
|
||||
status = 'BLOCKED'
|
||||
return finish(status, str(error), not mutated and owner_safe and not isinstance(error, LibraryBusy))
|
||||
if stage == 'release_check' and not mutated:
|
||||
status = 'BLOCKED'
|
||||
return finish(status, str(error), owner_safe)
|
||||
finally:
|
||||
if mutex is not None:
|
||||
if acquired:
|
||||
|
||||
@@ -217,23 +217,12 @@ def launch_pcb_process(command, cwd):
|
||||
|
||||
|
||||
def _process_details(name):
|
||||
queries = {
|
||||
'ExpeditionPCB.exe': "SELECT ProcessId, ParentProcessId, ExecutablePath, CommandLine FROM Win32_Process WHERE Name='ExpeditionPCB.exe'",
|
||||
'LibraryManager.exe': "SELECT ProcessId, ParentProcessId, ExecutablePath, CommandLine FROM Win32_Process WHERE Name='LibraryManager.exe'",
|
||||
'iCDBProjectBackup.exe': "SELECT ProcessId, ParentProcessId, ExecutablePath, CommandLine FROM Win32_Process WHERE Name='iCDBProjectBackup.exe'",
|
||||
'ReuseBlockImporter.exe': "SELECT ProcessId, ParentProcessId, ExecutablePath, CommandLine FROM Win32_Process WHERE Name='ReuseBlockImporter.exe'",
|
||||
'cscript.exe': "SELECT ProcessId, ParentProcessId, ExecutablePath, CommandLine FROM Win32_Process WHERE Name='cscript.exe'",
|
||||
'viewdraw.exe': "SELECT ProcessId, ParentProcessId, ExecutablePath, CommandLine FROM Win32_Process WHERE Name='viewdraw.exe'",
|
||||
}
|
||||
if name not in queries:
|
||||
if name not in {'ExpeditionPCB.exe', 'LibraryManager.exe', 'iCDBProjectBackup.exe',
|
||||
'ReuseBlockImporter.exe', 'cscript.exe', 'viewdraw.exe'}:
|
||||
raise ValueError(f'Unsupported process query: {name}')
|
||||
import win32com.client
|
||||
service = win32com.client.GetObject('winmgmts:')
|
||||
return [
|
||||
(int(p.ProcessId), str(p.ExecutablePath or ''), str(p.CommandLine or ''),
|
||||
int(p.ParentProcessId or 0))
|
||||
for p in service.ExecQuery(queries[name])
|
||||
]
|
||||
from .owner_probe import query_owners
|
||||
return [(row['pid'], row['executable'], row['command'], row['parent'])
|
||||
for row in query_owners((name,))]
|
||||
|
||||
|
||||
def _processes(name):
|
||||
@@ -247,12 +236,13 @@ def pcb_processes():
|
||||
|
||||
def is_reusable_circuit_pcb(exe, command, expected_pcb):
|
||||
"""Match the ReusableCircuit session for this CBB by argument, not install layout."""
|
||||
from .failed_session import _command_args
|
||||
exe = os.path.normcase(str(exe or ''))
|
||||
command = os.path.normcase(str(command or ''))
|
||||
args = _command_args(str(command or ''))
|
||||
expected = os.path.normcase(os.path.abspath(str(expected_pcb)))
|
||||
return (os.path.basename(exe) == 'expeditionpcb.exe'
|
||||
and '-reusablecircuit' in command
|
||||
and expected in command)
|
||||
and '-reusablecircuit' in {arg.casefold() for arg in args[1:]}
|
||||
and expected in {os.path.normcase(os.path.abspath(arg)) for arg in args[1:]})
|
||||
|
||||
|
||||
def select_reusable_circuit_pcb(candidates):
|
||||
@@ -616,11 +606,15 @@ def execute_job(job, emit):
|
||||
|
||||
root = Path(job['root'])
|
||||
block_root = Path(job['project']).parent.parent
|
||||
# COM publishes a shared active application. Never attach while another
|
||||
# native PCB session (including a retained failure) is still running.
|
||||
pcb_before = {pid for pid, _, _ in pcb_processes()}
|
||||
if pcb_before:
|
||||
raise RuntimeError(f'PCB_SESSION_ACTIVE: 已有 PCB 会话,请正常关闭后再校验: {sorted(pcb_before)}')
|
||||
# Unrelated designs stay open; COM and save helpers still require the exact
|
||||
# project identity before any integration or save call.
|
||||
from .failed_session import _command_args
|
||||
existing = tuple(pcb_processes())
|
||||
pcb_before = {pid for pid, _, _ in existing}
|
||||
expected = os.path.normcase(os.path.abspath(job['pcb']))
|
||||
for pid, _, command in existing:
|
||||
if command and expected in [os.path.normcase(os.path.abspath(a)) for a in _command_args(command)[1:]]:
|
||||
raise RuntimeError(f'PCB_SESSION_ACTIVE: 目标工程已经打开:{pid}')
|
||||
# Backups are user-managed on local and network libraries alike.
|
||||
mapped_drive = str(job.get('mapped_drive') or '')
|
||||
mapped_remote_root = str(job.get('mapped_remote_root') or '')
|
||||
@@ -630,13 +624,7 @@ def execute_job(job, emit):
|
||||
emit(stage='mapped_drive_context', **mapping)
|
||||
emit(stage='backup_skipped', reason='manual_backup_policy', source=str(block_root),
|
||||
detail='应用不自动备份;请在操作前手动备份。')
|
||||
from .icdb_ownership import database_directories, unreleased_addresses
|
||||
for database in database_directories(job['lmc_file'], job['project'], job['pcb']):
|
||||
icdb_address = prepare_icdb_address(database, root, emit=emit)
|
||||
if icdb_address.get('status') != 'ABSENT':
|
||||
raise RuntimeError(
|
||||
'ICDB_SESSION_UNCONFIRMED: 数据库存在服务器地址记录,无法确认独占使用;'
|
||||
'已保留地址文件,请先检查原 PCB/iCDB 会话。' + str(icdb_address))
|
||||
from .icdb_ownership import unreleased_addresses
|
||||
from .verify_diagnostics import collect_preflight_diagnostics, collect_native_failure_logs
|
||||
diagnostics = collect_preflight_diagnostics(job['pcb'], root)
|
||||
emit(stage='preflight_diagnostics', non_blocking=True,
|
||||
@@ -649,7 +637,7 @@ def execute_job(job, emit):
|
||||
pcb_log_offset = snapshot_log(pcb_log)
|
||||
integration_log_dir = Path(job['pcb']).parent / 'LogFiles'
|
||||
integration_offsets = {}
|
||||
for name in ('ForwardAnnotation.txt', 'MsgBoxResponse.log', 'PartPkg.log'):
|
||||
for name in (() if job.get('diagnostic_only') else ('ForwardAnnotation.txt', 'MsgBoxResponse.log', 'PartPkg.log')):
|
||||
path = integration_log_dir / name
|
||||
try:
|
||||
baseline = path.read_bytes()
|
||||
@@ -676,6 +664,8 @@ def execute_job(job, emit):
|
||||
# Inspect every source before returning a generic server/packager
|
||||
# failure: either can be a consequence of a lost library session.
|
||||
startup = pcb_log_reports_missing_server(job['pcb'], offset=pcb_log_offset)
|
||||
if job.get('diagnostic_only'):
|
||||
return startup
|
||||
integration = pcb_log_reports_integration_error(job['pcb'], offsets=integration_offsets)
|
||||
if 'ICDB_REPAIR_REQUIRED' in startup:
|
||||
return startup
|
||||
@@ -705,6 +695,8 @@ def execute_job(job, emit):
|
||||
reference = match[2]
|
||||
if not reference or (config.parent/reference).resolve() != library:
|
||||
raise ValueError(f'DIAGNOSTIC_LIBRARY_MISMATCH: {config}: {reference}')
|
||||
from .diagnostic_open import snapshot_diagnostic_logs
|
||||
job['diagnostic_log_baseline'] = snapshot_diagnostic_logs(job)
|
||||
else:
|
||||
ensure_pcb_central_library(
|
||||
job['pcb'],
|
||||
@@ -721,6 +713,7 @@ def execute_job(job, emit):
|
||||
# The successful background runs use the normal ReusableCircuit
|
||||
# launcher. Keep the experimental Library Manager menu route opt-in
|
||||
# for diagnostics only; it is not the production trigger on EE7.9.
|
||||
pcb_started_ns = time.time_ns()
|
||||
if bool(job.get('native_lm_verify', False)):
|
||||
from .library_manager_verify import launch_library_verify
|
||||
emit(stage='lm_launch', library=job['lmc_file'], block=job['block_name'])
|
||||
@@ -762,42 +755,51 @@ def execute_job(job, emit):
|
||||
parent_pid=worker_parent_pid or lm_pid, command=worker_command,
|
||||
binding='commandline' if is_reusable_circuit_pcb(
|
||||
worker_executable, worker_command, job['pcb']) else 'launcher_child')
|
||||
try:
|
||||
from .mentor_paths import discover_sdd_home
|
||||
home = discover_sdd_home(job.get('mentor_bin'))
|
||||
wdir = os.environ.get('WDIR', '').split(';')[0].strip()
|
||||
if wdir or home:
|
||||
log_root = Path(os.path.expandvars(wdir)) if wdir else home/'standard'
|
||||
(root/'diagnostics/native-client-context.json').write_text(json.dumps({
|
||||
'native_pid': worker_pid, 'started_ns': pcb_started_ns,
|
||||
'client_log_root': str(log_root/'iCDB/Client/Logs'),
|
||||
'database': str(Path(job['project']).parent/'database')},
|
||||
ensure_ascii=False), encoding='utf-8')
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
break
|
||||
time.sleep(.2)
|
||||
if worker_pid is None:
|
||||
raise RuntimeError('ReusableCircuit common 启动后未观察到 wg PCB 子进程')
|
||||
app, doc, pi = wait_for_target_document(
|
||||
job,
|
||||
lambda: win32com.client.GetActiveObject('MGCPCB.Application'),
|
||||
process_alive=lambda: any(candidate_pid in {lm_pid, worker_pid, worker_parent_pid}
|
||||
for candidate_pid, _, _ in pcb_processes()),
|
||||
emit=emit,
|
||||
error_reader=native_error,
|
||||
)
|
||||
identity_verified = True
|
||||
if job.get('diagnostic_only'):
|
||||
# The diagnostic opens only to establish current native evidence.
|
||||
# Do not refresh integration, save/commit Cert, or edit PRJ paths.
|
||||
pi = doc = app = None
|
||||
gc.collect()
|
||||
from .failed_session import close_failed_document
|
||||
diagnostic_close_attempted = True
|
||||
closed = close_failed_document(job, emit=emit)
|
||||
if closed.get('status') != 'CLOSED':
|
||||
raise RuntimeError(f'DIAGNOSTIC_CLOSE_UNCONFIRMED: {closed}')
|
||||
release_deadline = time.monotonic() + 30
|
||||
while True:
|
||||
released = cleanup_verify_processes(lm_pid, worker_pid, worker_parent_pid,
|
||||
expected_pcb=job['pcb'], baseline_pids=pcb_before, emit=emit)
|
||||
if (released and released.get('safe_to_continue')
|
||||
and not unreleased_addresses(job['lmc_file'], job['project'], job['pcb'])):
|
||||
break
|
||||
if time.monotonic() >= release_deadline:
|
||||
raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: 原生会话或数据库仍占用')
|
||||
time.sleep(.2)
|
||||
# Global PCB COM can wait on another design's modal window.
|
||||
# Opening checks use only the newly bound process and fresh logs.
|
||||
from .diagnostic_open import check_target_window
|
||||
def diagnostic_emit(**event):
|
||||
nonlocal diagnostic_close_attempted
|
||||
if event.get('stage') == 'diagnostic_wm_close':
|
||||
diagnostic_close_attempted = True
|
||||
emit(**event)
|
||||
checked = check_target_window(job, worker_pid, emit=diagnostic_emit,
|
||||
error_reader=native_error, launcher_process=launcher_process)
|
||||
released = cleanup_verify_processes(lm_pid, worker_pid, worker_parent_pid,
|
||||
expected_pcb=job['pcb'], baseline_pids=pcb_before, emit=emit)
|
||||
if (checked.get('status') != 'PASS' or not checked.get('native_processes_exited')
|
||||
or not released or not released.get('safe_to_continue')):
|
||||
raise RuntimeError(f'DIAGNOSTIC_CLOSE_UNCONFIRMED: {checked}; {released}')
|
||||
from .diagnostic_open import _read_bounded
|
||||
if detail := _read_bounded(native_error):
|
||||
raise RuntimeError(detail)
|
||||
completed = True
|
||||
emit(stage='diagnostic_complete', status='PASS')
|
||||
return {'status': 'PASS', 'stdout': 'ICDB 启动检查通过;未执行集成或保存,已关闭工程。'}
|
||||
return {'status': 'PASS', 'stdout': 'ICDB 启动检查通过;工程及启动器已退出。'}
|
||||
from .pcb_bridge import ProcessWatch
|
||||
with ProcessWatch((lm_pid, worker_pid, worker_parent_pid)) as watch:
|
||||
app, doc, pi = wait_for_target_document(
|
||||
job, lambda: win32com.client.GetActiveObject('MGCPCB.Application'),
|
||||
process_alive=watch.alive, emit=emit, error_reader=native_error)
|
||||
identity_verified = True
|
||||
# Do not acquire MGCPCBAutomationLicensing from this 64-bit Python
|
||||
# worker. EE7.9 registers that automation class for the 32-bit host;
|
||||
# the old, working path acquires the token inside the SysWOW64
|
||||
@@ -826,6 +828,8 @@ def execute_job(job, emit):
|
||||
emit(stage='save_helper', helper_pid=helper.pid)
|
||||
last_markers = ()
|
||||
while helper.poll() is None:
|
||||
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
|
||||
raise RuntimeError('VERIFY_CANCELLED: 已停止等待保存客户端')
|
||||
try:
|
||||
current = tuple(line.strip() for line in (root/'save.log').read_text(encoding='utf-8', errors='replace').splitlines() if line.strip())
|
||||
except OSError:
|
||||
@@ -862,7 +866,7 @@ def execute_job(job, emit):
|
||||
raise RuntimeError(f'PCB_RELEASE_UNCONFIRMED: 未确认 PCB 退出: {released}')
|
||||
addresses = unreleased_addresses(job['lmc_file'], job['project'], job['pcb'])
|
||||
if addresses:
|
||||
raise RuntimeError(f'ICDB_RELEASE_UNCONFIRMED: PCB 已退出但数据库地址记录仍存在;保留文件并停止批次: {addresses}')
|
||||
emit(stage='icdb_address_remaining', addresses=addresses, non_blocking=True)
|
||||
cert_pcb = block_root/'Cert'/Path(job['pcb']).relative_to(block_root/'Work')
|
||||
cert_evidence = collect_cert_evidence(block_root, cert_project, cert_pcb)
|
||||
emit(stage='cert_diagnostics', **cert_evidence)
|
||||
@@ -884,8 +888,8 @@ def execute_job(job, emit):
|
||||
if helper is not None and helper.poll() is None:
|
||||
emit(stage='save_helper_retained', helper_pid=helper.pid)
|
||||
elif diagnostic_close_attempted:
|
||||
# A timed-out close helper may still own an in-flight native Close.
|
||||
# Observe release below, but never start a second close helper.
|
||||
# The process-bound checker already sent its sole WM_CLOSE.
|
||||
# Preserve an unknown prompt; never fall back to global COM Close.
|
||||
pass
|
||||
elif not completed and identity_verified:
|
||||
try:
|
||||
@@ -945,6 +949,14 @@ def cleanup_verify_processes(lm_pid, worker_pid, worker_parent_pid=None, *,
|
||||
if (expected_pcb and int(pid) not in baseline
|
||||
and is_reusable_circuit_pcb(executable, command, expected_pcb)):
|
||||
tracked.add(int(pid))
|
||||
# Native launcher children can omit the PCB argument. Track only new
|
||||
# descendants of this task's already identified native processes.
|
||||
while True:
|
||||
children = {int(pid) for pid, _, _, parent in pcb_records
|
||||
if int(pid) not in baseline and int(parent) in tracked}
|
||||
if children.issubset(tracked):
|
||||
break
|
||||
tracked.update(children)
|
||||
alive = {int(record[0]) for record in (*pcb_records, *lm_records)}
|
||||
remaining = sorted(tracked & alive)
|
||||
result = {'safe_to_continue': not remaining, 'remaining_pids': remaining}
|
||||
@@ -990,14 +1002,19 @@ def worker_main(request_path):
|
||||
try:
|
||||
if job.get('supervisor_pid'):
|
||||
from .desktop_worker import start_supervisor_watchdog
|
||||
start_supervisor_watchdog(job['supervisor_pid'], cancel_path=job.get('cancel_signal'))
|
||||
start_supervisor_watchdog(job['supervisor_pid'], cancel_path=job.get('cancel_signal'), stop_clients=True)
|
||||
start_gate = Path(job.get('start_gate', '')) if job.get('start_gate') else None
|
||||
if start_gate is not None:
|
||||
gate_deadline = time.monotonic() + 15
|
||||
from .defaults import WORKER_START_GATE_TIMEOUT_SECONDS
|
||||
gate_deadline = time.monotonic() + WORKER_START_GATE_TIMEOUT_SECONDS
|
||||
while not start_gate.is_file():
|
||||
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
|
||||
raise RuntimeError('VERIFY_CANCELLED: 启动已取消,未启动 PCB')
|
||||
if time.monotonic() >= gate_deadline:
|
||||
raise RuntimeError('DIALOG_AGENT_START_TIMEOUT: 弹窗代理未就绪,未启动 PCB')
|
||||
time.sleep(.05)
|
||||
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
|
||||
raise RuntimeError('VERIFY_CANCELLED: 启动已取消,未启动 PCB')
|
||||
outcome = execute_job(job, emit)
|
||||
except Exception as error:
|
||||
traceback.print_exc()
|
||||
@@ -1443,6 +1460,8 @@ def read_library_flag(library, name, *, timeout_seconds=90, log_path=None):
|
||||
import win32con
|
||||
import win32process
|
||||
import win32service
|
||||
from pywinauto import Desktop
|
||||
from pywinauto.controls.common_controls import TreeViewWrapper
|
||||
|
||||
executable = library_manager_path()
|
||||
if not executable.is_file():
|
||||
@@ -1450,15 +1469,14 @@ def read_library_flag(library, name, *, timeout_seconds=90, log_path=None):
|
||||
|
||||
deadline = time.monotonic() + timeout_seconds
|
||||
desktop_name = 'CbbFlagRead_' + os.urandom(5).hex()
|
||||
desktop = win32service.CreateDesktop(desktop_name, 0, win32con.GENERIC_ALL, None)
|
||||
from pywinauto import Desktop
|
||||
from pywinauto.controls.common_controls import TreeViewWrapper
|
||||
desktop = None
|
||||
|
||||
handle = None
|
||||
pid = None
|
||||
handled = set()
|
||||
log = log_path or Path(library).parent/'LogFiles'/'cbb_flag_read_dialogs.jsonl'
|
||||
try:
|
||||
desktop = win32service.CreateDesktop(desktop_name, 0, win32con.GENERIC_ALL, None)
|
||||
startup = win32process.STARTUPINFO()
|
||||
startup.lpDesktop = 'winsta0\\' + desktop_name
|
||||
handle, thread, pid, _ = win32process.CreateProcess(
|
||||
@@ -1502,7 +1520,8 @@ def read_library_flag(library, name, *, timeout_seconds=90, log_path=None):
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
desktop.CloseDesktop()
|
||||
if desktop is not None:
|
||||
desktop.CloseDesktop()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -1531,12 +1550,13 @@ def read_library_tree_image_map(library, names, *, timeout_seconds=45, log_path=
|
||||
if not executable.is_file():
|
||||
return result
|
||||
desktop_name = 'CbbStatusRead_' + os.urandom(5).hex()
|
||||
desktop = win32service.CreateDesktop(desktop_name, 0, win32con.GENERIC_ALL, None)
|
||||
desktop = None
|
||||
handle = None
|
||||
pid = None
|
||||
handled = set()
|
||||
log = log_path or Path(library).parent/'LogFiles'/'cbb_status_read_dialogs.jsonl'
|
||||
try:
|
||||
desktop = win32service.CreateDesktop(desktop_name, 0, win32con.GENERIC_ALL, None)
|
||||
startup = win32process.STARTUPINFO()
|
||||
startup.lpDesktop = 'winsta0\\' + desktop_name
|
||||
handle, thread, pid, _ = win32process.CreateProcess(
|
||||
@@ -1590,7 +1610,8 @@ def read_library_tree_image_map(library, names, *, timeout_seconds=45, log_path=
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
desktop.CloseDesktop()
|
||||
if desktop is not None:
|
||||
desktop.CloseDesktop()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
"""Open the official backup UI; version selection and writes stay native."""
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
def native_backup_executable(mentor_bin=''):
|
||||
from .mentor_paths import discover_sdd_home
|
||||
home = discover_sdd_home(mentor_bin)
|
||||
executable = home/'iCDB/win32/bin/iCDBProjectBackup.exe' if home else None
|
||||
if executable is None or not executable.is_file():
|
||||
raise ValueError('未找到 iCDB Project Backup,请检查 Mentor 安装位置。')
|
||||
return executable
|
||||
|
||||
|
||||
def native_backup_project(library, block):
|
||||
from .verify_runner import INVALID_NAME_CHARS
|
||||
library = Path(library).absolute()
|
||||
if not block or block in ('.', '..') or any(c in block for c in INVALID_NAME_CHARS):
|
||||
raise ValueError('CBB 名称非法。')
|
||||
if not library.is_file():
|
||||
raise ValueError('中心库文件不存在。')
|
||||
work = library.parent/'ReusableBlocksLP'/block/'Work'
|
||||
expected = library.parent.resolve()/'ReusableBlocksLP'/block/'Work'
|
||||
if work.resolve() != expected:
|
||||
raise ValueError('工程路径通过链接指向其他位置。')
|
||||
projects = list(work.glob('*.prj'))
|
||||
if len(projects) != 1 or not projects[0].is_file():
|
||||
raise ValueError('无法唯一确定所选 CBB 的工程 PRJ。')
|
||||
project = projects[0]
|
||||
if (project.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT
|
||||
or not project.resolve().is_relative_to(expected)):
|
||||
raise ValueError('工程文件通过链接指向其他位置。')
|
||||
return project
|
||||
|
||||
|
||||
@dataclass
|
||||
class NativeBackupSession:
|
||||
process: object
|
||||
job: Path
|
||||
library: Path
|
||||
block: str
|
||||
path_lease: object = None
|
||||
|
||||
|
||||
def launch_native_backup(request):
|
||||
project = native_backup_project(request.lmc_file, request.block_name)
|
||||
native_backup_executable(request.mentor_bin)
|
||||
root = Path(request.evidence_dir).resolve()/('native-backup-'+uuid4().hex[:12])
|
||||
library_root = Path(request.lmc_file).resolve().parent
|
||||
if root.is_relative_to(library_root) or library_root.is_relative_to(root):
|
||||
raise ValueError('运行记录目录需位于中心库之外。')
|
||||
root.mkdir(parents=True)
|
||||
job = root/'request.json'
|
||||
job.write_text(json.dumps({'library': str(request.lmc_file), 'block': request.block_name,
|
||||
'project': str(project), 'mentor_bin': request.mentor_bin}, ensure_ascii=False), 'utf-8')
|
||||
command = ([sys.executable] if getattr(sys, 'frozen', False) else
|
||||
[sys.executable, '-m', 'cbb_refresh_verify'])+['--native-backup-worker', str(job)]
|
||||
process = subprocess.Popen(command, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
||||
return NativeBackupSession(process, job, Path(request.lmc_file), request.block_name)
|
||||
|
||||
|
||||
class _NativeBackupProcess:
|
||||
"""Track this visible tool and its descendants without killing on close."""
|
||||
def __init__(self, command, cwd):
|
||||
import win32con, win32job, win32process
|
||||
self.job = win32job.CreateJobObject(None, '')
|
||||
startup = win32process.STARTUPINFO()
|
||||
try:
|
||||
self.handle, thread, self.pid, _ = win32process.CreateProcess(
|
||||
command[0], subprocess.list2cmdline(command), None, None, False,
|
||||
win32con.CREATE_SUSPENDED, None, str(cwd), startup)
|
||||
except Exception:
|
||||
self.job.Close()
|
||||
raise
|
||||
try:
|
||||
win32job.AssignProcessToJobObject(self.job, self.handle)
|
||||
win32process.ResumeThread(thread)
|
||||
except Exception:
|
||||
# No native code has run while suspended; there can be no DB write.
|
||||
win32process.TerminateProcess(self.handle, 1)
|
||||
self.handle.Close(); self.job.Close()
|
||||
raise
|
||||
finally:
|
||||
thread.Close()
|
||||
|
||||
def poll(self):
|
||||
import win32process
|
||||
code = win32process.GetExitCodeProcess(self.handle)
|
||||
return None if code == 259 else code
|
||||
|
||||
def session_pids(self):
|
||||
import win32job
|
||||
return win32job.QueryInformationJobObject(self.job, win32job.JobObjectBasicProcessIdList)
|
||||
|
||||
def close(self):
|
||||
self.handle.Close(); self.job.Close()
|
||||
|
||||
|
||||
def native_backup_worker_main(job, *, process_factory=None):
|
||||
from .library_lock import LibraryLock
|
||||
from .management import _write_json
|
||||
job = Path(job)
|
||||
result = {'status': 'FAILED', 'safe_to_continue': True, 'restore_confirmed': False}
|
||||
native = None
|
||||
def write_evidence(name, value):
|
||||
try:
|
||||
_write_json(job.with_name(name), value)
|
||||
except Exception as error:
|
||||
# Evidence storage must never end supervision of a live transaction.
|
||||
result['evidence_error'] = str(error)
|
||||
try:
|
||||
record = json.loads(job.read_text('utf-8'))
|
||||
library, block = Path(record['library']), record['block']
|
||||
result.update(library=str(library), block=block)
|
||||
project = native_backup_project(library, block)
|
||||
if project != Path(record['project']):
|
||||
raise ValueError('工程身份已变化,未打开原生工具。')
|
||||
executable = native_backup_executable(record.get('mentor_bin', ''))
|
||||
released = True
|
||||
with LibraryLock(library, checkpoint=False, safe_to_release=lambda: released):
|
||||
native = (process_factory or _NativeBackupProcess)([str(executable), '-p', str(project)], project.parent)
|
||||
released = False
|
||||
result.update(status='OPEN', native_pid=native.pid, project=str(project), safe_to_continue=False)
|
||||
write_evidence('state.json', result)
|
||||
waiting = False
|
||||
while True:
|
||||
try:
|
||||
pids, exit_code = native.session_pids(), native.poll()
|
||||
except Exception as error:
|
||||
write_evidence('state.json', {**result,
|
||||
'status': 'RELEASE_UNCONFIRMED', 'detail': str(error)})
|
||||
time.sleep(.5)
|
||||
continue # Keep the lease while the live session cannot be observed.
|
||||
if not pids and exit_code is not None:
|
||||
break
|
||||
if exit_code is not None and not waiting:
|
||||
waiting = True
|
||||
write_evidence('state.json', {**result, 'status': 'WAITING_RELEASE'})
|
||||
time.sleep(.25)
|
||||
released = True
|
||||
result.update(status='CLOSED', native_exit_code=exit_code, safe_to_continue=True)
|
||||
return 0 if result['native_exit_code'] == 0 else 1
|
||||
except Exception as error:
|
||||
result.update(status='FAILED', detail=str(error), safe_to_continue=native is None)
|
||||
return 1
|
||||
finally:
|
||||
write_evidence('result.json', result)
|
||||
if native is not None:
|
||||
native.close() # No kill-on-close: never interrupt a native transaction.
|
||||
@@ -265,14 +265,8 @@ def validate_export_output(kind, code, report, log):
|
||||
|
||||
|
||||
def _process_snapshot():
|
||||
import win32com.client
|
||||
service = win32com.client.GetObject('winmgmts:')
|
||||
try:
|
||||
return [{'pid': int(p.ProcessId), 'parent': int(p.ParentProcessId or 0),
|
||||
'name': str(p.Name), 'executable': str(p.ExecutablePath or '')}
|
||||
for p in service.ExecQuery('SELECT ProcessId, ParentProcessId, Name, ExecutablePath FROM Win32_Process')]
|
||||
finally:
|
||||
service = None
|
||||
from .owner_probe import query_process_snapshot
|
||||
return query_process_snapshot(timeout_seconds=10)
|
||||
|
||||
|
||||
def _database_released(project_root):
|
||||
@@ -295,9 +289,20 @@ def _run_exports(project, root, mentor_home, timeout_seconds):
|
||||
"""Observe exact exporter/descendant handles; never kill a database owner."""
|
||||
import win32api, win32con, win32event, pywintypes
|
||||
root = Path(root)
|
||||
_write_json(root/'export-launch.json', {'started': False})
|
||||
before = _process_snapshot()
|
||||
if any(p['name'].casefold() in _OWNER_NAMES for p in before):
|
||||
try:
|
||||
_write_json(root/'export-launch.json', {'started': False})
|
||||
except OSError as error:
|
||||
return {'success': False, 'safe_to_continue': True, 'native_started': False,
|
||||
'detail': str(error)}
|
||||
diagnostic_warnings = []
|
||||
try:
|
||||
before = _process_snapshot()
|
||||
except Exception as error:
|
||||
return {'success': False, 'safe_to_continue': True, 'native_started': False,
|
||||
'detail': str(error)}
|
||||
from .backup_recovery import _native_scope_match
|
||||
if any(p['name'].casefold() in _OWNER_NAMES and _native_scope_match(
|
||||
p.get('command', ''), roots=(project.parent,)) is True for p in before):
|
||||
return {'success': False, 'safe_to_continue': False, 'detail': 'An existing iCDB owner prevents isolated identity export.'}
|
||||
if not _database_released(project.parent):
|
||||
return {'success': False, 'safe_to_continue': False, 'detail': 'Analysis copy has unreleased native addresses or DB handles.'}
|
||||
@@ -318,14 +323,20 @@ def _run_exports(project, root, mentor_home, timeout_seconds):
|
||||
for kind, command, report, log in commands:
|
||||
process = None
|
||||
handles = {}
|
||||
identities = {}
|
||||
released = False
|
||||
record = {'command': command, 'kind': kind, 'success': False, 'safe_to_continue': False}
|
||||
launch_attempted = False
|
||||
record = {'command': command, 'kind': kind, 'success': False,
|
||||
'safe_to_continue': False, 'native_started': False}
|
||||
try:
|
||||
deadline = time.monotonic()+float(timeout_seconds)
|
||||
with (root/(kind+'-stdout.txt')).open('wb') as output:
|
||||
_write_json(root/'export-launch.json', {'started': True})
|
||||
launch_attempted = True
|
||||
record['native_started'] = None
|
||||
process = subprocess.Popen(command, stdout=output, stderr=subprocess.STDOUT,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
record['native_started'] = True
|
||||
record['pid'] = process.pid
|
||||
descendants = {process.pid}
|
||||
_write_json(root/(kind+'-process.json'), record)
|
||||
@@ -336,13 +347,19 @@ def _run_exports(project, root, mentor_home, timeout_seconds):
|
||||
previous = len(descendants)
|
||||
descendants.update(p['pid'] for p in snapshot if p['parent'] in descendants)
|
||||
changed = len(descendants) != previous
|
||||
owners = [p for p in snapshot if p['pid'] in descendants or p['name'].casefold() in _OWNER_NAMES]
|
||||
owners = [p for p in snapshot if p['pid'] in descendants or (
|
||||
p['name'].casefold() in _OWNER_NAMES and _native_scope_match(
|
||||
p.get('command', ''), roots=(project.parent,)) is True)]
|
||||
for owner in owners:
|
||||
if owner['pid'] not in handles:
|
||||
try: handles[owner['pid']] = win32api.OpenProcess(win32con.SYNCHRONIZE, False, owner['pid'])
|
||||
except pywintypes.error as error:
|
||||
if error.winerror != 87: raise
|
||||
record['observed_pids'] = sorted(descendants | handles.keys())
|
||||
identities.update({owner['pid']:
|
||||
{key: owner.get(key, '') for key in ('pid', 'created', 'executable')}
|
||||
for owner in owners})
|
||||
record['process_identities'] = list(identities.values())
|
||||
if (process.poll() is not None and not owners
|
||||
and all(win32event.WaitForSingleObject(h, 0) == win32con.WAIT_OBJECT_0 for h in handles.values())):
|
||||
released = _database_released(project.parent)
|
||||
@@ -355,15 +372,37 @@ def _run_exports(project, root, mentor_home, timeout_seconds):
|
||||
validate_export_output(kind, process.returncode, report, log)
|
||||
record.update(success=True, detail='Native export complete and owners released.')
|
||||
except Exception as error:
|
||||
creation_rejected = (isinstance(error, (FileNotFoundError, PermissionError))
|
||||
or getattr(error, 'winerror', None) in (2, 3, 5, 193, 206, 740))
|
||||
if process is None and (not launch_attempted or creation_rejected):
|
||||
# Only a known CreateProcess rejection proves that no native owner started.
|
||||
released = True
|
||||
record['native_started'] = False
|
||||
_write_json(root/'export-launch.json', {'started': False})
|
||||
record.update(detail=str(error), safe_to_continue=released)
|
||||
return record
|
||||
finally:
|
||||
if process is not None and not released:
|
||||
_retained_exports.append((process, handles))
|
||||
import json
|
||||
owner_path = root/'export-owner.json'
|
||||
try:
|
||||
owner = json.loads(owner_path.read_text('utf-8')) if owner_path.is_file() else {}
|
||||
except (ValueError, OSError):
|
||||
owner = {} # Preserve unknown ownership; never lose the live handles.
|
||||
_retained_exports.append((process, handles, {
|
||||
'library': owner.get('library'), 'project': str(project), 'analysis_root': str(root)}))
|
||||
else:
|
||||
for handle in handles.values(): handle.Close()
|
||||
_write_json(root/(kind+'-process.json'), record)
|
||||
return {'success': True, 'safe_to_continue': True, 'detail': 'All three native exports completed and released.'}
|
||||
try:
|
||||
_write_json(root/(kind+'-process.json'), record)
|
||||
except OSError as error:
|
||||
if not released:
|
||||
raise
|
||||
warning = 'Export diagnostic write failed: '+str(error)
|
||||
diagnostic_warnings.append(warning)
|
||||
record['detail'] = (record.get('detail', '')+'\n'+warning).strip()
|
||||
return {'success': True, 'safe_to_continue': True,
|
||||
'detail': '\n'.join(['All three native exports completed and released.', *diagnostic_warnings])}
|
||||
|
||||
|
||||
def capture_identity(source, evidence_root, *, expected_library, owner_library, mentor_home,
|
||||
@@ -374,18 +413,22 @@ def capture_identity(source, evidence_root, *, expected_library, owner_library,
|
||||
from .scoped_manifest import copy_verified
|
||||
from .native_export_guard import begin_export_analysis, finish_export_analysis
|
||||
import win32event, win32con
|
||||
source, pcb, top = source_project(source)
|
||||
root = Path(evidence_root).absolute()
|
||||
library = Path(owner_library)
|
||||
lease = LibraryLock(library)
|
||||
if owned_snapshot(lease.path) is None:
|
||||
raise ValueError('Native identity capture requires a current-thread transaction library lease.')
|
||||
if (root.resolve().is_relative_to(source.parent) or source.parent.is_relative_to(root.resolve())
|
||||
or root.resolve().is_relative_to(library.parent.resolve())):
|
||||
raise ValueError('Native identity evidence must be independent of source and library.')
|
||||
check_exporters(mentor_home)
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
root = Path(evidence_root)
|
||||
try:
|
||||
root = root.absolute()
|
||||
source, pcb, top = source_project(source)
|
||||
library = Path(owner_library)
|
||||
lease = LibraryLock(library)
|
||||
if owned_snapshot(lease.path) is None:
|
||||
raise ValueError('Native identity capture requires a current-thread transaction library lease.')
|
||||
if (root.resolve().is_relative_to(source.parent) or source.parent.is_relative_to(root.resolve())
|
||||
or root.resolve().is_relative_to(library.parent.resolve())):
|
||||
raise ValueError('Native identity evidence must be independent of source and library.')
|
||||
check_exporters(mentor_home)
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
except Exception as error:
|
||||
return IdentityOutcome(None, True, str(error), root)
|
||||
acquired = False
|
||||
owner_safe = True
|
||||
outcome = IdentityOutcome(None, True, 'Identity capture did not start.', root)
|
||||
@@ -403,10 +446,11 @@ def capture_identity(source, evidence_root, *, expected_library, owner_library,
|
||||
export_token = begin_export_analysis(library, root, clone)
|
||||
owner_safe = False
|
||||
native = _run_exports(clone, root, mentor_home, timeout_seconds)
|
||||
_write_json(root/'native-outcome.json', native)
|
||||
if native.get('safe_to_continue') is True:
|
||||
finish_export_analysis(library, export_token)
|
||||
finish_export_analysis(library, export_token,
|
||||
native_not_started=native.get('native_started') is False)
|
||||
owner_safe = True
|
||||
_write_json(root/'native-outcome.json', native)
|
||||
if not owner_safe or not native.get('success'):
|
||||
outcome = IdentityOutcome(None, owner_safe, native.get('detail', 'Native export failed.'), root)
|
||||
else:
|
||||
@@ -423,6 +467,10 @@ def capture_identity(source, evidence_root, *, expected_library, owner_library,
|
||||
finally:
|
||||
if acquired: win32event.ReleaseMutex(mutex)
|
||||
mutex.Close()
|
||||
_write_json(root/'identity.json', {'identity': outcome.identity, 'safe_to_continue': outcome.safe_to_continue,
|
||||
'detail': outcome.detail, 'policy': POLICY})
|
||||
try:
|
||||
_write_json(root/'identity.json', {'identity': outcome.identity, 'safe_to_continue': outcome.safe_to_continue,
|
||||
'detail': outcome.detail, 'policy': POLICY})
|
||||
except OSError as error:
|
||||
outcome = IdentityOutcome(outcome.identity, outcome.safe_to_continue,
|
||||
outcome.detail+'\nIdentity summary write failed: '+str(error), root)
|
||||
return outcome
|
||||
@@ -7,11 +7,16 @@ from uuid import uuid4
|
||||
from .management import _write_json
|
||||
|
||||
|
||||
def assert_retained_exports_idle():
|
||||
def assert_retained_exports_idle(library=None):
|
||||
import win32con, win32event
|
||||
from .native_engineering_identity import _retained_exports
|
||||
from .library_lock import LibraryBusy
|
||||
for process, handles in _retained_exports:
|
||||
for entry in _retained_exports:
|
||||
process, handles = entry[:2]
|
||||
scope = entry[2] if len(entry) > 2 else {}
|
||||
if (library is not None and scope.get('library')
|
||||
and Path(scope['library']).resolve() != Path(library).resolve()):
|
||||
continue
|
||||
if process.poll() is None or any(win32event.WaitForSingleObject(handle, 0) != win32con.WAIT_OBJECT_0
|
||||
for handle in handles.values()):
|
||||
raise LibraryBusy('Native identity exporter or descendant has not released.')
|
||||
@@ -40,26 +45,33 @@ def begin_export_analysis(library, root, project):
|
||||
|
||||
|
||||
@contextmanager
|
||||
def prove_export_copies_released(library):
|
||||
def prove_export_copies_released(library, *, allow_unknown_checkpoint=False, unstarted_token=''):
|
||||
"""Fresh process and exclusive-copy proof, including after interpreter exit."""
|
||||
import win32file, win32con, pywintypes
|
||||
from .library_lock import blocker_path, checkpoint_record, _supervisor_alive, LibraryBusy
|
||||
from .native_engineering_identity import _process_snapshot, _OWNER_NAMES
|
||||
from .scoped_manifest import scan_tree
|
||||
assert_retained_exports_idle()
|
||||
library = Path(library).resolve()
|
||||
assert_retained_exports_idle(library)
|
||||
marker = blocker_path(library)
|
||||
checkpoint = checkpoint_record(marker)
|
||||
if marker.exists() and checkpoint is None:
|
||||
raise LibraryBusy('Invalid library checkpoint cannot release export ownership.')
|
||||
if not allow_unknown_checkpoint:
|
||||
raise LibraryBusy('Invalid library checkpoint cannot release export ownership.')
|
||||
# Only the explicit release path supplies full-library/native proof and
|
||||
# archives the unchanged metadata while its coordination handle is held.
|
||||
assert_retained_exports_idle()
|
||||
if any(p['name'].casefold() in _OWNER_NAMES for p in _process_snapshot()):
|
||||
raise LibraryBusy('Unknown export checkpoint still has a possible native identity owner.')
|
||||
yield []
|
||||
return
|
||||
if checkpoint is None or 'export_analysis' not in checkpoint:
|
||||
yield []
|
||||
return
|
||||
records = checkpoint['export_analysis']
|
||||
if not isinstance(records, list) or not records:
|
||||
raise LibraryBusy('Invalid export-analysis ownership record.')
|
||||
owners = [p for p in _process_snapshot() if p['name'].casefold() in _OWNER_NAMES]
|
||||
if owners: raise LibraryBusy(f'Native identity owners remain active: {owners}')
|
||||
snapshot = None
|
||||
copies = []
|
||||
with ExitStack() as stack:
|
||||
for record in records:
|
||||
@@ -78,15 +90,43 @@ def prove_export_copies_released(library):
|
||||
processes = [root/(kind+'-process.json') for kind in ('ascii', 'csv', 'edif')
|
||||
if (root/(kind+'-process.json')).exists()]
|
||||
if not processes:
|
||||
launch = json.loads((root/'export-launch.json').read_text(encoding='utf-8'))
|
||||
if launch != {'started': False}:
|
||||
launch_path = root/'export-launch.json'
|
||||
launch = json.loads(launch_path.read_text('utf-8')) if launch_path.exists() else None
|
||||
unstarted_current_lease = False
|
||||
if unstarted_token and record['token'] == unstarted_token:
|
||||
# In-memory no-start proof may clear its own guard even
|
||||
# when creating the first launch record failed.
|
||||
from .management_transaction import current_lease
|
||||
current = current_lease(library)
|
||||
unstarted_current_lease = (record['lease_id'] == current['lease_id']
|
||||
and record['supervisor_pid'] == current['supervisor_pid'])
|
||||
if launch != {'started': False} and not (launch is None and unstarted_current_lease):
|
||||
raise ValueError('Export launch has no confirmed process record.')
|
||||
else:
|
||||
if snapshot is None:
|
||||
snapshot = _process_snapshot()
|
||||
from .backup_recovery import _native_scope_match
|
||||
if any(p['name'].casefold() in _OWNER_NAMES and _native_scope_match(
|
||||
p.get('command', ''), roots=(project.parent,)) is True for p in snapshot):
|
||||
raise LibraryBusy('A native identity owner is bound to this analysis copy.')
|
||||
for path in processes:
|
||||
process = json.loads(path.read_text(encoding='utf-8'))
|
||||
if ('pid' not in process and process.get('safe_to_continue') is True
|
||||
and process.get('native_started') is False
|
||||
and json.loads((root/'export-launch.json').read_text('utf-8')) == {'started': False}):
|
||||
continue # Failed CreateProcess: no native ownership was acquired.
|
||||
pids = process.get('observed_pids', []) + [process['pid']]
|
||||
if any(not isinstance(pid, int) or pid <= 0 for pid in pids):
|
||||
raise ValueError('Invalid export process identity.')
|
||||
if any(_supervisor_alive(pid) for pid in pids):
|
||||
identities = {p['pid']: p for p in process.get('process_identities', [])}
|
||||
def original_alive(pid):
|
||||
recorded = identities.get(pid, {})
|
||||
current = next((p for p in snapshot if p['pid'] == pid), None)
|
||||
if recorded.get('created') and current and current.get('created'):
|
||||
return (recorded['created'] == current['created']
|
||||
and recorded.get('executable') == current.get('executable'))
|
||||
return any(p['pid'] == pid for p in snapshot) or _supervisor_alive(pid)
|
||||
if any(original_alive(pid) for pid in pids):
|
||||
raise LibraryBusy('A recorded export process or descendant remains alive.')
|
||||
entries = scan_tree(root/'project')
|
||||
if any(path.name.casefold() == 'saddress.adr' for path in entries):
|
||||
@@ -105,9 +145,10 @@ def prove_export_copies_released(library):
|
||||
yield copies
|
||||
|
||||
|
||||
def finish_export_analysis(library, token):
|
||||
def finish_export_analysis(library, token, *, native_not_started=False):
|
||||
from .library_lock import _guard, blocker_path, checkpoint_record, LibraryBusy
|
||||
with _guard, prove_export_copies_released(library):
|
||||
with _guard, prove_export_copies_released(library,
|
||||
unstarted_token=token if native_not_started else ''):
|
||||
marker = blocker_path(library)
|
||||
checkpoint = checkpoint_record(marker)
|
||||
records = checkpoint.get('export_analysis', []) if checkpoint else []
|
||||
|
||||
@@ -21,6 +21,12 @@ from .scoped_manifest import hash_file
|
||||
from .network_path import absolute_preserving_drive
|
||||
|
||||
_retained_workers = []
|
||||
|
||||
|
||||
class NativeOperationError(RuntimeError):
|
||||
def __init__(self, detail, *, safe_to_continue):
|
||||
super().__init__(detail)
|
||||
self.safe_to_continue = safe_to_continue
|
||||
# Coordinator-owned Create/Add/conflict/update/remove/backup-reimport evidence:
|
||||
# diagnostics/issue2-native-crud-20261103/engine-e2e/cycle-result.json
|
||||
_PRODUCTION_ADD_VALIDATED = True
|
||||
@@ -62,6 +68,28 @@ class NativeManagementAdapter:
|
||||
self.timeout_seconds = timeout_seconds
|
||||
self.mapped_drive = ''
|
||||
self.mapped_remote_root = ''
|
||||
self._pending_workers = {}
|
||||
|
||||
def release_confirmed(self, library):
|
||||
"""Reap only this adapter's timed-out worker after its own release result."""
|
||||
key = str(Path(library).resolve()).casefold()
|
||||
pending = self._pending_workers.get(key)
|
||||
if pending is None:
|
||||
return False
|
||||
worker, evidence = pending
|
||||
if worker.poll() is None:
|
||||
return False
|
||||
try:
|
||||
result = json.loads((evidence/'result.json').read_text(encoding='utf-8'))
|
||||
if result.get('safe_to_continue') is not True:
|
||||
return False
|
||||
except (OSError, ValueError, TypeError, AttributeError):
|
||||
return False
|
||||
worker.close()
|
||||
if worker in _retained_workers:
|
||||
_retained_workers.remove(worker)
|
||||
del self._pending_workers[key]
|
||||
return True
|
||||
|
||||
def bind_library_mapping(self, drive, remote_root):
|
||||
self.mapped_drive = drive or ''
|
||||
@@ -105,14 +133,18 @@ class NativeManagementAdapter:
|
||||
}
|
||||
|
||||
def _worker(self, job, evidence):
|
||||
evidence = Path(evidence)
|
||||
evidence.mkdir(parents=True, exist_ok=False)
|
||||
desktop = 'CbbManagement_' + uuid4().hex[:12]
|
||||
timeout = float(job.get('timeout_seconds', self.timeout_seconds))
|
||||
job = {**job, 'desktop': desktop, 'mentor_home': str(self.home or ''),
|
||||
'mapped_drive': job.get('mapped_drive', self.mapped_drive),
|
||||
'mapped_remote_root': job.get('mapped_remote_root', self.mapped_remote_root),
|
||||
'timeout_seconds': timeout, 'supervisor_pid': os.getpid()}
|
||||
try:
|
||||
evidence = Path(evidence)
|
||||
evidence.mkdir(parents=True, exist_ok=False)
|
||||
desktop = 'CbbManagement_' + uuid4().hex[:12]
|
||||
timeout = float(job.get('timeout_seconds', self.timeout_seconds))
|
||||
job = {**job, 'desktop': desktop, 'mentor_home': str(self.home or ''),
|
||||
'mapped_drive': job.get('mapped_drive', self.mapped_drive),
|
||||
'mapped_remote_root': job.get('mapped_remote_root', self.mapped_remote_root),
|
||||
'timeout_seconds': timeout, 'supervisor_pid': os.getpid()}
|
||||
except Exception as error:
|
||||
error.safe_to_continue = True
|
||||
raise
|
||||
if job['operation'] == 'add':
|
||||
import win32con, win32event
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
@@ -158,6 +190,23 @@ class NativeManagementAdapter:
|
||||
return self._launch_worker(job, evidence)
|
||||
|
||||
def _launch_worker(self, job, evidence):
|
||||
state = {'attempted': False, 'worker': None, 'released': False}
|
||||
try:
|
||||
return self._launch_worker_observed(job, evidence, state)
|
||||
except Exception as error:
|
||||
proof = getattr(error, 'worker_launch_release', None)
|
||||
no_launch = (isinstance(proof, dict) and proof.get('safe_to_continue') is True
|
||||
and proof.get('process_created') is False and proof.get('worker_exited') is True
|
||||
and proof.get('remaining_pids') == [])
|
||||
error.safe_to_continue = (not state['attempted'] or state['released']
|
||||
or (state['worker'] is None and no_launch))
|
||||
if state['worker'] is not None and not error.safe_to_continue:
|
||||
if state['worker'] not in _retained_workers:
|
||||
_retained_workers.append(state['worker'])
|
||||
self._pending_workers[str(Path(job['library']).resolve()).casefold()] = (state['worker'], evidence)
|
||||
raise
|
||||
|
||||
def _launch_worker_observed(self, job, evidence, state):
|
||||
from .desktop_worker import DesktopWorker
|
||||
request_path = evidence/'request.json'
|
||||
desktop, timeout = job['desktop'], job['timeout_seconds']
|
||||
@@ -168,13 +217,17 @@ class NativeManagementAdapter:
|
||||
_write_json(request_path, job)
|
||||
command = ([sys.executable] if getattr(sys, 'frozen', False)
|
||||
else [sys.executable, '-m', 'cbb_refresh_verify'])
|
||||
state['attempted'] = True
|
||||
worker = (self.worker_factory or DesktopWorker)(command + ['--management-worker', str(request_path)], desktop)
|
||||
state['worker'] = worker
|
||||
worker.cbb_library = str(Path(job['library']).resolve())
|
||||
while worker.poll() is None and time.monotonic() < deadline:
|
||||
time.sleep(.1)
|
||||
if worker.poll() is None:
|
||||
# DesktopWorker.close() requests a kill without a cancellation file.
|
||||
# Keep this exact worker alive until its native call returns normally.
|
||||
_retained_workers.append(worker)
|
||||
self._pending_workers[str(Path(job['library']).resolve()).casefold()] = (worker, evidence)
|
||||
if add_job:
|
||||
(evidence/'cancel-native-add.signal').touch()
|
||||
return {'success': False, 'safe_to_continue': False,
|
||||
@@ -183,6 +236,7 @@ class NativeManagementAdapter:
|
||||
result = json.loads((evidence/'result.json').read_text(encoding='utf-8'))
|
||||
if not isinstance(result.get('safe_to_continue'), bool):
|
||||
raise ValueError('原生释放记录缺失')
|
||||
state['released'] = result['safe_to_continue']
|
||||
return result
|
||||
except (OSError, ValueError) as error:
|
||||
return {'success': False, 'safe_to_continue': False, 'detail': str(error)}
|
||||
@@ -192,7 +246,8 @@ class NativeManagementAdapter:
|
||||
def catalog(self, library, evidence):
|
||||
result = self._worker({'operation': 'catalog', 'library': str(absolute_preserving_drive(library))}, evidence)
|
||||
if not result.get('success') or not result.get('safe_to_continue'):
|
||||
raise RuntimeError(result.get('detail', '原生目录复读未确认,禁止文件夹回退。'))
|
||||
raise NativeOperationError(result.get('detail', '原生目录复读未确认,禁止文件夹回退。'),
|
||||
safe_to_continue=result.get('safe_to_continue') is True)
|
||||
return Catalog(Path(result['library']), int(result['flow']),
|
||||
tuple(CatalogEntry(**entry) for entry in result['entries']), result['safe_to_continue'])
|
||||
|
||||
@@ -228,48 +283,65 @@ class NativeManagementAdapter:
|
||||
from .management_transaction import current_lease, prepare_transaction
|
||||
from .management import source_project
|
||||
from .backup_recovery import _align_library
|
||||
if not self.capabilities()['add'].supported:
|
||||
raise ValueError(self.capabilities()['add'].reason)
|
||||
try:
|
||||
if not self.capabilities()['add'].supported:
|
||||
raise ValueError(self.capabilities()['add'].reason)
|
||||
validate_native_copy_paths(request.source, request.library, request.name)
|
||||
except ValueError as error:
|
||||
current_lease(request.library)
|
||||
original_assets = asset_identity(original_source, project_library(original_source))
|
||||
staged, pcb, _ = source_project(request.source, request.top_level_block)
|
||||
if staged.parent != Path(root).resolve()/'source':
|
||||
raise ValueError('Only the engine staged source can be aligned for native Add.')
|
||||
_align_library(staged, pcb, request.library)
|
||||
if asset_identity(staged, request.library) != original_assets:
|
||||
raise ValueError('Staged engineering assets differ from the original source.')
|
||||
except Exception as error:
|
||||
return request, IdentityOutcome(None, True, str(error), Path(root))
|
||||
current_lease(request.library)
|
||||
original_assets = asset_identity(original_source, project_library(original_source))
|
||||
staged, pcb, _ = source_project(request.source, request.top_level_block)
|
||||
if staged.parent != Path(root).resolve()/'source':
|
||||
raise ValueError('Only the engine staged source can be aligned for native Add.')
|
||||
_align_library(staged, pcb, request.library)
|
||||
if asset_identity(staged, request.library) != original_assets:
|
||||
raise ValueError('Staged engineering assets differ from the original source.')
|
||||
proof = capture_identity(staged, Path(root)/'source-identity', expected_library=request.library,
|
||||
owner_library=request.library, mentor_home=self.home, timeout_seconds=request.timeout_seconds)
|
||||
if proof.identity is None or not proof.safe_to_continue:
|
||||
return request, proof
|
||||
token = prepare_transaction(request, root, proof.identity, mentor_home=self.home,
|
||||
fixture=getattr(self, '_fixture_authority', None))
|
||||
try:
|
||||
token = prepare_transaction(request, root, proof.identity, mentor_home=self.home,
|
||||
fixture=getattr(self, '_fixture_authority', None))
|
||||
except Exception as error:
|
||||
return request, IdentityOutcome(None, proof.safe_to_continue, str(error), Path(root))
|
||||
return replace(request, transaction_token=token), proof
|
||||
|
||||
def _add_transaction(self, request, evidence):
|
||||
from contextlib import contextmanager
|
||||
from .management_transaction import validate_transaction
|
||||
from .library_lock import LibraryLock
|
||||
from .native_engineering_identity import capture_identity, project_library
|
||||
from .management import source_project
|
||||
from .backup_recovery import _align_library, _idle_check
|
||||
job = {'operation': 'add', 'authority_kind': 'management', 'transaction_nonce': request.transaction_token,
|
||||
'library': str(absolute_preserving_drive(request.library)), 'source': str(request.source),
|
||||
'name': request.name, 'partition': request.partition, 'top_level_block': request.top_level_block,
|
||||
'source_identity': engineering_identity(request.source), 'supervisor_pid': os.getpid(),
|
||||
'mentor_home': str(self.home), 'timeout_seconds': request.timeout_seconds,
|
||||
'mapped_drive': request.mapped_drive, 'mapped_remote_root': request.mapped_remote_root}
|
||||
prepared = validate_transaction(job, evidence.parent)
|
||||
owner_safe = False
|
||||
with LibraryLock(request.library, safe_to_release=lambda: owner_safe):
|
||||
try:
|
||||
job = {'operation': 'add', 'authority_kind': 'management', 'transaction_nonce': request.transaction_token,
|
||||
'library': str(absolute_preserving_drive(request.library)), 'source': str(request.source),
|
||||
'name': request.name, 'partition': request.partition, 'top_level_block': request.top_level_block,
|
||||
'source_identity': engineering_identity(request.source), 'supervisor_pid': os.getpid(),
|
||||
'mentor_home': str(self.home), 'timeout_seconds': request.timeout_seconds,
|
||||
'mapped_drive': request.mapped_drive, 'mapped_remote_root': request.mapped_remote_root}
|
||||
prepared = validate_transaction(job, evidence.parent)
|
||||
except Exception as error:
|
||||
error.safe_to_continue = True
|
||||
raise
|
||||
owner_safe = True
|
||||
@contextmanager
|
||||
def preserve_release():
|
||||
nonlocal owner_safe
|
||||
try:
|
||||
yield
|
||||
except Exception as error:
|
||||
owner_safe = getattr(error, 'safe_to_continue', owner_safe) is True
|
||||
error.safe_to_continue = owner_safe
|
||||
raise
|
||||
with LibraryLock(request.library, safe_to_release=lambda: owner_safe), preserve_release():
|
||||
owner_safe = False
|
||||
result = self._worker(job, evidence)
|
||||
owner_safe = result.get('safe_to_continue') is True
|
||||
if not owner_safe or not result.get('success'):
|
||||
return NativeOutcome(False, owner_safe, result.get('detail', 'Native Add failed.'), evidence_path=evidence)
|
||||
owner_safe = False
|
||||
# The native editor may leave PCB/pcb.prj relative to the staged
|
||||
# location. Correct only documented library-reference tokens after
|
||||
# its owner has exited, then reopen the native catalog independently.
|
||||
@@ -277,12 +349,10 @@ class NativeManagementAdapter:
|
||||
work = Path(request.library).parent/'ReusableBlocksLP'/request.name/'Work'
|
||||
projects = list(work.glob('*.prj'))
|
||||
if len(projects) != 1:
|
||||
owner_safe = False
|
||||
return NativeOutcome(True, False, 'Registered engineering project is not unique.',
|
||||
return NativeOutcome(True, owner_safe, 'Registered engineering project is not unique.',
|
||||
identity_matches=False, evidence_path=evidence)
|
||||
target, pcb, _ = source_project(projects[0], request.top_level_block)
|
||||
_idle_check(request.library, target, pcb)
|
||||
owner_safe = False
|
||||
from .maintenance_entry import maintenance_project_files
|
||||
project_files = maintenance_project_files(target, pcb)
|
||||
before_refs = {str(p): hash_file(p) for p in project_files}
|
||||
@@ -291,13 +361,13 @@ class NativeManagementAdapter:
|
||||
raise ValueError('Registered project references do not resolve to the exact target library.')
|
||||
_write_json(evidence/'reference-alignment.json', {'before': before_refs,
|
||||
'after': {str(p): hash_file(p) for p in project_files}, 'library': job['library']})
|
||||
owner_safe = False
|
||||
catalog = self.catalog(request.library, evidence/'reopen-aligned')
|
||||
owner_safe = catalog.safe_to_continue
|
||||
entries = [entry for entry in catalog.entries if entry.name == request.name and entry.partition == request.partition]
|
||||
if (not owner_safe or Path(catalog.library).resolve() != Path(request.library).resolve()
|
||||
or catalog.flow != 1 or len(entries) != 1):
|
||||
owner_safe = False
|
||||
return NativeOutcome(True, False, 'Aligned target did not reopen with the exact catalog identity.',
|
||||
return NativeOutcome(True, owner_safe, 'Aligned target did not reopen with the exact catalog identity.',
|
||||
identity_matches=False, evidence_path=evidence)
|
||||
owner_safe = False
|
||||
proof = capture_identity(target, evidence/'registered-identity', expected_library=request.library,
|
||||
@@ -906,17 +976,21 @@ def _catalog_native(job, root):
|
||||
def _catalog_com(job, root):
|
||||
import pythoncom, win32com.client, win32con, win32gui, win32process
|
||||
from .mentor_adapter import _process_details
|
||||
if job['operation'] == 'add':
|
||||
if job.get('authority_kind') == 'management':
|
||||
from .management_transaction import validate_transaction
|
||||
validate_transaction(job, root.parent)
|
||||
else:
|
||||
validate_owned_fixture_add(job, root)
|
||||
desktop, name = _current_desktop()
|
||||
if name != job['desktop'] or not name.startswith('CbbManagement_'):
|
||||
raise RuntimeError('拒绝在非本次私有桌面读取原生目录。')
|
||||
if _process_details('LibraryManager.exe'):
|
||||
raise RuntimeError('已有 Library Manager 运行,请关闭后重试。')
|
||||
try:
|
||||
if job['operation'] == 'add':
|
||||
if job.get('authority_kind') == 'management':
|
||||
from .management_transaction import validate_transaction
|
||||
validate_transaction(job, root.parent)
|
||||
else:
|
||||
validate_owned_fixture_add(job, root)
|
||||
desktop, name = _current_desktop()
|
||||
if name != job['desktop'] or not name.startswith('CbbManagement_'):
|
||||
raise RuntimeError('拒绝在非本次私有桌面读取原生目录。')
|
||||
if _process_details('LibraryManager.exe'):
|
||||
raise RuntimeError('已有 Library Manager 运行,请关闭后重试。')
|
||||
except Exception as error:
|
||||
error.safe_to_continue = True
|
||||
raise
|
||||
stop = threading.Event()
|
||||
refused = []
|
||||
observed = []
|
||||
@@ -1059,7 +1133,7 @@ def management_worker_main(request_path):
|
||||
request_path = Path(request_path)
|
||||
root = request_path.parent
|
||||
job = json.loads(request_path.read_text(encoding='utf-8'))
|
||||
result = {'success': False, 'safe_to_continue': False}
|
||||
result = {'success': False, 'safe_to_continue': True}
|
||||
try:
|
||||
_, desktop = _current_desktop()
|
||||
if desktop != job['desktop'] or not desktop.startswith('CbbManagement_'):
|
||||
@@ -1077,6 +1151,7 @@ def management_worker_main(request_path):
|
||||
raise ValueError('Native Add requires Logical-Physical.')
|
||||
if engineering_identity(job['source']) != job.get('source_identity'):
|
||||
raise ValueError('Staged source engineering identity changed before native Add.')
|
||||
result['safe_to_continue'] = False
|
||||
result = _catalog_native(job, root)
|
||||
elif job['operation'] == 'remove':
|
||||
adapter = NativeManagementAdapter(mentor_home=job['mentor_home'])
|
||||
@@ -1090,8 +1165,13 @@ def management_worker_main(request_path):
|
||||
command = [str(adapter.home/'lm/win32/bin/CleanWGLib.exe'), str(job['library']), 'F4', str(input_path)]
|
||||
_write_json(root/'command.json', command)
|
||||
with (root/'native-output.txt').open('wb') as output:
|
||||
process = subprocess.Popen(command, stdout=output, stderr=subprocess.STDOUT,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
result['safe_to_continue'] = False
|
||||
try:
|
||||
process = subprocess.Popen(command, stdout=output, stderr=subprocess.STDOUT,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
except (FileNotFoundError, PermissionError):
|
||||
result['safe_to_continue'] = True
|
||||
raise
|
||||
_write_json(root/'native-process.json', {'pid': process.pid, 'command': command})
|
||||
# Never terminate this native database owner on timeout.
|
||||
try:
|
||||
@@ -1099,12 +1179,15 @@ def management_worker_main(request_path):
|
||||
except subprocess.TimeoutExpired:
|
||||
result.update(detail=f'TIMEOUT: CleanWGLib PID {process.pid} 尚未释放')
|
||||
else:
|
||||
result.update(safe_to_continue=True, exit_code=code)
|
||||
text = (root/'native-output.txt').read_bytes().decode('mbcs', errors='replace')
|
||||
result.update(success=removal_output_ok(code, text, job['name'], job['partition']),
|
||||
safe_to_continue=True, detail=text, exit_code=code)
|
||||
detail=text)
|
||||
else:
|
||||
raise ValueError('未验证的原生管理操作')
|
||||
except Exception as error:
|
||||
if getattr(error, 'safe_to_continue', None) is True:
|
||||
result['safe_to_continue'] = True
|
||||
result['detail'] = str(error)
|
||||
result['exception'] = _exception_details(error)
|
||||
finally:
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Interpret the current Project Backup loading session, before any Repair."""
|
||||
import ntpath
|
||||
import re
|
||||
|
||||
|
||||
def _same(left, right):
|
||||
return ntpath.normcase(ntpath.normpath(str(left))) == ntpath.normcase(ntpath.normpath(str(right)))
|
||||
|
||||
|
||||
def classify_inspection(project, database, output):
|
||||
result = {'status': 'UNCONFIRMED', 'repair_required': False}
|
||||
if not isinstance(output, str):
|
||||
return result
|
||||
loaded = re.findall(r'Loading project file \[([^\]\r\n]+)\]\.', output)
|
||||
if len(loaded) != 1 or not _same(loaded[0], project):
|
||||
return result
|
||||
checking = 'Checking if project is in use.'
|
||||
if checking not in output:
|
||||
return result
|
||||
current = output.rsplit(checking, 1)[1]
|
||||
if re.search(r'\bProject is in use\b', current, re.I):
|
||||
return {**result, 'status': 'IN_USE'}
|
||||
if ("Project is not in use. Full iCDB Project Backup's functionality is available." not in current
|
||||
or 'Backup information loaded correctly.' not in current):
|
||||
return result
|
||||
# This exact native error was captured from the isolated EE7.9.5 project.
|
||||
# A generic 'try Repair' or an old error before the latest check is not proof.
|
||||
inconsistency_pattern = (
|
||||
r"Project database \[([^\]\r\n]+)\] is inconsistent\. It has been manually copied while the iCDB Server was running\. "
|
||||
r"Please use iCDB Project Backup 'Repair project' functionality to fix this issue\.")
|
||||
inconsistent = re.findall(inconsistency_pattern, current)
|
||||
from .icdb_recovery import _session_losses
|
||||
losses = list(_session_losses(current))
|
||||
if (len(inconsistent) > 1 or any(not _same(path, database) for path in inconsistent)
|
||||
or len(losses) > 1 or any(not lost.get('session') or lost.get('scope') != 'project'
|
||||
or not _same(lost.get('database_path', ''), database) for lost in losses)):
|
||||
return result
|
||||
required = bool(inconsistent or losses)
|
||||
remaining = re.sub(inconsistency_pattern, '', current)
|
||||
if required:
|
||||
remaining = remaining.replace('Please try to repair the project!', '')
|
||||
if re.search(r'\berror\b|try to repair|inconsistent|corrupt', remaining, re.I):
|
||||
return result
|
||||
return {'status': 'NOT_IN_USE', 'repair_required': bool(required)}
|
||||
|
||||
|
||||
def confirmed_inspection(target, record):
|
||||
"""Only an exact, exited, inspection-only native process grants a verdict."""
|
||||
if (not isinstance(record, dict) or record.get('inspection_only') is not True
|
||||
or record.get('repair_requested') is not False
|
||||
or type(record.get('native_pid')) is not int or record['native_pid'] <= 0
|
||||
or record.get('native_exit_code') != 0
|
||||
or record.get('release', {}).get('native_exited') is not True
|
||||
or not _same(record.get('project', ''), target.project)
|
||||
or not _same(record.get('database', ''), target.database)
|
||||
or record.get('unknown_dialogs')):
|
||||
return False
|
||||
expected = classify_inspection(target.project, target.database, record.get('output'))
|
||||
return (expected['status'] in ('NOT_IN_USE', 'IN_USE')
|
||||
and record.get('status') == expected['status']
|
||||
and record.get('repair_required') is expected['repair_required'])
|
||||
@@ -253,8 +253,11 @@ def repair_release_state(request, target, native_result):
|
||||
|
||||
|
||||
def run_native_repair(target, root, *, mentor_bin='', timeout_seconds=300, progress=None,
|
||||
maintenance_context=None):
|
||||
maintenance_context=None, inspection_only=False, stop=None):
|
||||
"""Supervise the GUI on its own desktop; a repair timeout never kills it."""
|
||||
if stop is not None and stop.is_set():
|
||||
return {'status': 'CANCELLED', 'native_started': False,
|
||||
'detail': '原生操作启动前已取消', 'release': {'safe_to_continue': True}}
|
||||
from .desktop_worker import DesktopWorker
|
||||
root = Path(root)
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
@@ -264,16 +267,23 @@ def run_native_repair(target, root, *, mentor_bin='', timeout_seconds=300, progr
|
||||
job_path.write_text(json.dumps({'project': str(target.project), 'database': str(target.database),
|
||||
'root': str(root), 'mentor_bin': str(mentor_bin or ''), 'timeout': timeout_seconds,
|
||||
'cancel_signal': str(cancel), 'supervisor_pid': os.getpid(), 'desktop': desktop,
|
||||
'maintenance_context': maintenance_context},
|
||||
'maintenance_context': maintenance_context, 'inspection_only': inspection_only},
|
||||
ensure_ascii=False), encoding='utf-8')
|
||||
command = ([sys.executable] if getattr(sys, 'frozen', False) else
|
||||
[sys.executable, '-m', 'cbb_refresh_verify']) + ['--repair-worker', str(job_path)]
|
||||
worker = DesktopWorker(command, desktop)
|
||||
worker.bind_cancellation(cancel)
|
||||
deadline = time.monotonic()+max(1, float(timeout_seconds))+5
|
||||
# Worker admission includes filesystem/ownership checks before the native
|
||||
# timeout begins. Bound that preparation separately; never extend on polls.
|
||||
deadline = time.monotonic()+60+max(1, float(timeout_seconds))+5
|
||||
event_count = 0
|
||||
cancelled = False
|
||||
try:
|
||||
while worker.poll() is None and time.monotonic()<deadline:
|
||||
if not cancelled and stop is not None and stop.is_set():
|
||||
worker.request_stop()
|
||||
cancelled = True
|
||||
deadline = min(deadline, time.monotonic()+5)
|
||||
event_file = root/'repair-events.jsonl'
|
||||
if progress and event_file.is_file():
|
||||
lines = event_file.read_text('utf-8').splitlines()
|
||||
@@ -287,11 +297,13 @@ def run_native_repair(target, root, *, mentor_bin='', timeout_seconds=300, progr
|
||||
outcome = root/'repair-result.json'
|
||||
if worker.poll() is None or not outcome.is_file():
|
||||
worker.request_stop()
|
||||
return {'status': 'TIMEOUT_UNRELEASED', 'worker_pid': worker.pid, 'desktop': desktop,
|
||||
return {'status': 'CANCELLED_UNRELEASED' if cancelled else 'TIMEOUT_UNRELEASED', 'worker_pid': worker.pid, 'desktop': desktop,
|
||||
'release': {'safe_to_continue': False},
|
||||
'detail': '原生修复尚未确认结束,保留操作并停止批次', 'evidence_path': str(root)}
|
||||
result = json.loads(outcome.read_text('utf-8'))
|
||||
if worker.returncode != 0 and result.get('status') == 'REPAIRED':
|
||||
if cancelled:
|
||||
result.update(status='CANCELLED', repair_required=False)
|
||||
if worker.returncode != 0 and result.get('status') in ('REPAIRED', 'NOT_IN_USE', 'IN_USE'):
|
||||
result['status'] = 'UNCONFIRMED'
|
||||
return {**result, 'evidence_path': str(root)}
|
||||
finally:
|
||||
|
||||
@@ -98,7 +98,7 @@ def _repair_command(executable):
|
||||
|
||||
|
||||
def _windows(pid):
|
||||
import win32gui, win32process
|
||||
import win32api, win32gui, win32process
|
||||
windows = []
|
||||
def observe(hwnd, _):
|
||||
if win32process.GetWindowThreadProcessId(hwnd)[1] != pid or not win32gui.IsWindowVisible(hwnd):
|
||||
@@ -109,10 +109,14 @@ def _windows(pid):
|
||||
children.append({'hwnd': handle, 'text': win32gui.GetWindowText(handle),
|
||||
'class': win32gui.GetClassName(handle), 'id': win32gui.GetDlgCtrlID(handle),
|
||||
'enabled': bool(win32gui.IsWindowEnabled(handle))})
|
||||
# Empty window lists are valid. pywin32 otherwise interprets a stale
|
||||
# thread error (observed ERROR_FILE_NOT_FOUND) as an enum failure.
|
||||
win32api.SetLastError(0)
|
||||
win32gui.EnumChildWindows(hwnd, child, None)
|
||||
windows.append({'hwnd': hwnd, 'title': win32gui.GetWindowText(hwnd),
|
||||
'class': win32gui.GetClassName(hwnd), 'enabled': bool(win32gui.IsWindowEnabled(hwnd)),
|
||||
'children': children})
|
||||
win32api.SetLastError(0)
|
||||
win32gui.EnumWindows(observe, None)
|
||||
return windows
|
||||
|
||||
@@ -180,15 +184,98 @@ def _native_evidence(project, database, pid, started_ns, baseline, *, output_tex
|
||||
'restore_tail': restore_log[-8192:]}
|
||||
|
||||
|
||||
def _inspect_project(job, process, emit):
|
||||
"""Observe this process's native query; never send a Repair/menu command."""
|
||||
import win32con, win32gui
|
||||
from .native_occupancy import classify_inspection
|
||||
project, database = Path(job['project']), Path(job['database'])
|
||||
result = {'status': 'UNCONFIRMED', 'project': str(project), 'database': str(database),
|
||||
'native_pid': process.pid, 'inspection_only': True, 'repair_requested': False,
|
||||
'repair_required': False, 'output': ''}
|
||||
deadline = time.monotonic() + max(1, float(job['timeout']))
|
||||
closing = False
|
||||
last_state = None
|
||||
# Reserve a short cooperative-close grace after the inspection deadline.
|
||||
while process.poll() is None and time.monotonic() < deadline + 3:
|
||||
windows = [w for w in _windows(process.pid) if not (
|
||||
w['title'] == '' and w['class'] in ('UAC_InputIndicatorOverlayWnd', 'UAC Input Indicator'))]
|
||||
shells = [w for w in windows if w['class'].startswith('Afx:') and w['title'] == 'iCDB Project Backup']
|
||||
exact = [w for w in windows if w['class'].startswith('Afx:')
|
||||
and w['title'].casefold() == ('iCDB Project Backup - '+str(project)).casefold()]
|
||||
# EE7.9 can keep the generic shell title while loading the requested PRJ.
|
||||
# Its Output still binds the project; waiting only for the decorated title
|
||||
# turns a valid session into a false timeout.
|
||||
mains = exact or shells
|
||||
main = mains[0] if len(mains) == 1 else None
|
||||
unknown = [w for w in windows if w is not main and w not in shells]
|
||||
if unknown:
|
||||
result.update(status='UNCONFIRMED', unknown_dialogs=unknown)
|
||||
break
|
||||
current = _native_output(windows)
|
||||
state = {'main_found': main is not None, 'output_readable': current is not None,
|
||||
'windows': windows}
|
||||
if state != last_state:
|
||||
(Path(job['root'])/'inspection-state.json').write_text(
|
||||
json.dumps(state, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
emit(stage='native_occupancy_wait', main_found=state['main_found'], output_readable=state['output_readable'])
|
||||
last_state = state
|
||||
if current is not None:
|
||||
result['output'] = current
|
||||
cancelled = Path(job['cancel_signal']).exists()
|
||||
expired = time.monotonic() >= deadline
|
||||
verdict = classify_inspection(project, database, current)
|
||||
if cancelled:
|
||||
result.update(status='CANCELLED', repair_required=False)
|
||||
if not closing and main and main['enabled'] and (cancelled or expired or verdict['status'] != 'UNCONFIRMED'):
|
||||
if not cancelled and not expired: result.update(verdict)
|
||||
emit(stage='native_occupancy', **result)
|
||||
win32gui.PostMessage(main['hwnd'], win32con.WM_CLOSE, 0, 0)
|
||||
closing = True
|
||||
time.sleep(.2)
|
||||
exited = process.poll() is not None
|
||||
result['native_exit_code'] = process.poll()
|
||||
result['release'] = {'native_exited': exited,
|
||||
'addresses': [str(database/'cdbsvr/sAddress.adr')] if (database/'cdbsvr/sAddress.adr').exists() else [],
|
||||
'safe_to_continue': exited and result['status'] == 'NOT_IN_USE'}
|
||||
if not exited:
|
||||
result.update(status='TIMEOUT_UNRELEASED', repair_required=False)
|
||||
result['detail'] = ('原生检查窗口未返回 Output,未执行 Repair。'
|
||||
if not result['output'] else '原生检查工具未退出,未执行 Repair。')
|
||||
return result
|
||||
|
||||
|
||||
class _CancellationFile:
|
||||
def __init__(self, path):
|
||||
self.path = Path(path)
|
||||
self._next_poll = 0.0
|
||||
self._cancelled = False
|
||||
self.polls = 0
|
||||
self.poll_seconds = 0.0
|
||||
|
||||
def is_set(self):
|
||||
# scan_tree checks between every entry. Avoid issuing tens of
|
||||
# thousands of filesystem requests just to observe one IPC flag.
|
||||
# The direct checks before Popen/Repair remain immediate.
|
||||
now = time.monotonic()
|
||||
if not self._cancelled and now >= self._next_poll:
|
||||
self._cancelled = self.path.exists()
|
||||
finished = time.monotonic()
|
||||
self.polls += 1
|
||||
self.poll_seconds += finished-now
|
||||
self._next_poll = finished + .1
|
||||
return self._cancelled
|
||||
|
||||
|
||||
def repair_worker_main(job_path):
|
||||
import win32con, win32gui
|
||||
from .native_repair import RepairTarget, check_repair_access
|
||||
from .mentor_paths import discover_sdd_home
|
||||
from .icdb_recovery import snapshot_log
|
||||
job = json.loads(Path(job_path).read_text('utf-8'))
|
||||
stop = _CancellationFile(job['cancel_signal'])
|
||||
root = Path(job['root'])
|
||||
project, database = Path(job['project']), Path(job['database'])
|
||||
result = {'status': 'BLOCKED', 'project': str(project), 'database': str(database),
|
||||
result = {'status': 'BLOCKED', 'native_started': False, 'project': str(project), 'database': str(database),
|
||||
'release': {'safe_to_continue': False}}
|
||||
process = None
|
||||
def emit(**event):
|
||||
@@ -208,9 +295,9 @@ def repair_worker_main(job_path):
|
||||
if home is None:
|
||||
raise ValueError('NATIVE_REPAIR_UNAVAILABLE: 未找到 Mentor 安装目录')
|
||||
executable = home/'iCDB/win32/bin/iCDBProjectBackup.exe'
|
||||
command_id = _repair_command(executable)
|
||||
command_id = None if job.get('inspection_only') else _repair_command(executable)
|
||||
from .mentor_adapter import pcb_processes, _process_details
|
||||
if pcb_processes() or _process_details('LibraryManager.exe'):
|
||||
if not job.get('inspection_only') and (pcb_processes() or _process_details('LibraryManager.exe')):
|
||||
raise ValueError('REPAIR_DATABASE_IN_USE')
|
||||
maintenance_context = job.get('maintenance_context')
|
||||
if maintenance_context is not None:
|
||||
@@ -218,22 +305,43 @@ def repair_worker_main(job_path):
|
||||
from .verify_runner import VerifyRequest
|
||||
maintenance_request = VerifyRequest(Path(maintenance_context['library']),
|
||||
maintenance_context['block'], root, maintenance=True)
|
||||
with maintenance_target_guard(maintenance_request, maintenance_context) as checked:
|
||||
if (checked['target'].project.resolve() != project.resolve()
|
||||
or checked['target'].database.resolve() != database.resolve()):
|
||||
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED')
|
||||
check_repair_access(RepairTarget(project, database))
|
||||
emit(stage='backup_skipped', reason='manual_backup_policy',
|
||||
detail='应用不自动备份;Mentor 原生修复仍可能生成自身备份。')
|
||||
emit(stage='native_preflight', detail='正在核对本次原生工具的目标及占用')
|
||||
if job.get('inspection_only'):
|
||||
from .scoped_manifest import scan_tree
|
||||
def check_cancelled():
|
||||
if stop.is_set():
|
||||
raise InterruptedError('检查已取消')
|
||||
scan_tree(project.parent, check=check_cancelled)
|
||||
else:
|
||||
check_repair_access(RepairTarget(project, database))
|
||||
emit(stage='backup_skipped', reason='manual_backup_policy',
|
||||
detail='应用不自动备份;Mentor 原生修复仍可能生成自身备份。')
|
||||
if Path(job['cancel_signal']).exists():
|
||||
raise ValueError('REPAIR_CANCELLED_BEFORE_LAUNCH')
|
||||
if maintenance_context is not None:
|
||||
with maintenance_target_guard(maintenance_request, maintenance_context): pass
|
||||
# Manual backup policy leaves no mutation between preparation and
|
||||
# launch. Run the complete guard once here, retaining its identity,
|
||||
# address and exclusive-access checks immediately before Popen.
|
||||
with maintenance_target_guard(maintenance_request, maintenance_context, stop=stop) as checked:
|
||||
if (checked['target'].project.resolve() != project.resolve()
|
||||
or checked['target'].database.resolve() != database.resolve()):
|
||||
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED')
|
||||
emit(stage='native_preflight_complete', cancellation_polls=stop.polls,
|
||||
cancellation_poll_seconds=round(stop.poll_seconds, 3))
|
||||
if Path(job['cancel_signal']).exists():
|
||||
raise ValueError('REPAIR_CANCELLED_BEFORE_LAUNCH')
|
||||
baseline = snapshot_log(project.parent/'Log Files/ProjectBackupLog.txt')
|
||||
started_ns = time.time_ns()
|
||||
if Path(job['cancel_signal']).exists():
|
||||
raise ValueError('REPAIR_CANCELLED_BEFORE_LAUNCH')
|
||||
process = subprocess.Popen([str(executable), '-p', str(project)], cwd=str(project.parent))
|
||||
result['native_started'] = True
|
||||
result['native_pid'] = process.pid
|
||||
emit(stage='native_started', pid=process.pid, project=str(project))
|
||||
if job.get('inspection_only'):
|
||||
result = _inspect_project(job, process, emit)
|
||||
(root/'repair-result.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
return 0 if result['status'] in ('NOT_IN_USE', 'IN_USE') else 1
|
||||
deadline = time.monotonic()+max(1, float(job['timeout']))
|
||||
invoked = confirmed = closing = False
|
||||
evidence = None
|
||||
@@ -336,6 +444,8 @@ def repair_worker_main(job_path):
|
||||
detail='原生 Repair 未取得完整成功/释放证据,未重试校验')
|
||||
except Exception as error:
|
||||
result.update(detail=str(error), status='RETAINED' if process and process.poll() is None else 'BLOCKED')
|
||||
result['preflight_cancellation'] = {'polls': stop.polls,
|
||||
'seconds': round(stop.poll_seconds, 3)}
|
||||
# Never terminate a repair or its database owner. Retained PID/desktop is
|
||||
# reported to the parent, including unknown native prompts.
|
||||
(root/'repair-result.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
|
||||
@@ -9,6 +9,20 @@ import ntpath
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Protocol
|
||||
from functools import wraps
|
||||
from threading import RLock
|
||||
from weakref import WeakValueDictionary
|
||||
|
||||
_retained_path_leases = {}
|
||||
_live_path_leases = WeakValueDictionary()
|
||||
_path_lease_guard = RLock()
|
||||
|
||||
|
||||
def _lease_locked(method):
|
||||
@wraps(method)
|
||||
def locked(*args, **kwargs):
|
||||
with _path_lease_guard: return method(*args, **kwargs)
|
||||
return locked
|
||||
|
||||
|
||||
class NetworkPathError(RuntimeError):
|
||||
@@ -45,23 +59,35 @@ class WindowsWNetBackend:
|
||||
def __init__(self) -> None:
|
||||
self._mpr = ctypes.WinDLL("mpr", use_last_error=True)
|
||||
self._kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
self._unavailable_drives = set()
|
||||
|
||||
def mapping(self, drive: str) -> str | None:
|
||||
size = wintypes.DWORD(32768)
|
||||
buffer = ctypes.create_unicode_buffer(size.value)
|
||||
error = self._mpr.WNetGetConnectionW(drive, buffer, ctypes.byref(size))
|
||||
if error == 0:
|
||||
return buffer.value
|
||||
if error == self.ERROR_NOT_CONNECTED:
|
||||
return None
|
||||
raise OSError(error, f"WNetGetConnectionW({drive})")
|
||||
|
||||
def mappings(self) -> dict[str, str]:
|
||||
result: dict[str, str] = {}
|
||||
self._unavailable_drives = set()
|
||||
for code in range(ord("D"), ord("Z") + 1):
|
||||
drive = f"{chr(code)}:"
|
||||
size = wintypes.DWORD(32768)
|
||||
buffer = ctypes.create_unicode_buffer(size.value)
|
||||
error = self._mpr.WNetGetConnectionW(drive, buffer, ctypes.byref(size))
|
||||
if error == 0:
|
||||
result[drive] = buffer.value
|
||||
elif error != self.ERROR_NOT_CONNECTED:
|
||||
raise OSError(error, f"WNetGetConnectionW({drive})")
|
||||
try:
|
||||
remote = self.mapping(drive)
|
||||
except OSError:
|
||||
self._unavailable_drives.add(drive)
|
||||
continue
|
||||
if remote:
|
||||
result[drive] = remote
|
||||
return result
|
||||
|
||||
def used_drives(self) -> set[str]:
|
||||
mask = int(self._kernel32.GetLogicalDrives())
|
||||
return {
|
||||
return getattr(self, '_unavailable_drives', set()) | {
|
||||
f"{chr(ord('A') + index)}:"
|
||||
for index in range(26)
|
||||
if mask & (1 << index)
|
||||
@@ -88,6 +114,14 @@ def _same_remote(left: str, right: str) -> bool:
|
||||
return ntpath.normcase(ntpath.normpath(left)) == ntpath.normcase(ntpath.normpath(right))
|
||||
|
||||
|
||||
def _mapping(backend, drive):
|
||||
direct = getattr(backend, 'mapping', None)
|
||||
if callable(direct):
|
||||
return direct(drive)
|
||||
return next((value for key, value in backend.mappings().items()
|
||||
if str(key).upper().rstrip('\\/') == drive.upper()), None)
|
||||
|
||||
|
||||
def ensure_mapped_drive_visible(drive: str, remote_root: str, *,
|
||||
backend: WNetBackend | None = None) -> dict[str, object]:
|
||||
"""Ensure a worker process can see the mapped drive used by Mentor.
|
||||
@@ -108,13 +142,11 @@ def ensure_mapped_drive_visible(drive: str, remote_root: str, *,
|
||||
normalized_drive = raw_drive.upper()
|
||||
backend = backend or WindowsWNetBackend()
|
||||
try:
|
||||
mappings = backend.mappings()
|
||||
current = _mapping(backend, normalized_drive)
|
||||
except OSError as error:
|
||||
raise NetworkPathError(
|
||||
f"NETWORK_UNAVAILABLE: 无法读取网络盘映射 {normalized_drive}: {error}"
|
||||
) from error
|
||||
current = next((value for key, value in mappings.items()
|
||||
if str(key).upper().rstrip('\\/') == normalized_drive), None)
|
||||
if current:
|
||||
if _same_remote(current, raw_remote):
|
||||
return {'drive': normalized_drive, 'remote_root': current, 'created': False}
|
||||
@@ -180,7 +212,11 @@ class LibraryPathLease:
|
||||
_closed: bool = False
|
||||
_retained_for_recovery: bool = False
|
||||
|
||||
def __post_init__(self):
|
||||
with _path_lease_guard: _live_path_leases[id(self)] = self
|
||||
|
||||
@classmethod
|
||||
@_lease_locked
|
||||
def acquire(cls, path, *, backend: WNetBackend | None = None) -> "LibraryPathLease":
|
||||
raw = _normalize_input_path(path)
|
||||
if not raw.startswith("\\\\"):
|
||||
@@ -189,8 +225,7 @@ class LibraryPathLease:
|
||||
if drive:
|
||||
try:
|
||||
backend = backend or WindowsWNetBackend()
|
||||
remote = next((value for key, value in backend.mappings().items()
|
||||
if str(key).upper().rstrip('\\/') == drive.upper()), '')
|
||||
remote = _mapping(backend, drive.upper()) or ''
|
||||
except (OSError, AttributeError):
|
||||
remote = ''
|
||||
return cls(local, local, drive.upper(), remote, False, backend)
|
||||
@@ -225,20 +260,61 @@ class LibraryPathLease:
|
||||
f"NETWORK_UNAVAILABLE: 无法挂载中心库 {remote_root}: {error}"
|
||||
) from error
|
||||
|
||||
@_lease_locked
|
||||
def retain_for_recovery(self) -> None:
|
||||
"""Keep the Mentor drive available to a retained native session."""
|
||||
self._retained_for_recovery = True
|
||||
_retained_path_leases[id(self)] = self
|
||||
|
||||
@_lease_locked
|
||||
def release_after_recovery(self, proof) -> bool:
|
||||
"""Restore normal mapping lifetime after this library's release proof."""
|
||||
if not isinstance(proof, dict) or proof.get('status') != 'RELEASE_CONFIRMED':
|
||||
return False
|
||||
candidates = [str(path) for path in (self.display_path, self.mentor_path)
|
||||
if str(path).casefold().endswith('.lmc')]
|
||||
drive, tail = ntpath.splitdrive(str(self.mentor_path))
|
||||
if (self.remote_root and drive.upper() == self.drive.upper()
|
||||
and str(self.mentor_path).casefold().endswith('.lmc')):
|
||||
candidates.append(self.remote_root + tail)
|
||||
library = str(proof.get('library') or '')
|
||||
if not any(_same_remote(library, candidate) for candidate in candidates):
|
||||
return False
|
||||
self._retained_for_recovery = False
|
||||
_retained_path_leases.pop(id(self), None)
|
||||
return True
|
||||
|
||||
@_lease_locked
|
||||
def transfer_ownership(self, other) -> None:
|
||||
"""Keep a shared mapping alive for the currently loaded library."""
|
||||
if (isinstance(other, LibraryPathLease) and not other._closed
|
||||
and self.created and self.drive.upper() == other.drive.upper()
|
||||
and self.remote_root and _same_remote(self.remote_root, other.remote_root)):
|
||||
other.created, other._backend = True, self._backend
|
||||
self.created = False
|
||||
|
||||
@_lease_locked
|
||||
def close(self) -> None:
|
||||
if self._closed:
|
||||
return
|
||||
self._closed = True
|
||||
if self._retained_for_recovery or not self.created or self._backend is None or not self.drive:
|
||||
if self._retained_for_recovery:
|
||||
return
|
||||
if not self.created or self._backend is None or not self.drive:
|
||||
self._closed = True
|
||||
return
|
||||
for live in tuple(_live_path_leases.values()):
|
||||
same_backend = (live._backend is self._backend or
|
||||
isinstance(self._backend, WindowsWNetBackend) and isinstance(live._backend, WindowsWNetBackend))
|
||||
if live is not self and not live._closed and same_backend:
|
||||
self.transfer_ownership(live)
|
||||
if not self.created:
|
||||
self._closed = True
|
||||
return
|
||||
try:
|
||||
current = self._backend.mappings().get(self.drive)
|
||||
current = _mapping(self._backend, self.drive)
|
||||
if current and _same_remote(current, self.remote_root):
|
||||
self._backend.cancel_mapping(self.drive)
|
||||
self._closed = True
|
||||
except OSError as error:
|
||||
raise NetworkPathError(
|
||||
f"NETWORK_UNAVAILABLE: 释放临时盘符 {self.drive} 失败: {error}"
|
||||
@@ -249,3 +325,20 @@ class LibraryPathLease:
|
||||
|
||||
def __exit__(self, exc_type, exc_value, traceback) -> None:
|
||||
self.close()
|
||||
|
||||
|
||||
def release_retained_path_leases(proof, *, current_lease=None) -> int:
|
||||
"""Recover matching leases even after the UI dropped its old reference."""
|
||||
released = 0
|
||||
for lease in tuple(_retained_path_leases.values()):
|
||||
if not lease.release_after_recovery(proof):
|
||||
continue
|
||||
if lease is not current_lease:
|
||||
lease.transfer_ownership(current_lease)
|
||||
try:
|
||||
lease.close()
|
||||
except NetworkPathError:
|
||||
_retained_path_leases[id(lease)] = lease
|
||||
raise
|
||||
released += 1
|
||||
return released
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Cooperative FIFO admission for this application's native operations."""
|
||||
from threading import Condition
|
||||
|
||||
|
||||
class QueueCancelled(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class NativeQueue:
|
||||
def __init__(self):
|
||||
self.condition = Condition()
|
||||
self.pending = []
|
||||
self.active = False
|
||||
|
||||
def wake(self):
|
||||
with self.condition: self.condition.notify_all()
|
||||
|
||||
def run(self, action, *, stop=None, waiting=None, ready=lambda: True):
|
||||
ticket = object()
|
||||
acquired, notified = False, False
|
||||
with self.condition: self.pending.append((ticket, ready))
|
||||
try:
|
||||
while not acquired:
|
||||
with self.condition:
|
||||
if stop is not None and stop.is_set():
|
||||
raise QueueCancelled('已取消排队,未启动原生操作。')
|
||||
first = next((token for token, available in self.pending if available()), None)
|
||||
if not self.active and first is ticket:
|
||||
self.pending = [entry for entry in self.pending if entry[0] is not ticket]
|
||||
self.active = acquired = True
|
||||
else:
|
||||
self.condition.wait(.1)
|
||||
if not acquired and not notified and waiting is not None:
|
||||
notified = True
|
||||
try: waiting()
|
||||
except Exception: pass
|
||||
if stop is not None and stop.is_set():
|
||||
raise QueueCancelled('已取消排队,未启动原生操作。')
|
||||
return action()
|
||||
finally:
|
||||
with self.condition:
|
||||
self.pending = [entry for entry in self.pending if entry[0] is not ticket]
|
||||
if acquired: self.active = False
|
||||
self.condition.notify_all()
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Bound WMI enumeration in a read-only helper, never in the Qt thread."""
|
||||
from pathlib import Path
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
|
||||
def query_owners(names, *, timeout_seconds=10):
|
||||
names = tuple(names)
|
||||
if not names or any(not re.fullmatch(r'[\w.-]+\.exe', name, re.I) for name in names):
|
||||
raise ValueError('OWNER_QUERY_INVALID')
|
||||
return _query_processes(names, timeout_seconds=timeout_seconds)
|
||||
|
||||
|
||||
def query_process_snapshot(*, timeout_seconds=10):
|
||||
"""Bound a complete process tree; retain unknown executable descendants."""
|
||||
return _query_processes(None, timeout_seconds=timeout_seconds)
|
||||
|
||||
|
||||
def _query_processes(names, *, timeout_seconds):
|
||||
full_snapshot = names is None
|
||||
request = {'snapshot_version': 1} if full_snapshot else {'names': names}
|
||||
with tempfile.TemporaryDirectory(prefix='cbb-owner-probe-') as directory:
|
||||
job = Path(directory)/'request.json'
|
||||
job.write_text(json.dumps(request), encoding='utf-8')
|
||||
command = ([sys.executable] if getattr(sys, 'frozen', False) else
|
||||
[sys.executable, '-m', 'cbb_refresh_verify']) + ['--owner-probe', str(job)]
|
||||
try:
|
||||
result = subprocess.run(command, timeout=max(.1, min(10, timeout_seconds)),
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
||||
except subprocess.TimeoutExpired as error:
|
||||
# This helper only enumerates processes; it never launches Mentor
|
||||
# or acquires a native database session.
|
||||
raise RuntimeError('OWNER_QUERY_TIMEOUT: 进程查询超时,占用状态无法确认') from error
|
||||
try:
|
||||
record = json.loads(job.with_name('result.json').read_text('utf-8'))
|
||||
rows = record['owners']
|
||||
identity_matches = (type(record.get('snapshot_version')) is int and record['snapshot_version'] == 1
|
||||
if full_snapshot else record.get('names') == list(names))
|
||||
if result.returncode != 0 or not identity_matches or not isinstance(rows, list):
|
||||
raise ValueError('invalid result')
|
||||
seen = set()
|
||||
for row in rows:
|
||||
if (type(row['pid']) is not int or row['pid'] < (0 if full_snapshot else 1)
|
||||
or row['pid'] in seen or not isinstance(row['name'], str) or not row['name']
|
||||
or not full_snapshot and row['name'].casefold() not in {n.casefold() for n in names}
|
||||
or full_snapshot and not isinstance(row['created'], str)
|
||||
or not isinstance(row['command'], str) or not isinstance(row['executable'], str)
|
||||
or type(row['parent']) is not int or row['parent'] < 0):
|
||||
raise ValueError('invalid owner')
|
||||
seen.add(row['pid'])
|
||||
return rows
|
||||
except (OSError, ValueError, KeyError, TypeError, AttributeError) as error:
|
||||
raise RuntimeError('OWNER_QUERY_UNCONFIRMED: 进程查询未返回有效证据') from error
|
||||
|
||||
|
||||
def owner_probe_main(job):
|
||||
import pythoncom
|
||||
import win32com.client
|
||||
job = Path(job)
|
||||
request = json.loads(job.read_text('utf-8'))
|
||||
full_snapshot = request == {'snapshot_version': 1} and type(request.get('snapshot_version')) is int
|
||||
names = request.get('names')
|
||||
if not full_snapshot:
|
||||
if (not isinstance(names, list) or not names
|
||||
or any(not isinstance(name, str) or not re.fullmatch(r'[\w.-]+\.exe', name, re.I) for name in names)):
|
||||
return 1
|
||||
pythoncom.CoInitialize()
|
||||
try:
|
||||
service = win32com.client.GetObject('winmgmts:')
|
||||
query = ('SELECT ProcessId,Name,CommandLine,ExecutablePath,ParentProcessId' +
|
||||
(',CreationDate' if full_snapshot else '') + ' FROM Win32_Process')
|
||||
if not full_snapshot:
|
||||
query += ' WHERE ' + ' OR '.join(f"Name='{name}'" for name in names)
|
||||
rows = [{'pid': int(item.ProcessId), 'name': str(item.Name),
|
||||
'command': str(item.CommandLine or ''), 'executable': str(item.ExecutablePath or ''),
|
||||
'parent': int(item.ParentProcessId or 0),
|
||||
**({'created': str(item.CreationDate or '')} if full_snapshot else {})}
|
||||
for item in service.ExecQuery(query)]
|
||||
service = None
|
||||
response = {'snapshot_version': 1} if full_snapshot else {'names': names}
|
||||
job.with_name('result.json').write_text(json.dumps({**response, 'owners': rows}), encoding='utf-8')
|
||||
return 0
|
||||
finally:
|
||||
pythoncom.CoUninitialize()
|
||||
@@ -91,6 +91,35 @@ def require_document_identity(document, job):
|
||||
return integration
|
||||
|
||||
|
||||
class ProcessWatch:
|
||||
"""Hold this task's native handles; repeated COM attach polls never run WMI."""
|
||||
def __init__(self, pids):
|
||||
self.pids = set(int(pid) for pid in pids if pid)
|
||||
self.handles = None
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def alive(self):
|
||||
import pywintypes, win32api, win32con, win32event
|
||||
if self.handles is None:
|
||||
self.handles = []
|
||||
try:
|
||||
for pid in self.pids:
|
||||
try:
|
||||
self.handles.append(win32api.OpenProcess(win32con.SYNCHRONIZE, False, pid))
|
||||
except pywintypes.error as error:
|
||||
if error.winerror != 87: raise
|
||||
except Exception:
|
||||
self.__exit__(None, None, None)
|
||||
raise
|
||||
return any(win32event.WaitForSingleObject(h, 0) != win32con.WAIT_OBJECT_0 for h in self.handles)
|
||||
|
||||
def __exit__(self, *_):
|
||||
for handle in self.handles or (): handle.Close()
|
||||
self.handles = []
|
||||
|
||||
|
||||
def wait_for_target_document(job, app_provider, *, process_alive, emit=lambda **event: None,
|
||||
error_reader=None, sleep=time.sleep):
|
||||
"""Wait for the exact launched document; the parent process owns timeout."""
|
||||
@@ -131,18 +160,3 @@ def wait_for_target_document(job, app_provider, *, process_alive, emit=lambda **
|
||||
last_observation = observation
|
||||
sleep(.25)
|
||||
raise PcbBridgeError('PCB_EXITED_BEFORE_COM', 'PCB 在 COM 文档就绪前退出')
|
||||
|
||||
|
||||
def execution_outcome(*, save_complete: bool, pcb_exited: bool,
|
||||
fatal_error: str = '') -> dict[str, object]:
|
||||
if fatal_error:
|
||||
code, _, detail = str(fatal_error).partition(':')
|
||||
return {'status': 'FAIL', 'error_code': code.strip() or 'FATAL_DIALOG',
|
||||
'stderr': detail.strip() or str(fatal_error), 'safe_to_continue': True}
|
||||
if not save_complete:
|
||||
return {'status': 'FAIL', 'error_code': 'SAVE_NOT_CONFIRMED',
|
||||
'stderr': '保存/关闭未完成', 'safe_to_continue': True}
|
||||
if not pcb_exited:
|
||||
return {'status': 'FAIL', 'error_code': 'PCB_EXIT_NOT_CONFIRMED',
|
||||
'stderr': '保存后未确认 PCB 退出', 'safe_to_continue': True}
|
||||
return {'status': 'PASS', 'stdout': 'Project Integration 已同步;保存、关闭和 PCB 退出均已确认。'}
|
||||
@@ -199,7 +199,13 @@ def _validate_current_processes(job, prelaunch, target_pid, launcher_pid, worker
|
||||
or not is_reusable_circuit_pcb(launcher[2], launcher[3], job['pcb'])):
|
||||
raise ValueError('POST_REPAIR_PROCESS_IDENTITY_MISMATCH')
|
||||
allowed = {target_pid, launcher_pid, worker_pid, int(job['supervisor_pid']), *companion_pids}
|
||||
if any(r[0] not in allowed for r in rows): raise ValueError('POST_REPAIR_FOREIGN_OWNER')
|
||||
foreign = [r for r in rows if r[0] not in allowed]
|
||||
if foreign:
|
||||
from .management import _write_json
|
||||
_write_json(Path(job['root'])/'foreign-owners.json', {'allowed_pids': sorted(allowed),
|
||||
'observed': [{'pid': r[0], 'name': r[1], 'executable': r[2], 'command': r[3], 'parent_pid': r[4]}
|
||||
for r in foreign]})
|
||||
raise ValueError(f'POST_REPAIR_FOREIGN_OWNER: {[(r[0], r[1]) for r in foreign]}')
|
||||
|
||||
|
||||
class ConsentController:
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Explicit copy-based recovery after failed maintenance; never auto-replay."""
|
||||
from dataclasses import asdict
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
def offers_reimport(result):
|
||||
return (result.status == 'FAIL' and result.evidence_path is not None
|
||||
and any(attempt.get('status') in {
|
||||
'REPAIR_VALIDATION_FAILED', 'MISSING_HEALTHY_BACKUP', 'NATIVE_REPAIR_FAILED'}
|
||||
for attempt in result.recovery_attempts))
|
||||
|
||||
|
||||
def run_reimport_recovery(requests, *, previous_evidence, evidence_dir,
|
||||
adapter=None, stop=None, progress=None):
|
||||
from .management import ManagementResult, _write_json, source_project, run_management_batch
|
||||
from .library_lock import release_retained_library
|
||||
requests = tuple(requests)
|
||||
if not requests or stop is not None and stop.is_set():
|
||||
return []
|
||||
library = requests[0].library.resolve()
|
||||
evidence_dir = Path(evidence_dir).resolve()
|
||||
if evidence_dir.is_relative_to(library.parent) or library.parent.is_relative_to(evidence_dir):
|
||||
raise ValueError('恢复记录必须位于目标库之外。')
|
||||
root = evidence_dir/('reimport-' + uuid4().hex)
|
||||
root.mkdir(parents=True)
|
||||
report = root/'recovery.json'
|
||||
record = {'library': str(library), 'previous_evidence': previous_evidence,
|
||||
'requests': [asdict(r) for r in requests], 'original_repair_succeeded': False}
|
||||
stage = 'preflight'
|
||||
def save(stage, **extra):
|
||||
record.update(stage=stage, **extra)
|
||||
_write_json(report, record)
|
||||
def cancelled():
|
||||
if stop is not None and stop.is_set():
|
||||
save('cancelled', management_started=False)
|
||||
return True
|
||||
return False
|
||||
try:
|
||||
save(stage, management_started=False)
|
||||
for request in requests:
|
||||
if (request.operation != 'update' or request.library.resolve() != library
|
||||
or not previous_evidence.get(request.name)):
|
||||
raise ValueError('恢复目标与原失败项不一致。')
|
||||
source, _, _ = source_project(request.source, request.top_level_block)
|
||||
if (source.parent.is_relative_to(library.parent)
|
||||
or library.parent.is_relative_to(source.parent)):
|
||||
raise ValueError('请选择目标中心库之外的完整工程副本。')
|
||||
if cancelled(): return []
|
||||
stage = 'release_check'
|
||||
save(stage)
|
||||
if progress: progress({'stage': stage, 'detail': '正在检查原生会话释放,尚未替换条目'})
|
||||
import inspect
|
||||
block_name = requests[0].name if len(requests) == 1 else None
|
||||
if 'block_name' in inspect.signature(release_retained_library).parameters:
|
||||
proof = release_retained_library(library, root/'release', block_name=block_name)
|
||||
else:
|
||||
proof = release_retained_library(library, root/'release')
|
||||
if proof.get('status') != 'RELEASE_CONFIRMED':
|
||||
raise ValueError('原生会话释放未确认,未开始导入。')
|
||||
save('released', release=proof)
|
||||
if cancelled(): return []
|
||||
stage = 'management'
|
||||
save(stage, management_started=True)
|
||||
results = run_management_batch(requests, adapter=adapter, stop=stop, progress=progress)
|
||||
save('complete', results=[asdict(result) for result in results],
|
||||
version_review_required=True)
|
||||
return results
|
||||
except Exception as error:
|
||||
save('release_failed' if stage == 'release_check' else 'failed', detail=str(error))
|
||||
guidance = ('请正常关闭提示中的原生程序;若提示数据库地址记录,请先对对应工程执行 ICDB 维护,再重试副本恢复。'
|
||||
if stage == 'release_check' else '')
|
||||
return [ManagementResult(r.operation, r.library, r.name, r.partition, r.source,
|
||||
r.auto_verify, stage, 'BLOCKED' if stage != 'management' else 'RECOVERY_REQUIRED',
|
||||
False, f'副本恢复未完成:{error}。{guidance}原修复失败记录仍保留。', report) for r in requests]
|
||||
@@ -58,6 +58,11 @@ class RunTimings:
|
||||
elif stage == 'identity_verified':
|
||||
self.end('pcb_startup', now)
|
||||
self.begin('integration', now)
|
||||
elif stage == 'diagnostic_native_loaded_candidate':
|
||||
self.end('pcb_startup', now)
|
||||
self.begin('diagnostic_close', now)
|
||||
elif stage == 'diagnostic_complete':
|
||||
self.end('diagnostic_close', now)
|
||||
elif stage == 'integration_action':
|
||||
key = ACTION_KEYS.get(event.get('action'))
|
||||
if key:
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
Option Explicit
|
||||
Dim app, doc, pi, licensing, token, expected, attempt, stable, measuredStart, operationOK
|
||||
Dim app, doc, pi, licensing, token, expected, attempt, stable, measuredStart, operationOK, remaining
|
||||
expected = WScript.Arguments(0)
|
||||
Set app = GetObject(, "MGCPCB.Application")
|
||||
Set doc = app.ActiveDocument
|
||||
@@ -55,6 +55,13 @@ WScript.Echo "CLOSE_OK"
|
||||
Set pi = Nothing
|
||||
Set doc = Nothing
|
||||
Set licensing = Nothing
|
||||
Set remaining = app.ActiveDocument
|
||||
If Not remaining Is Nothing Then
|
||||
Set remaining = Nothing
|
||||
WScript.Echo "APP_RETAINED_OTHER_DOCUMENT"
|
||||
WScript.Quit 10
|
||||
End If
|
||||
Set remaining = Nothing
|
||||
measuredStart = Timer
|
||||
app.Quit
|
||||
LogElapsed "quit", measuredStart
|
||||
|
||||
@@ -15,6 +15,15 @@ import stat
|
||||
|
||||
|
||||
MANIFEST_VERSION = 1
|
||||
MANIFEST_RULE_VERSION = 1
|
||||
_ROOT_RUNTIME_PREFIX = 'work.before-restore-'
|
||||
_ROOT_RUNTIME_PATH = ('projectbackup', 'backups')
|
||||
_NATIVE_RUNTIME_DIRECTORIES = ('log', 'dbcheck', 'dbrestore')
|
||||
_NATIVE_SERVER_DIRECTORY = 'cdbsvr'
|
||||
_PROJECT_PCB_DIRECTORY = 'pcb'
|
||||
_PROJECT_DATABASE_PREFIXES = (('database',), (_PROJECT_PCB_DIRECTORY, 'database'))
|
||||
_NONPRIMARY_FILENAMES = ('saddress.adr',)
|
||||
_NONPRIMARY_FILENAME_PREFIXES = ('~$',)
|
||||
_NONPRIMARY_DIRECTORIES = frozenset({
|
||||
'log', 'logs', 'temp', 'tmp', '__pycache__', 'backup', 'backups',
|
||||
'output', 'outputs', 'report', 'reports', 'gerber', 'gerbers', 'odb++',
|
||||
@@ -29,22 +38,21 @@ def _root_runtime(directories):
|
||||
"""Known runtime/history children of a library or project workspace root."""
|
||||
return bool(directories and (
|
||||
directories[0] in _NONPRIMARY_DIRECTORIES
|
||||
or directories[0].startswith('work.before-restore-')
|
||||
or directories[:2] == ('projectbackup', 'backups')))
|
||||
or directories[0].startswith(_ROOT_RUNTIME_PREFIX)
|
||||
or directories[:len(_ROOT_RUNTIME_PATH)] == _ROOT_RUNTIME_PATH))
|
||||
|
||||
|
||||
def _native_runtime(directories, database_prefix):
|
||||
runtime_prefix = database_prefix + ('cdbsvr',)
|
||||
runtime_prefix = database_prefix + (_NATIVE_SERVER_DIRECTORY,)
|
||||
return (directories[:len(runtime_prefix)] == runtime_prefix
|
||||
and len(directories) > len(runtime_prefix)
|
||||
and directories[len(runtime_prefix)] in ('log', 'dbcheck', 'dbrestore'))
|
||||
and directories[len(runtime_prefix)] in _NATIVE_RUNTIME_DIRECTORIES)
|
||||
|
||||
|
||||
def _project_runtime(directories):
|
||||
return (_root_runtime(directories)
|
||||
or (directories[:1] == ('pcb',) and _root_runtime(directories[1:]))
|
||||
or _native_runtime(directories, ('database',))
|
||||
or _native_runtime(directories, ('pcb', 'database')))
|
||||
or (directories[:1] == (_PROJECT_PCB_DIRECTORY,) and _root_runtime(directories[1:]))
|
||||
or any(_native_runtime(directories, prefix) for prefix in _PROJECT_DATABASE_PREFIXES))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -85,7 +93,8 @@ class ManifestScope:
|
||||
"""
|
||||
directories = parts if directory else parts[:-1]
|
||||
if not directory and (Path(parts[-1]).suffix in _NONPRIMARY_SUFFIXES
|
||||
or parts[-1] == 'saddress.adr' or parts[-1].startswith('~$')):
|
||||
or parts[-1] in _NONPRIMARY_FILENAMES
|
||||
or parts[-1].startswith(_NONPRIMARY_FILENAME_PREFIXES)):
|
||||
return True
|
||||
if self.kind == 'project':
|
||||
return _project_runtime(directories)
|
||||
@@ -123,6 +132,36 @@ class ManifestScope:
|
||||
return 'shared_dependency'
|
||||
|
||||
|
||||
def comparison_rules(scope):
|
||||
"""Describe semantic exclusions using the classifier's rule constants."""
|
||||
project_positions = ['project root or its PCB child']
|
||||
project_native = ' or '.join('/'.join(prefix + (_NATIVE_SERVER_DIRECTORY,))
|
||||
for prefix in _PROJECT_DATABASE_PREFIXES)
|
||||
native_positions = [project_native + ' under project root']
|
||||
if scope.kind == 'library':
|
||||
project_positions = ['library root', 'selected CBB Work/Cert root or its PCB child']
|
||||
native_positions = [
|
||||
project_native + ' under selected CBB Work/Cert',
|
||||
'SymbolLibs/<partition>/' + _NATIVE_SERVER_DIRECTORY,
|
||||
'<shared dependency>/' + _NATIVE_SERVER_DIRECTORY,
|
||||
]
|
||||
return {
|
||||
'rule_version': MANIFEST_RULE_VERSION,
|
||||
'excluded_categories': sorted(_NONPRIMARY_DIRECTORIES),
|
||||
'excluded_suffixes': sorted(_NONPRIMARY_SUFFIXES),
|
||||
'runtime_exclusions': {
|
||||
'directory_name_positions': project_positions,
|
||||
'directory_prefixes': [_ROOT_RUNTIME_PREFIX],
|
||||
'relative_directories': ['/'.join(_ROOT_RUNTIME_PATH)],
|
||||
'native_directory_names': sorted(_NATIVE_RUNTIME_DIRECTORIES),
|
||||
'native_directory_positions': native_positions,
|
||||
'file_names': list(_NONPRIMARY_FILENAMES),
|
||||
'file_name_prefixes': list(_NONPRIMARY_FILENAME_PREFIXES),
|
||||
'coordination_checkpoints': 'recognized CBB coordination checkpoints',
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def hash_file(path):
|
||||
digest = hashlib.sha256()
|
||||
with Path(path).open('rb') as stream:
|
||||
@@ -136,7 +175,7 @@ def _coordination_checkpoint(path):
|
||||
return checkpoint_record(path) is not None
|
||||
|
||||
|
||||
def scan_tree(root, *, scope=None, exclude=None):
|
||||
def scan_tree(root, *, scope=None, exclude=None, check=None):
|
||||
"""Refuse links/special files; optionally prune trees outside semantic scope.
|
||||
|
||||
Copies always call this without a scope, validating complete membership.
|
||||
@@ -148,8 +187,10 @@ def scan_tree(root, *, scope=None, exclude=None):
|
||||
entries = {}
|
||||
folders = [root]
|
||||
while folders:
|
||||
if check is not None: check()
|
||||
with os.scandir(folders.pop()) as scanned:
|
||||
for entry in scanned:
|
||||
if check is not None: check()
|
||||
path = Path(entry.path)
|
||||
if exclude is not None and path.is_relative_to(exclude):
|
||||
continue
|
||||
@@ -269,7 +310,10 @@ def copy_verified(source, destination, *, scope=None, progress=None, hash_functi
|
||||
|
||||
Native icdb.dat/LMC files are held with exclusive read handles for the copy.
|
||||
Their expected SHA256 comes from the source read stream, independently of
|
||||
hashing destination bytes. Failures retain the partial destination evidence.
|
||||
hashing destination bytes. Unlocked primary files are also hashed while
|
||||
streaming the copy, then rehashed at source to detect even same-size/mtime
|
||||
edits. Every primary destination is independently hashed. Failures retain
|
||||
the partial destination evidence.
|
||||
Progress receives one dict with stage, hashed_files/bytes and copied_files.
|
||||
"""
|
||||
import win32con
|
||||
@@ -327,9 +371,15 @@ def copy_verified(source, destination, *, scope=None, progress=None, hash_functi
|
||||
shutil.copystat(path, copied)
|
||||
if stream_hash is not None:
|
||||
digest = stream_hash.hexdigest()
|
||||
elif label is not None:
|
||||
stream_hash = hashlib.sha256()
|
||||
with path.open('rb') as incoming, copied.open('wb') as outgoing:
|
||||
for data in iter(lambda: incoming.read(1024 * 1024), b''):
|
||||
stream_hash.update(data)
|
||||
outgoing.write(data)
|
||||
shutil.copystat(path, copied)
|
||||
digest = stream_hash.hexdigest()
|
||||
else:
|
||||
if label is not None:
|
||||
digest = hash_function(path)
|
||||
shutil.copy2(path, copied)
|
||||
before, after = entries[path], path.stat()
|
||||
if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Small, asynchronous entry point for recovery from a healthy CBB project."""
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
|
||||
from PySide6.QtCore import QObject, QThreadPool, Signal
|
||||
from PySide6.QtWidgets import (QComboBox, QDialog, QFileDialog, QFormLayout,
|
||||
@@ -23,6 +24,8 @@ class BackupRecoveryDialog(QDialog):
|
||||
self.resize(620, 230)
|
||||
self.request_factory = request_factory
|
||||
self.recoverer = recoverer
|
||||
self.native_queue = None
|
||||
self.stop = Event()
|
||||
self.busy = False
|
||||
self.pool = QThreadPool(self)
|
||||
self.pool.setMaxThreadCount(1)
|
||||
@@ -38,6 +41,9 @@ class BackupRecoveryDialog(QDialog):
|
||||
self.restore_button.clicked.connect(self._restore)
|
||||
self.close_button = QPushButton('关闭')
|
||||
self.close_button.clicked.connect(self.reject)
|
||||
self.cancel_queue_button = QPushButton('取消排队')
|
||||
self.cancel_queue_button.setEnabled(False)
|
||||
self.cancel_queue_button.clicked.connect(self.stop.set)
|
||||
self.status_label = QLabel(MANUAL_BACKUP_NOTICE + ' 所选备份先在隔离库中验证;安装时旧 Work 仅改名保留。')
|
||||
self.status_label.setWordWrap(True)
|
||||
layout = QFormLayout(self)
|
||||
@@ -50,6 +56,7 @@ class BackupRecoveryDialog(QDialog):
|
||||
buttons = QHBoxLayout()
|
||||
buttons.addStretch()
|
||||
buttons.addWidget(self.restore_button)
|
||||
buttons.addWidget(self.cancel_queue_button)
|
||||
buttons.addWidget(self.close_button)
|
||||
layout.addRow(buttons)
|
||||
|
||||
@@ -84,11 +91,24 @@ class BackupRecoveryDialog(QDialog):
|
||||
QMessageBox.Yes | QMessageBox.No, QMessageBox.No) != QMessageBox.Yes:
|
||||
return
|
||||
self.busy = True
|
||||
self.stop.clear()
|
||||
self._set_enabled(False)
|
||||
self.status_label.setText('正在准备恢复…')
|
||||
self.started.emit(name)
|
||||
self.worker = ServiceWorker(lambda: recoverer(
|
||||
request, source, progress=self.signals.progress.emit))
|
||||
def execute():
|
||||
action = lambda: recoverer(request, source, progress=self.signals.progress.emit)
|
||||
if self.native_queue is None: return action()
|
||||
from ..operation_queue import QueueCancelled
|
||||
def restore():
|
||||
self.signals.progress.emit({'stage': 'queue_acquired'})
|
||||
return action()
|
||||
try:
|
||||
return self.native_queue.run(restore, stop=self.stop, waiting=lambda: self.signals.progress.emit(
|
||||
{'stage': 'waiting_native_slot', 'detail': '已排队,等待当前检查结束'}))
|
||||
except QueueCancelled as error:
|
||||
from ..verify_runner import VerifyResult
|
||||
return VerifyResult('CANCELLED', stderr=str(error))
|
||||
self.worker = ServiceWorker(execute)
|
||||
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)
|
||||
@@ -101,6 +121,8 @@ class BackupRecoveryDialog(QDialog):
|
||||
|
||||
def _progress(self, event):
|
||||
if isinstance(event, dict):
|
||||
if event.get('stage') in ('waiting_native_slot', 'queue_acquired'):
|
||||
self.cancel_queue_button.setEnabled(event['stage'] == 'waiting_native_slot')
|
||||
message = event.get('message') or event.get('detail')
|
||||
if message:
|
||||
self.status_label.setText(str(message))
|
||||
@@ -121,6 +143,7 @@ class BackupRecoveryDialog(QDialog):
|
||||
|
||||
def _finished(self):
|
||||
self.busy = False
|
||||
self.cancel_queue_button.setEnabled(False)
|
||||
self._set_enabled(True)
|
||||
|
||||
def reject(self):
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
"""A check batch owns its snapshot and yields the native queue after each CBB."""
|
||||
from threading import Event
|
||||
from PySide6.QtCore import QObject, QThreadPool, Signal
|
||||
from .workers import ServiceWorker
|
||||
from ..operation_queue import QueueCancelled
|
||||
from ..verify_runner import VerifyResult, run_verify, write_batch_report
|
||||
from ..icdb_maintenance import write_maintenance_report
|
||||
|
||||
|
||||
class IcdbCheckTask(QObject):
|
||||
event = Signal(object)
|
||||
item_done = Signal(str, object)
|
||||
finished = Signal(object)
|
||||
|
||||
def __init__(self, requests, queue, report_root, *, verifier=None, path_lease=None, parent=None):
|
||||
super().__init__(parent)
|
||||
self.requests = tuple(requests)
|
||||
self.queue, self.report_root = queue, report_root
|
||||
self.path_lease = path_lease
|
||||
self.verifier = verifier or (lambda req: run_verify(req, progress=self.event.emit, stop=self.stop))
|
||||
self.results = []
|
||||
self.stop = Event()
|
||||
self.active = False
|
||||
self.paused = False
|
||||
self.invalidated = set()
|
||||
self.ready_names = set()
|
||||
self.running = False
|
||||
self.report = None
|
||||
self.report_error = ''
|
||||
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1)
|
||||
|
||||
def start(self):
|
||||
self.active = True
|
||||
self._next()
|
||||
|
||||
def cancel(self):
|
||||
self.stop.set(); self.queue.wake()
|
||||
if not self.running and self.active: self._next()
|
||||
|
||||
def pause(self):
|
||||
self.paused = True
|
||||
|
||||
def invalidate(self, names):
|
||||
self.invalidated.update(names)
|
||||
|
||||
def update_statuses(self, statuses):
|
||||
self.ready_names = (self.ready_names - statuses.keys()) | {
|
||||
name for name, status in statuses.items() if status == 'READY'}
|
||||
|
||||
def resume(self):
|
||||
self.paused = False; self.queue.wake()
|
||||
if not self.running and self.active: self._next()
|
||||
|
||||
def _next(self):
|
||||
if self.running or not self.active: return
|
||||
if self.stop.is_set() or self.results and not self.results[-1].safe_to_continue:
|
||||
self.results.extend(VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB')
|
||||
for _ in self.requests[len(self.results):])
|
||||
if len(self.results) == len(self.requests):
|
||||
self._report(); return
|
||||
if self.paused: return
|
||||
request = self.requests[len(self.results)]
|
||||
def check():
|
||||
try:
|
||||
def execute():
|
||||
if request.block_name in self.ready_names:
|
||||
return VerifyResult('SKIPPED', stderr='工程已为 READY,跳过 ICDB 检查。')
|
||||
if request.block_name in self.invalidated:
|
||||
return VerifyResult('SKIPPED', stderr='目标已有后续管理操作,请重新检查。')
|
||||
self.event.emit({'stage': 'icdb_check_start', 'block': request.block_name})
|
||||
return self.verifier(request)
|
||||
return self.queue.run(execute, stop=self.stop, ready=lambda: not self.paused,
|
||||
waiting=lambda: self.event.emit({'stage': 'waiting_native_slot', 'block': request.block_name,
|
||||
'detail': '已排队,等待当前原生操作结束'}))
|
||||
except QueueCancelled as error:
|
||||
return VerifyResult('CANCELLED', stderr=str(error))
|
||||
except Exception as error:
|
||||
return VerifyResult('FAIL', stderr=str(error), safe_to_continue=False,
|
||||
error_category='ICDB_INSPECTION_UNCONFIRMED')
|
||||
self.running = True
|
||||
self.worker = ServiceWorker(check)
|
||||
self.worker.signals.succeeded.connect(self._record)
|
||||
self.worker.signals.finished.connect(self._item_finished)
|
||||
self.pool.start(self.worker)
|
||||
|
||||
def _record(self, result):
|
||||
name = self.requests[len(self.results)].block_name
|
||||
self.results.append(result)
|
||||
if result.status in ('CANCELLED', 'QUEUE_STOP'): self.stop.set()
|
||||
self.item_done.emit(name, result)
|
||||
|
||||
def _item_finished(self):
|
||||
self.running = False
|
||||
self._next()
|
||||
|
||||
def _report(self):
|
||||
self.running = True
|
||||
def write():
|
||||
try:
|
||||
report = write_batch_report(self.requests, self.results, self.report_root)
|
||||
write_maintenance_report(self.requests, self.results, report, ())
|
||||
return report, ''
|
||||
except Exception as error:
|
||||
return None, str(error)
|
||||
self.worker = ServiceWorker(write)
|
||||
self.worker.signals.succeeded.connect(self._report_ready)
|
||||
self.worker.signals.finished.connect(self._complete)
|
||||
self.pool.start(self.worker)
|
||||
|
||||
def _report_ready(self, payload):
|
||||
self.report, self.report_error = payload
|
||||
|
||||
def _complete(self):
|
||||
self.running = self.active = False
|
||||
self.finished.emit(self)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -14,16 +14,20 @@ from ..management import run_management_batch, validate_name
|
||||
RESULT_LABELS = {
|
||||
'REMOVED': '已移除', 'UPLOADED': '已上传 / 未自动校验',
|
||||
'UPLOADED_VERIFIED': '已上传且校验通过', 'UPLOADED_VERIFY_FAILED': '已上传但校验未通过',
|
||||
'UPLOAD_FAILED': '上传失败', 'RECOVERY_REQUIRED': '需要人工恢复 / 队列已停止',
|
||||
'UPLOAD_FAILED': '上传失败', 'RECOVERY_REQUIRED': '需要人工恢复',
|
||||
'BLOCKED': '操作被阻止', 'UNSUPPORTED': '当前环境不支持',
|
||||
}
|
||||
STAGE_LABELS = {
|
||||
'prepare_identity': '正在核对来源工程内容',
|
||||
'catalog_before': '正在核对原生目录', 'baseline': '正在记录中心库内容基线',
|
||||
'stage_source': '正在复制并检查来源工程', 'native_remove': '正在原生移除',
|
||||
'removed': '原条目已移除', 'native_add': '正在原生上传', 'uploaded': '上传身份已确认',
|
||||
'stage_source': '正在复制并检查来源工程', 'native_remove': '正在移除',
|
||||
'removed': '原条目已移除', 'native_add': '正在上传', 'uploaded': '上传已确认',
|
||||
'verify': '正在校验上传结果', 'verified': '校验已返回', 'copy': '正在准备来源副本',
|
||||
'hash': '正在校验主要文件',
|
||||
'release_check': '正在检查工程是否被占用',
|
||||
'previous_release_check': '正在复核历史占用',
|
||||
'previous_release_confirmed': '历史会话已确认释放',
|
||||
'previous_release_unconfirmed': '占用复核未通过',
|
||||
}
|
||||
|
||||
|
||||
@@ -33,14 +37,22 @@ class ManagementSignals(QObject):
|
||||
|
||||
class ManagementDialog(QDialog):
|
||||
completed = Signal(object)
|
||||
before_execute = Signal(object)
|
||||
|
||||
def __init__(self, requests, parent=None, *, adapter=None, runner=None):
|
||||
def __init__(self, requests, parent=None, *, adapter=None, runner=None, recovery_from=None):
|
||||
super().__init__(parent)
|
||||
self.templates = tuple(requests)
|
||||
self.template = self.templates[0]
|
||||
self.operation = self.template.operation
|
||||
self.adapter = adapter
|
||||
self.native_queue = None
|
||||
self.recovery_from = dict(recovery_from or {})
|
||||
self.runner = runner or run_management_batch
|
||||
if self.recovery_from and runner is None:
|
||||
from ..reimport_recovery import run_reimport_recovery
|
||||
self.runner = lambda requests, **kwargs: run_reimport_recovery(requests,
|
||||
previous_evidence=self.recovery_from,
|
||||
evidence_dir=self.template.evidence_dir.parent/'reimport-recovery', **kwargs)
|
||||
self.busy = False
|
||||
self.executed = False
|
||||
self.stop = Event()
|
||||
@@ -62,16 +74,26 @@ class ManagementDialog(QDialog):
|
||||
self.status_label = QLabel(MANUAL_BACKUP_NOTICE + ' 更新会先移除再重新导入,失败时请使用手动备份恢复。')
|
||||
self.status_label.setWordWrap(True)
|
||||
self.output = QTextEdit(); self.output.setReadOnly(True)
|
||||
self.output.document().setMaximumBlockCount(2000)
|
||||
self.output.hide()
|
||||
self.logs_button = QPushButton('查看日志')
|
||||
self.logs_button.setCheckable(True)
|
||||
self.logs_button.toggled.connect(self.output.setVisible)
|
||||
if self.recovery_from:
|
||||
self.setWindowTitle('从副本恢复 CBB')
|
||||
self.status_label.setText('修复未完成。请选择完整工程副本(.prj)。所列 CBB 将替换为副本中的版本。\n'
|
||||
+ MANUAL_BACKUP_NOTICE)
|
||||
self.output.append('\n'.join(f'原失败记录 {name}:{path}' for name, path in self.recovery_from.items()))
|
||||
self.execute_button = QPushButton('预览并确认执行…')
|
||||
self.execute_button.clicked.connect(self._execute)
|
||||
self.stop_button = QPushButton('当前项结束后停止'); self.stop_button.setEnabled(False)
|
||||
self.stop_button.clicked.connect(self.stop.set)
|
||||
self.close_button = QPushButton('关闭'); self.close_button.clicked.connect(self.reject)
|
||||
layout = QVBoxLayout(self)
|
||||
layout.addWidget(QLabel(f'目标库:{self.template.library}\n操作记录:{self.template.evidence_dir}'))
|
||||
layout.addWidget(QLabel(f'目标库:{self.template.library}'))
|
||||
layout.addWidget(self.table)
|
||||
layout.addWidget(self.sources_button); layout.addWidget(self.auto_verify)
|
||||
layout.addWidget(self.status_label); layout.addWidget(self.output)
|
||||
layout.addWidget(self.status_label); layout.addWidget(self.logs_button); layout.addWidget(self.output)
|
||||
buttons = QHBoxLayout()
|
||||
for widget in (self.execute_button, self.stop_button, self.close_button): buttons.addWidget(widget)
|
||||
layout.addLayout(buttons)
|
||||
@@ -132,16 +154,31 @@ class ManagementDialog(QDialog):
|
||||
description = ('同名更新会原生移除并重新导入;导入失败需要使用手动备份恢复。' if self.operation == 'update'
|
||||
else '将通过原生操作移除所列 CBB;恢复时需要使用手动备份。' if self.operation == 'remove'
|
||||
else '新增同名冲突会拒绝覆盖,完整来源工程将先复制到暂存区。')
|
||||
if self.recovery_from:
|
||||
description = ('将用所选副本替换这些 CBB。操作会先移除原条目,再导入副本;'
|
||||
'导入失败时需要用备份恢复。请确认副本版本。')
|
||||
answer = QMessageBox.question(self, '确认管理操作',
|
||||
f'{MANUAL_BACKUP_NOTICE}\n{description}\n\n目标库:{self.template.library}\n{preview}\n\n'
|
||||
f'操作记录与检查点:{self.template.evidence_dir}\n确认继续执行?', QMessageBox.Yes | QMessageBox.No,
|
||||
'确认继续执行?', QMessageBox.Yes | QMessageBox.No,
|
||||
QMessageBox.No)
|
||||
if answer != QMessageBox.Yes:
|
||||
return
|
||||
self.busy = True; self.executed = True
|
||||
self._enabled(False)
|
||||
self.worker = ServiceWorker(lambda: self.runner(requests, adapter=self.adapter, stop=self.stop,
|
||||
progress=self.signals.progress.emit))
|
||||
self.before_execute.emit([r.name for r in requests])
|
||||
def execute():
|
||||
action = lambda: self.runner(requests, adapter=self.adapter, stop=self.stop,
|
||||
progress=self.signals.progress.emit)
|
||||
if self.native_queue is None: return action()
|
||||
from ..operation_queue import QueueCancelled
|
||||
try:
|
||||
return self.native_queue.run(action, stop=self.stop, waiting=lambda: self.signals.progress.emit(
|
||||
{'stage': 'waiting_native_slot', 'detail': '已排队,等待当前检查结束'}))
|
||||
except QueueCancelled as error:
|
||||
from ..management import ManagementResult
|
||||
return [ManagementResult(r.operation, r.library, r.name, r.partition, r.source, r.auto_verify,
|
||||
'complete', 'BLOCKED', True, str(error)) for r in requests]
|
||||
self.worker = ServiceWorker(execute)
|
||||
self.worker.signals.succeeded.connect(self._result)
|
||||
self.worker.signals.failed.connect(self._failed)
|
||||
self.worker.signals.finished.connect(self._finished)
|
||||
@@ -155,7 +192,9 @@ class ManagementDialog(QDialog):
|
||||
|
||||
def _progress(self, event):
|
||||
stage = str(event.get('stage', ''))
|
||||
text = f'{event.get("block", "")} {STAGE_LABELS.get(stage, RESULT_LABELS.get(stage, stage))}'
|
||||
text = f'{event.get("block", "")} {STAGE_LABELS.get(stage, RESULT_LABELS.get(stage, "正在处理"))}'
|
||||
if stage == 'waiting_native_slot': text = str(event.get('detail', '已排队,等待执行'))
|
||||
self.output.append(str(event))
|
||||
if 'copied_files' in event:
|
||||
text += f' {event["copied_files"]}/{event.get("total_files", "?")}'
|
||||
elif 'hashed_files' in event:
|
||||
@@ -163,14 +202,32 @@ class ManagementDialog(QDialog):
|
||||
self.status_label.setText(text)
|
||||
|
||||
def _result(self, results):
|
||||
lines = []
|
||||
lines, summaries = [], []
|
||||
for result in results:
|
||||
text = f'{result.name}:{RESULT_LABELS.get(result.status, result.status)} — {result.detail}'
|
||||
summary = f'{result.name}:{RESULT_LABELS.get(result.status, result.status)}'
|
||||
text = f'{summary} — {result.detail}'
|
||||
changes = getattr(result, 'change_report', None)
|
||||
if changes:
|
||||
if changes.get('status') == 'RECORDED':
|
||||
text += (f'\n已比对的工程文件:新增 {len(changes["added"])}、删除 {len(changes["deleted"])}、'
|
||||
f'修改 {len(changes["modified"])};范围仅限报告列出的工程文件。')
|
||||
else:
|
||||
summary += ',变更清单待核对'
|
||||
text += '\n'+changes.get('detail', '变更清单未确认')
|
||||
if getattr(result, 'release_proof', None):
|
||||
text += '\n历史会话已释放;历史工程数据的恢复状态需另行核对。'
|
||||
if not result.safe_to_continue:
|
||||
summary += ',原生会话释放待确认'
|
||||
if self.recovery_from and result.status == 'UPLOADED_VERIFIED':
|
||||
summary += ',版本待核对。'
|
||||
elif result.status not in ('UPLOADED', 'UPLOADED_VERIFIED', 'REMOVED'):
|
||||
summary += ',详情请查看日志。'
|
||||
summaries.append(summary)
|
||||
if result.evidence_path:
|
||||
text += f'\n记录:{result.evidence_path}'
|
||||
lines.append(text)
|
||||
message = '\n'.join(lines) if lines else '队列已取消,未执行任何项。'
|
||||
self.status_label.setText(message); self.output.append(message)
|
||||
self.status_label.setText('\n'.join(summaries) if summaries else message); self.output.append(message)
|
||||
self.completed.emit(results)
|
||||
|
||||
def _failed(self, error):
|
||||
|
||||
@@ -7,6 +7,7 @@ once after cleanup if the worker was killed while a native file was open.
|
||||
from pathlib import Path
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import stat
|
||||
import tempfile
|
||||
import subprocess
|
||||
@@ -124,7 +125,7 @@ def collect_native_failure_logs(pcb_path, evidence_root, *, max_bytes=NATIVE_LOG
|
||||
|
||||
def _collect_icdb_recovery(source, evidence_root):
|
||||
"""Only promote a native error whose log changed after this launch."""
|
||||
from .icdb_recovery import read_log_failure
|
||||
from .icdb_recovery import read_log_failure, read_icdb_error
|
||||
root = Path(evidence_root)/'diagnostics'
|
||||
try:
|
||||
baseline = json.loads((root/'startup-log-baseline.json').read_text('utf-8'))
|
||||
@@ -135,6 +136,9 @@ def _collect_icdb_recovery(source, evidence_root):
|
||||
_, recovery = read_log_failure(source, checkpoint)
|
||||
if recovery:
|
||||
_write_record(root/'icdb-recovery.json', {**recovery, 'source': str(source)})
|
||||
message = read_icdb_error(source, checkpoint)
|
||||
if message:
|
||||
_write_record(root/'icdb-error-content.json', {'native_message': message, 'source': str(source)})
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
pass # Unknown freshness must not replace the original failure.
|
||||
|
||||
@@ -143,9 +147,56 @@ def _collect_icdb_recovery(source, evidence_root):
|
||||
def failure_logs_main(request_path):
|
||||
job = json.loads(Path(request_path).read_text(encoding='utf-8'))
|
||||
collect_native_failure_logs(job['pcb'], job['root'])
|
||||
collect_native_client_error(job['root'])
|
||||
return 0
|
||||
|
||||
|
||||
def collect_native_client_error(evidence_root):
|
||||
"""Read only this PCB PID's new iCDB manager log in the bounded log helper."""
|
||||
root = Path(evidence_root)/'diagnostics'
|
||||
try:
|
||||
context = json.loads((root/'native-client-context.json').read_text('utf-8'))
|
||||
pid, started = context['native_pid'], context['started_ns']
|
||||
if type(pid) is not int or pid <= 0 or type(started) is not int:
|
||||
return
|
||||
target = str(context['database']).replace('/', '\\').casefold()
|
||||
if not target:
|
||||
return
|
||||
from .icdb_recovery import decode_log
|
||||
for directory in Path(context['client_log_root']).glob(f'*-{pid}'):
|
||||
for source in directory.glob('*.iCDBManager.txt'):
|
||||
with source.open('rb') as stream:
|
||||
metadata = os.fstat(stream.fileno())
|
||||
if (metadata.st_mtime_ns < started
|
||||
or getattr(metadata, 'st_birthtime_ns', started) < started):
|
||||
continue
|
||||
header = stream.read(16*1024)
|
||||
stream.seek(0, os.SEEK_END)
|
||||
size = stream.tell()
|
||||
stream.seek(max(0, size-NATIVE_LOG_MAX_BYTES))
|
||||
tail = stream.read(NATIVE_LOG_MAX_BYTES)
|
||||
if not re.search(rf'\bPID\s*\[{pid}\]', decode_log(header)):
|
||||
continue
|
||||
# The native iCDB logger supplies the domain; a pathname in a
|
||||
# generic PCB error alone never establishes this identity.
|
||||
lines = decode_log(tail).splitlines()
|
||||
if size > NATIVE_LOG_MAX_BYTES:
|
||||
lines = lines[1:] # The first bounded-tail line may start mid-message.
|
||||
message = next((line for line in lines
|
||||
if re.search(r'\bERROR\s*:', line, re.I)
|
||||
and target in line.replace('/', '\\').casefold()), '')
|
||||
if message:
|
||||
target_file = root/'native-logs/current-icdb-manager.txt'
|
||||
target_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
target_file.write_bytes(tail)
|
||||
_write_record(root/'icdb-error-content.json', {'native_message': 'iCDB: '+message,
|
||||
'source': str(source), 'native_pid': pid, 'started_ns': started,
|
||||
'database': context['database'], 'evidence': str(target_file)})
|
||||
return
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
pass # A missing/ambiguous native log must not replace the open failure.
|
||||
|
||||
|
||||
def capture_failure_logs_with_timeout(request_path, *, timeout_seconds=8):
|
||||
"""Post-cleanup retry in a killable helper, not a potentially stuck SMB thread."""
|
||||
request_path = Path(request_path)
|
||||
|
||||
@@ -14,6 +14,7 @@ native menu invocation happens on the worker's private desktop.
|
||||
from dataclasses import asdict, dataclass, field, replace
|
||||
from pathlib import Path
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
@@ -32,6 +33,22 @@ ERROR_TEXT = re.compile(r'failed|error|cannot connect|bad data', re.IGNORECASE)
|
||||
INVALID_NAME_CHARS = '\\/:*?"<>|'
|
||||
|
||||
|
||||
def _notify_progress(callback, *args):
|
||||
"""A failed observer cannot change native execution or release facts."""
|
||||
if callback is not None:
|
||||
try:
|
||||
callback(*args)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).warning('Progress notification failed', exc_info=True)
|
||||
|
||||
|
||||
def _write_optional_evidence(path, value):
|
||||
try:
|
||||
path.write_text(json.dumps(value, ensure_ascii=False, default=str, indent=2), encoding='utf-8')
|
||||
except OSError:
|
||||
logging.getLogger(__name__).warning('Could not write diagnostic evidence %s', path, exc_info=True)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class VerifyRequest:
|
||||
lmc_file: Path
|
||||
@@ -56,13 +73,13 @@ class VerifyRequest:
|
||||
# A reserved iCDB range is a host-wide prerequisite failure. Do not
|
||||
# launch a PCB that is guaranteed to time out; batch orchestration will
|
||||
# record this item and continue with the next one.
|
||||
strict_port_check: bool = True
|
||||
strict_port_check: bool = False
|
||||
# A mapped drive can be invisible to an elevated/private worker on Win10.
|
||||
# Preserve the parent session's mapping identity so the worker can restore
|
||||
# it before launching Library Manager/PCB.
|
||||
mapped_drive: str = ''
|
||||
mapped_remote_root: str = ''
|
||||
auto_repair: bool = True
|
||||
auto_repair: bool = False
|
||||
maintenance: bool = False
|
||||
post_repair_proof: object | None = field(default=None, repr=False, compare=False)
|
||||
diagnostic_only: bool = False
|
||||
@@ -85,6 +102,7 @@ class VerifyResult:
|
||||
timings_seconds: dict[str, float] = field(default_factory=dict)
|
||||
incomplete_timing_phases: tuple[str, ...] = ()
|
||||
recovery_attempts: tuple[dict, ...] = ()
|
||||
release_proof: dict | None = None
|
||||
|
||||
|
||||
def resolve_importer(mentor_bin: str | None = None) -> Path:
|
||||
@@ -135,7 +153,8 @@ def classify_output(exit_code: int | None, output: str, *, timed_out: bool = Fal
|
||||
from .icdb_recovery import parse_session_loss
|
||||
if parse_session_loss(output):
|
||||
return 'FAIL'
|
||||
if exit_code == 0 and SUCCESS_TEXT.search(output) and not ERROR_TEXT.search(output):
|
||||
diagnostic_text = re.sub(r'\b0\s+errors?\b', '', output, flags=re.I)
|
||||
if exit_code == 0 and SUCCESS_TEXT.search(output) and not ERROR_TEXT.search(diagnostic_text):
|
||||
return 'PASS'
|
||||
if ERROR_TEXT.search(output):
|
||||
return 'FAIL'
|
||||
@@ -157,7 +176,8 @@ def preflight(request):
|
||||
if len(projects) != 1:
|
||||
raise ValueError(f'{name}: 缺少或无法唯一确定 Work 下的工程 PRJ')
|
||||
project = absolute_preserving_drive(projects[0])
|
||||
content = project.read_text(encoding='utf-8', errors='replace')
|
||||
from .backup_recovery import _project_text
|
||||
content = _project_text(project)
|
||||
refs = re.findall(r'^KEY PCBDesignPath "([^"]+)"', content, re.M)
|
||||
if not refs:
|
||||
raise ValueError(f'{name}: 工程没有 PCBDesignPath')
|
||||
@@ -220,7 +240,17 @@ def _stop_worker(process, *, timeout=5):
|
||||
try:
|
||||
process.wait(timeout=timeout)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
process.kill() # Automation clients only; never the native tree.
|
||||
process.wait(timeout=5)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
if hasattr(process, 'stop_automation_clients'):
|
||||
process.stop_automation_clients()
|
||||
return process.poll() is not None
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _normalize_bridge_result(probe):
|
||||
@@ -270,6 +300,11 @@ def classify_failure_category(detail):
|
||||
from .icdb_recovery import ERROR_CODE, parse_session_loss
|
||||
if ERROR_CODE.casefold() in lower or parse_session_loss(text):
|
||||
return ERROR_CODE
|
||||
if 'back annotation is not allowed on verified (or once verified) reusable blocks.' in lower:
|
||||
# Preserve the native integration failure even when shutdown adds a
|
||||
# secondary release warning. This category does not grant permission
|
||||
# to reimport or change safe_to_continue.
|
||||
return 'CBB_REIMPORT_REQUIRED'
|
||||
if any(code in lower for code in (
|
||||
'pcb_release_unconfirmed', 'icdb_release_unconfirmed',
|
||||
'icdb_session_unconfirmed', 'pcb_session_active', 'database_recovery_required')):
|
||||
@@ -475,7 +510,7 @@ def native_lm_verify_enabled():
|
||||
}
|
||||
|
||||
|
||||
def _cleanup_session_processes(root, *, lm_pid, target_pid, pcb, pcb_baseline,
|
||||
def _cleanup_session_processes(root, *, lm_pid, target_pid, pcb, pcb_baseline, launcher_pid=None,
|
||||
progress=None):
|
||||
"""Record native release or retention after automation has stopped."""
|
||||
from .mentor_adapter import cleanup_verify_processes
|
||||
@@ -494,12 +529,12 @@ def _cleanup_session_processes(root, *, lm_pid, target_pid, pcb, pcb_baseline,
|
||||
except OSError:
|
||||
pass
|
||||
if progress:
|
||||
progress(event)
|
||||
_notify_progress(progress, event)
|
||||
|
||||
return cleanup_verify_processes(
|
||||
lm_pid,
|
||||
target_pid,
|
||||
None,
|
||||
launcher_pid,
|
||||
expected_pcb=pcb,
|
||||
baseline_pids=pcb_baseline,
|
||||
emit=emit,
|
||||
@@ -507,7 +542,7 @@ def _cleanup_session_processes(root, *, lm_pid, target_pid, pcb, pcb_baseline,
|
||||
|
||||
|
||||
def run_verify(request, *, progress=None, flag_reader=None, process_runner=None, port_check=None,
|
||||
dialog_supervisor_factory=None, version_prompt=None):
|
||||
dialog_supervisor_factory=None, version_prompt=None, stop=None):
|
||||
# Cover contents checking, native work and final state reads with one
|
||||
# session-wide mutex. The worker-stage lock below is reentrant on Windows.
|
||||
import win32event, win32con
|
||||
@@ -516,36 +551,41 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
acquired = False
|
||||
library_lock = None
|
||||
previous_release = None
|
||||
release_confirmed = True
|
||||
remaining_clients = ()
|
||||
def clients_released():
|
||||
if release_confirmed:
|
||||
return True
|
||||
from .library_lock import _supervisor_alive
|
||||
return bool(remaining_clients) and not any(_supervisor_alive(pid) for pid in remaining_clients)
|
||||
try:
|
||||
acquired = win32event.WaitForSingleObject(mutex, 0) in (
|
||||
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
||||
if not acquired:
|
||||
return VerifyResult('BLOCKED', stderr='已有 CBB 校验任务运行,请等待结束。',
|
||||
safe_to_continue=False)
|
||||
safe_to_continue=True, error_category='NATIVE_CHANNEL_BUSY')
|
||||
if request.maintenance:
|
||||
from .maintenance_entry import maintenance_needed, run_existing_address_maintenance
|
||||
try:
|
||||
needed = maintenance_needed(request)
|
||||
except (ValueError, OSError) as error:
|
||||
return VerifyResult('BLOCKED', stderr=str(error), safe_to_continue=False)
|
||||
if needed:
|
||||
return run_existing_address_maintenance(request, progress=progress,
|
||||
verify=lambda req: _run_verify_serialized(req, progress=progress, flag_reader=flag_reader,
|
||||
process_runner=process_runner, port_check=port_check,
|
||||
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt))
|
||||
from .library_lock import LibraryLock, LibraryBusy
|
||||
from .maintenance_entry import run_icdb_check
|
||||
return run_icdb_check(request, progress=progress, stop=stop)
|
||||
from .library_lock import LibraryLock, LibraryBusy, recheck_previous_release
|
||||
import pywintypes
|
||||
if Path(request.lmc_file).is_file():
|
||||
try:
|
||||
library_lock = LibraryLock(request.lmc_file, safe_to_release=lambda: release_confirmed)
|
||||
previous_release = recheck_previous_release(request.lmc_file,
|
||||
Path(request.evidence_dir)/'previous-release', block_name=request.block_name, progress=progress)
|
||||
library_lock = LibraryLock(request.lmc_file, checkpoint=False,
|
||||
safe_to_release=clients_released)
|
||||
library_lock.__enter__()
|
||||
except LibraryBusy as error:
|
||||
return VerifyResult('BLOCKED', stderr=str(error), safe_to_continue=False)
|
||||
return VerifyResult('FAIL', stderr=str(error), error_category='LIBRARY_IN_USE')
|
||||
except (OSError, ValueError, RuntimeError, pywintypes.error) as error:
|
||||
return VerifyResult('FAIL', stderr=str(error), error_category='LIBRARY_ACCESS_FAILED')
|
||||
release_confirmed = False
|
||||
result = _run_verify_serialized(
|
||||
request, progress=progress, flag_reader=flag_reader,
|
||||
process_runner=process_runner, port_check=port_check,
|
||||
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt)
|
||||
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt, stop=stop)
|
||||
if (request.auto_repair and result.status not in {'TIMEOUT', 'BLOCKED'}
|
||||
and result.error_category == 'ICDB_REPAIR_REQUIRED'
|
||||
and result.evidence_path):
|
||||
@@ -624,6 +664,24 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
|
||||
except OSError:
|
||||
pass # Keep the native/repair errors even if evidence storage fails.
|
||||
release_confirmed = result.safe_to_continue
|
||||
if not release_confirmed and result.evidence_path:
|
||||
try:
|
||||
release = json.loads(result.evidence_path.with_name('session-release.json').read_text('utf-8'))
|
||||
release_confirmed = (release.get('worker_exited') is True
|
||||
and release.get('safe_to_continue') is True and release.get('block') == request.block_name
|
||||
and Path(release['library']).resolve() == Path(request.lmc_file).resolve())
|
||||
if (release.get('worker_exited') is True and not release.get('error')
|
||||
and not release.get('close_errors') and not release.get('automation_release', {}).get('error')
|
||||
and release.get('block') == request.block_name
|
||||
and Path(release['library']).resolve() == Path(request.lmc_file).resolve()):
|
||||
remaining_clients = tuple(pid for pid in release.get('remaining_pids', [])
|
||||
if type(pid) is int and pid > 0)
|
||||
except (OSError, ValueError, KeyError):
|
||||
pass
|
||||
if previous_release is not None:
|
||||
result = replace(result, release_proof=previous_release)
|
||||
if result.evidence_path:
|
||||
_write_optional_evidence(result.evidence_path, {'block_name': request.block_name, **asdict(result)})
|
||||
return result
|
||||
finally:
|
||||
try:
|
||||
@@ -637,12 +695,23 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
|
||||
|
||||
|
||||
def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_runner=None,
|
||||
port_check=None, dialog_supervisor_factory=None, version_prompt=None):
|
||||
port_check=None, dialog_supervisor_factory=None, version_prompt=None, stop=None):
|
||||
timing = RunTimings()
|
||||
result = _run_verify(request, timing=timing, progress=progress, flag_reader=flag_reader,
|
||||
process_runner=process_runner, port_check=port_check,
|
||||
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt)
|
||||
if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP'} and result.evidence_path:
|
||||
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt, stop=stop)
|
||||
if not request.auto_repair and result.evidence_path:
|
||||
try:
|
||||
release = json.loads(result.evidence_path.with_name('session-release.json').read_text('utf-8'))
|
||||
if (release.get('block') == request.block_name
|
||||
and Path(release['library']).resolve() == Path(request.lmc_file).resolve()):
|
||||
released = release.get('worker_exited') is True and release.get('safe_to_continue') is True
|
||||
result = replace(result, safe_to_continue=released)
|
||||
if not released and result.status == 'PASS':
|
||||
result = replace(result, status='FAIL', stderr='原生会话或自动化客户端尚未退出。')
|
||||
except (OSError, ValueError, KeyError):
|
||||
pass
|
||||
if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP', 'CANCELLED'} and result.evidence_path:
|
||||
job_path = result.evidence_path.with_name('request.json')
|
||||
if job_path.is_file():
|
||||
timing.begin('failure_diagnostics')
|
||||
@@ -668,8 +737,7 @@ def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_
|
||||
detail = result.stderr
|
||||
if recovery and RECOVERY_ACTION not in detail:
|
||||
detail = (detail + '\n' + recovery_detail(recovery)).strip()
|
||||
result = replace(result, safe_to_continue=False, stderr=detail,
|
||||
error_category=ERROR_CODE)
|
||||
result = replace(result, stderr=detail, error_category=ERROR_CODE)
|
||||
if recovery and result.evidence_path:
|
||||
try:
|
||||
record_path = result.evidence_path.parent/'diagnostics/icdb-recovery.json'
|
||||
@@ -686,28 +754,29 @@ def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_
|
||||
error_stage=(result.error_stage or (unfinished[-1] if unfinished else 'execution')
|
||||
if result.status not in {"PASS", "SKIPPED"} else ""))
|
||||
if result.evidence_path:
|
||||
result.evidence_path.write_text(json.dumps(
|
||||
{'block_name': request.block_name, **asdict(result)},
|
||||
ensure_ascii=False, default=str, indent=2), encoding='utf-8')
|
||||
result.evidence_path.with_name('performance.json').write_text(json.dumps({
|
||||
_write_optional_evidence(result.evidence_path, {'block_name': request.block_name, **asdict(result)})
|
||||
_write_optional_evidence(result.evidence_path.with_name('performance.json'), {
|
||||
'block_name': request.block_name, 'status': result.status,
|
||||
'unit': 'seconds', 'timings_seconds': durations,
|
||||
'incomplete_timing_phases': unfinished,
|
||||
'clock': 'monotonic; save helper subphases: VBScript Timer (midnight adjusted)',
|
||||
'notes': 'phase totals overlap action/call subphases; skipped phases are absent',
|
||||
}, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
})
|
||||
if progress:
|
||||
progress({'stage': 'performance', 'block': request.block_name,
|
||||
_notify_progress(progress, {'stage': 'performance', 'block': request.block_name,
|
||||
'timings_seconds': durations, 'incomplete_timing_phases': unfinished,
|
||||
'detail': ' '.join(f'{key}={value:.3f}s' for key, value in durations.items())})
|
||||
if request.logging_context:
|
||||
request.logging_context.logger.info('operation=cbb_verify block=%s status=%s flag=%s evidence=%s error=%s timings_seconds=%s',
|
||||
request.block_name, result.status, result.library_flag, result.evidence_path, result.stderr, durations)
|
||||
try:
|
||||
request.logging_context.logger.info('operation=cbb_verify block=%s status=%s flag=%s evidence=%s error=%s timings_seconds=%s',
|
||||
request.block_name, result.status, result.library_flag, result.evidence_path, result.stderr, durations)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).warning('Operation logging failed', exc_info=True)
|
||||
return result
|
||||
|
||||
|
||||
def _run_verify(request, *, timing, progress=None, flag_reader=None, process_runner=None, port_check=None,
|
||||
dialog_supervisor_factory=None, version_prompt=None):
|
||||
dialog_supervisor_factory=None, version_prompt=None, stop=None):
|
||||
"""Refresh one CBB and record its evidence.
|
||||
|
||||
``flag_reader`` is a read-only probe returning an authoritative ``BridgeResult``.
|
||||
@@ -716,12 +785,14 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
not depend on the host's port reservations.
|
||||
"""
|
||||
root = Path(request.evidence_dir).resolve()/('verify-' + uuid4().hex[:12])
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
try:
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
except OSError as error:
|
||||
return VerifyResult('FAIL', stderr=f'无法创建操作记录目录:{error}')
|
||||
fingerprint = runtime_fingerprint(request.mentor_bin)
|
||||
(root/'runtime.json').write_text(
|
||||
json.dumps(fingerprint, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
_write_optional_evidence(root/'runtime.json', fingerprint)
|
||||
if progress:
|
||||
progress({'stage': 'runtime_fingerprint', 'block': request.block_name,
|
||||
_notify_progress(progress, {'stage': 'runtime_fingerprint', 'block': request.block_name,
|
||||
**fingerprint})
|
||||
result_path = root/'result.json'
|
||||
runner = process_runner or (lambda command, timeout, cwd:
|
||||
@@ -739,6 +810,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
pass
|
||||
return replace(result, evidence_path=result_path)
|
||||
|
||||
if stop is not None and stop.is_set():
|
||||
return finish(VerifyResult('CANCELLED', stderr='已取消,未启动校验。'))
|
||||
timing.begin('preflight')
|
||||
try:
|
||||
project, pcb = preflight(request)
|
||||
@@ -747,17 +820,6 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
finally:
|
||||
timing.end('preflight')
|
||||
|
||||
from .icdb_ownership import unreleased_addresses
|
||||
try:
|
||||
addresses = unreleased_addresses(request.lmc_file, project, pcb)
|
||||
if addresses:
|
||||
return finish(VerifyResult('BLOCKED', safe_to_continue=False,
|
||||
stderr='ICDB_SESSION_UNCONFIRMED: 原生数据库所有权未释放,未开始内容检查或校验:'
|
||||
+ '; '.join(addresses)))
|
||||
except OSError as error:
|
||||
return finish(VerifyResult('BLOCKED', safe_to_continue=False,
|
||||
stderr=f'ICDB_SESSION_UNCONFIRMED: 无法确认数据库所有权:{error}'))
|
||||
|
||||
content_check_enabled = not request.diagnostic_only and bool(str(request.libspec).strip() and str(request.dms_login_config).strip())
|
||||
if content_check_enabled:
|
||||
try:
|
||||
@@ -766,7 +828,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
return finish(VerifyResult('BLOCKED', stderr=str(error)))
|
||||
command = build_content_check_command(request, executable)
|
||||
if progress:
|
||||
progress({'stage': 'content_check_start', 'block': request.block_name,
|
||||
_notify_progress(progress, {'stage': 'content_check_start', 'block': request.block_name,
|
||||
'detail': ' '.join(command)})
|
||||
timing.begin('content_check')
|
||||
try:
|
||||
@@ -788,16 +850,15 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
stdout=stdout, report_path=report, content_check_exit_code=exit_code,
|
||||
safe_to_continue=not timed_out))
|
||||
if progress:
|
||||
progress({'stage': 'content_check_done', 'block': request.block_name, 'status': 'PASS'})
|
||||
_notify_progress(progress, {'stage': 'content_check_done', 'block': request.block_name, 'status': 'PASS'})
|
||||
|
||||
# The design server needs a port in 10000-10100; a system reservation there
|
||||
# blocks every item, so fail fast with the fix instead of timing out.
|
||||
# Sampling cannot establish that the whole native port range is unusable.
|
||||
from .mentor_adapter import icdb_ports_bindable
|
||||
check_ports = port_check or icdb_ports_bindable
|
||||
ports_ok, ports_detail = check_ports()
|
||||
if not ports_ok:
|
||||
if progress:
|
||||
progress({'stage': 'port_warning', 'block': request.block_name, 'detail': ports_detail})
|
||||
_notify_progress(progress, {'stage': 'port_warning', 'block': request.block_name, 'detail': ports_detail})
|
||||
if request.strict_port_check:
|
||||
return finish(VerifyResult('BLOCKED', stderr=ports_detail))
|
||||
|
||||
@@ -814,14 +875,17 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
'cancel_signal': str(root/'cancel-worker.signal'),
|
||||
'start_gate': str(root/'start-worker.signal')}
|
||||
consent = None
|
||||
if request.post_repair_proof is not None:
|
||||
from .post_repair_consent import PostRepairProof, ConsentController, exact_prompt
|
||||
if not isinstance(request.post_repair_proof, PostRepairProof):
|
||||
return finish(VerifyResult('BLOCKED', stderr='POST_REPAIR_PROOF_REQUIRED', safe_to_continue=False))
|
||||
job['post_repair_consent'] = request.post_repair_proof.for_job(job)
|
||||
consent = ConsentController(request.post_repair_proof, job)
|
||||
job_path = root/'request.json'
|
||||
job_path.write_text(json.dumps(job, ensure_ascii=False), encoding='utf-8')
|
||||
try:
|
||||
if request.post_repair_proof is not None:
|
||||
from .post_repair_consent import PostRepairProof, ConsentController, exact_prompt
|
||||
if not isinstance(request.post_repair_proof, PostRepairProof):
|
||||
return finish(VerifyResult('BLOCKED', stderr='POST_REPAIR_PROOF_REQUIRED'))
|
||||
job['post_repair_consent'] = request.post_repair_proof.for_job(job)
|
||||
consent = ConsentController(request.post_repair_proof, job)
|
||||
job_path.write_text(json.dumps(job, ensure_ascii=False), encoding='utf-8')
|
||||
except Exception as error:
|
||||
return finish(VerifyResult('FAIL', stderr=str(error)))
|
||||
events = root/'events.jsonl'
|
||||
offset = 0
|
||||
target_pid = None
|
||||
@@ -841,10 +905,13 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
lock_status = win32event.WaitForSingleObject(mutex, 0)
|
||||
if lock_status not in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED):
|
||||
mutex.Close()
|
||||
return finish(VerifyResult('BLOCKED', stderr='已有 CBB 校验任务运行,请等待结束。', safe_to_continue=False))
|
||||
return finish(VerifyResult('BLOCKED', stderr='已有 CBB 校验任务运行;本次未启动。',
|
||||
safe_to_continue=True, error_category='NATIVE_CHANNEL_BUSY'))
|
||||
worker_launch_attempted = False
|
||||
try:
|
||||
timing.begin('worker_setup')
|
||||
with (root/'worker.log').open('w', encoding='utf-8') as log:
|
||||
worker_launch_attempted = True
|
||||
if request.interactive_input:
|
||||
process = DesktopWorker(
|
||||
worker_command(job_path), None, interactive_input=True)
|
||||
@@ -862,9 +929,10 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
if hasattr(process, 'start_companion'):
|
||||
from .dialog_agent import DialogAgentClient
|
||||
from .dialog_rules import default_rules_path, load_rules
|
||||
dialog_agent = DialogAgentClient.start(process, root/'dialog-agent')
|
||||
dialog_agent = DialogAgentClient.start(process, root/'dialog-agent', stop=stop)
|
||||
dialog_supervisor = DialogSupervisor(
|
||||
AgentDialogBackend(dialog_agent),
|
||||
AgentDialogBackend(dialog_agent, pids=lambda: {
|
||||
int(pid) for pid in (target_pid, lm_pid, launcher_pid) if pid}),
|
||||
rules=load_rules(default_rules_path()),
|
||||
)
|
||||
else:
|
||||
@@ -877,8 +945,14 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
desktop=process.desktop,
|
||||
pids=lambda: ({value for value in (target_pid, lm_pid) if value is not None}),
|
||||
)
|
||||
if stop is not None and stop.is_set():
|
||||
raise InterruptedError('VERIFY_CANCELLED: 启动已取消,未启动 PCB')
|
||||
Path(job['start_gate']).touch()
|
||||
while process.poll() is None:
|
||||
if stop is not None and stop.is_set():
|
||||
_stop_worker(process)
|
||||
return finish(VerifyResult('CANCELLED', stderr='已取消当前校验。',
|
||||
safe_to_continue=False, error_stage=phase.value))
|
||||
if events.exists():
|
||||
with events.open(encoding='utf-8') as stream:
|
||||
stream.seek(offset)
|
||||
@@ -913,7 +987,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
0.1, float(request.timeout_seconds))
|
||||
deadline.touch()
|
||||
last_activity_key = activity_key
|
||||
if progress: progress(event)
|
||||
if progress: _notify_progress(progress, event)
|
||||
offset = stream.tell()
|
||||
if verify_invoked and target_pid is None and time.monotonic() - last_observation >= .5:
|
||||
from .post_verify_diagnostics import observe_post_verify
|
||||
@@ -1017,14 +1091,14 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
if dispatch_failure is not None:
|
||||
status, detail = dispatch_failure
|
||||
if progress:
|
||||
progress({
|
||||
_notify_progress(progress, {
|
||||
'stage': 'verify_dispatch_failed',
|
||||
'block': request.block_name,
|
||||
'detail': detail,
|
||||
'observation': last_post_verify_observation,
|
||||
})
|
||||
return finish(VerifyResult(status, stderr=detail, safe_to_continue=False))
|
||||
return finish(VerifyResult('TIMEOUT', stderr='操作超时;已停止自动化并保留原生会话,停止批次,请检查恢复记录。', error_stage=phase.value, safe_to_continue=False))
|
||||
return finish(VerifyResult('TIMEOUT', stderr='操作超时,当前项未完成。', error_stage=phase.value, safe_to_continue=False))
|
||||
time.sleep(.2)
|
||||
worker_result = root/'outcome.json'
|
||||
if not worker_result.exists():
|
||||
@@ -1036,9 +1110,25 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
except Exception as error:
|
||||
if 'process' in locals() and process.poll() is None:
|
||||
_stop_worker(process)
|
||||
return finish(VerifyResult('FAIL', stderr=str(error), safe_to_continue=False))
|
||||
launch_release = getattr(error, 'worker_launch_release', None) if 'process' not in locals() else None
|
||||
if not worker_launch_attempted:
|
||||
launch_release = {'process_created': False, 'worker_exited': True,
|
||||
'safe_to_continue': True, 'remaining_pids': []}
|
||||
no_launch = (isinstance(launch_release, dict)
|
||||
and launch_release.get('process_created') is False
|
||||
and launch_release.get('worker_exited') is True
|
||||
and launch_release.get('safe_to_continue') is True
|
||||
and launch_release.get('remaining_pids') == [])
|
||||
if no_launch:
|
||||
_write_optional_evidence(root/'session-release.json', {
|
||||
**launch_release, 'block': request.block_name, 'library': str(request.lmc_file),
|
||||
'worker_pid': None})
|
||||
status = 'CANCELLED' if stop is not None and stop.is_set() else 'FAIL'
|
||||
return finish(VerifyResult(status, stderr=str(error), safe_to_continue=no_launch))
|
||||
finally:
|
||||
close_errors = []
|
||||
worker_exited = False
|
||||
automation_release = {'safe_to_continue': False}
|
||||
if 'dialog_agent' in locals() and dialog_agent is not None:
|
||||
try:
|
||||
dialog_agent.close()
|
||||
@@ -1046,15 +1136,37 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
close_errors.append(str(error))
|
||||
if 'process' in locals():
|
||||
try:
|
||||
worker_exited = process.poll() is not None
|
||||
if not worker_exited:
|
||||
worker_exited = _stop_worker(process)
|
||||
if hasattr(process, 'automation_release_state'):
|
||||
automation_release = process.automation_release_state()
|
||||
else:
|
||||
automation_release = {'safe_to_continue': worker_exited, 'remaining_pids': []}
|
||||
process.close()
|
||||
except Exception as error:
|
||||
close_errors.append(str(error))
|
||||
if 'process' in locals():
|
||||
try:
|
||||
if events.is_file():
|
||||
with events.open(encoding='utf-8') as stream:
|
||||
stream.seek(offset)
|
||||
for line in stream:
|
||||
try:
|
||||
event = json.loads(line)
|
||||
timing.record(event)
|
||||
if event.get('pcb_pid'): target_pid = event['pcb_pid']
|
||||
if event.get('launcher_pid'): launcher_pid = event['launcher_pid']
|
||||
if event.get('lm_pid'): lm_pid = event['lm_pid']
|
||||
if event.get('stage') == 'pcb_baseline': pcb_baseline = set(event.get('pids', ()))
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
continue
|
||||
offset = stream.tell()
|
||||
release_result = _cleanup_session_processes(
|
||||
root,
|
||||
lm_pid=lm_pid,
|
||||
target_pid=target_pid,
|
||||
launcher_pid=launcher_pid,
|
||||
pcb=pcb,
|
||||
pcb_baseline=pcb_baseline,
|
||||
progress=progress,
|
||||
@@ -1065,16 +1177,28 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
from .icdb_ownership import unreleased_addresses
|
||||
addresses = unreleased_addresses(request.lmc_file, project, pcb)
|
||||
if addresses:
|
||||
release_result = {**(release_result or {}), 'safe_to_continue': False,
|
||||
'icdb_address': addresses[0], 'icdb_addresses': addresses}
|
||||
release_result = {**(release_result or {}), 'icdb_addresses': addresses}
|
||||
except OSError as error:
|
||||
close_errors.append(str(error))
|
||||
if close_errors:
|
||||
release_result = {**(release_result or {}), 'safe_to_continue': False,
|
||||
'close_errors': close_errors}
|
||||
if not worker_exited or not automation_release.get('safe_to_continue'):
|
||||
release_result = {**(release_result or {}), 'safe_to_continue': False,
|
||||
'automation_release': automation_release, 'worker_exited': worker_exited}
|
||||
release_result['remaining_pids'] = sorted(set(release_result.get('remaining_pids', []))
|
||||
| set(automation_release.get('remaining_pids', [])))
|
||||
try:
|
||||
(root/'session-release.json').write_text(json.dumps({
|
||||
**(release_result or {}), 'block': request.block_name,
|
||||
'library': str(request.lmc_file), 'worker_exited': worker_exited,
|
||||
'worker_pid': getattr(process, 'pid', None)},
|
||||
ensure_ascii=False, default=str, indent=2), encoding='utf-8')
|
||||
except OSError:
|
||||
pass
|
||||
if not release_result or not release_result.get('safe_to_continue'):
|
||||
if 'result' in locals():
|
||||
result = replace(result, status='FAIL', safe_to_continue=False,
|
||||
result = replace(result, status='FAIL' if result.status == 'PASS' else result.status, safe_to_continue=False,
|
||||
stderr=(result.stderr + '\nPCB_RELEASE_UNCONFIRMED: 未确认原生会话退出').strip())
|
||||
recovery = {'desktop': job['desktop'], 'project': str(project),
|
||||
'pcb': str(pcb), 'release': release_result,
|
||||
@@ -1108,16 +1232,16 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
def record_attempt(record):
|
||||
bridge_records.append(record)
|
||||
if progress:
|
||||
progress({'stage': 'library_flag_probe', 'block': request.block_name, **record})
|
||||
_notify_progress(progress, {'stage': 'library_flag_probe', 'block': request.block_name, **record})
|
||||
try:
|
||||
probe = read_library_flag_with_retry(
|
||||
flag_reader or read_library_flag_if_available, Path(request.lmc_file),
|
||||
request.block_name, on_attempt=record_attempt)
|
||||
result = apply_post_verify_status(result, probe)
|
||||
result = replace(result, bridge_attempts=tuple(bridge_records))
|
||||
(root/'bridge-status.json').write_text(json.dumps(bridge_records, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
_write_optional_evidence(root/'bridge-status.json', bridge_records)
|
||||
if progress:
|
||||
progress({'stage': 'library_flag', 'block': request.block_name,
|
||||
_notify_progress(progress, {'stage': 'library_flag', 'block': request.block_name,
|
||||
'library_flag': result.library_flag, 'detail': result.library_flag_detail})
|
||||
finally:
|
||||
timing.end('library_flag')
|
||||
@@ -1143,10 +1267,10 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
|
||||
result = VerifyResult('FAIL', stderr=str(error), safe_to_continue=False)
|
||||
results.append(result)
|
||||
# Never start another writer after an unconfirmed native shutdown.
|
||||
queue_stop = queue_stop or result.status == 'QUEUE_STOP' or not result.safe_to_continue
|
||||
queue_stop = queue_stop or result.status in {'QUEUE_STOP', 'CANCELLED'} or not result.safe_to_continue
|
||||
if queue_stop and stop is not None:
|
||||
stop.set()
|
||||
if progress: progress(request.block_name, result)
|
||||
if progress: _notify_progress(progress, request.block_name, result)
|
||||
return results
|
||||
|
||||
|
||||
@@ -1167,11 +1291,21 @@ def write_failure_report(requests, results, root, *, path=None):
|
||||
root = Path(root); root.mkdir(parents=True, exist_ok=True)
|
||||
path = Path(path) if path else root/('failures-' + time.strftime('%Y%m%d-%H%M%S') + '-' + uuid4().hex[:6] + '.log')
|
||||
failed = [(req, result) for req, result in zip(requests, results)
|
||||
if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP'}]
|
||||
if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP'}
|
||||
and not (result.status in {'CHECKED', 'REPAIRED'} and result.safe_to_continue)]
|
||||
passed = sum(result.status == 'PASS' for result in results)
|
||||
skipped = len(results)-passed-len(failed)
|
||||
lines = ['CBB Verify 失败清单', f'总数: {len(results)} 成功: {passed} 失败: {len(failed)} 未执行: {skipped}',
|
||||
checked = sum(result.status == 'CHECKED' and result.safe_to_continue for result in results)
|
||||
repaired = sum(result.status == 'REPAIRED' and result.safe_to_continue for result in results)
|
||||
skipped = len(results)-passed-len(failed)-checked-repaired
|
||||
lines = ['CBB Verify 失败清单', f'总数: {len(results)} 成功: {passed} 失败: {len(failed)} 未执行: {skipped} 仅检查未修复: {checked} ICDB已修复待校验: {repaired}',
|
||||
'CBB\t状态\t错误分类\t失败阶段\t桥状态\t原始错误\t证据\t实际耗时(秒)']
|
||||
if requests and all(req.maintenance for req in requests):
|
||||
from .icdb_maintenance import maintenance_counts
|
||||
counts = maintenance_counts(results)
|
||||
lines[:2] = ['ICDB 检查异常清单',
|
||||
f'总数: {len(results)} 未发现异常: {checked} 发现问题: {counts["issues_found"]} '
|
||||
f'占用: {counts["in_use"]} 无法确认: {counts["unconfirmed"]} '
|
||||
f'取消: {counts["cancelled"]} 未执行: {counts["skipped"]}']
|
||||
for req, result in failed:
|
||||
timings = ' '.join(f'{key}={value:.3f}s' +
|
||||
('(unfinished)' if key in result.incomplete_timing_phases else '')
|
||||
@@ -1192,6 +1326,8 @@ def write_batch_report(requests, results, root):
|
||||
path = root/('batch-' + time.strftime('%Y%m%d-%H%M%S') + '-' + uuid4().hex[:6] + '.log')
|
||||
lines = ['CBB Verify 批量结果',
|
||||
'流程: LMC 原生 Verify / ReusableCircuit PCB -> Project Integration -> Save/Close -> IsVerifiedReuseBlock READY(金标准)']
|
||||
if requests and all(req.maintenance for req in requests):
|
||||
lines = ['ICDB 批量检查结果', '流程: 原生 PCB 打开检查;不执行 Repair、Restore 或 CBB 校验。']
|
||||
for req, result in zip(requests, results):
|
||||
detail = _report_field(result.stderr or result.stdout.strip()[:200])
|
||||
seconds = ' '.join(f'{key}={value:.3f}s' +
|
||||
|
||||
@@ -69,7 +69,7 @@ def test_crashed_worker_cannot_pass_even_with_pass_file(tmp_path, monkeypatch, o
|
||||
pytest.fail('A crashed writer must not become PASS via a pre-existing READY flag')
|
||||
result = run_verify(request(tmp_path), port_check=lambda: (True, ''), flag_reader=must_not_query)
|
||||
assert result.status == 'FAIL'
|
||||
assert result.safe_to_continue is False
|
||||
assert result.safe_to_continue is True # Proven release permits another item; crash stays FAIL.
|
||||
|
||||
|
||||
def test_supervisor_crash_stops_registered_save_helper_but_not_native(tmp_path):
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
from threading import Event, Thread
|
||||
import time
|
||||
|
||||
|
||||
def test_native_queue_is_fifo_and_waiting_cancel_never_runs_action():
|
||||
from cbb_refresh_verify.operation_queue import NativeQueue, QueueCancelled
|
||||
queue = NativeQueue()
|
||||
holding, release, waiting, cancelled = Event(), Event(), Event(), Event()
|
||||
order = []
|
||||
first = Thread(target=lambda: queue.run(lambda: (holding.set(), release.wait(3), order.append('first'))))
|
||||
first.start(); assert holding.wait(1)
|
||||
def second():
|
||||
try: queue.run(lambda: order.append('cancelled'), stop=cancelled, waiting=waiting.set)
|
||||
except QueueCancelled: pass
|
||||
second_thread = Thread(target=second); second_thread.start(); assert waiting.wait(1)
|
||||
cancelled.set(); second_thread.join(1); assert not second_thread.is_alive()
|
||||
third = Thread(target=lambda: queue.run(lambda: order.append('third')))
|
||||
third.start(); release.set(); first.join(2); third.join(2)
|
||||
assert order == ['first', 'third']
|
||||
|
||||
|
||||
def test_background_scan_keeps_ui_usable_and_yields_between_projects(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
started, release = Event(), Event()
|
||||
order = []
|
||||
def verify(request):
|
||||
order.append(request.block_name)
|
||||
if request.block_name == 'Beta':
|
||||
started.set(); release.wait(3)
|
||||
return VerifyResult('CHECKED')
|
||||
window = load_window(qtbot, tmp_path, monkeypatch, verifier=verify)
|
||||
window._run(['Beta', 'Gamma'], maintenance=True)
|
||||
try:
|
||||
qtbot.waitUntil(started.is_set)
|
||||
assert not window.busy and window.search_edit.isEnabled() and window.load_button.isEnabled()
|
||||
window.search_edit.setText('Gamma')
|
||||
assert [r.name for r in window.visible_records()] == ['Gamma']
|
||||
window._start(lambda: order.append('foreground'), lambda _: None)
|
||||
qtbot.wait(30)
|
||||
assert order == ['Beta']
|
||||
release.set()
|
||||
qtbot.waitUntil(lambda: not window.icdb_task.active and not window.busy)
|
||||
assert order == ['Beta', 'foreground', 'Gamma']
|
||||
assert window.search_edit.text() == 'Gamma'
|
||||
assert window.icdb_repair_button.isEnabled()
|
||||
finally:
|
||||
release.set()
|
||||
|
||||
|
||||
def test_unconfirmed_open_is_amber_and_does_not_claim_icdb_damage(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
window = load_window(qtbot, tmp_path, monkeypatch, verifier=lambda _: VerifyResult('FAIL',
|
||||
error_category='DATABASE_SAFETY_STOP', stderr='Continue to open read/write?'))
|
||||
window._run(['Beta'], maintenance=True)
|
||||
qtbot.waitUntil(lambda: not window.icdb_task.active)
|
||||
cell = window.cbb_table.item(window._row_by_name['Beta'], 3)
|
||||
assert '未确认' in cell.text() and 'ICDB 错误' not in cell.text()
|
||||
assert cell.background().color().name() == '#fff8e1'
|
||||
|
||||
|
||||
|
||||
|
||||
def test_later_management_invalidates_old_recovery_offer(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
from test_reimport_recovery import failed_repair
|
||||
window = load_window(qtbot, tmp_path, monkeypatch,
|
||||
verifier=lambda _: failed_repair(tmp_path/'old/result.json', safe=True))
|
||||
window._run(['Beta'], maintenance=True)
|
||||
qtbot.waitUntil(lambda: not window._icdb_active())
|
||||
action = next(b for b in window.icdb_summary.buttons() if '副本' in b.text())
|
||||
assert action.isEnabled()
|
||||
window._invalidate_check_targets('test.lmc', ['Beta'])
|
||||
assert not action.isEnabled() and not window._reimport_offers
|
||||
@@ -0,0 +1,122 @@
|
||||
"""Background check and foreground queue interaction regressions."""
|
||||
from threading import Event
|
||||
|
||||
import pytest
|
||||
|
||||
from test_ui_filters import load_window
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
|
||||
|
||||
def background(window, qtbot):
|
||||
started, release = Event(), Event()
|
||||
calls=[]
|
||||
def verify(request):
|
||||
calls.append(request.block_name)
|
||||
if request.block_name=='Beta':
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
return VerifyResult('CHECKED')
|
||||
window.verifier=verify
|
||||
window._run(['Beta','Gamma'],maintenance=True)
|
||||
qtbot.waitUntil(started.is_set)
|
||||
return release,calls
|
||||
|
||||
|
||||
def finish(window, qtbot, release):
|
||||
release.set()
|
||||
window.icdb_task.resume()
|
||||
qtbot.waitUntil(lambda:not window._icdb_active() and not window.busy)
|
||||
qtbot.waitUntil(lambda:window.pool.activeThreadCount()==0)
|
||||
|
||||
|
||||
def test_stop_whole_queue_does_not_resume_background_checks(qtbot,tmp_path,monkeypatch):
|
||||
window=load_window(qtbot,tmp_path,monkeypatch)
|
||||
release,calls=background(window,qtbot)
|
||||
try:
|
||||
window._start(lambda:None,lambda _:None)
|
||||
qtbot.waitUntil(lambda:bool(window.native_queue.pending))
|
||||
window.stop_button.click()
|
||||
release.set()
|
||||
qtbot.waitUntil(lambda:not window._icdb_active() and not window.busy)
|
||||
assert calls==['Beta'],f'Cancelled queue still ran: {calls}'
|
||||
finally:finish(window,qtbot,release)
|
||||
|
||||
|
||||
def test_check_progress_survives_queued_verify(qtbot,tmp_path,monkeypatch):
|
||||
window=load_window(qtbot,tmp_path,monkeypatch,
|
||||
status_refresher=lambda names,path:{name:'PENDING' for name in names})
|
||||
release,calls=background(window,qtbot)
|
||||
try:
|
||||
assert not window.icdb_progress.isHidden()
|
||||
window._run(['Gamma'])
|
||||
assert not window.icdb_progress.isHidden(),'Queued verify hid the active check progress'
|
||||
finally:finish(window,qtbot,release)
|
||||
|
||||
|
||||
def test_release_failure_is_not_labelled_as_read_write_prompt(qtbot,tmp_path,monkeypatch):
|
||||
window=load_window(qtbot,tmp_path,monkeypatch,verifier=lambda request:VerifyResult(
|
||||
'FAIL',error_category='DATABASE_SAFETY_STOP',safe_to_continue=False,
|
||||
stderr='PCB_RELEASE_UNCONFIRMED: launcher still running'))
|
||||
window._run(['Beta'],maintenance=True)
|
||||
qtbot.waitUntil(lambda:not window._icdb_active())
|
||||
cell=window.cbb_table.item(window._row_by_name['Beta'],3)
|
||||
assert '读写确认' not in cell.text(),cell.text()
|
||||
|
||||
|
||||
def test_pending_check_skips_a_target_that_has_become_ready(qtbot,tmp_path,monkeypatch):
|
||||
window=load_window(qtbot,tmp_path,monkeypatch)
|
||||
release,calls=background(window,qtbot)
|
||||
try:
|
||||
window.icdb_task.pause()
|
||||
release.set()
|
||||
qtbot.waitUntil(lambda:len(window.icdb_task.results)==1 and not window.icdb_task.running)
|
||||
window._apply_refreshed_records((('Gamma',),{'Gamma':'READY'},{},''))
|
||||
assert 'Gamma' in window.ready_names
|
||||
window.icdb_task.resume()
|
||||
qtbot.waitUntil(lambda:not window._icdb_active())
|
||||
assert calls==['Beta'],f'Already READY target was opened again: {calls}'
|
||||
finally:finish(window,qtbot,release)
|
||||
|
||||
|
||||
def test_worker_refresh_excludes_ready_before_any_gui_result_callback(qtbot,tmp_path,monkeypatch):
|
||||
window=load_window(qtbot,tmp_path,monkeypatch,
|
||||
status_refresher=lambda names,path:{name:'READY' for name in names})
|
||||
release,calls=background(window,qtbot)
|
||||
try:
|
||||
window._start(lambda:window._read_affected_records(('Gamma',)),lambda payload:None)
|
||||
qtbot.waitUntil(lambda:bool(window.native_queue.pending))
|
||||
release.set()
|
||||
qtbot.waitUntil(lambda:not window._icdb_active() and not window.busy)
|
||||
assert window._records_by_name['Gamma'].status=='UNKNOWN'
|
||||
assert calls==['Beta']
|
||||
assert window.icdb_task.results[1].status=='SKIPPED'
|
||||
assert 'READY' in window.icdb_task.results[1].stderr
|
||||
finally:finish(window,qtbot,release)
|
||||
|
||||
|
||||
def test_another_library_ready_status_cannot_skip_this_library_target(qtbot,tmp_path,monkeypatch):
|
||||
window=load_window(qtbot,tmp_path,monkeypatch)
|
||||
release,calls=background(window,qtbot)
|
||||
try:
|
||||
window._publish_check_statuses('other.lmc',{'Gamma':'READY'})
|
||||
release.set()
|
||||
qtbot.waitUntil(lambda:not window._icdb_active())
|
||||
assert calls==['Beta','Gamma']
|
||||
finally:finish(window,qtbot,release)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('detail,safe,expected',[
|
||||
('Continue to open the design with read/write access permission?',True,'读写确认'),
|
||||
('PCB_RELEASE_UNCONFIRMED: launcher still running',False,'释放未确认'),
|
||||
('ICDB_RELEASE_UNCONFIRMED: database still occupied',False,'释放未确认'),
|
||||
('PCB_SESSION_ACTIVE: target already open',True,'会话或数据库状态待确认'),
|
||||
])
|
||||
def test_safety_stop_label_tracks_actual_reason(qtbot,tmp_path,monkeypatch,detail,safe,expected):
|
||||
window=load_window(qtbot,tmp_path,monkeypatch,verifier=lambda request:VerifyResult(
|
||||
'FAIL',error_category='DATABASE_SAFETY_STOP',safe_to_continue=safe,stderr=detail))
|
||||
window._run(['Beta'],maintenance=True)
|
||||
qtbot.waitUntil(lambda:not window._icdb_active())
|
||||
cell=window.cbb_table.item(window._row_by_name['Beta'],3)
|
||||
assert expected in cell.text()
|
||||
assert cell.toolTip()==detail
|
||||
assert cell.background().color().name()=='#fff8e1'
|
||||
@@ -144,10 +144,68 @@ def test_idle_guard_queries_supported_native_process_names(recovery_files, monke
|
||||
queries.append(query)
|
||||
return []
|
||||
monkeypatch.setattr(win32com.client, 'GetObject', lambda _: EmptyProcesses())
|
||||
from cbb_refresh_verify import owner_probe
|
||||
import subprocess
|
||||
monkeypatch.setattr(owner_probe.subprocess, 'run', lambda command, **kw:
|
||||
subprocess.CompletedProcess(command, owner_probe.owner_probe_main(command[-1])))
|
||||
_idle_check(request.lmc_file, original, original.parent/'PCB/A.pcb')
|
||||
assert any("Name='viewdraw.exe'" in query for query in queries)
|
||||
|
||||
|
||||
def test_idle_guard_ignores_unrelated_project_and_prefix_sibling(recovery_files, monkeypatch):
|
||||
from cbb_refresh_verify.backup_recovery import _idle_check
|
||||
from cbb_refresh_verify import mentor_adapter
|
||||
request, original, _ = recovery_files
|
||||
unrelated = original.parent.with_name(original.parent.name+'Old')/'PCB/A.pcb'
|
||||
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: [(123, '', str(unrelated))])
|
||||
monkeypatch.setattr(mentor_adapter, '_process_details', lambda name:
|
||||
[(123, 'ExpeditionPCB.exe', f'ExpeditionPCB.exe "{unrelated}" -ReusableCircuit', 0)]
|
||||
if name == 'ExpeditionPCB.exe' else [])
|
||||
_idle_check(request.lmc_file, original, original.parent/'PCB/A.pcb')
|
||||
|
||||
|
||||
def test_idle_guard_rejects_exact_target_process(recovery_files, monkeypatch):
|
||||
from cbb_refresh_verify.backup_recovery import _idle_check
|
||||
from cbb_refresh_verify import mentor_adapter
|
||||
request, original, _ = recovery_files
|
||||
target = original.parent/'PCB/A.pcb'
|
||||
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: [])
|
||||
monkeypatch.setattr(mentor_adapter, '_process_details', lambda name:
|
||||
[(123, 'ExpeditionPCB.exe', f'ExpeditionPCB.exe "{target}" -ReusableCircuit', 0)]
|
||||
if name == 'ExpeditionPCB.exe' else [])
|
||||
with pytest.raises(ValueError, match='TARGET_NATIVE_OWNER_ACTIVE'):
|
||||
_idle_check(request.lmc_file, original, target)
|
||||
|
||||
|
||||
def test_prelaunch_recovery_rejection_has_no_unreleased_session(recovery_files):
|
||||
from cbb_refresh_verify.backup_recovery import recover_from_backup
|
||||
request, _, source = recovery_files
|
||||
def reject(*args): raise ValueError('target unavailable before launch')
|
||||
result = recover_from_backup(request, source, idle_check=reject,
|
||||
verifier=lambda *a, **k: pytest.fail('prelaunch rejection must not start native'))
|
||||
assert result.status == 'BLOCKED'
|
||||
assert result.safe_to_continue
|
||||
|
||||
|
||||
def test_report_write_failure_does_not_lose_prelaunch_release_fact(recovery_files, monkeypatch):
|
||||
from cbb_refresh_verify.backup_recovery import recover_from_backup
|
||||
import win32event
|
||||
from uuid import uuid4
|
||||
create_mutex = win32event.CreateMutex
|
||||
monkeypatch.setattr(win32event, 'CreateMutex', lambda security, owned, name:
|
||||
create_mutex(security, owned, name+'-test-'+uuid4().hex))
|
||||
request, _, source = recovery_files
|
||||
original_write = Path.write_text
|
||||
def write(path, *args, **kwargs):
|
||||
if path.name == 'recovery-result.json': raise OSError('report disk unavailable')
|
||||
return original_write(path, *args, **kwargs)
|
||||
monkeypatch.setattr(Path, 'write_text', write)
|
||||
def reject(*args): raise ValueError('prelaunch unavailable')
|
||||
result = recover_from_backup(request, source, idle_check=reject)
|
||||
assert result.status == 'BLOCKED' and result.safe_to_continue
|
||||
assert 'report disk unavailable' in result.stderr
|
||||
|
||||
|
||||
def test_copy_refuses_directory_junction_before_copying(tmp_path):
|
||||
import subprocess
|
||||
from cbb_refresh_verify.backup_recovery import _copy_verified
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
"""Only live clients stop a batch; native writes are replaced by fixtures."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
|
||||
import pytest
|
||||
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
from test_verify_runner import fixture, request, PORTS_OK
|
||||
|
||||
|
||||
@pytest.mark.parametrize('status,detail', [('FAIL', 'UNKNOWN_DIALOG: native prompt'),
|
||||
('TIMEOUT', 'native operation timed out')])
|
||||
@pytest.mark.parametrize('released', [True, False])
|
||||
def test_batch_continuation_follows_actual_release(tmp_path, monkeypatch, status, detail, released):
|
||||
fixture(tmp_path)
|
||||
launches = []
|
||||
class Worker:
|
||||
desktop = None
|
||||
returncode = 1
|
||||
def __init__(self, command, *_a, **_k):
|
||||
launches.append(command)
|
||||
Path(command[-1]).with_name('outcome.json').write_text(json.dumps({
|
||||
'status': status, 'stderr': detail, 'safe_to_continue': False}))
|
||||
def poll(self): return 1
|
||||
def close(self): pass
|
||||
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker)
|
||||
monkeypatch.setattr(runner, '_cleanup_session_processes', lambda *a, **k:
|
||||
{'safe_to_continue': released, 'remaining_pids': [] if released else [123]})
|
||||
monkeypatch.setattr('cbb_refresh_verify.verify_diagnostics.capture_failure_logs_with_timeout', lambda *_: None)
|
||||
req = request(tmp_path)
|
||||
try:
|
||||
results = runner.run_batch([req, req], verifier=lambda r: runner.run_verify(r, port_check=PORTS_OK))
|
||||
assert results[0].status == status and results[0].safe_to_continue is released
|
||||
assert len(launches) == (2 if released else 1)
|
||||
assert results[1].status == (status if released else 'SKIPPED')
|
||||
finally:
|
||||
from cbb_refresh_verify import library_lock as locks
|
||||
with locks._guard:
|
||||
owner = locks._owners.pop(locks.LibraryLock(req.lmc_file).key, None)
|
||||
if owner: owner['handle'].Close()
|
||||
|
||||
|
||||
def test_item_failure_with_confirmed_release_does_not_stop_unrelated_items(tmp_path):
|
||||
from cbb_refresh_verify.verify_runner import VerifyRequest, VerifyResult
|
||||
library = tmp_path/'library.lmc'; library.touch()
|
||||
requests = [VerifyRequest(library, name, tmp_path/'evidence') for name in ('A', 'B')]
|
||||
calls = []
|
||||
def verify(request):
|
||||
calls.append(request.block_name)
|
||||
return VerifyResult('FAIL' if request.block_name == 'A' else 'PASS',
|
||||
stderr='单项失败但会话已释放' if request.block_name == 'A' else '',
|
||||
safe_to_continue=True)
|
||||
results = runner.run_batch(requests, verifier=verify)
|
||||
assert calls == ['A', 'B']
|
||||
assert [result.status for result in results] == ['FAIL', 'PASS']
|
||||
|
||||
|
||||
def test_stop_worker_escalates_only_after_cooperative_deadline():
|
||||
calls = []
|
||||
class Worker:
|
||||
stopped = False
|
||||
def request_stop(self): calls.append('cancel')
|
||||
def wait(self, timeout=5):
|
||||
calls.append('wait')
|
||||
if not self.stopped: raise TimeoutError()
|
||||
def kill(self): calls.append('client_stop'); self.stopped = True
|
||||
def poll(self): return 1 if self.stopped else None
|
||||
assert runner._stop_worker(Worker(), timeout=.1) is True
|
||||
assert calls == ['cancel', 'wait', 'client_stop', 'wait']
|
||||
|
||||
|
||||
def test_cancel_reaches_current_supervised_worker(tmp_path, monkeypatch):
|
||||
fixture(tmp_path)
|
||||
stop = Event()
|
||||
cancelled = []
|
||||
class Worker:
|
||||
desktop = None
|
||||
returncode = None
|
||||
def __init__(self, command, *_a, **_k):
|
||||
self.job = json.loads(Path(command[-1]).read_text('utf-8'))
|
||||
stop.set()
|
||||
def bind_cancellation(self, path): self.cancel = Path(path)
|
||||
def request_stop(self):
|
||||
self.cancel.touch(); cancelled.append(self.cancel)
|
||||
self.returncode = 1
|
||||
def wait(self, **_k): return 1
|
||||
def poll(self): return self.returncode
|
||||
def close(self): pass
|
||||
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker)
|
||||
monkeypatch.setattr(runner, '_cleanup_session_processes', lambda *a, **k: {'safe_to_continue': True})
|
||||
monkeypatch.setattr('cbb_refresh_verify.verify_diagnostics.capture_failure_logs_with_timeout', lambda *_: None)
|
||||
result = runner.run_verify(request(tmp_path), stop=stop, port_check=PORTS_OK)
|
||||
assert result.status == 'CANCELLED' and result.safe_to_continue
|
||||
assert len(cancelled) == 1 and cancelled[0].is_file()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('text,expected', [
|
||||
('content checking completed successfully! 0 errors, 0 warnings', 'PASS'),
|
||||
('content checking completed successfully! 10 errors', 'FAIL'),
|
||||
('content checking completed successfully! error: missing symbol', 'FAIL'),
|
||||
('content checking completed successfully! 0 errors\nERROR: cannot connect', 'FAIL'),
|
||||
])
|
||||
def test_zero_error_count_does_not_block_content_check(text, expected):
|
||||
assert runner.classify_output(0, text) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize('codec', ['utf-16', 'utf-8-sig', 'mbcs'])
|
||||
def test_preflight_reads_native_project_encodings(tmp_path, codec):
|
||||
work = fixture(tmp_path)
|
||||
(work/'CBB1.prj').write_bytes(('# 中文工程\nKEY PCBDesignPath "PCB\\actual.pcb"\n').encode(codec))
|
||||
project, pcb = runner.preflight(request(tmp_path))
|
||||
assert pcb == work/'PCB/actual.pcb'
|
||||
|
||||
|
||||
def test_unrelated_pcb_does_not_block_target_before_launch(tmp_path, monkeypatch):
|
||||
from test_verify_worker_stability import exercise_worker
|
||||
from cbb_refresh_verify import mentor_adapter as adapter
|
||||
job, events, execute = exercise_worker(tmp_path, monkeypatch)
|
||||
monkeypatch.setattr(adapter, 'pcb_processes', lambda: ((999, 'ExpeditionPCB.exe', '"ExpeditionPCB.exe" "C:\\other\\board.pcb"'),))
|
||||
assert execute()['status'] == 'PASS'
|
||||
assert any(e['stage'] == 'pcb_launch' for e in events)
|
||||
|
||||
|
||||
def test_sampling_ports_only_warn_by_default(tmp_path, monkeypatch):
|
||||
fixture(tmp_path)
|
||||
launches, warnings = [], []
|
||||
class Worker:
|
||||
desktop = None
|
||||
returncode = 0
|
||||
def __init__(self, command, *_a, **_k):
|
||||
launches.append(command)
|
||||
Path(command[-1]).with_name('outcome.json').write_text('{"status":"PASS"}')
|
||||
def poll(self): return 0
|
||||
def close(self): pass
|
||||
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker)
|
||||
monkeypatch.setattr(runner, '_cleanup_session_processes', lambda *a, **k: {'safe_to_continue': True})
|
||||
result = runner.run_verify(request(tmp_path), port_check=lambda: (False, 'sample unavailable'),
|
||||
flag_reader=lambda *_: __import__('cbb_refresh_verify.status_bridge', fromlist=['BridgeResult']).BridgeResult('READY', 'IsVerifiedReuseBlock', 1),
|
||||
progress=warnings.append)
|
||||
assert launches and result.status == 'PASS'
|
||||
assert any(e['stage'] == 'port_warning' for e in warnings)
|
||||
|
||||
|
||||
def test_cleanup_includes_late_native_descendant_without_pcb_argument(monkeypatch):
|
||||
from cbb_refresh_verify import mentor_adapter as adapter
|
||||
rows = [(10, 'ExpeditionPCB.exe', '', 1), (11, 'ExpeditionPCB.exe', '', 10),
|
||||
(99, 'ExpeditionPCB.exe', '', 77)]
|
||||
monkeypatch.setattr(adapter, '_process_details', lambda name: rows if name == 'ExpeditionPCB.exe' else [])
|
||||
result = adapter.cleanup_verify_processes(None, None, 10, baseline_pids={99})
|
||||
assert not result['safe_to_continue'] and result['remaining_pids'] == [10, 11]
|
||||
|
||||
|
||||
def test_save_client_without_worker_still_prevents_continuation(tmp_path, monkeypatch):
|
||||
fixture(tmp_path)
|
||||
class Worker:
|
||||
desktop = None
|
||||
returncode = 1
|
||||
def __init__(self, command, *_a, **_k):
|
||||
Path(command[-1]).with_name('outcome.json').write_text('{"status":"FAIL"}')
|
||||
def poll(self): return 1
|
||||
def close(self): pass
|
||||
def automation_release_state(self): return {'safe_to_continue': False, 'remaining_pids': [333]}
|
||||
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker)
|
||||
monkeypatch.setattr(runner, '_cleanup_session_processes', lambda *a, **k: {'safe_to_continue': True})
|
||||
monkeypatch.setattr('cbb_refresh_verify.verify_diagnostics.capture_failure_logs_with_timeout', lambda *_: None)
|
||||
req = request(tmp_path)
|
||||
try:
|
||||
result = runner.run_verify(req, port_check=PORTS_OK)
|
||||
assert not result.safe_to_continue
|
||||
proof = json.loads(result.evidence_path.with_name('session-release.json').read_text('utf-8'))
|
||||
assert proof['worker_exited'] is True
|
||||
assert proof['automation_release']['remaining_pids'] == [333]
|
||||
assert proof['remaining_pids'] == [333]
|
||||
finally:
|
||||
from cbb_refresh_verify import library_lock as locks
|
||||
with locks._guard:
|
||||
owner = locks._owners.pop(locks.LibraryLock(req.lmc_file).key, None)
|
||||
if owner: owner['handle'].Close()
|
||||
|
||||
|
||||
def test_closed_desktop_worker_keeps_exit_status_without_using_closed_handle(monkeypatch):
|
||||
from types import SimpleNamespace
|
||||
from cbb_refresh_verify import desktop_worker as desktop
|
||||
worker = desktop.DesktopWorker.__new__(desktop.DesktopWorker)
|
||||
handle = SimpleNamespace(closed=False)
|
||||
def close(): handle.closed = True
|
||||
handle.Close = close
|
||||
worker.handle = handle
|
||||
worker.job = SimpleNamespace(Close=lambda: None)
|
||||
worker.desktop = None; worker.companions = []; worker.companion_pids = []
|
||||
def code(h):
|
||||
assert not h.closed, 'Read from a closed Win32 process handle'
|
||||
return 1
|
||||
monkeypatch.setattr(desktop.win32process, 'GetExitCodeProcess', code)
|
||||
worker.close()
|
||||
assert worker.poll() == 1
|
||||
worker.close() # Idempotent cleanup.
|
||||
|
||||
|
||||
def test_native_process_queries_use_bounded_shared_helper(monkeypatch):
|
||||
from cbb_refresh_verify import mentor_adapter as adapter
|
||||
calls = []
|
||||
def query(names):
|
||||
calls.append(names)
|
||||
return [{'pid': 12, 'executable': 'ExpeditionPCB.exe', 'command': 'native', 'parent': 11}]
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', query)
|
||||
assert adapter._process_details('ExpeditionPCB.exe') == [(12, 'ExpeditionPCB.exe', 'native', 11)]
|
||||
assert calls == [('ExpeditionPCB.exe',)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('script', ['save_verified_block.vbs', 'close_failed_block.vbs'])
|
||||
def test_save_and_failure_close_clients_are_both_tracked(script, monkeypatch):
|
||||
from cbb_refresh_verify import desktop_worker as desktop
|
||||
worker = desktop.DesktopWorker.__new__(desktop.DesktopWorker)
|
||||
worker.pid = 11; worker._closed = True; worker._exit_code = 1
|
||||
command = f'cscript.exe //nologo "{Path(desktop.__file__).with_name(script)}" "C:\\fixture\\design.prj"'
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_a, **_k: [
|
||||
{'pid': 22, 'parent': 11, 'command': command},
|
||||
{'pid': 33, 'parent': 99, 'command': command},
|
||||
{'pid': 44, 'parent': 11, 'command': 'cscript.exe unrelated.vbs'}])
|
||||
proof = worker.automation_release_state()
|
||||
assert proof['safe_to_continue'] is False and proof['remaining_pids'] == [22]
|
||||
|
||||
|
||||
def test_watchdog_with_cancel_signal_stops_clients_after_supervisor_exit(tmp_path):
|
||||
import subprocess, sys, time
|
||||
import win32api, win32con, win32process
|
||||
supervisor = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)'])
|
||||
script = tmp_path/'watchdog.py'; ready = tmp_path/'ready.json'; cancel = tmp_path/'cancel.signal'
|
||||
script.write_text(
|
||||
'import sys, subprocess, time, json\nfrom pathlib import Path\n'
|
||||
'from cbb_refresh_verify.desktop_worker import start_supervisor_watchdog, launch_save_helper\n'
|
||||
f'start_supervisor_watchdog({supervisor.pid}, cancel_path={str(cancel)!r}, stop_clients=True)\n'
|
||||
'native = subprocess.Popen([sys.executable,"-c","import time; time.sleep(30)"])\n'
|
||||
'client = launch_save_helper([sys.executable,"-c","import time; time.sleep(30)"])\n'
|
||||
f'Path({str(ready)!r}).write_text(json.dumps([native.pid,client.pid]))\n'
|
||||
'time.sleep(30)\n', encoding='utf-8')
|
||||
worker = subprocess.Popen([sys.executable, str(script)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
handles = []
|
||||
try:
|
||||
deadline = time.monotonic()+10
|
||||
while not ready.exists() and worker.poll() is None and time.monotonic()<deadline:
|
||||
time.sleep(.05)
|
||||
assert ready.exists()
|
||||
for pid in json.loads(ready.read_text()):
|
||||
handles.append(win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_TERMINATE, False, pid))
|
||||
supervisor.terminate(); supervisor.wait(5)
|
||||
assert worker.wait(10) == 75 and cancel.is_file()
|
||||
assert win32process.GetExitCodeProcess(handles[0]) == 259
|
||||
assert win32process.GetExitCodeProcess(handles[1]) != 259
|
||||
finally:
|
||||
for p in (supervisor, worker):
|
||||
if p.poll() is None: p.terminate()
|
||||
p.wait(5)
|
||||
for h in handles:
|
||||
if win32process.GetExitCodeProcess(h) == 259: win32process.TerminateProcess(h, 0)
|
||||
h.Close()
|
||||
@@ -84,11 +84,30 @@ def test_scan_reuses_checkpoint_and_queries_only_missing(tmp_path):
|
||||
encoding="utf-8",
|
||||
)
|
||||
bridge = FakeBridge()
|
||||
records = BatchStatusSession(bridge).scan(["A", "B"], lmc, checkpoint)
|
||||
records = BatchStatusSession(bridge).scan(["A", "B"], lmc, checkpoint, resume=True)
|
||||
assert bridge.requests == ["B"]
|
||||
assert {record.block_name for record in records} == {"A", "B"}
|
||||
|
||||
|
||||
def test_default_scan_refreshes_cached_ready_after_payload_change(tmp_path):
|
||||
lmc = tmp_path/'library.lmc'; lmc.write_bytes(b'library')
|
||||
checkpoint = tmp_path/'scan.jsonl'
|
||||
BatchStatusSession(FakeBridge()).scan(['A'], lmc, checkpoint)
|
||||
# The lightweight fingerprint cannot prove payload status is unchanged.
|
||||
fingerprint = fingerprint_library(lmc)
|
||||
(tmp_path/'payload.pcb').write_bytes(b'native edit without LMC change')
|
||||
assert fingerprint_library(lmc) == fingerprint
|
||||
class PendingBridge(FakeBridge):
|
||||
def query(self, *args, **kwargs):
|
||||
self.requests.append(args[1])
|
||||
return BridgeResult('PENDING', 'fake')
|
||||
bridge = PendingBridge()
|
||||
records = BatchStatusSession(bridge).scan(['A'], lmc, checkpoint)
|
||||
assert [record.status for record in records] == ['PENDING']
|
||||
assert bridge.requests == ['A']
|
||||
assert len(checkpoint.read_text('utf-8').splitlines()) == 1
|
||||
|
||||
|
||||
def test_timeout_isolated_and_later_item_continues(tmp_path):
|
||||
lmc = tmp_path / "mentor_lib.lmc"
|
||||
lmc.write_bytes(b"library")
|
||||
@@ -99,7 +118,7 @@ def test_timeout_isolated_and_later_item_continues(tmp_path):
|
||||
assert records[1].status == "PENDING"
|
||||
|
||||
|
||||
def test_protocol_path_mismatch_stops_repeating_same_global_failure(tmp_path):
|
||||
def test_protocol_path_mismatch_records_each_queried_item(tmp_path):
|
||||
class BrokenProtocolBridge:
|
||||
def __init__(self):
|
||||
self.requests = []
|
||||
@@ -116,7 +135,7 @@ def test_protocol_path_mismatch_stops_repeating_same_global_failure(tmp_path):
|
||||
['A', 'B', 'C'], lmc, tmp_path / 'scan.jsonl'
|
||||
)
|
||||
|
||||
assert bridge.requests == ['A']
|
||||
assert bridge.requests == ['A', 'B', 'C']
|
||||
assert [record.status for record in records] == ['MALFORMED'] * 3
|
||||
|
||||
|
||||
@@ -172,3 +191,26 @@ def test_authoritative_status_map_never_reuses_previous_scan_status(tmp_path, mo
|
||||
assert first == {'A': 'PENDING'}
|
||||
assert second == {'A': 'READY'}
|
||||
assert calls == ['A', 'A']
|
||||
|
||||
|
||||
def test_retry_rechecks_failed_scan_without_library_changes(tmp_path):
|
||||
lmc = tmp_path/'library.lmc'; lmc.write_bytes(b'library')
|
||||
checkpoint = tmp_path/'scan.jsonl'
|
||||
first = BatchStatusSession(FakeBridge(timeout_name='A')).scan(['A', 'B'], lmc, checkpoint)
|
||||
assert first[0].status == 'TIMEOUT'
|
||||
bridge = FakeBridge()
|
||||
second = BatchStatusSession(bridge).scan(['A', 'B'], lmc, checkpoint, resume=True)
|
||||
assert bridge.requests == ['A']
|
||||
assert second[0].status == 'READY'
|
||||
|
||||
|
||||
def test_missing_x86_runtime_does_not_restart_for_every_cbb(tmp_path):
|
||||
class BrokenBridge(FakeBridge):
|
||||
def query(self, library, name, **kwargs):
|
||||
self.requests.append(name)
|
||||
raise BridgeResponseError('状态桥进程失败: -1073741515')
|
||||
lmc = tmp_path/'library.lmc'; lmc.write_bytes(b'library')
|
||||
bridge = BrokenBridge()
|
||||
result = BatchStatusSession(bridge).scan(['A', 'B', 'C'], lmc, tmp_path/'scan.jsonl')
|
||||
assert bridge.requests == ['A']
|
||||
assert [row.status for row in result] == ['UNAVAILABLE'] * 3
|
||||
@@ -82,5 +82,5 @@ def test_fingerprint_change_does_not_reuse_checkpoint(tmp_path):
|
||||
from cbb_refresh_verify.status_bridge import BridgeResult
|
||||
return BridgeResult("PENDING", "fake")
|
||||
bridge = Bridge()
|
||||
BatchStatusSession(bridge).scan(["A"], lmc, checkpoint)
|
||||
BatchStatusSession(bridge).scan(["A"], lmc, checkpoint, resume=True)
|
||||
assert bridge.requests == ["A"]
|
||||
@@ -0,0 +1,207 @@
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure, expected', [
|
||||
('desktop', []),
|
||||
('job', ['desktop']),
|
||||
('process', ['job', 'desktop']),
|
||||
('thread', ['thread', 'terminate', 'process', 'job', 'desktop']),
|
||||
])
|
||||
def test_constructor_rolls_back_allocated_resources(monkeypatch, failure, expected):
|
||||
import cbb_refresh_verify.desktop_worker as module
|
||||
|
||||
closed = []
|
||||
error = RuntimeError(failure + ' failed')
|
||||
|
||||
class FakeJob:
|
||||
def Close(self):
|
||||
closed.append('job')
|
||||
|
||||
class FakeDesktop:
|
||||
def CloseDesktop(self):
|
||||
closed.append('desktop')
|
||||
|
||||
class FakeProcess:
|
||||
def Close(self):
|
||||
closed.append('process')
|
||||
|
||||
class FakeThread:
|
||||
def Close(self):
|
||||
closed.append('thread')
|
||||
raise error
|
||||
|
||||
def allocate(stage, value):
|
||||
if failure == stage:
|
||||
raise error
|
||||
return value
|
||||
|
||||
process = FakeProcess()
|
||||
monkeypatch.setattr(module.win32service, 'CreateDesktop',
|
||||
lambda *args: allocate('desktop', FakeDesktop()))
|
||||
monkeypatch.setattr(module.win32job, 'CreateJobObject',
|
||||
lambda *args: allocate('job', FakeJob()))
|
||||
monkeypatch.setattr(module.win32process, 'STARTUPINFO', lambda: type('Startup', (), {})())
|
||||
monkeypatch.setattr(module.win32process, 'CreateProcess',
|
||||
lambda *args: allocate('process', (process, FakeThread(), 321, 1)))
|
||||
|
||||
def terminate(handle, code):
|
||||
assert handle is process
|
||||
closed.append('terminate')
|
||||
|
||||
monkeypatch.setattr(module.win32process, 'TerminateProcess', terminate)
|
||||
|
||||
with pytest.raises(RuntimeError) as caught:
|
||||
module.DesktopWorker(['worker.exe'], 'PrivateDesk')
|
||||
|
||||
assert caught.value is error
|
||||
assert closed == expected
|
||||
|
||||
|
||||
def test_library_flag_loads_ui_dependencies_before_creating_private_desktop(monkeypatch, tmp_path):
|
||||
import builtins
|
||||
import win32service
|
||||
import cbb_refresh_verify.mentor_adapter as module
|
||||
|
||||
created = []
|
||||
original_import = builtins.__import__
|
||||
executable = tmp_path / 'LibraryManager.exe'
|
||||
executable.touch()
|
||||
|
||||
def deny_pywinauto(name, *args, **kwargs):
|
||||
if name == 'pywinauto' or name.startswith('pywinauto.'):
|
||||
raise ImportError('pywinauto unavailable')
|
||||
return original_import(name, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(builtins, '__import__', deny_pywinauto)
|
||||
monkeypatch.setattr(module, 'library_manager_path', lambda: executable)
|
||||
monkeypatch.setattr(win32service, 'CreateDesktop',
|
||||
lambda *args: created.append(args))
|
||||
|
||||
with pytest.raises(ImportError, match='pywinauto unavailable'):
|
||||
module.read_library_flag('library.lmc', 'Block')
|
||||
|
||||
assert created == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reader', ['read_library_flag', 'read_library_tree_image_map'])
|
||||
def test_reader_does_not_create_desktop_before_preparation_finishes(monkeypatch, tmp_path, reader):
|
||||
import win32service
|
||||
import cbb_refresh_verify.mentor_adapter as module
|
||||
|
||||
closed = []
|
||||
|
||||
class FakeDesktop:
|
||||
def CloseDesktop(self):
|
||||
closed.append('closed')
|
||||
|
||||
class InvalidLibrary:
|
||||
def __fspath__(self):
|
||||
raise ValueError('invalid library path')
|
||||
|
||||
executable = tmp_path / 'LibraryManager.exe'
|
||||
executable.touch()
|
||||
monkeypatch.setattr(module, 'library_manager_path', lambda: executable)
|
||||
monkeypatch.setattr(win32service, 'CreateDesktop',
|
||||
lambda *args: closed.append('created') or FakeDesktop())
|
||||
|
||||
with pytest.raises(ValueError, match='invalid library path'):
|
||||
getattr(module, reader)(InvalidLibrary(), 'Block')
|
||||
|
||||
assert closed == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reader', ['read_library_flag', 'read_library_tree_image_map'])
|
||||
def test_reader_closes_desktop_when_process_launch_fails(monkeypatch, tmp_path, reader):
|
||||
import win32service
|
||||
import win32process
|
||||
import cbb_refresh_verify.mentor_adapter as module
|
||||
|
||||
closed = []
|
||||
|
||||
class FakeDesktop:
|
||||
def CloseDesktop(self):
|
||||
closed.append('desktop')
|
||||
|
||||
def fail(*args):
|
||||
raise RuntimeError('launch failed')
|
||||
|
||||
executable = tmp_path / 'LibraryManager.exe'
|
||||
executable.touch()
|
||||
monkeypatch.setattr(module, 'library_manager_path', lambda: executable)
|
||||
monkeypatch.setattr(win32service, 'CreateDesktop', lambda *args: FakeDesktop())
|
||||
monkeypatch.setattr(win32process, 'CreateProcess', fail)
|
||||
if reader == 'read_library_flag':
|
||||
flag, detail = module.read_library_flag(tmp_path / 'library.lmc', 'Block')
|
||||
assert flag == module.FLAG_UNKNOWN
|
||||
assert 'launch failed' in detail
|
||||
else:
|
||||
with pytest.raises(RuntimeError, match='launch failed'):
|
||||
module.read_library_tree_image_map(tmp_path / 'library.lmc', ['Block'])
|
||||
assert closed == ['desktop']
|
||||
|
||||
|
||||
def test_constructor_releases_private_desktop_when_process_launch_fails(monkeypatch):
|
||||
import cbb_refresh_verify.desktop_worker as module
|
||||
|
||||
class Handle:
|
||||
def __init__(self):
|
||||
self.closed = False
|
||||
|
||||
def Close(self):
|
||||
self.closed = True
|
||||
|
||||
def CloseDesktop(self):
|
||||
self.closed = True
|
||||
|
||||
desktop = Handle()
|
||||
job = Handle()
|
||||
|
||||
monkeypatch.setattr(module.win32service, 'CreateDesktop', lambda *args: desktop)
|
||||
monkeypatch.setattr(module.win32job, 'CreateJobObject', lambda *args: job)
|
||||
monkeypatch.setattr(module.win32process, 'STARTUPINFO', lambda: type('Startup', (), {})())
|
||||
monkeypatch.setattr(module.win32process, 'CreateProcess',
|
||||
lambda *args: (_ for _ in ()).throw(RuntimeError('launch failed')))
|
||||
|
||||
with pytest.raises(RuntimeError, match='launch failed') as caught:
|
||||
module.DesktopWorker(['worker.exe'], 'PrivateDesk')
|
||||
|
||||
assert desktop.closed is True
|
||||
assert job.closed is True
|
||||
assert caught.value.worker_launch_release == {
|
||||
'process_created': False, 'safe_to_continue': True, 'worker_exited': True, 'remaining_pids': []}
|
||||
|
||||
|
||||
def test_partial_launch_cleanup_never_claims_native_descendants_released(monkeypatch):
|
||||
import cbb_refresh_verify.desktop_worker as module
|
||||
class Handle:
|
||||
def Close(self): pass
|
||||
def CloseDesktop(self): pass
|
||||
class Thread:
|
||||
def Close(self): raise OSError('thread handle cleanup failed')
|
||||
monkeypatch.setattr(module.win32service, 'CreateDesktop', lambda *args: Handle())
|
||||
monkeypatch.setattr(module.win32job, 'CreateJobObject', lambda *args: Handle())
|
||||
monkeypatch.setattr(module.win32process, 'STARTUPINFO', lambda: type('Startup', (), {})())
|
||||
monkeypatch.setattr(module.win32process, 'CreateProcess', lambda *args: (Handle(), Thread(), 123, 456))
|
||||
terminated = []
|
||||
monkeypatch.setattr(module.win32process, 'TerminateProcess', lambda *args: terminated.append(args))
|
||||
with pytest.raises(OSError, match='thread handle cleanup failed') as caught:
|
||||
module.DesktopWorker(['worker.exe'], 'PrivateDesk')
|
||||
assert caught.value.worker_launch_release == {
|
||||
'process_created': True, 'safe_to_continue': False, 'worker_exited': False, 'remaining_pids': [123]}
|
||||
assert len(terminated) == 1
|
||||
|
||||
|
||||
def test_release_probe_allows_measured_owner_helper_startup_time(monkeypatch):
|
||||
import cbb_refresh_verify.desktop_worker as module
|
||||
from cbb_refresh_verify import owner_probe
|
||||
worker = module.DesktopWorker.__new__(module.DesktopWorker)
|
||||
worker.pid = 123
|
||||
worker._closed = True
|
||||
worker._exit_code = 1
|
||||
def query(names, *, timeout_seconds):
|
||||
# Real helper measured ~4.75s including interpreter + COM startup.
|
||||
if timeout_seconds < 5:
|
||||
raise RuntimeError('OWNER_QUERY_TIMEOUT')
|
||||
return []
|
||||
monkeypatch.setattr(owner_probe, 'query_owners', query)
|
||||
assert worker.automation_release_state() == {'safe_to_continue': True, 'remaining_pids': []}
|
||||
@@ -0,0 +1,338 @@
|
||||
import importlib
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def diagnostic():
|
||||
assert importlib.util.find_spec('cbb_refresh_verify.diagnostic_open') is not None, 'diagnostic open module is missing'
|
||||
return importlib.import_module('cbb_refresh_verify.diagnostic_open')
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def job(tmp_path):
|
||||
project = tmp_path / 'IP101GR'
|
||||
pcb = project / 'PCB/IP101GR.pcb'
|
||||
pcb.parent.mkdir(parents=True)
|
||||
pcb.write_bytes(b'pcb')
|
||||
return {'project': str(project / 'IP101GR.prj'), 'pcb': str(pcb), 'root': str(tmp_path / 'evidence'),
|
||||
'desktop': 'CbbDiagnosticTest', 'timeout': .03}
|
||||
|
||||
|
||||
def write_logs(job, *, pid=42, foreign=False, success=True):
|
||||
project = Path(job['project']).parent
|
||||
logdir = Path(job['pcb']).parent / 'LogFiles'
|
||||
logdir.mkdir(parents=True, exist_ok=True)
|
||||
pcb = str(Path(job['pcb'])) if not foreign else str(project.parent / 'other/PCB/IP101GR.pcb')
|
||||
(logdir / 'PCBAutoSave.txt').write_text('Job Name: ' + pcb + '\n', encoding='utf-8')
|
||||
(logdir / 'PCBLogFile.txt').write_text('Successfully read the design.\n' if success else 'Loading\n', encoding='utf-8')
|
||||
database = str(project / 'database') if not foreign else str(project.parent / 'other/database')
|
||||
logs = project / 'database/cdbsvr/log/current'
|
||||
logs.mkdir(parents=True, exist_ok=True)
|
||||
(logs / 'current.txt').write_text(
|
||||
f'S: Project path [{database}] on file system [NTFS]\n'
|
||||
f'S: Project file (.prj) path [{project / "IP101GR.prj"}] on file system [NTFS]\n'
|
||||
f'S: Started up automatically by iCDB Client: ABS:ABS:{pid}\n'
|
||||
'S: iCDB database loaded\n'
|
||||
f'SC[455]: Registered sub-client [Expedition PCB_123] with ID [1] for session ID [455] host [Abs] user [ABS] process ID [{pid}]\n',
|
||||
encoding='utf-8')
|
||||
|
||||
|
||||
def test_old_success_logs_are_not_current_open_evidence(diagnostic, job):
|
||||
write_logs(job)
|
||||
baseline = diagnostic.snapshot_diagnostic_logs(job)
|
||||
assert diagnostic._load_evidence(job, 42, baseline) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('pid,foreign,success', [(99, False, True), (42, True, True), (42, False, False)])
|
||||
def test_foreign_pid_path_or_incomplete_load_cannot_pass(diagnostic, job, pid, foreign, success):
|
||||
baseline = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job, pid=pid, foreign=foreign, success=success)
|
||||
assert diagnostic._load_evidence(job, 42, baseline) is None
|
||||
|
||||
|
||||
def test_current_full_path_and_pcb_pid_logs_prove_open_only(diagnostic, job):
|
||||
baseline = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
evidence = diagnostic._load_evidence(job, 42, baseline)
|
||||
assert evidence['pcb'] == job['pcb']
|
||||
assert evidence['pcb_pid'] == 42
|
||||
|
||||
|
||||
def test_old_prefix_in_appended_log_cannot_supply_target_identity(diagnostic, job):
|
||||
write_logs(job)
|
||||
baseline = diagnostic.snapshot_diagnostic_logs(job)
|
||||
for path in Path(job['project']).parent.rglob('*.txt'):
|
||||
with path.open('a', encoding='utf-8') as output:
|
||||
output.write('unrelated new record\n')
|
||||
assert diagnostic._load_evidence(job, 42, baseline) is None
|
||||
|
||||
|
||||
def frame(job, *, title='IP101GR'):
|
||||
return {'hwnd': 10, 'pid': 42, 'class': 'Afx:123',
|
||||
'text': f'Expedition PCB - Reusable Block - [{title}]', 'enabled': True,
|
||||
'children': [{'hwnd': 11, 'class': 'MDIClient', 'text': '', 'parent': 10},
|
||||
{'hwnd': 12, 'class': 'Afx:document', 'text': title, 'parent': 11}]}
|
||||
|
||||
|
||||
def test_target_title_without_target_mdi_does_not_pass(diagnostic, job):
|
||||
window = frame(job)
|
||||
window['children'][1]['text'] = 'another_project'
|
||||
assert diagnostic._target_frame([window], Path(job['pcb']).stem) is None
|
||||
|
||||
|
||||
class Session:
|
||||
instances = []
|
||||
def __init__(self, job, pid, launcher):
|
||||
self.alive = True
|
||||
self.closed = False
|
||||
self.posted = []
|
||||
self.instances.append(self)
|
||||
def pcb_alive(self):
|
||||
return self.alive
|
||||
def launcher_alive(self):
|
||||
return self.alive
|
||||
def post(self, hwnd, message):
|
||||
self.posted.append((hwnd, message))
|
||||
self.alive = False
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
def test_unknown_prompt_is_preserved_and_never_closed(diagnostic, job, monkeypatch):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
|
||||
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [frame(job),
|
||||
{'hwnd': 20, 'pid': 42, 'class': '#32770', 'text': 'Unknown question', 'children': []}])
|
||||
with pytest.raises(RuntimeError, match='DIAGNOSTIC_CLOSE_UNCONFIRMED'):
|
||||
diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)
|
||||
assert Session.instances[-1].posted == []
|
||||
assert Session.instances[-1].closed
|
||||
|
||||
|
||||
def test_success_posts_one_exact_close_and_reports_only_open_check(diagnostic, job, monkeypatch):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
|
||||
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [frame(job)] if Session.instances[-1].alive else [])
|
||||
outcome = diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)
|
||||
assert outcome['status'] == 'PASS'
|
||||
assert outcome['check'] == 'native_open_only'
|
||||
assert outcome['native_processes_exited'] is True
|
||||
assert outcome['library_ownership'] == 'NOT_ASSESSED'
|
||||
assert Session.instances[-1].posted == [(10, 0x10)]
|
||||
assert Session.instances[-1].closed
|
||||
|
||||
|
||||
def test_transient_startup_window_cannot_abort_before_target_is_loaded(diagnostic, job, monkeypatch):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
|
||||
calls = []
|
||||
def windows(pid):
|
||||
calls.append(True)
|
||||
if len(calls) == 1:
|
||||
return [{'hwnd': 20, 'pid': 42, 'class': 'VendorSplash', 'text': '', 'children': []}]
|
||||
return [frame(job)] if Session.instances[-1].alive else []
|
||||
monkeypatch.setattr(diagnostic, '_windows', windows)
|
||||
job['timeout'] = 1
|
||||
assert diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)['status'] == 'PASS'
|
||||
assert Session.instances[-1].posted == [(10, 0x10)]
|
||||
|
||||
|
||||
def test_native_caption_variant_uses_proven_target_mdi(diagnostic, job, monkeypatch):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
|
||||
target = frame(job)
|
||||
target['text'] = 'Expedition PCB - [IP101GR]'
|
||||
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [target] if Session.instances[-1].alive else [])
|
||||
assert diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)['status'] == 'PASS'
|
||||
|
||||
|
||||
def test_cancel_does_not_wait_for_open_timeout(diagnostic, job, monkeypatch):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
cancel = Path(job['root']).parent / 'cancel'
|
||||
cancel.touch()
|
||||
job['cancel_signal'] = str(cancel)
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
|
||||
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [])
|
||||
with pytest.raises(RuntimeError, match='VERIFY_CANCELLED'):
|
||||
diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)
|
||||
assert Session.instances[-1].posted == []
|
||||
assert Session.instances[-1].closed
|
||||
|
||||
|
||||
def test_cancel_after_close_request_still_waits_for_own_launcher_exit(diagnostic, job, monkeypatch):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
cancel = Path(job['root']).parent / 'cancel'
|
||||
job['cancel_signal'] = str(cancel)
|
||||
class DelayedLauncher(Session):
|
||||
polls = 0
|
||||
def post(self, hwnd, message):
|
||||
super().post(hwnd, message)
|
||||
cancel.touch()
|
||||
def launcher_alive(self):
|
||||
self.polls += 1
|
||||
return self.polls < 3
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', DelayedLauncher)
|
||||
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [frame(job)] if Session.instances[-1].alive else [])
|
||||
assert diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)['status'] == 'PASS'
|
||||
assert Session.instances[-1].polls >= 3
|
||||
|
||||
|
||||
@pytest.mark.parametrize('owner,window_class', [(10, 'VendorModal'), (0, 'VendorModal'),
|
||||
(0, 'Internet Explorer_Hidden')])
|
||||
def test_unknown_custom_owned_window_blocks_close(diagnostic, job, monkeypatch, owner, window_class):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
|
||||
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [frame(job),
|
||||
{'hwnd': 20, 'pid': 42, 'class': window_class, 'text': 'Unclassified prompt',
|
||||
'owner': owner, 'enabled': True, 'children': []}])
|
||||
with pytest.raises(RuntimeError, match='DIAGNOSTIC_CLOSE_UNCONFIRMED'):
|
||||
diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)
|
||||
assert Session.instances[-1].posted == []
|
||||
|
||||
|
||||
def test_empty_desktop_resets_stale_win32_last_error(diagnostic, monkeypatch):
|
||||
import win32api
|
||||
import win32gui
|
||||
import pywintypes
|
||||
seen = []
|
||||
def empty(callback, context):
|
||||
seen.append(win32api.GetLastError())
|
||||
raise pywintypes.error(0, 'EnumWindows', 'empty desktop')
|
||||
monkeypatch.setattr(win32gui, 'EnumWindows', empty)
|
||||
win32api.SetLastError(170)
|
||||
assert diagnostic._windows(42) == []
|
||||
assert seen == [0]
|
||||
|
||||
|
||||
def test_missing_launcher_cannot_claim_verified_native_release(diagnostic, job):
|
||||
with pytest.raises(RuntimeError, match='DIAGNOSTIC_LAUNCHER_REQUIRED'):
|
||||
diagnostic._NativeSession(job, 42, None)
|
||||
|
||||
|
||||
def test_buffered_full_pcb_path_must_be_verified_after_normal_close(diagnostic, job, monkeypatch):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
autosave = Path(job['pcb']).parent / 'LogFiles/PCBAutoSave.txt'
|
||||
autosave.write_text('', encoding='utf-8')
|
||||
class BufferedSession(Session):
|
||||
def post(self, hwnd, message):
|
||||
super().post(hwnd, message)
|
||||
autosave.write_text('Job Name: ' + job['pcb'] + '\n', encoding='utf-8')
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', BufferedSession)
|
||||
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [frame(job)] if Session.instances[-1].alive else [])
|
||||
outcome = diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)
|
||||
assert outcome['status'] == 'PASS'
|
||||
assert Session.instances[-1].posted == [(10, 0x10)]
|
||||
|
||||
|
||||
def test_large_unrelated_history_does_not_block_current_evidence(diagnostic, job):
|
||||
logs = Path(job['project']).parent / 'database/cdbsvr/log'
|
||||
for index in range(270):
|
||||
directory = logs / f'2000-01-01 00.00.00-{index:05}'
|
||||
directory.mkdir(parents=True)
|
||||
(directory / '2000.01.01.txt').write_bytes(b'old unrelated history\n' * 14000)
|
||||
baseline = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
assert diagnostic._load_evidence(job, 42, baseline) is not None
|
||||
|
||||
|
||||
def test_pcb_logs_follow_actual_pcb_directory(diagnostic, job):
|
||||
pcb = Path(job['pcb']).parent.parent / 'AlternativePCB/IP101GR.pcb'
|
||||
pcb.parent.mkdir()
|
||||
pcb.write_bytes(b'pcb')
|
||||
job['pcb'] = str(pcb)
|
||||
baseline = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
assert diagnostic._load_evidence(job, 42, baseline)['pcb'] == str(pcb)
|
||||
|
||||
|
||||
def test_only_exact_owned_save_prompt_gets_no_after_diagnostic_close(diagnostic, job, monkeypatch):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
class SaveSession(Session):
|
||||
closing = False
|
||||
def post(self, hwnd, message):
|
||||
self.posted.append((hwnd, message))
|
||||
if message == 0x10:
|
||||
self.closing = True
|
||||
else:
|
||||
self.alive = False
|
||||
closing_scans = []
|
||||
def windows(pid):
|
||||
state = Session.instances[-1]
|
||||
if not state.closing:
|
||||
return [frame(job)]
|
||||
closing_scans.append(True)
|
||||
if len(closing_scans) == 1:
|
||||
return [{'hwnd': 20, 'pid': 42, 'class': '#32770', 'text': '',
|
||||
'owner': 10, 'children': []}]
|
||||
return [{'hwnd': 20, 'pid': 42, 'class': '#32770', 'text': 'Expedition PCB',
|
||||
'owner': 10, 'children': [
|
||||
{'hwnd': 30, 'class': 'Static', 'text': 'Do you want to save the reusable block cell?', 'id': -1},
|
||||
{'hwnd': 31, 'class': 'Button', 'text': '&No', 'id': 7}]}]
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', SaveSession)
|
||||
monkeypatch.setattr(diagnostic, '_windows', windows)
|
||||
outcome = diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)
|
||||
assert outcome['status'] == 'PASS'
|
||||
assert Session.instances[-1].posted == [(10, 0x10), (31, 0xF5)]
|
||||
|
||||
|
||||
def test_no_pass_when_normal_close_never_flushes_full_pcb_path(diagnostic, job, monkeypatch):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
(Path(job['pcb']).parent / 'LogFiles/PCBAutoSave.txt').write_bytes(b'')
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
|
||||
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [frame(job)] if Session.instances[-1].alive else [])
|
||||
with pytest.raises(RuntimeError, match='fresh full PCB path not confirmed after close'):
|
||||
diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)
|
||||
assert Session.instances[-1].posted == [(10, 0x10)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('filename,accepted', [('IP101GR.pcb', True), ('Foreign.pcb', False)])
|
||||
def test_standard_save_question_requires_exact_target_filename(diagnostic, job, monkeypatch, filename, accepted):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
class SaveSession(Session):
|
||||
closing = False
|
||||
def post(self, hwnd, message):
|
||||
self.posted.append((hwnd, message))
|
||||
if message == 0x10:
|
||||
self.closing = True
|
||||
else:
|
||||
self.alive = False
|
||||
def windows(pid):
|
||||
if not Session.instances[-1].closing:
|
||||
return [frame(job)]
|
||||
return [{'hwnd': 20, 'pid': 42, 'class': '#32770', 'text': 'Expedition PCB', 'owner': 10,
|
||||
'children': [{'hwnd': 30, 'class': 'Static', 'text': f'Save changes to {filename}?', 'id': -1},
|
||||
{'hwnd': 31, 'class': 'Button', 'text': '否(&N)', 'id': 7},
|
||||
{'hwnd': 32, 'class': 'Button', 'text': '是(&Y)', 'id': 6},
|
||||
{'hwnd': 33, 'class': 'Button', 'text': '取消', 'id': 2}]}]
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', SaveSession)
|
||||
monkeypatch.setattr(diagnostic, '_windows', windows)
|
||||
if accepted:
|
||||
assert diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)['status'] == 'PASS'
|
||||
assert Session.instances[-1].posted == [(10, 0x10), (31, 0xF5)]
|
||||
else:
|
||||
with pytest.raises(RuntimeError, match='DIAGNOSTIC_CLOSE_UNCONFIRMED'):
|
||||
diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)
|
||||
assert Session.instances[-1].posted == [(10, 0x10)]
|
||||
|
||||
|
||||
def test_recycled_window_from_another_pid_never_receives_close(diagnostic, monkeypatch):
|
||||
import win32process
|
||||
session = diagnostic._NativeSession.__new__(diagnostic._NativeSession)
|
||||
session.pid = 42
|
||||
session.pcb_alive = lambda: True
|
||||
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda hwnd: (1, 99))
|
||||
with pytest.raises(RuntimeError, match='DIAGNOSTIC_STALE_WINDOW'):
|
||||
session.post(10, 0x10)
|
||||
@@ -412,6 +412,79 @@ def test_agent_start_failure_releases_listener(tmp_path):
|
||||
DialogAgentClient.start(FailedWorker(), tmp_path)
|
||||
|
||||
|
||||
def _slow_start_client(tmp_path, monkeypatch, *, delay, stop=None):
|
||||
import socket
|
||||
from types import SimpleNamespace
|
||||
from cbb_refresh_verify import dialog_agent as module
|
||||
client = DialogAgentClient.prepare(tmp_path, desktop_name='test')
|
||||
client.listener.close()
|
||||
elapsed = [0.0]
|
||||
class Listener:
|
||||
closed = False
|
||||
def settimeout(self, timeout): self.timeout = timeout
|
||||
def accept(self):
|
||||
if elapsed[0] < delay:
|
||||
elapsed[0] += self.timeout
|
||||
if stop is not None and elapsed[0] >= .4: stop.set()
|
||||
raise socket.timeout()
|
||||
return SimpleNamespace(setsockopt=lambda *a: None), None
|
||||
def close(self): self.closed = True
|
||||
class Channel:
|
||||
def __init__(self, connection): pass
|
||||
def receive(self, timeout): return {'token': client.paths.token}
|
||||
def send(self, *a): pass
|
||||
def close(self): pass
|
||||
client.listener = Listener()
|
||||
monkeypatch.setattr(module, 'JsonChannel', Channel)
|
||||
monkeypatch.setattr(module.time, 'monotonic', lambda: elapsed[0])
|
||||
monkeypatch.setattr(DialogAgentClient, 'prepare', classmethod(lambda cls, *a, **k: client))
|
||||
worker = SimpleNamespace(name='test', start_companion=lambda command: None)
|
||||
return client, worker, elapsed
|
||||
|
||||
|
||||
def test_frozen_agent_can_initialize_after_the_old_ten_second_deadline(tmp_path, monkeypatch):
|
||||
client, worker, elapsed = _slow_start_client(tmp_path, monkeypatch, delay=12)
|
||||
assert DialogAgentClient.start(worker, tmp_path) is client
|
||||
assert elapsed[0] >= 12 and client.channel is not None
|
||||
assert client.timeout_seconds == 2 # Normal IPC does not inherit the startup budget.
|
||||
|
||||
|
||||
def test_agent_startup_wait_responds_to_cancel_without_starting_pcb(tmp_path, monkeypatch):
|
||||
import pytest
|
||||
from threading import Event
|
||||
stop = Event()
|
||||
client, worker, elapsed = _slow_start_client(tmp_path, monkeypatch, delay=100, stop=stop)
|
||||
with pytest.raises(InterruptedError, match='VERIFY_CANCELLED'):
|
||||
DialogAgentClient.start(worker, tmp_path, stop=stop)
|
||||
assert elapsed[0] < 1 and client.listener.closed
|
||||
|
||||
|
||||
def test_agent_startup_still_has_an_absolute_deadline(tmp_path, monkeypatch):
|
||||
import pytest
|
||||
client, worker, elapsed = _slow_start_client(tmp_path, monkeypatch, delay=100)
|
||||
with pytest.raises(TimeoutError):
|
||||
DialogAgentClient.start(worker, tmp_path)
|
||||
assert 29 <= elapsed[0] <= 31 and client.listener.closed
|
||||
|
||||
|
||||
def test_cancellation_during_authenticated_handshake_never_releases_startup(tmp_path, monkeypatch):
|
||||
import pytest
|
||||
from threading import Event
|
||||
from cbb_refresh_verify import dialog_agent as module
|
||||
stop = Event()
|
||||
client, worker, _ = _slow_start_client(tmp_path, monkeypatch, delay=0)
|
||||
class Channel:
|
||||
def __init__(self, connection): pass
|
||||
def receive(self, timeout):
|
||||
stop.set()
|
||||
return {'token': client.paths.token}
|
||||
def close(self): pass
|
||||
monkeypatch.setattr(module, 'JsonChannel', Channel)
|
||||
with pytest.raises(InterruptedError, match='VERIFY_CANCELLED'):
|
||||
DialogAgentClient.start(worker, tmp_path, stop=stop)
|
||||
assert client.channel is None and client.listener.closed
|
||||
|
||||
|
||||
def test_memory_channel_timeout_is_bounded_and_partial_packets_survive():
|
||||
import socket
|
||||
import pytest
|
||||
@@ -436,7 +509,7 @@ def test_loopback_connection_rejects_wrong_agent_token(tmp_path):
|
||||
import socket
|
||||
import pytest
|
||||
from cbb_refresh_verify.dialog_agent import JsonChannel, DialogAgentProtocolError
|
||||
client = DialogAgentClient.prepare(tmp_path, desktop_name='test', timeout_seconds=.3)
|
||||
client = DialogAgentClient.prepare(tmp_path, desktop_name='test', timeout_seconds=2)
|
||||
wrong = JsonChannel(socket.create_connection(('127.0.0.1', client.paths.port), timeout=1))
|
||||
try:
|
||||
wrong.send({'token': 'not-the-agent'})
|
||||
|
||||
@@ -86,6 +86,18 @@ def test_probe_keeps_visible_non_dialog_classes():
|
||||
assert snapshots[0].process_name == "proc-1010.exe"
|
||||
|
||||
|
||||
def test_pid_scope_excludes_foreign_dialog_before_child_or_uia_read():
|
||||
gui = FakeGui({10: {'class_name': '#32770', 'text': 'owned'},
|
||||
20: {'class_name': '#32770', 'text': 'other project'}})
|
||||
class Uia:
|
||||
def controls(self, hwnd):
|
||||
assert hwnd == 10, 'Foreign project was probed'
|
||||
return ()
|
||||
probe = make_probe(gui, (20, 10), Uia())
|
||||
assert [w.hwnd for w in probe.capture(PHASE, pids={1010})] == [10]
|
||||
assert probe.capture(PHASE, pids=set()) == ()
|
||||
|
||||
|
||||
def test_disappearing_window_is_skipped_without_hiding_other_windows():
|
||||
gui = FakeGui({
|
||||
10: {"class_name": "GXWND", "text": "gone"},
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.parametrize('cancel,gate_present', [(False, False), (True, False), (True, True)])
|
||||
def test_worker_waits_for_cold_agent_but_cancellation_never_opens_pcb(tmp_path, monkeypatch, cancel, gate_present):
|
||||
from cbb_refresh_verify import mentor_adapter as adapter
|
||||
import pythoncom
|
||||
gate, stop = tmp_path/'start.signal', tmp_path/'cancel.signal'
|
||||
if gate_present: gate.touch()
|
||||
if cancel: stop.touch()
|
||||
clock, opened = [0.0], []
|
||||
def advance(seconds):
|
||||
clock[0] += seconds
|
||||
if not cancel and clock[0] >= 20: gate.touch()
|
||||
monkeypatch.setattr(adapter, 'time', SimpleNamespace(monotonic=lambda: clock[0], sleep=advance,
|
||||
strftime=lambda *_: 'test'))
|
||||
monkeypatch.setattr(pythoncom, 'CoInitialize', lambda: None)
|
||||
monkeypatch.setattr(pythoncom, 'CoUninitialize', lambda: None)
|
||||
monkeypatch.setattr(adapter, 'execute_job', lambda *args: opened.append(True) or {'status': 'PASS'})
|
||||
job = tmp_path/'request.json'
|
||||
job.write_text(json.dumps({'root': str(tmp_path), 'block_name': 'fixture',
|
||||
'start_gate': str(gate), 'cancel_signal': str(stop)}), encoding='utf-8')
|
||||
result = adapter.worker_main(job)
|
||||
assert result == (1 if cancel else 0)
|
||||
assert opened == ([] if cancel else [True])
|
||||
if cancel:
|
||||
outcome = json.loads((tmp_path/'outcome.json').read_text('utf-8'))
|
||||
assert 'VERIFY_CANCELLED' in outcome['stderr']
|
||||
@@ -72,7 +72,8 @@ def test_serial_guard_covers_preflight_and_content_check(tmp_path, monkeypatch):
|
||||
try:
|
||||
second = runner.run_verify(VerifyRequest(tmp_path/'lib.lmc', 'second', tmp_path/'evidence'))
|
||||
assert second.status == 'BLOCKED'
|
||||
assert not second.safe_to_continue
|
||||
assert second.safe_to_continue
|
||||
assert second.error_category == 'NATIVE_CHANNEL_BUSY'
|
||||
assert calls == ['first']
|
||||
finally:
|
||||
release.set()
|
||||
|
||||
@@ -50,7 +50,7 @@ def test_failed_startup_normally_closes_owned_empty_pcb(tmp_path, monkeypatch, t
|
||||
|
||||
|
||||
@pytest.mark.parametrize('obstacle', ['baseline', 'wrong_path', 'path_prefix', 'desktop', 'address',
|
||||
'dialog', 'document_title', 'mdi_document', 'disabled', 'no_diagnosis'])
|
||||
'dialog', 'document_title', 'mdi_document', 'disabled'])
|
||||
def test_failed_startup_preserves_unconfirmed_or_busy_session(tmp_path, monkeypatch, obstacle):
|
||||
import win32gui
|
||||
from cbb_refresh_verify import native_repair_ui
|
||||
@@ -79,6 +79,97 @@ def test_failed_startup_preserves_unconfirmed_or_busy_session(tmp_path, monkeypa
|
||||
assert not messages
|
||||
|
||||
|
||||
def test_owned_empty_shell_closes_without_an_icdb_diagnosis(tmp_path, monkeypatch):
|
||||
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||
(tmp_path/'diagnostics/icdb-recovery.json').unlink()
|
||||
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
|
||||
assert result['status'] == 'CLOSED' and not records and len(messages) == 1
|
||||
|
||||
|
||||
def read_write_fixture(tmp_path, monkeypatch):
|
||||
import win32gui, win32con
|
||||
from cbb_refresh_verify.post_repair_consent import PROMPT_TEXT
|
||||
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||
(tmp_path/'diagnostics/icdb-recovery.json').unlink()
|
||||
visible = {100, 200}
|
||||
classes = {100: 'Afx:main', 200: '#32770', 201: 'Button', 202: 'Button', 203: 'Static'}
|
||||
names = {100: 'Expedition PCB', 200: 'Expedition PCB', 201: 'Yes', 202: 'No', 203: PROMPT_TEXT}
|
||||
identifiers = {201: 6, 202: 7, 203: 65535}
|
||||
monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg: [fn(h, arg) for h in tuple(visible)])
|
||||
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda h, fn, arg:
|
||||
[fn(c, arg) for c in (201, 202, 203)] if h == 200 else None)
|
||||
monkeypatch.setattr(win32gui, 'GetClassName', classes.__getitem__)
|
||||
monkeypatch.setattr(win32gui, 'GetWindowText', names.__getitem__)
|
||||
monkeypatch.setattr(win32gui, 'GetDlgCtrlID', identifiers.__getitem__)
|
||||
monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda h: h != 100 or 200 not in visible)
|
||||
monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda h: h in visible or h in identifiers)
|
||||
def post(hwnd, message, *_):
|
||||
messages.append((hwnd, message))
|
||||
if hwnd == 202 and message == win32con.BM_CLICK:
|
||||
visible.remove(200)
|
||||
elif hwnd == 100 and message == win32con.WM_CLOSE:
|
||||
records.clear()
|
||||
monkeypatch.setattr(win32gui, 'PostMessage', post)
|
||||
return job, records, messages, names, visible
|
||||
|
||||
|
||||
def test_captured_read_write_question_is_declined_and_own_empty_shell_exits(tmp_path, monkeypatch):
|
||||
import win32con
|
||||
job, records, messages, _, _ = read_write_fixture(tmp_path, monkeypatch)
|
||||
# A pre-existing address must not prevent cancelling our own attempted open.
|
||||
address = tmp_path/'database/cdbsvr/sAddress.adr'
|
||||
address.parent.mkdir(parents=True)
|
||||
address.write_text('existing foreign or stale address')
|
||||
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
|
||||
assert result['status'] == 'CLOSED' and result['release']['safe_to_continue']
|
||||
assert messages == [(202, win32con.BM_CLICK), (100, win32con.WM_CLOSE)]
|
||||
assert not records and address.read_text() == 'existing foreign or stale address'
|
||||
assert result['cancelled_prompt'] == 'read_write_access'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('obstacle', ['text', 'foreign_pid', 'baseline', 'wrong_path', 'desktop', 'stuck'])
|
||||
def test_read_write_cancel_never_accepts_unconfirmed_or_unclosed_prompt(tmp_path, monkeypatch, obstacle):
|
||||
import win32gui, win32process, win32con
|
||||
from cbb_refresh_verify import native_repair_ui
|
||||
job, records, messages, names, _ = read_write_fixture(tmp_path, monkeypatch)
|
||||
if obstacle == 'text': names[203] += ' Different recovery operation.'
|
||||
if obstacle == 'foreign_pid':
|
||||
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda h: (1, 99 if h == 200 else 12))
|
||||
if obstacle == 'wrong_path': records[0] = (12, records[0][1], 'other.pcb -ReusableCircuit', 11)
|
||||
if obstacle == 'desktop': monkeypatch.setattr(native_repair_ui, '_current_desktop_name', lambda: 'Default')
|
||||
if obstacle == 'stuck':
|
||||
monkeypatch.setattr(win32gui, 'PostMessage', lambda h, m, *_: messages.append((h, m)))
|
||||
result = failed_session.close_failed_startup(job, 12,
|
||||
baseline_pids=(12,) if obstacle == 'baseline' else (), timeout_seconds=0)
|
||||
assert result['status'] == 'RETAINED' and records
|
||||
assert messages == ([(202, win32con.BM_CLICK)] if obstacle == 'stuck' else [])
|
||||
|
||||
|
||||
def test_version_choice_is_cancelled_without_selecting_or_confirming_a_version(tmp_path, monkeypatch):
|
||||
import win32gui, win32con
|
||||
from test_pcb_version_choice import captured
|
||||
job, records, messages, _, visible = read_write_fixture(tmp_path, monkeypatch)
|
||||
snapshot = captured()
|
||||
children = [c for c in snapshot.controls if c.handle and c.handle != snapshot.hwnd]
|
||||
mapping = {300+i: c for i, c in enumerate(children)}
|
||||
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda h, fn, arg:
|
||||
[fn(c, arg) for c in mapping] if h == 200 else None)
|
||||
monkeypatch.setattr(win32gui, 'GetClassName', lambda h: mapping[h].class_name if h in mapping else
|
||||
'#32770' if h == 200 else 'Afx:main')
|
||||
monkeypatch.setattr(win32gui, 'GetWindowText', lambda h: mapping[h].name if h in mapping else
|
||||
'Database Restoration' if h == 200 else 'Expedition PCB')
|
||||
monkeypatch.setattr(win32gui, 'GetDlgCtrlID', lambda h: mapping[h].control_id)
|
||||
cancel = next(h for h, c in mapping.items() if c.control_id == 2)
|
||||
def post(h, m, *_):
|
||||
messages.append((h, m))
|
||||
if h == cancel: visible.remove(200)
|
||||
elif h == 100: records.clear()
|
||||
monkeypatch.setattr(win32gui, 'PostMessage', post)
|
||||
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
|
||||
assert result['status'] == 'CLOSED' and result['cancelled_prompt'] == 'pcb_version_choice'
|
||||
assert messages == [(cancel, win32con.BM_CLICK), (100, win32con.WM_CLOSE)]
|
||||
|
||||
|
||||
def test_requested_close_without_exit_is_not_reported_closed(tmp_path, monkeypatch):
|
||||
import win32gui
|
||||
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||
@@ -90,6 +181,26 @@ def test_requested_close_without_exit_is_not_reported_closed(tmp_path, monkeypat
|
||||
assert records
|
||||
|
||||
|
||||
@pytest.mark.parametrize('exits', [True, False])
|
||||
def test_after_owned_close_transient_empty_command_waits_for_exit(tmp_path, monkeypatch, exits):
|
||||
from types import SimpleNamespace
|
||||
import win32gui
|
||||
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||
ticks = [0.0]
|
||||
def post(hwnd, message, *_):
|
||||
messages.append((hwnd, message))
|
||||
records[0] = (12, '', '', 11) # WMI during process teardown.
|
||||
def advance(seconds):
|
||||
ticks[0] += seconds
|
||||
if exits: records.clear()
|
||||
monkeypatch.setattr(win32gui, 'PostMessage', post)
|
||||
monkeypatch.setattr(failed_session, 'time', SimpleNamespace(monotonic=lambda: ticks[0], sleep=advance))
|
||||
result = failed_session.close_failed_startup(job, 12, timeout_seconds=1)
|
||||
assert ticks[0] > 0 and len(messages) == 1
|
||||
assert result['status'] == ('CLOSED' if exits else 'RETAINED')
|
||||
assert 'STARTUP_PROCESS_UNCONFIRMED' not in result.get('detail', '')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('obstacle', ['address', 'dialog', 'process'])
|
||||
def test_startup_close_waits_for_native_state_transitions(tmp_path, monkeypatch, obstacle):
|
||||
from types import SimpleNamespace
|
||||
@@ -149,13 +260,13 @@ def test_failed_startup_accepts_current_owned_database_failure_dialog(tmp_path,
|
||||
|
||||
|
||||
@pytest.mark.parametrize('pid,phase', [(99, 'PCB_STARTING'), (12, 'SAVING')])
|
||||
def test_failed_startup_rejects_unrelated_failure_dialog(tmp_path, monkeypatch, pid, phase):
|
||||
def test_unrelated_failure_record_is_not_needed_to_close_own_empty_shell(tmp_path, monkeypatch, pid, phase):
|
||||
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||
(tmp_path/'diagnostics/icdb-recovery.json').unlink()
|
||||
(tmp_path/'dialogs.jsonl').write_text(json.dumps({
|
||||
'pid': pid, 'phase': phase, 'error_code': 'MENTOR_DATABASE_LOAD_FAILED'})+'\n')
|
||||
assert failed_session.close_failed_startup(job, 12, timeout_seconds=0)['status'] == 'RETAINED'
|
||||
assert not messages
|
||||
assert failed_session.close_failed_startup(job, 12, timeout_seconds=0)['status'] == 'CLOSED'
|
||||
assert len(messages) == 1 and not records
|
||||
|
||||
|
||||
@pytest.mark.parametrize('exits', [True, False])
|
||||
|
||||
@@ -200,14 +200,14 @@ def test_worker_attempts_normal_close_after_idle_integration_failure(tmp_path, m
|
||||
assert not any(event['stage'] == 'save_start' for event in events)
|
||||
|
||||
|
||||
def test_stop_requests_cooperative_cancel_without_terminating_busy_client(tmp_path):
|
||||
def test_stop_cancels_then_stops_automation_client_after_deadline(tmp_path):
|
||||
calls = []
|
||||
class BusyWorker:
|
||||
def request_stop(self): calls.append('cancel')
|
||||
def wait(self, timeout): raise TimeoutError('native Save still running')
|
||||
def kill(self): calls.append('kill')
|
||||
runner._stop_worker(BusyWorker(), timeout=0)
|
||||
assert calls == ['cancel']
|
||||
assert calls == ['cancel', 'kill']
|
||||
|
||||
|
||||
def test_status_server_close_allows_eof_cleanup_before_termination(tmp_path):
|
||||
@@ -225,21 +225,22 @@ def test_status_server_close_allows_eof_cleanup_before_termination(tmp_path):
|
||||
assert marker.is_file()
|
||||
|
||||
|
||||
def test_shared_symbol_database_owner_blocks_content_check_and_pcb(tmp_path, monkeypatch):
|
||||
def test_shared_address_does_not_block_actual_content_check(tmp_path, monkeypatch):
|
||||
from test_verify_runner import fixture, request
|
||||
fixture(tmp_path)
|
||||
address = tmp_path/'SymbolLibs/__ReusableBlocksSymb/cdbsvr/sAddress.adr'
|
||||
address.parent.mkdir(parents=True)
|
||||
address.write_bytes(b'unknown native owner')
|
||||
req = request(tmp_path, libspec='EE', dms_login_config='login')
|
||||
outcome = runner.run_verify(req, process_runner=lambda *args: pytest.fail('must not launch importer'))
|
||||
assert outcome.status == 'BLOCKED'
|
||||
assert outcome.safe_to_continue is False
|
||||
assert '__ReusableBlocksSymb' in outcome.stderr
|
||||
calls = []
|
||||
outcome = runner.run_verify(req, process_runner=lambda *args:
|
||||
(calls.append(args) or (1, 'ERROR: shared database unavailable', '', False)))
|
||||
assert calls and outcome.status == 'FAIL' and outcome.safe_to_continue
|
||||
assert 'shared database unavailable' in outcome.stderr
|
||||
assert address.read_bytes() == b'unknown native owner'
|
||||
|
||||
|
||||
def test_shared_symbol_database_must_be_released_before_pass(tmp_path, monkeypatch):
|
||||
def test_shared_address_is_diagnostic_after_successful_native_execution(tmp_path, monkeypatch):
|
||||
from test_verify_worker_stability import exercise_worker
|
||||
from cbb_refresh_verify import mentor_adapter as adapter
|
||||
job, events, execute = exercise_worker(tmp_path, monkeypatch)
|
||||
@@ -250,9 +251,8 @@ def test_shared_symbol_database_must_be_released_before_pass(tmp_path, monkeypat
|
||||
address.write_bytes(b'shared owner retained')
|
||||
return original(*args, **kwargs)
|
||||
monkeypatch.setattr(adapter.subprocess, 'Popen', helper)
|
||||
with pytest.raises(RuntimeError, match='ICDB_RELEASE_UNCONFIRMED'):
|
||||
execute()
|
||||
assert not any(event['stage'] == 'complete' for event in events)
|
||||
assert execute()['status'] == 'PASS'
|
||||
assert any(event['stage'] == 'icdb_address_remaining' for event in events)
|
||||
|
||||
|
||||
def test_cooperative_supervisor_loss_keeps_pending_save_helper_alive(tmp_path):
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
"""Batch ICDB checks open diagnostically without dispatching Repair."""
|
||||
from dataclasses import replace
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from test_maintenance_entry import case, no_native_launch
|
||||
|
||||
|
||||
@pytest.mark.parametrize('scenario,status,category,safe', [
|
||||
('healthy', 'CHECKED', '', True),
|
||||
('fault', 'FAIL', 'ICDB_REPAIR_REQUIRED', True),
|
||||
('generic', 'FAIL', 'MENTOR_DATABASE_LOAD_FAILED', True),
|
||||
('unreleased', 'FAIL', 'MENTOR_DATABASE_LOAD_FAILED', False),
|
||||
('cancelled', 'CANCELLED', '', True),
|
||||
])
|
||||
def test_batch_check_opens_pcb_without_repair(case, monkeypatch, scenario, status, category, safe):
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair, maintenance_entry as entry
|
||||
from test_icdb_open_check import NATIVE_ERROR
|
||||
request, _, address = case
|
||||
calls = []
|
||||
def open_pcb(probe, **kwargs):
|
||||
assert probe.diagnostic_only and not probe.maintenance and not probe.auto_repair
|
||||
calls.append('open')
|
||||
return runner.VerifyResult('PASS' if scenario=='healthy' else 'CANCELLED' if scenario=='cancelled' else 'FAIL',
|
||||
stderr=NATIVE_ERROR if scenario=='fault' else '' if scenario in ('healthy','cancelled') else 'Failed to open document.',
|
||||
error_category='' if scenario in ('healthy','cancelled') else 'MENTOR_DATABASE_LOAD_FAILED',
|
||||
safe_to_continue=scenario!='unreleased')
|
||||
monkeypatch.setattr(runner,'_run_verify_serialized',open_pcb)
|
||||
monkeypatch.setattr(native_repair,'run_native_repair',lambda *a,**k:pytest.fail('scan requested Project Backup'))
|
||||
monkeypatch.setattr(entry,'assert_native_idle',lambda:pytest.fail('scan used host-wide owner gate'))
|
||||
result=runner.run_verify(replace(request,auto_repair=True))
|
||||
assert calls==['open']
|
||||
assert (result.status,result.error_category,result.safe_to_continue)==(status,category,safe)
|
||||
assert result.library_flag=='UNKNOWN' and result.recovery_attempts==()
|
||||
assert address.read_bytes()==b'old server address - preserved'
|
||||
record=json.loads(result.evidence_path.read_text('utf-8'))
|
||||
assert record['operation']=='icdb_batch_check' and record['automatic_repair'] is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize('before_launch',[True,False])
|
||||
def test_cancellation_never_dispatches_repair_or_reports_a_clean_check(case,monkeypatch,before_launch):
|
||||
from threading import Event
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
request,_,_=case
|
||||
stop=Event();calls=[]
|
||||
if before_launch:stop.set()
|
||||
def open_pcb(probe,**kwargs):
|
||||
calls.append('open');stop.set()
|
||||
return runner.VerifyResult('PASS')
|
||||
monkeypatch.setattr(runner,'_run_verify_serialized',open_pcb)
|
||||
result=runner.run_verify(request,stop=stop)
|
||||
assert result.status=='CANCELLED' and result.safe_to_continue
|
||||
assert calls==([] if before_launch else ['open'])
|
||||
|
||||
|
||||
def test_released_icdb_fault_continues_the_check_batch(case,monkeypatch):
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
from test_icdb_open_check import NATIVE_ERROR
|
||||
request,_,_=case
|
||||
calls=[]
|
||||
def open_pcb(probe,**kwargs):
|
||||
calls.append('open')
|
||||
return runner.VerifyResult('FAIL',stderr=NATIVE_ERROR) if len(calls)==1 else runner.VerifyResult('PASS')
|
||||
monkeypatch.setattr(runner,'_run_verify_serialized',open_pcb)
|
||||
results=runner.run_batch([request,request])
|
||||
assert calls==['open','open']
|
||||
assert [result.status for result in results]==['FAIL','CHECKED']
|
||||
|
||||
|
||||
def test_inspection_ignores_other_pcb_and_skips_exclusive_repair_probe(tmp_path, monkeypatch):
|
||||
import win32con
|
||||
from test_native_repair import repair_worker_fixture
|
||||
from test_native_occupancy import output
|
||||
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
|
||||
data = json.loads(job.read_text('utf-8')); data['inspection_only'] = True
|
||||
job.write_text(json.dumps(data), encoding='utf-8')
|
||||
monkeypatch.setattr('cbb_refresh_verify.mentor_adapter.pcb_processes', lambda: [(999, 'other.pcb', '')])
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_repair.check_repair_access',
|
||||
lambda *a: pytest.fail('inspection used exclusive Repair admission'))
|
||||
monkeypatch.setattr(ui, '_repair_command', lambda *a: pytest.fail('inspection resolved Repair command'))
|
||||
monkeypatch.setattr(ui, '_native_output', lambda *_: output(data['project'], data['database'], busy=True))
|
||||
assert ui.repair_worker_main(job) == 0
|
||||
assert actions == [(100, win32con.WM_CLOSE)]
|
||||
|
||||
|
||||
def test_ui_check_summary_reports_findings_and_never_claims_repair(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
requests, prompts = [], []
|
||||
window = load_window(qtbot, tmp_path, monkeypatch,
|
||||
verifier=lambda req: (requests.append(req) or VerifyResult('FAIL',
|
||||
error_category='ICDB_REPAIR_REQUIRED', stderr='发现 ICDB 问题,未执行修复。')),
|
||||
status_refresher=lambda names, _: {name: 'PENDING' for name in names})
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: (prompts.append(a[2]) or QMessageBox.Yes))
|
||||
window.search_edit.setText('Beta')
|
||||
window.icdb_repair_button.click(); qtbot.waitUntil(lambda: not window._icdb_active())
|
||||
assert requests[0].maintenance and not requests[0].auto_repair
|
||||
assert '批量检查' in window.icdb_repair_button.text()
|
||||
assert not any('手动备份' in text for text in prompts)
|
||||
assert window.summary.windowTitle() == 'ICDB 批量检查结果'
|
||||
assert '发现问题 1' in window.summary.text()
|
||||
assert '修复并校验通过' not in window.summary.detailedText()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('category,label', [('ICDB_DATABASE_IN_USE', '占用 1'),
|
||||
('ICDB_INSPECTION_UNCONFIRMED', '无法确认 1')])
|
||||
def test_busy_or_unknown_inspection_is_not_labelled_as_database_damage(qtbot, tmp_path, monkeypatch, category, label):
|
||||
from test_ui_filters import load_window
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
window = load_window(qtbot, tmp_path, monkeypatch,
|
||||
verifier=lambda _: VerifyResult('FAIL', error_category=category, stderr='暂未完成检查。'),
|
||||
status_refresher=lambda names, _: {name: 'PENDING' for name in names})
|
||||
window.search_edit.setText('Beta')
|
||||
window.icdb_repair_button.click(); qtbot.waitUntil(lambda: not window._icdb_active())
|
||||
assert label in window.summary.text()
|
||||
assert 'ICDB 问题' not in window.cbb_table.item(window._row_by_name['Beta'], 3).text()
|
||||
|
||||
|
||||
def test_missing_pcb_is_skipped_from_icdb_batch_check_and_restore(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
from cbb_refresh_verify.models import CbbRecord
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
calls = []
|
||||
window = load_window(qtbot, tmp_path, monkeypatch,
|
||||
records=(CbbRecord('Missing', 'Power', status='PENDING'),),
|
||||
verifier=lambda req: (calls.append(req.block_name) or VerifyResult('CHECKED')),
|
||||
status_refresher=lambda names, _: {name: 'PENDING' for name in names})
|
||||
assert not window.icdb_repair_button.isEnabled()
|
||||
assert not window.batch_button.isEnabled() and not window.backup_restore_button.isEnabled()
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_missing_project_rows_are_excluded_from_icdb_batch_check(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
from cbb_refresh_verify.models import CbbRecord
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
window = load_window(qtbot, tmp_path, monkeypatch,
|
||||
records=(CbbRecord('Missing', 'Power', status='PENDING'),
|
||||
CbbRecord('Good', 'Power', status='PENDING')),
|
||||
verifier=lambda req: VerifyResult('CHECKED'),
|
||||
status_refresher=lambda names, _: {name: 'PENDING' for name in names})
|
||||
window.skipped_names.add('Missing')
|
||||
window._update()
|
||||
assert window._maintenance_names() == ['Good']
|
||||
|
||||
|
||||
def test_check_reports_describe_inspection_without_pcb_verification(case, tmp_path):
|
||||
from cbb_refresh_verify.verify_runner import write_batch_report, failure_report_path, VerifyResult
|
||||
request, _, _ = case
|
||||
report = write_batch_report([request], [VerifyResult('FAIL',
|
||||
error_category='ICDB_REPAIR_REQUIRED', stderr='发现 ICDB 问题,未执行修复。')], tmp_path/'reports')
|
||||
full = report.read_text('utf-8-sig')
|
||||
failed = failure_report_path(report).read_text('utf-8-sig')
|
||||
assert 'ICDB 批量检查' in full and 'Project Integration' not in full
|
||||
assert 'PCB 打开检查' in full and 'Project Backup 加载检查' not in full
|
||||
assert 'ICDB 检查异常' in failed and '发现问题: 1' in failed
|
||||
assert 'ICDB已修复待校验' not in failed
|
||||
@@ -0,0 +1,133 @@
|
||||
"""PCB open errors identify ICDB findings by native content, never by code alone."""
|
||||
from dataclasses import replace
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from test_maintenance_entry import case, no_native_launch
|
||||
|
||||
|
||||
NATIVE_ERROR = (
|
||||
'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 [C:\\isolated\\Work\\database\\icdb.dat] in old, unsupported format)')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('message,expected', [
|
||||
(NATIVE_ERROR, True),
|
||||
('Unable to open iCDB connection.', True),
|
||||
('iCDB database check FAILED', True),
|
||||
('iCDB database check PASSED', False),
|
||||
('0x8004021E: Failed to open document.', False),
|
||||
('ICDB_REPAIR_REQUIRED: Failed to open document.', False),
|
||||
('Cannot open [C:\\icdb\\icdb.dat].', False),
|
||||
('PCB file was not found. Evidence: C:\\icdb\\result.json', False),
|
||||
])
|
||||
def test_error_content_requires_an_icdb_failure_message(message, expected):
|
||||
from cbb_refresh_verify.icdb_recovery import icdb_error_content
|
||||
assert bool(icdb_error_content(message)) is expected
|
||||
|
||||
|
||||
def test_unknown_icdb_description_in_an_actual_open_error_is_retained():
|
||||
from cbb_refresh_verify.icdb_recovery import icdb_error_content
|
||||
assert icdb_error_content('iCDB connection: E_NEW_NATIVE_CODE', error_message=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('mode', ['append', 'rewrite', 'retained', 'unchanged'])
|
||||
def test_native_error_content_is_from_this_open_attempt(tmp_path, mode):
|
||||
from cbb_refresh_verify.icdb_recovery import snapshot_log, read_icdb_error
|
||||
path = tmp_path/'PCBLogFile.txt'
|
||||
previous = 'old header\n'+NATIVE_ERROR+'\n' if mode in ('retained','unchanged') else 'old header\n'
|
||||
path.write_text(previous, 'utf-8')
|
||||
baseline = snapshot_log(path)
|
||||
if mode == 'append': path.write_text(previous+NATIVE_ERROR, 'utf-8')
|
||||
elif mode == 'rewrite': path.write_text('new header\n'+NATIVE_ERROR, 'utf-8')
|
||||
elif mode == 'retained': path.write_text('new header\n'+NATIVE_ERROR+'\nNormal startup', 'utf-8')
|
||||
assert bool(read_icdb_error(path, baseline)) is (mode in ('append','rewrite'))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure,category', [(NATIVE_ERROR,'ICDB_REPAIR_REQUIRED'),
|
||||
('0x8004021E: Failed to open document.','MENTOR_DATABASE_LOAD_FAILED')])
|
||||
def test_batch_scan_opens_without_repair_and_classifies_native_content(case, monkeypatch, failure, category):
|
||||
from cbb_refresh_verify import maintenance_entry as entry, verify_runner as runner, native_repair
|
||||
request, _, address = case
|
||||
probes=[]
|
||||
monkeypatch.setattr(native_repair,'run_native_repair',lambda *a,**k:pytest.fail('scan dispatched Project Backup'))
|
||||
def diagnose(probe, **kw):
|
||||
probes.append(probe)
|
||||
return runner.VerifyResult('FAIL',stderr=failure,error_category='MENTOR_DATABASE_LOAD_FAILED')
|
||||
monkeypatch.setattr(runner,'run_verify',diagnose)
|
||||
result=entry.run_icdb_check(replace(request,auto_repair=True))
|
||||
assert len(probes)==1 and probes[0].diagnostic_only and not probes[0].maintenance
|
||||
assert not probes[0].auto_repair and not probes[0].native_lm_verify
|
||||
assert result.status=='FAIL' and result.error_category==category and result.safe_to_continue
|
||||
assert result.library_flag=='UNKNOWN' and result.recovery_attempts==()
|
||||
assert address.read_bytes()==b'old server address - preserved'
|
||||
|
||||
|
||||
def test_scan_uses_the_current_open_evidence_even_when_popup_is_generic(case, monkeypatch):
|
||||
from cbb_refresh_verify import maintenance_entry as entry, verify_runner as runner
|
||||
request, _, _=case
|
||||
def diagnose(probe, **kw):
|
||||
root=probe.evidence_dir/'verify-current'; (root/'diagnostics').mkdir(parents=True)
|
||||
(root/'diagnostics/icdb-error-content.json').write_text(json.dumps(
|
||||
{'native_message':NATIVE_ERROR,'source':'PCBLogFile.txt'}),'utf-8')
|
||||
result=root/'result.json'; result.write_text('{}','utf-8')
|
||||
return runner.VerifyResult('FAIL',stderr='Problem encountered while opening one of the database files.',
|
||||
evidence_path=result,error_category='MENTOR_DATABASE_LOAD_FAILED')
|
||||
monkeypatch.setattr(runner,'run_verify',diagnose)
|
||||
result=entry.run_icdb_check(request)
|
||||
assert result.error_category=='ICDB_REPAIR_REQUIRED' and NATIVE_ERROR in result.stderr
|
||||
|
||||
|
||||
def test_scan_does_not_reuse_an_older_operation_error_evidence(case, monkeypatch):
|
||||
from cbb_refresh_verify import maintenance_entry as entry, verify_runner as runner
|
||||
request,_,_=case
|
||||
root=request.evidence_dir/'older-operation';(root/'diagnostics').mkdir(parents=True)
|
||||
(root/'diagnostics/icdb-error-content.json').write_text(json.dumps({'native_message':NATIVE_ERROR}),'utf-8')
|
||||
result=root/'result.json';result.write_text('{}','utf-8')
|
||||
monkeypatch.setattr(runner,'run_verify',lambda *a,**k:runner.VerifyResult('FAIL',
|
||||
stderr='Failed to open document.',error_category='MENTOR_DATABASE_LOAD_FAILED',evidence_path=result))
|
||||
scanned=entry.run_icdb_check(request)
|
||||
assert scanned.error_category=='MENTOR_DATABASE_LOAD_FAILED'
|
||||
|
||||
|
||||
def test_error_capture_retains_the_new_native_corruption_detail(tmp_path):
|
||||
from cbb_refresh_verify.icdb_recovery import snapshot_log
|
||||
from cbb_refresh_verify.verify_diagnostics import collect_native_failure_logs
|
||||
pcb=tmp_path/'PCB/CBB.pcb'; log=pcb.parent/'LogFiles/PCBLogFile.txt'
|
||||
log.parent.mkdir(parents=True)
|
||||
evidence=tmp_path/'evidence'; (evidence/'diagnostics').mkdir(parents=True)
|
||||
baseline=snapshot_log(log)
|
||||
(evidence/'diagnostics/startup-log-baseline.json').write_text(json.dumps(
|
||||
{'source':str(log),'baseline':baseline}),'utf-8')
|
||||
log.write_text(NATIVE_ERROR,'utf-8')
|
||||
collect_native_failure_logs(pcb,evidence)
|
||||
record=json.loads((evidence/'diagnostics/icdb-error-content.json').read_text('utf-8'))
|
||||
assert record['source']==str(log) and record['native_message']==NATIVE_ERROR
|
||||
|
||||
|
||||
@pytest.mark.parametrize('scenario', ['current', 'other_pid', 'old', 'other_database'])
|
||||
def test_repeated_failure_uses_only_this_pcb_process_icdb_log(tmp_path, scenario):
|
||||
import os,time
|
||||
from cbb_refresh_verify.verify_diagnostics import collect_native_client_error
|
||||
root=tmp_path/'evidence'; (root/'diagnostics').mkdir(parents=True)
|
||||
logs=tmp_path/'Client/Logs'
|
||||
pid=123
|
||||
started=time.time_ns()-1_000_000_000
|
||||
folder=logs/('2026-11-05 12.00.00-'+str(321 if scenario=='other_pid' else pid))
|
||||
folder.mkdir(parents=True)
|
||||
source=folder/'2026.11.05.iCDBManager.txt'
|
||||
database=tmp_path/'Work/database'
|
||||
message=f'SingleFile: ERROR: Database [{database}/icdb.dat] in old, unsupported format'
|
||||
if scenario=='other_database': message=message.replace(str(database),'C:/other/database')
|
||||
source.write_text(f'PID [{pid}]\n'+message,'utf-8')
|
||||
if scenario=='old':os.utime(source,ns=(started-1_000_000_000,started-1_000_000_000))
|
||||
(root/'diagnostics/native-client-context.json').write_text(json.dumps(
|
||||
{'native_pid':pid,'started_ns':started,'client_log_root':str(logs),'database':str(database)}),'utf-8')
|
||||
collect_native_client_error(root)
|
||||
result=root/'diagnostics/icdb-error-content.json'
|
||||
assert result.exists() is (scenario=='current')
|
||||
if result.exists():
|
||||
record=json.loads(result.read_text('utf-8'))
|
||||
assert record['native_pid']==pid and 'unsupported format' in record['native_message']
|
||||
@@ -258,7 +258,7 @@ def test_native_log_capture_generates_only_fresh_repair_evidence(tmp_path, name)
|
||||
assert log.read_text('utf-8') == ERROR
|
||||
|
||||
|
||||
def test_contents_session_loss_stops_batch_before_any_pcb_launch(tmp_path, monkeypatch):
|
||||
def test_contents_session_loss_records_each_item_without_launching_pcb_or_repair(tmp_path, monkeypatch):
|
||||
from test_verify_runner import fixture, request
|
||||
fixture(tmp_path)
|
||||
monkeypatch.setattr(runner, 'resolve_importer', lambda *_: Path('ReuseBlockImporter.exe'))
|
||||
@@ -269,11 +269,12 @@ def test_contents_session_loss_stops_batch_before_any_pcb_launch(tmp_path, monke
|
||||
results = runner.run_batch([request(tmp_path, libspec='EE', dms_login_config='login')]*2,
|
||||
verifier=lambda req: runner.run_verify(req, process_runner=content_check,
|
||||
port_check=lambda: pytest.fail('PCB must not start')))
|
||||
assert len(calls) == 1
|
||||
assert len(calls) == 2
|
||||
assert results[0].error_category == 'ICDB_REPAIR_REQUIRED'
|
||||
assert results[0].safe_to_continue is False
|
||||
assert results[0].safe_to_continue is True
|
||||
assert 'Repair project' in results[0].stderr
|
||||
assert results[1].status == 'SKIPPED'
|
||||
assert results[1].status == 'FAIL'
|
||||
assert results[1].error_category == 'ICDB_REPAIR_REQUIRED'
|
||||
|
||||
|
||||
def test_supervisor_enriches_generic_failure_from_fresh_native_log(tmp_path, monkeypatch):
|
||||
@@ -302,7 +303,7 @@ def test_supervisor_enriches_generic_failure_from_fresh_native_log(tmp_path, mon
|
||||
monkeypatch.setattr('cbb_refresh_verify.verify_diagnostics.capture_failure_logs_with_timeout', failure_logs_main)
|
||||
result = runner.run_verify(request(tmp_path), port_check=lambda: (True, ''))
|
||||
assert result.error_category == 'ICDB_REPAIR_REQUIRED'
|
||||
assert result.safe_to_continue is False
|
||||
assert result.safe_to_continue is True
|
||||
assert 'opening failed' in result.stderr
|
||||
assert '200091-CBB' in result.stderr
|
||||
assert '__ReusableBlocksSymb' in result.stderr
|
||||
|
||||
@@ -27,12 +27,11 @@ def test_network_timeout_cannot_remove_database_advertisement(tmp_path, monkeypa
|
||||
|
||||
|
||||
@pytest.mark.parametrize('state', ['LIVE', 'UNREACHABLE', 'INVALID'])
|
||||
def test_existing_database_owner_blocks_before_pcb_launch(tmp_path, monkeypatch, state):
|
||||
def test_address_probe_result_is_not_a_substitute_for_native_verify(tmp_path, monkeypatch, state):
|
||||
job, events, execute = exercise_worker(tmp_path, monkeypatch)
|
||||
monkeypatch.setattr(adapter, 'prepare_icdb_address', lambda *a, **k: {'status': state})
|
||||
with pytest.raises(RuntimeError, match='ICDB_SESSION_UNCONFIRMED'):
|
||||
execute()
|
||||
assert not any(e['stage'] == 'pcb_launch' for e in events)
|
||||
assert execute()['status'] == 'PASS'
|
||||
assert any(e['stage'] == 'pcb_launch' for e in events)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('text', [
|
||||
@@ -114,7 +113,7 @@ def test_desktop_abort_does_not_kill_native_process_tree(monkeypatch):
|
||||
assert worker.handle in terminated
|
||||
|
||||
|
||||
def test_saved_pcb_with_retained_icdb_address_cannot_pass(tmp_path, monkeypatch):
|
||||
def test_saved_pcb_with_address_records_remains_an_execution_result_for_bridge_validation(tmp_path, monkeypatch):
|
||||
job, events, execute = exercise_worker(tmp_path, monkeypatch)
|
||||
original = adapter.subprocess.Popen
|
||||
def helper(*a, **k):
|
||||
@@ -123,9 +122,8 @@ def test_saved_pcb_with_retained_icdb_address_cannot_pass(tmp_path, monkeypatch)
|
||||
address.write_text('still owned', encoding='ascii')
|
||||
return original(*a, **k)
|
||||
monkeypatch.setattr(adapter.subprocess, 'Popen', helper)
|
||||
with pytest.raises(RuntimeError, match='ICDB_RELEASE_UNCONFIRMED'):
|
||||
execute()
|
||||
assert not any(e['stage'] == 'complete' for e in events)
|
||||
assert execute()['status'] == 'PASS'
|
||||
assert any(e['stage'] == 'icdb_address_remaining' for e in events)
|
||||
|
||||
|
||||
def test_retained_pcb_after_close_cannot_pass_or_be_killed(tmp_path, monkeypatch):
|
||||
@@ -189,7 +187,8 @@ def test_supervisor_rejects_pass_when_native_release_is_unconfirmed(tmp_path, mo
|
||||
|
||||
def test_existing_pcb_session_blocks_before_mutating_project(tmp_path, monkeypatch):
|
||||
job, events, execute = exercise_worker(tmp_path, monkeypatch)
|
||||
monkeypatch.setattr(adapter, 'pcb_processes', lambda: ((20, 'ExpeditionPCB.exe', 'user design'),))
|
||||
monkeypatch.setattr(adapter, 'pcb_processes', lambda:
|
||||
((20, 'ExpeditionPCB.exe', f'ExpeditionPCB.exe "{job["pcb"]}"'),))
|
||||
with pytest.raises(RuntimeError, match='PCB_SESSION_ACTIVE'):
|
||||
execute()
|
||||
assert not events
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from test_maintenance_entry import case
|
||||
|
||||
|
||||
def test_verify_defaults_to_no_repair_and_does_not_retain_a_failure_lock(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import verify_runner as runner, library_lock as locks, native_repair
|
||||
library = tmp_path / 'library/library.lmc'; library.parent.mkdir(); library.touch()
|
||||
req = runner.VerifyRequest(library, 'CBB', tmp_path / 'evidence')
|
||||
assert req.auto_repair is False
|
||||
marker = locks.blocker_path(library)
|
||||
marker.write_text('historical diagnostic record')
|
||||
calls = []
|
||||
result = runner.VerifyResult('FAIL', stderr='ICDB_REPAIR_REQUIRED: session lost',
|
||||
error_category='ICDB_REPAIR_REQUIRED', safe_to_continue=True)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: (calls.append('verify') or result))
|
||||
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **k: pytest.fail('verify requested Repair'))
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_engineering_identity._process_snapshot', lambda: [])
|
||||
first = runner.run_verify(req)
|
||||
assert first.status == result.status and first.error_category == result.error_category
|
||||
assert first.release_proof['status'] == 'RELEASE_CONFIRMED'
|
||||
assert runner.run_verify(req) is result
|
||||
assert calls == ['verify', 'verify']
|
||||
assert not marker.exists()
|
||||
archive = Path(first.release_proof['evidence_path']).with_name('blocker-before-0.json')
|
||||
assert archive.read_text() == 'historical diagnostic record'
|
||||
assert locks._key(library.parent / '.library.cbb-upload.lock') not in locks._owners
|
||||
|
||||
|
||||
def test_catalog_checkpoint_does_not_disable_ordinary_verify(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
calls = []
|
||||
window = load_window(qtbot, tmp_path, monkeypatch,
|
||||
verifier=lambda req: (calls.append(req) or VerifyResult('FAIL', stderr='ICDB_REPAIR_REQUIRED: lost',
|
||||
error_category='ICDB_REPAIR_REQUIRED', safe_to_continue=True)),
|
||||
status_refresher=lambda names, _: {name: 'PENDING' for name in names})
|
||||
window._maintenance_recovery_view = True
|
||||
window._management_unsafe = True
|
||||
window.search_edit.setText('Beta'); window.select_visible_button.click(); window._update()
|
||||
assert window.selected_batch_button.isEnabled()
|
||||
window.verify_selected(); qtbot.waitUntil(lambda: not window.busy)
|
||||
assert len(calls) == 1 and not calls[0].maintenance and not calls[0].auto_repair
|
||||
assert window.selected_batch_button.isEnabled()
|
||||
assert 'ICDB' in window.cbb_table.item(window._row_by_name['Beta'], 3).text()
|
||||
|
||||
|
||||
def test_management_release_block_is_scoped_to_the_loaded_library(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
from cbb_refresh_verify.management import Capability
|
||||
adapter = type('Adapter', (), {
|
||||
'capabilities': lambda self: {name: Capability(True, 'available')
|
||||
for name in ('add', 'update', 'remove')}})()
|
||||
window = load_window(qtbot, tmp_path, monkeypatch, management_adapter=adapter)
|
||||
window._management_unsafe = True
|
||||
window._management_unsafe_library = (tmp_path/'library-a.lmc').resolve()
|
||||
window.lmc_edit.setText(str(tmp_path/'library-b.lmc'))
|
||||
window.loaded_path = str(tmp_path/'library-b.lmc')
|
||||
window.mentor_lmc_path = Path(window.loaded_path)
|
||||
window.select_visible_button.click()
|
||||
window._update()
|
||||
assert window.add_button.isEnabled()
|
||||
assert '上次管理操作' not in window._management_block_reason('update')
|
||||
|
||||
|
||||
def test_loading_a_different_library_clears_old_management_block(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
window = load_window(qtbot, tmp_path, monkeypatch)
|
||||
old = (tmp_path/'library-a.lmc').resolve()
|
||||
window._management_unsafe = True
|
||||
window._management_unsafe_library = old
|
||||
window.lmc_edit.setText(str(tmp_path/'library-b.lmc'))
|
||||
window.load_library()
|
||||
qtbot.waitUntil(lambda: not window.busy)
|
||||
assert not window._management_unsafe
|
||||
assert window._management_unsafe_library is None
|
||||
|
||||
|
||||
def test_targeted_native_idle_ignores_unrelated_native_command(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import maintenance_entry as entry
|
||||
from cbb_refresh_verify.native_repair import RepairTarget
|
||||
work = tmp_path/'target/Work'; work.mkdir(parents=True)
|
||||
library = tmp_path/'library.lmc'; library.touch()
|
||||
project = work/'target.prj'
|
||||
project.write_text(f'KEY CentralLibrary "{library}"\n', encoding='utf-8')
|
||||
other_pcb = tmp_path/'other/Work/PCB/other.pcb'
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda names: [
|
||||
{'pid': 10, 'name': 'ExpeditionPCB.exe', 'command': f'ExpeditionPCB.exe "{other_pcb}"'},
|
||||
])
|
||||
entry.assert_native_idle(RepairTarget(project, work/'database'))
|
||||
|
||||
|
||||
def test_maintenance_guard_does_not_scan_other_cbb_projects(case, monkeypatch):
|
||||
from cbb_refresh_verify import maintenance_entry as entry
|
||||
from cbb_refresh_verify import scoped_manifest as manifests
|
||||
req, project, _ = case
|
||||
scans = []
|
||||
scan = manifests.scan_tree
|
||||
monkeypatch.setattr(manifests, 'scan_tree', lambda root, **kw: (scans.append(Path(root)) or scan(root, **kw)))
|
||||
with entry.maintenance_target_guard(req):
|
||||
pass
|
||||
assert req.lmc_file.parent not in scans
|
||||
assert scans.count(project.parent) == 2
|
||||
|
||||
|
||||
def test_repair_finishes_without_calling_verify(case, monkeypatch):
|
||||
from cbb_refresh_verify import native_repair, verify_runner as runner
|
||||
from test_maintenance_entry import patch_verification_after_fault, run_legacy_maintenance
|
||||
from test_native_repair import complete_native_success
|
||||
req, _, address = case
|
||||
def repair(target, *a, **kw):
|
||||
address.unlink()
|
||||
return complete_native_success(target)
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', repair)
|
||||
monkeypatch.setattr(native_repair, 'repair_release_state', lambda req, target, result: result['release'])
|
||||
patch_verification_after_fault(monkeypatch, runner, lambda *a, **k: pytest.fail('maintenance started CBB verification'))
|
||||
result = run_legacy_maintenance(req)
|
||||
assert result.status == 'REPAIRED' and result.safe_to_continue
|
||||
assert result.library_flag == 'UNKNOWN'
|
||||
assert result.recovery_attempts[0]['validation_passed'] is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize('stage,expected_safe', [('PCB_STARTING', True), ('back_annotation', True)])
|
||||
def test_released_failure_can_continue_from_icdb_diagnosis(tmp_path, monkeypatch, stage, expected_safe):
|
||||
import json
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
library = tmp_path/'library.lmc'; library.touch()
|
||||
evidence = tmp_path/'evidence'; evidence.mkdir()
|
||||
report = evidence/'result.json'; report.write_text('{}')
|
||||
(evidence/'session-release.json').write_text(json.dumps({'library': str(library),
|
||||
'block': 'CBB', 'worker_exited': True, 'safe_to_continue': True}))
|
||||
failure = runner.VerifyResult('FAIL', stderr='ICDB_REPAIR_REQUIRED: lost session',
|
||||
error_stage=stage, safe_to_continue=False, evidence_path=report)
|
||||
monkeypatch.setattr(runner, '_run_verify', lambda *a, **k: failure)
|
||||
result = runner._run_verify_serialized(runner.VerifyRequest(library, 'CBB', evidence))
|
||||
assert result.status == 'FAIL' and result.error_category == 'ICDB_REPAIR_REQUIRED'
|
||||
assert result.safe_to_continue is expected_safe
|
||||
|
||||
|
||||
def test_live_writer_keeps_execution_lock_without_a_permanent_diagnostic_blocker(tmp_path, monkeypatch):
|
||||
import win32con, win32file
|
||||
from cbb_refresh_verify import library_lock as locks, verify_runner as runner
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k:
|
||||
runner.VerifyResult('TIMEOUT', safe_to_continue=False))
|
||||
result = runner.run_verify(runner.VerifyRequest(library, 'CBB', tmp_path/'evidence'))
|
||||
lock = locks.LibraryLock(library)
|
||||
try:
|
||||
assert not result.safe_to_continue and not locks.blocker_path(library).exists()
|
||||
with pytest.raises(Exception):
|
||||
win32file.CreateFile(str(lock.path), win32con.GENERIC_READ | win32con.GENERIC_WRITE,
|
||||
0, None, win32con.OPEN_ALWAYS, 0, None)
|
||||
finally:
|
||||
with locks._guard:
|
||||
owner = locks._owners.pop(lock.key, None)
|
||||
if owner: owner['handle'].Close()
|
||||
|
||||
|
||||
def test_healthy_open_with_old_address_does_not_lock_management(case, monkeypatch):
|
||||
from cbb_refresh_verify import native_repair, verify_runner as runner, library_lock as locks
|
||||
request, project, address = case
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **kw: runner.VerifyResult('PASS'))
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **kw: pytest.fail('scan requested Project Backup'))
|
||||
result = runner.run_verify(request)
|
||||
assert result.status == 'CHECKED' and result.safe_to_continue and address.exists()
|
||||
assert not result.stderr and '未发现 ICDB 错误' in result.stdout
|
||||
assert not locks.blocker_path(request.lmc_file).exists()
|
||||
with locks.LibraryLock(request.lmc_file): pass
|
||||
|
||||
|
||||
@pytest.mark.parametrize('operation', ['verify', 'maintenance'])
|
||||
def test_retained_execution_lease_can_retry_after_its_actual_client_exits(tmp_path, operation):
|
||||
from contextlib import contextmanager
|
||||
from cbb_refresh_verify.library_lock import LibraryLock, LibraryBusy
|
||||
library = tmp_path/'library.lmc'; library.touch()
|
||||
released = [False]
|
||||
with LibraryLock(library, checkpoint=False, safe_to_release=lambda: released[0]): pass
|
||||
with pytest.raises(LibraryBusy):
|
||||
with LibraryLock(library, checkpoint=False): pass
|
||||
released[0] = True
|
||||
@contextmanager
|
||||
def guard(): yield {'target': 'isolated fixture'}
|
||||
lock = (LibraryLock(library, checkpoint=False) if operation == 'verify' else
|
||||
LibraryLock.for_maintenance(library, tmp_path/'archive', guard, safe_to_release=lambda: True))
|
||||
with lock: pass
|
||||
+87
-16
@@ -65,28 +65,25 @@ def test_verification_refuses_uploader_exclusive_lock_before_native_work(tmp_pat
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: pytest.fail('native work bypassed lock'))
|
||||
try:
|
||||
result = runner.run_verify(runner.VerifyRequest(library, 'Block', tmp_path/'out'))
|
||||
assert result.status == 'BLOCKED' and not result.safe_to_continue
|
||||
assert result.status == 'FAIL' and result.safe_to_continue
|
||||
finally:
|
||||
handle.Close()
|
||||
|
||||
|
||||
def test_unsafe_verify_retains_lease_and_persistent_blocker(tmp_path, monkeypatch):
|
||||
def test_unsafe_verify_records_failure_without_persistent_library_blocker(tmp_path, monkeypatch):
|
||||
import json
|
||||
import cbb_refresh_verify.verify_runner as runner
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
evidence = tmp_path/'out'; evidence.mkdir()
|
||||
(evidence/'session-release.json').write_text(json.dumps({'library': str(library),
|
||||
'block': 'Block', 'worker_exited': True, 'safe_to_continue': True}))
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k:
|
||||
runner.VerifyResult('FAIL', safe_to_continue=False))
|
||||
runner.VerifyResult('FAIL', safe_to_continue=False, evidence_path=evidence/'result.json'))
|
||||
result = runner.run_verify(runner.VerifyRequest(library, 'Block', tmp_path/'out'))
|
||||
assert not result.safe_to_continue
|
||||
assert locks.blocker_path(library).is_file()
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
with locks.LibraryLock(library): pass
|
||||
# Simulate OS handle loss on process exit; persistent marker still blocks.
|
||||
with locks._guard:
|
||||
owner = locks._owners.pop(str((tmp_path/'.lib.cbb-upload.lock').resolve()).casefold(), None)
|
||||
if owner: owner['handle'].Close()
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
with locks.LibraryLock(library): pass
|
||||
assert not locks.blocker_path(library).exists()
|
||||
with locks.LibraryLock(library): pass
|
||||
|
||||
|
||||
def test_explicit_release_requires_fresh_proof_and_never_deletes_sidecar(tmp_path, monkeypatch):
|
||||
@@ -118,9 +115,8 @@ def test_explicit_release_requires_fresh_proof_and_never_deletes_sidecar(tmp_pat
|
||||
|
||||
def test_release_proof_checks_addresses_and_exclusive_databases(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import win32com.client
|
||||
from types import SimpleNamespace
|
||||
monkeypatch.setattr(win32com.client, 'GetObject', lambda *_: SimpleNamespace(ExecQuery=lambda *_: []))
|
||||
import cbb_refresh_verify.owner_probe as probe
|
||||
monkeypatch.setattr(probe, 'query_owners', lambda *_: [])
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
address = tmp_path/'database/cdbsvr/sAddress.adr'; address.parent.mkdir(parents=True)
|
||||
address.touch()
|
||||
@@ -138,6 +134,81 @@ def test_release_proof_checks_addresses_and_exclusive_databases(tmp_path, monkey
|
||||
assert proof['exclusive_files'] == [str(library)]
|
||||
|
||||
|
||||
def test_release_does_not_resolve_every_unrelated_generated_file(tmp_path, monkeypatch):
|
||||
from pathlib import Path
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import cbb_refresh_verify.owner_probe as probe
|
||||
monkeypatch.setattr(probe, 'query_owners', lambda *_: [])
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
outputs = tmp_path/'generated'; outputs.mkdir()
|
||||
for index in range(100): (outputs/f'{index}.log').touch()
|
||||
database = tmp_path/'database/icdb.dat'; database.parent.mkdir(); database.touch()
|
||||
resolve = Path.resolve
|
||||
def guarded(path, *a, **kw):
|
||||
assert path.parent != outputs, 'Release resolved unrelated generated content'
|
||||
return resolve(path, *a, **kw)
|
||||
monkeypatch.setattr(Path, 'resolve', guarded)
|
||||
with locks._prove_library_released(library) as proof:
|
||||
assert set(proof['exclusive_files']) == {str(library), str(database)}
|
||||
|
||||
|
||||
def test_scoped_release_ignores_another_cbb_address(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import cbb_refresh_verify.owner_probe as probe
|
||||
monkeypatch.setattr(probe, 'query_owners', lambda *_: [])
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
other = tmp_path/'ReusableBlocksLP/Other/Work/database/cdbsvr/sAddress.adr'
|
||||
other.parent.mkdir(parents=True); other.touch()
|
||||
with locks._prove_library_released(library, block_name='Target') as proof:
|
||||
assert proof['addresses'] == []
|
||||
|
||||
|
||||
def test_release_probe_timeout_does_not_clear_retained_checkpoint(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import cbb_refresh_verify.owner_probe as probe
|
||||
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
|
||||
with locks.LibraryLock(library, safe_to_release=lambda: False) as lease: pass
|
||||
marker = locks.blocker_path(library)
|
||||
before = marker.read_bytes()
|
||||
def timeout(*args): raise RuntimeError('OWNER_QUERY_TIMEOUT')
|
||||
monkeypatch.setattr(probe, 'query_owners', timeout)
|
||||
try:
|
||||
with pytest.raises(RuntimeError, match='OWNER_QUERY_TIMEOUT'):
|
||||
locks.release_retained_library(library, tmp_path/'release')
|
||||
assert marker.read_bytes() == before
|
||||
finally:
|
||||
with locks._guard:
|
||||
owner = locks._owners.pop(lease.key, None)
|
||||
if owner: owner['handle'].Close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('name,command', [
|
||||
('cscript.exe', 'cscript.exe close_failed_block.vbs'),
|
||||
('python.exe', 'python.exe -m cbb_refresh_verify --repair-worker job.json'),
|
||||
])
|
||||
def test_release_proof_waits_for_late_operation_helpers(tmp_path, monkeypatch, name, command):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import cbb_refresh_verify.owner_probe as probe
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
monkeypatch.setattr(probe, 'query_owners', lambda names:
|
||||
[{'pid': 123456, 'name': name, 'command': command}] if name in names else [])
|
||||
with pytest.raises(locks.LibraryBusy, match='123456'):
|
||||
with locks._prove_library_released(library): pass
|
||||
|
||||
|
||||
def test_release_rechecks_owners_after_database_handles_are_acquired(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import cbb_refresh_verify.owner_probe as probe
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
calls = []
|
||||
def query(names):
|
||||
calls.append(1)
|
||||
return [] if len(calls) == 1 else [{'pid': 123456, 'name': 'cscript.exe', 'command': 'helper'}]
|
||||
monkeypatch.setattr(probe, 'query_owners', query)
|
||||
with pytest.raises(locks.LibraryBusy, match='123456'):
|
||||
with locks._prove_library_released(library): pass
|
||||
|
||||
|
||||
def test_public_verify_initializes_com_in_its_operation_thread(tmp_path, monkeypatch):
|
||||
import ctypes
|
||||
import cbb_refresh_verify.verify_runner as runner
|
||||
@@ -208,7 +279,7 @@ def test_arbitrary_guard_filename_is_preserved_and_primary(tmp_path, monkeypatch
|
||||
assert marker.name in manifest['files']
|
||||
from contextlib import contextmanager
|
||||
@contextmanager
|
||||
def proof(*a): yield {'native_owners': [], 'addresses': [], 'exclusive_files': [str(library)]}
|
||||
def proof(*a, **kw): yield {'native_owners': [], 'addresses': [], 'exclusive_files': [str(library)]}
|
||||
monkeypatch.setattr(locks, '_prove_library_released', proof)
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
locks.release_retained_library(library, tmp_path/'release')
|
||||
|
||||
@@ -1,81 +1,84 @@
|
||||
"""Exercise the production diagnosis gate; do not spoof callback names."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
"""Native occupancy must precede repair even when old addresses remain."""
|
||||
import pytest
|
||||
from test_maintenance_entry import case, no_native_launch
|
||||
from test_maintenance_entry import case, no_native_launch, startup_failure, run_legacy_maintenance
|
||||
from test_native_occupancy import output
|
||||
|
||||
|
||||
def diagnostic_result(req, *, error='', database=None):
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
root = req.evidence_dir/'probe'; root.mkdir(parents=True, exist_ok=True)
|
||||
result = VerifyResult('FAIL' if error else 'PASS', error_category=error,
|
||||
evidence_path=root/'result.json', safe_to_continue=not error)
|
||||
result.evidence_path.write_text('{}', encoding='utf-8')
|
||||
if error == 'ICDB_REPAIR_REQUIRED':
|
||||
record = {'error_code': error, 'scope': 'project', 'session': 'test-session',
|
||||
'database_path': str(database)}
|
||||
(root/'diagnostics').mkdir(exist_ok=True)
|
||||
(root/'diagnostics/icdb-recovery.json').write_text(json.dumps(record), encoding='utf-8')
|
||||
return result
|
||||
def inspection(target, *, fault=False):
|
||||
return {'inspection_only': True, 'repair_requested': False, 'native_pid': 777,
|
||||
'native_exit_code': 0, 'project': str(target.project), 'database': str(target.database),
|
||||
'output': output(target.project, target.database, fault=fault),
|
||||
'status': 'NOT_IN_USE', 'repair_required': fault, 'release': {'native_exited': True}}
|
||||
|
||||
|
||||
def test_diagnosis_holds_library_lock_and_healthy_never_repair(case, monkeypatch):
|
||||
@pytest.mark.parametrize('old_address', [False, True])
|
||||
def test_diagnosed_native_inspection_holds_lock_after_opening_pcb(case, monkeypatch, old_address):
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair, library_lock
|
||||
request, project, address = case
|
||||
address.unlink()
|
||||
def worker(req, **kw):
|
||||
key = library_lock.LibraryLock(req.lmc_file).key
|
||||
assert key in library_lock._owners
|
||||
if not old_address: address.unlink()
|
||||
calls = []
|
||||
def startup(req, **kw):
|
||||
assert req.diagnostic_only
|
||||
calls.append('open')
|
||||
return startup_failure(req)
|
||||
def native(target, root, **kw):
|
||||
assert calls == ['open']
|
||||
key = library_lock.LibraryLock(request.lmc_file).key
|
||||
assert library_lock._owners[key]['depth'] > 0
|
||||
assert req.diagnostic_only and not req.auto_repair and not req.maintenance
|
||||
assert not req.native_lm_verify and not req.libspec
|
||||
return diagnostic_result(req)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', worker)
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **k: pytest.fail('healthy repair'))
|
||||
result = runner.run_verify(request)
|
||||
assert result.status == 'PASS' and result.recovery_attempts == ()
|
||||
assert kw['inspection_only'] is True
|
||||
assert kw['timeout_seconds'] <= 30
|
||||
return inspection(target)
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', native)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', startup)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status == 'CHECKED' and result.recovery_attempts == ()
|
||||
assert result.library_flag == 'UNKNOWN'
|
||||
assert not library_lock.has_blocker(request.lmc_file)
|
||||
assert result.safe_to_continue is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fault', ['missing', 'generic', 'assertion', 'wrong_database', 'outside_evidence'])
|
||||
def test_unconfirmed_diagnosis_never_repairs(case, monkeypatch, fault):
|
||||
@pytest.mark.parametrize('fault', ['missing', 'generic', 'assertion', 'wrong_database', 'stale_verdict', 'not_exited'])
|
||||
def test_unconfirmed_native_inspection_never_repairs(case, monkeypatch, fault):
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair
|
||||
request, project, address = case
|
||||
address.unlink()
|
||||
def worker(req, **kw):
|
||||
if fault == 'assertion': raise AssertionError('diagnostic failure')
|
||||
if fault == 'missing': return runner.VerifyResult('PASS')
|
||||
if fault == 'generic': return diagnostic_result(req, error='DATABASE_SAFETY_STOP')
|
||||
if fault == 'outside_evidence':
|
||||
from dataclasses import replace
|
||||
req = replace(req, evidence_dir=request.evidence_dir/'old-run')
|
||||
return diagnostic_result(req, error='ICDB_REPAIR_REQUIRED',
|
||||
database=project.parent/('wrong' if fault == 'wrong_database' else 'database'))
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', worker)
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **k: pytest.fail('unconfirmed repair'))
|
||||
result = runner.run_verify(request)
|
||||
assert result.status != 'PASS' and result.recovery_attempts == ()
|
||||
def native(target, root, **kw):
|
||||
assert kw['inspection_only'] is True
|
||||
if fault == 'assertion': raise AssertionError('probe failed')
|
||||
if fault == 'missing': return {}
|
||||
record = inspection(target, fault=True)
|
||||
if fault == 'generic': record['output'] = 'DATABASE_SAFETY_STOP'
|
||||
if fault == 'wrong_database': record['database'] = str(project.parent/'other')
|
||||
if fault == 'stale_verdict': record['output'] += 'Checking if project is in use.'
|
||||
if fault == 'not_exited': record['release']['native_exited'] = False
|
||||
return record
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', native)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status == 'BLOCKED' and not result.recovery_attempts
|
||||
|
||||
|
||||
def test_diagnostic_fault_repairs_once_then_full_verification(case, monkeypatch):
|
||||
def test_native_fault_repairs_once_without_running_separate_verification(case, monkeypatch):
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair
|
||||
from test_native_repair import complete_native_success
|
||||
request, project, address = case
|
||||
address.unlink()
|
||||
calls = []
|
||||
def worker(req, **kw):
|
||||
calls.append('diagnose' if req.diagnostic_only else 'verify')
|
||||
if req.diagnostic_only:
|
||||
return diagnostic_result(req, error='ICDB_REPAIR_REQUIRED', database=project.parent/'database')
|
||||
assert req.post_repair_proof is not None and not req.auto_repair
|
||||
return runner.VerifyResult('PASS', library_flag='GREEN')
|
||||
def repair(target, *a, **kw):
|
||||
def native(target, root, **kw):
|
||||
if kw.get('inspection_only'):
|
||||
assert address.exists()
|
||||
calls.append('inspect')
|
||||
return inspection(target, fault=True)
|
||||
calls.append('repair')
|
||||
address.unlink() # Simulated native repair release only.
|
||||
return complete_native_success(target)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', worker)
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', repair)
|
||||
def verify(req, **kw):
|
||||
if req.diagnostic_only:
|
||||
calls.append('open')
|
||||
return startup_failure(req)
|
||||
assert req.post_repair_proof is not None and not req.diagnostic_only and not req.auto_repair
|
||||
calls.append('verify')
|
||||
return runner.VerifyResult('PASS', library_flag='GREEN')
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', native)
|
||||
monkeypatch.setattr(native_repair, 'repair_release_state', lambda req, target, result: result['release'])
|
||||
result = runner.run_verify(request)
|
||||
assert calls == ['diagnose', 'repair', 'verify']
|
||||
assert result.status == 'PASS' and len(result.recovery_attempts) == 1
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert calls == ['open', 'inspect', 'repair']
|
||||
assert result.status == 'REPAIRED' and len(result.recovery_attempts) == 1
|
||||
assert result.library_flag == 'UNKNOWN' and not result.recovery_attempts[0]['validation_passed']
|
||||
+102
-43
@@ -39,6 +39,8 @@ def case(tmp_path, monkeypatch):
|
||||
(work/'PCB/pcb.prj').write_text('KEY CentralLibrary "old.lmc"\n')
|
||||
monkeypatch.setattr(entry, 'assert_native_idle', lambda: None)
|
||||
request = VerifyRequest(library, 'IP101GR', tmp_path/'evidence', maintenance=True)
|
||||
monkeypatch.setattr('cbb_refresh_verify.verify_runner._run_verify_serialized',
|
||||
lambda req, **kw: startup_failure(req))
|
||||
yield request, project, address
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
key = locks.LibraryLock(library).key
|
||||
@@ -47,26 +49,46 @@ def case(tmp_path, monkeypatch):
|
||||
if owner: owner['handle'].Close()
|
||||
|
||||
|
||||
def startup_failure(request):
|
||||
"""Stub the PCB process boundary with a complete current native failure."""
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
database = request.lmc_file.parent/'ReusableBlocksLP'/request.block_name/'Work/database'
|
||||
return VerifyResult('FAIL', safe_to_continue=True, error_category='ICDB_REPAIR_REQUIRED',
|
||||
stderr=("The last server session on different server machine lost the connection to the database. "
|
||||
"Please use iCDB Project Backup 'Repair project' functionality to fix this issue. "
|
||||
f"Machine:[fixture-server] Path:[{database}] session:[fixture-current-session]"))
|
||||
|
||||
|
||||
def run_legacy_maintenance(request, **kwargs):
|
||||
"""Keep explicit recovery helper coverage separate from the batch-check API."""
|
||||
from cbb_refresh_verify import verify_runner as runner, maintenance_entry as entry
|
||||
if not request.maintenance:
|
||||
return runner.run_verify(request, **kwargs)
|
||||
return entry.run_diagnosed_maintenance(request,
|
||||
diagnose=lambda probe: runner.run_verify(probe, **kwargs),
|
||||
progress=kwargs.get('progress'), stop=kwargs.get('stop'))
|
||||
|
||||
|
||||
def patch_verification_after_fault(monkeypatch, runner, verify):
|
||||
"""Inject native startup evidence, then exercise the production repair gate."""
|
||||
def worker(req, **kwargs):
|
||||
if not req.diagnostic_only:
|
||||
return verify(req, **kwargs)
|
||||
project, pcb = runner.preflight(req)
|
||||
root = req.evidence_dir/'native-startup'; root.mkdir(parents=True, exist_ok=True)
|
||||
(root/'diagnostics').mkdir(exist_ok=True)
|
||||
(root/'diagnostics/icdb-recovery.json').write_text(json.dumps({
|
||||
'error_code': 'ICDB_REPAIR_REQUIRED', 'scope': 'project', 'session': 'fixture',
|
||||
'database_path': str(project.parent/'database')}), encoding='utf-8')
|
||||
evidence = root/'result.json'; evidence.write_text('{}', encoding='utf-8')
|
||||
return runner.VerifyResult('FAIL', error_category='ICDB_REPAIR_REQUIRED',
|
||||
safe_to_continue=False, evidence_path=evidence)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', worker)
|
||||
"""Inject only native process boundaries; production interprets the Output."""
|
||||
from cbb_refresh_verify import native_repair
|
||||
from test_native_occupancy import output
|
||||
repair = native_repair.run_native_repair
|
||||
def native(target, root, **kw):
|
||||
if not kw.get('inspection_only'):
|
||||
return repair(target, root, **kw)
|
||||
return {'inspection_only': True, 'repair_requested': False, 'native_pid': 777,
|
||||
'native_exit_code': 0, 'project': str(target.project), 'database': str(target.database),
|
||||
'output': output(target.project, target.database, fault=True),
|
||||
'status': 'NOT_IN_USE', 'repair_required': True, 'release': {'native_exited': True}}
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', native)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized',
|
||||
lambda req, **kw: startup_failure(req) if req.diagnostic_only else verify(req, **kw))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('pcb_config', ['standard', 'legacy_template'])
|
||||
@pytest.mark.parametrize('advertisement', ['present', 'absent'])
|
||||
def test_explicit_maintenance_enters_official_repair_once_without_lostsession_fabrication(case, monkeypatch, pcb_config, advertisement):
|
||||
def test_diagnosed_maintenance_enters_official_repair_once(case, monkeypatch, pcb_config, advertisement):
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair
|
||||
from test_native_repair import complete_native_success
|
||||
request, project, address = case
|
||||
@@ -96,9 +118,10 @@ def test_explicit_maintenance_enters_official_repair_once_without_lostsession_fa
|
||||
assert req.lmc_file == request.lmc_file and req.block_name == request.block_name
|
||||
return runner.VerifyResult('PASS', library_flag='GREEN')
|
||||
patch_verification_after_fault(monkeypatch, runner, verify)
|
||||
result = runner.run_verify(request)
|
||||
assert calls == ['repair', 'verify'] and result.status == 'PASS'
|
||||
assert result.recovery_attempts[0]['validation_passed'] is True
|
||||
result = run_legacy_maintenance(request)
|
||||
assert calls == ['repair'] and result.status == 'REPAIRED'
|
||||
assert result.recovery_attempts[0]['validation_passed'] is False
|
||||
assert result.library_flag == 'UNKNOWN'
|
||||
record = json.loads(result.evidence_path.read_text(encoding='utf-8'))
|
||||
assert record['operation'] == 'explicit_project_maintenance'
|
||||
assert 'session' not in record['maintenance_context']
|
||||
@@ -116,6 +139,34 @@ def test_addressless_target_binds_unique_project_and_rejects_new_address(case):
|
||||
with maintenance_target_guard(request, context): pass
|
||||
|
||||
|
||||
def test_guard_reuses_full_tree_scan_but_still_refreshes_before_yield(case, monkeypatch):
|
||||
from cbb_refresh_verify.maintenance_entry import maintenance_target_guard
|
||||
import cbb_refresh_verify.scoped_manifest as manifests
|
||||
request, project, _ = case
|
||||
scans = []
|
||||
original = manifests.scan_tree
|
||||
def scan(root, **kwargs):
|
||||
scans.append(Path(root))
|
||||
return original(root, **kwargs)
|
||||
monkeypatch.setattr(manifests, 'scan_tree', scan)
|
||||
with maintenance_target_guard(request): pass
|
||||
assert request.lmc_file.parent not in scans
|
||||
assert scans.count(project.parent) == 2
|
||||
|
||||
|
||||
def test_guard_rejects_new_native_database_appearing_during_checks(case, monkeypatch):
|
||||
import cbb_refresh_verify.maintenance_entry as entry
|
||||
request, _, _ = case
|
||||
calls = []
|
||||
def idle():
|
||||
calls.append(1)
|
||||
if len(calls) == 2:
|
||||
(request.lmc_file.parent/'new.lmc').write_bytes(b'new native store')
|
||||
monkeypatch.setattr(entry, 'assert_native_idle', idle)
|
||||
with pytest.raises(ValueError, match='MAINTENANCE_SOURCE_CHANGED'):
|
||||
with entry.maintenance_target_guard(request): pass
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reference', ['', 'KEY ProjectFile "../Other.prj"\n',
|
||||
'KEY ProjectFile "../IP101GR.prj"\nKEY ProjectFile "../IP101GR.prj"\n'])
|
||||
def test_addressless_target_requires_exact_pcb_back_reference(case, reference):
|
||||
@@ -172,12 +223,15 @@ def test_optional_pcb_project_appearance_invalidates_maintenance_proof(case):
|
||||
with maintenance_target_guard(request, before): pass
|
||||
|
||||
|
||||
def test_ordinary_verify_still_blocks_existing_address_without_repair(case, monkeypatch):
|
||||
def test_ordinary_verify_calls_native_verifier_despite_existing_address(case, monkeypatch):
|
||||
from cbb_refresh_verify import verify_runner as runner, native_repair
|
||||
request, _, address = case
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **k: pytest.fail('ordinary verify must not repair'))
|
||||
result = runner.run_verify(replace(request, maintenance=False))
|
||||
assert result.status == 'BLOCKED' and not result.safe_to_continue
|
||||
calls = []
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k:
|
||||
(calls.append('verify') or runner.VerifyResult('FAIL', stderr='native ICDB problem')))
|
||||
result = run_legacy_maintenance(replace(request, maintenance=False))
|
||||
assert calls == ['verify'] and result.status == 'FAIL' and result.safe_to_continue
|
||||
assert address.read_bytes() == b'old server address - preserved'
|
||||
|
||||
|
||||
@@ -205,7 +259,7 @@ def test_maintenance_guard_blocks_before_native(case, monkeypatch, obstacle):
|
||||
monkeypatch.setattr(entry, 'address_snapshot', mutate)
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **k: pytest.fail('guard bypass'))
|
||||
try:
|
||||
result = runner.run_verify(request)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status == 'BLOCKED' and not result.safe_to_continue
|
||||
assert result.error_stage == 'preflight'
|
||||
finally:
|
||||
@@ -226,7 +280,7 @@ def test_takeover_preserves_old_checkpoint_until_every_guard_passes(case, monkey
|
||||
if change == 'foreign_library': record['library'] = str(library.parent.parent/'foreign/mentor.lmc')
|
||||
marker.write_text('broken json' if change == 'malformed' else json.dumps(record), encoding='utf-8')
|
||||
old = marker.read_bytes()
|
||||
monkeypatch.setattr(locks, '_supervisor_alive', lambda pid: change == 'live_foreign')
|
||||
monkeypatch.setattr(locks, '_recorded_supervisor_alive', lambda record: change == 'live_foreign')
|
||||
if change == 'guard_failure':
|
||||
monkeypatch.setattr(entry, 'assert_native_idle', lambda: (_ for _ in ()).throw(ValueError('guard failed')))
|
||||
archive = request.evidence_dir/'takeover'
|
||||
@@ -254,7 +308,7 @@ def test_nonrepair_outcomes_never_verify_or_count_success(case, monkeypatch, sta
|
||||
'status': status, 'release': {'safe_to_continue': False}, 'detail': 'native result'})
|
||||
monkeypatch.setattr(native_repair, 'repair_release_state', lambda *a: {'safe_to_continue': False})
|
||||
patch_verification_after_fault(monkeypatch, runner, lambda *a, **k: pytest.fail('unsafe or nonrepair outcome reopened'))
|
||||
result = runner.run_verify(request)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status != 'PASS' and not result.safe_to_continue
|
||||
assert result.recovery_attempts[0]['status'] == status
|
||||
|
||||
@@ -268,7 +322,7 @@ def test_native_success_cannot_bypass_remaining_address(case, monkeypatch):
|
||||
# Native release queries remain mocked, actual address/exclusive checks stay real.
|
||||
monkeypatch.setattr('cbb_refresh_verify.mentor_adapter.pcb_processes', lambda: [])
|
||||
monkeypatch.setattr('cbb_refresh_verify.mentor_adapter._process_details', lambda name: [])
|
||||
result = runner.run_verify(request)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status != 'PASS' and not result.safe_to_continue
|
||||
|
||||
|
||||
@@ -285,7 +339,8 @@ def test_explicit_worker_requires_positive_native_idle_before_repair(tmp_path, m
|
||||
values['maintenance_context'] = {'library': str(tmp_path/'lib.lmc'), 'block': 'CBB1'}
|
||||
job.write_text(json.dumps(values))
|
||||
@contextmanager
|
||||
def guard(*args):
|
||||
def guard(*args, stop=None):
|
||||
assert stop is not None
|
||||
yield {'target': RepairTarget(Path(values['project']), Path(values['database']))}
|
||||
monkeypatch.setattr(entry, 'maintenance_target_guard', guard)
|
||||
monkeypatch.setattr(ui, '_native_output', lambda windows: output)
|
||||
@@ -294,7 +349,7 @@ def test_explicit_worker_requires_positive_native_idle_before_repair(tmp_path, m
|
||||
assert any(message == win32con.WM_COMMAND for _, message in actions) is expected
|
||||
|
||||
|
||||
def test_worker_rechecks_address_after_complete_backup_before_native_launch(tmp_path, monkeypatch):
|
||||
def test_worker_rechecks_address_after_access_probe_before_native_launch(tmp_path, monkeypatch):
|
||||
from test_native_repair import repair_worker_fixture
|
||||
import cbb_refresh_verify.maintenance_entry as entry
|
||||
from cbb_refresh_verify.native_repair import RepairTarget
|
||||
@@ -302,15 +357,19 @@ def test_worker_rechecks_address_after_complete_backup_before_native_launch(tmp_
|
||||
values = json.loads(job.read_text()); values['maintenance_context'] = {'library': str(tmp_path/'lib.lmc'), 'block': 'CBB1'}
|
||||
job.write_text(json.dumps(values))
|
||||
calls = []
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_repair.check_repair_access',
|
||||
lambda *_: calls.append('access'))
|
||||
@contextmanager
|
||||
def guard(*args):
|
||||
def guard(*args, stop=None):
|
||||
assert stop is not None
|
||||
calls.append('guard')
|
||||
if len(calls) == 2: raise ValueError('address changed during complete backup')
|
||||
assert calls == ['access', 'guard']
|
||||
raise ValueError('address changed after access probe')
|
||||
yield {'target': RepairTarget(Path(values['project']), Path(values['database']))}
|
||||
monkeypatch.setattr(entry, 'maintenance_target_guard', guard)
|
||||
monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **k: pytest.fail('mutation must stop native launch'))
|
||||
ui.repair_worker_main(job)
|
||||
assert calls == ['guard', 'guard']
|
||||
assert calls == ['access', 'guard']
|
||||
assert 'address changed' in json.loads((root/'repair-result.json').read_text())['detail']
|
||||
|
||||
|
||||
@@ -342,11 +401,11 @@ def test_independent_cbb_address_does_not_select_or_block_current_project(case):
|
||||
|
||||
|
||||
@pytest.mark.parametrize('status,complete,expected_safe', [
|
||||
('RESTORED_REVIEW_REQUIRED', True, False), ('DATABASE_BUSY', True, False),
|
||||
('UNKNOWN_DIALOG', True, False), ('UNCONFIRMED', True, False),
|
||||
('MISSING_HEALTHY_BACKUP', False, False), ('NATIVE_REPAIR_FAILED', False, False),
|
||||
('RESTORED_REVIEW_REQUIRED', True, True), ('DATABASE_BUSY', True, True),
|
||||
('UNKNOWN_DIALOG', True, True), ('UNCONFIRMED', True, True),
|
||||
('MISSING_HEALTHY_BACKUP', False, True), ('NATIVE_REPAIR_FAILED', False, True),
|
||||
('MISSING_HEALTHY_BACKUP', True, True), ('NATIVE_REPAIR_FAILED', True, True)])
|
||||
def test_physical_release_alone_does_not_authorize_queue(case, monkeypatch, status, complete, expected_safe):
|
||||
def test_failed_content_does_not_block_other_items_after_actual_release(case, monkeypatch, status, complete, expected_safe):
|
||||
from cbb_refresh_verify import native_repair, verify_runner as runner, library_lock
|
||||
from test_native_repair import complete_native_success
|
||||
request, _, address = case
|
||||
@@ -359,7 +418,7 @@ def test_physical_release_alone_does_not_authorize_queue(case, monkeypatch, stat
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', repair)
|
||||
monkeypatch.setattr(native_repair, 'repair_release_state', lambda req, target, result: result['release'])
|
||||
patch_verification_after_fault(monkeypatch, runner, lambda *a, **k: pytest.fail('nonrepair outcome reopened'))
|
||||
result = runner.run_verify(request)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status != 'PASS'
|
||||
assert result.safe_to_continue is expected_safe
|
||||
assert result.recovery_attempts[0]['status'] == status
|
||||
@@ -378,11 +437,11 @@ def test_successful_icdb_repair_then_version_choice_reports_partial_completion(c
|
||||
patch_verification_after_fault(monkeypatch, runner, lambda *a, **k: runner.VerifyResult('FAIL',
|
||||
error_category='PCB_VERSION_CHOICE_REQUIRED', stderr='PCB版本待选:最后用户保存/自动保存 2026/9/24 23:06',
|
||||
safe_to_continue=False, evidence_path=request.evidence_dir/'verify/result.json'))
|
||||
result = runner.run_verify(request)
|
||||
assert result.status == 'FAIL' and not result.safe_to_continue
|
||||
assert 'ICDB原生修复已完成' in result.stderr and '尚未校验通过' in result.stderr
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status == 'REPAIRED' and result.safe_to_continue
|
||||
assert '待单独校验' in result.stdout
|
||||
assert result.recovery_attempts[0]['native_status'] == 'REPAIRED'
|
||||
assert result.recovery_attempts[0]['status'] == 'PCB_VERSION_CHOICE_REQUIRED'
|
||||
assert result.recovery_attempts[0]['status'] == 'REPAIRED_UNVERIFIED'
|
||||
assert result.recovery_attempts[0]['validation_passed'] is False
|
||||
|
||||
|
||||
@@ -399,7 +458,7 @@ def test_user_chosen_pcb_history_is_not_reported_as_lossless_repair(case, monkey
|
||||
'choice': 'last_user_saved', 'date': '2026/9/24 23:06', 'confirm_sent': True, 'historical_restore': True}))
|
||||
return runner.VerifyResult('PASS', library_flag='GREEN', evidence_path=root/'result.json')
|
||||
patch_verification_after_fault(monkeypatch, runner, verify)
|
||||
result = runner.run_verify(request)
|
||||
assert result.status == 'PASS'
|
||||
assert result.recovery_attempts[0]['status'] == 'RESTORED_REVIEW_REQUIRED'
|
||||
assert result.recovery_attempts[0]['pcb_version']['choice'] == 'last_user_saved'
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status == 'REPAIRED' and result.library_flag == 'UNKNOWN'
|
||||
assert result.recovery_attempts[0]['status'] == 'REPAIRED_UNVERIFIED'
|
||||
assert not (request.evidence_dir/'verify').exists()
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Ownership scoping only: no native process or execution mutex is started."""
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def scope(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify.native_repair import RepairTarget
|
||||
from cbb_refresh_verify import native_management, native_engineering_identity
|
||||
library = tmp_path/'a/lib.lmc'
|
||||
library.parent.mkdir()
|
||||
library.touch()
|
||||
other = tmp_path/'b/lib.lmc'
|
||||
other.parent.mkdir()
|
||||
other.touch()
|
||||
project = tmp_path/'work/main.prj'
|
||||
project.parent.mkdir()
|
||||
project.write_text(f'KEY CentralLibrary "{library}"\n')
|
||||
target = RepairTarget(project, project.parent/'database')
|
||||
monkeypatch.setattr(native_management, '_retained_workers', [])
|
||||
monkeypatch.setattr(native_engineering_identity, '_retained_exports', [])
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_a, **_k: [])
|
||||
return target, library, other
|
||||
|
||||
|
||||
@pytest.mark.parametrize('kind', ['management', 'export'])
|
||||
@pytest.mark.parametrize('ownership', ['same', 'other', 'unknown'])
|
||||
def test_retained_native_ownership_is_scoped_only_with_proven_library(scope, monkeypatch, kind, ownership):
|
||||
from cbb_refresh_verify import maintenance_entry as entry
|
||||
target, library, other = scope
|
||||
claimed = library if ownership == 'same' else other if ownership == 'other' else None
|
||||
worker = SimpleNamespace(poll=lambda: None, cbb_library=claimed)
|
||||
if kind == 'management':
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_management._retained_workers', [worker])
|
||||
else:
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_engineering_identity._retained_exports',
|
||||
[(worker, {}, {'library': str(claimed)} if claimed else {})])
|
||||
if ownership == 'other':
|
||||
entry.assert_native_idle(target)
|
||||
else:
|
||||
with pytest.raises(Exception, match='(OWNER_ACTIVE|exporter)'):
|
||||
entry.assert_native_idle(target)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reference', ['missing', 'conflicting', 'invalid', 'empty_extra'])
|
||||
def test_unproven_library_does_not_exclude_retained_workers(scope, monkeypatch, reference):
|
||||
from cbb_refresh_verify import maintenance_entry as entry
|
||||
target, library, other = scope
|
||||
target.project.write_text('' if reference == 'missing' else
|
||||
f'KEY CentralLibrary "{library}"\nKEY CentralLibrary "{other}"' if reference == 'conflicting' else
|
||||
f'KEY CentralLibrary "{library}"\nKEY CentralLibrary ""' if reference == 'empty_extra' else
|
||||
'KEY CentralLibrary "missing.lmc"')
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_management._retained_workers',
|
||||
[SimpleNamespace(poll=lambda: None, cbb_library=other)])
|
||||
with pytest.raises(ValueError, match='OWNER_ACTIVE'):
|
||||
entry.assert_native_idle(target)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('source', ['project', 'pcb', 'database', 'lmc', 'shared', 'job', 'unknown', 'other'])
|
||||
def test_native_commands_include_target_and_shared_library_ownership(scope, monkeypatch, tmp_path, source):
|
||||
from cbb_refresh_verify import maintenance_entry as entry
|
||||
target, library, other = scope
|
||||
job = tmp_path/'request.json'
|
||||
job.write_text(json.dumps({'library': str(library)}))
|
||||
command = {
|
||||
'project': f'ExpeditionPCB.exe "{target.project}"',
|
||||
'pcb': f'ExpeditionPCB.exe "{target.project.parent / "PCB/board.pcb"}"',
|
||||
'database': f'iCDBProjectBackup.exe -icdb="{target.database}"',
|
||||
'lmc': f'LibraryManager.exe "{library}"',
|
||||
'shared': f'viewdraw.exe -project="{library.parent / "SymbolLibs/database"}"',
|
||||
'job': f'python.exe --management-worker "{job}"',
|
||||
'unknown': 'ExpeditionPCB.exe',
|
||||
'other': f'LibraryManager.exe "{other}"',
|
||||
}[source]
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_a, **_k:
|
||||
[{'pid': 987654, 'name': 'python.exe' if source == 'job' else 'ExpeditionPCB.exe',
|
||||
'command': command}])
|
||||
if source == 'other':
|
||||
entry.assert_native_idle(target)
|
||||
else:
|
||||
with pytest.raises(ValueError, match='OWNER_ACTIVE'):
|
||||
entry.assert_native_idle(target)
|
||||
|
||||
|
||||
def test_no_target_keeps_global_retained_owner_guard(scope, monkeypatch):
|
||||
from cbb_refresh_verify import maintenance_entry as entry
|
||||
_, _, other = scope
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_management._retained_workers',
|
||||
[SimpleNamespace(poll=lambda: None, cbb_library=other)])
|
||||
with pytest.raises(ValueError, match='OWNER_ACTIVE'):
|
||||
entry.assert_native_idle()
|
||||
@@ -31,12 +31,28 @@ def test_diagnostic_worker_closes_without_integration_save_or_config_edit(tmp_pa
|
||||
def forbidden(*args, **kwargs):
|
||||
pytest.fail('diagnosis attempted integration/save/config rewrite')
|
||||
monkeypatch.setattr(adapter, 'ensure_pcb_central_library', forbidden)
|
||||
monkeypatch.setattr(adapter, 'pcb_log_reports_integration_error', forbidden)
|
||||
original_read = Path.read_bytes
|
||||
def read_bytes(path):
|
||||
if path.name in ('ForwardAnnotation.txt', 'MsgBoxResponse.log', 'PartPkg.log'):
|
||||
pytest.fail('opening check read unrelated integration history')
|
||||
return original_read(path)
|
||||
monkeypatch.setattr(Path, 'read_bytes', read_bytes)
|
||||
monkeypatch.setattr('cbb_refresh_verify.integration.refresh_integration', forbidden)
|
||||
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.launch_save_helper', forbidden)
|
||||
monkeypatch.setattr('cbb_refresh_verify.pcb_bridge.wait_for_target_document', forbidden)
|
||||
monkeypatch.setattr('cbb_refresh_verify.failed_session.close_failed_document', forbidden)
|
||||
closes = []
|
||||
monkeypatch.setattr('cbb_refresh_verify.failed_session.close_failed_document',
|
||||
lambda job, **kw: closes.append(job) or {'status': 'CLOSED'})
|
||||
def check(job, pid, **kw):
|
||||
assert pid == 2 and kw['launcher_process'].pid == 1
|
||||
assert job['diagnostic_log_baseline']['started_ns']
|
||||
closes.append(job)
|
||||
kw['emit'](stage='diagnostic_wm_close')
|
||||
return {'status': 'PASS', 'native_processes_exited': True}
|
||||
monkeypatch.setattr('cbb_refresh_verify.diagnostic_open.check_target_window', check)
|
||||
result = execute()
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
assert VerifyResult(**result).status == 'PASS'
|
||||
assert result['status'] == 'PASS'
|
||||
assert len(closes) == 1
|
||||
assert not any(e['stage'] in ('save_start', 'saved_and_closed') for e in events)
|
||||
@@ -47,8 +63,13 @@ def test_diagnostic_close_failure_never_returns_healthy(tmp_path, monkeypatch):
|
||||
job, events, execute = diagnostic_worker(tmp_path, monkeypatch)
|
||||
job['diagnostic_only'] = True
|
||||
closes = []
|
||||
monkeypatch.setattr('cbb_refresh_verify.failed_session.close_failed_document',
|
||||
lambda *a, **kw: closes.append(a) or {'status': 'RETAINED'})
|
||||
def check(*a, **kw):
|
||||
closes.append(a)
|
||||
kw['emit'](stage='diagnostic_wm_close')
|
||||
raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED')
|
||||
monkeypatch.setattr('cbb_refresh_verify.diagnostic_open.check_target_window', check)
|
||||
monkeypatch.setattr('cbb_refresh_verify.failed_session.close_failed_startup',
|
||||
lambda *a, **kw: pytest.fail('must not send another close after WM_CLOSE'))
|
||||
with pytest.raises(RuntimeError, match='DIAGNOSTIC_CLOSE_UNCONFIRMED'):
|
||||
execute()
|
||||
assert len(closes) == 1
|
||||
@@ -71,6 +92,8 @@ def diagnostic_worker(tmp_path, monkeypatch):
|
||||
job, events, execute = exercise_worker(tmp_path, monkeypatch)
|
||||
(Path(job['pcb']).parent/'pcb.prj').write_text(
|
||||
'KEY CentralLibrary "' + job['lmc_file'] + '"\n', encoding='utf-8')
|
||||
monkeypatch.setattr('cbb_refresh_verify.diagnostic_open.check_target_window',
|
||||
lambda *a, **kw: {'status': 'PASS', 'native_processes_exited': True})
|
||||
return job, events, execute
|
||||
|
||||
|
||||
@@ -98,16 +121,51 @@ def test_diagnostic_runner_skips_importer_and_ready_verification(tmp_path, monke
|
||||
assert captured['diagnostic_only'] is True
|
||||
|
||||
|
||||
def test_diagnostic_waits_for_normal_exit_after_close_returns(tmp_path, monkeypatch):
|
||||
def test_diagnostic_cannot_pass_with_unconfirmed_process_exit(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import mentor_adapter as adapter
|
||||
job, events, execute = diagnostic_worker(tmp_path, monkeypatch)
|
||||
job['diagnostic_only'] = True
|
||||
observations = []
|
||||
def release(*a, **kw):
|
||||
observations.append(True)
|
||||
return {'safe_to_continue': len(observations) > 1}
|
||||
monkeypatch.setattr(adapter, 'cleanup_verify_processes', release)
|
||||
monkeypatch.setattr('cbb_refresh_verify.failed_session.close_failed_document',
|
||||
monkeypatch.setattr(adapter, 'cleanup_verify_processes',
|
||||
lambda *a, **kw: {'safe_to_continue': False, 'remaining_pids': [2]})
|
||||
with pytest.raises(RuntimeError, match='DIAGNOSTIC_CLOSE_UNCONFIRMED'):
|
||||
execute()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('when', ['document_ready', 'closing'])
|
||||
def test_diagnostic_checks_late_startup_errors_before_declaring_healthy(tmp_path, monkeypatch, when):
|
||||
from cbb_refresh_verify import mentor_adapter as adapter
|
||||
job, events, execute = diagnostic_worker(tmp_path, monkeypatch)
|
||||
job['diagnostic_only'] = True
|
||||
source = Path(job['pcb']).parent/'LogFiles/PCBLogFile.txt'
|
||||
def late_fault():
|
||||
source.parent.mkdir(exist_ok=True)
|
||||
source.write_text("The last server session on different server machine lost the connection to the database. "
|
||||
f"Machine:[fixture] Path:[{Path(job['project']).parent/'database'}] session:[current]", encoding='utf-8')
|
||||
closes = []
|
||||
def check(*a, **kw):
|
||||
if when == 'document_ready':
|
||||
late_fault()
|
||||
raise RuntimeError(kw['error_reader']())
|
||||
closes.append(True)
|
||||
kw['emit'](stage='diagnostic_wm_close')
|
||||
late_fault()
|
||||
return {'status': 'PASS', 'native_processes_exited': True}
|
||||
monkeypatch.setattr('cbb_refresh_verify.diagnostic_open.check_target_window', check)
|
||||
monkeypatch.setattr('cbb_refresh_verify.failed_session.close_failed_startup',
|
||||
lambda *a, **kw: {'status': 'CLOSED'})
|
||||
with pytest.raises(RuntimeError, match='ICDB_REPAIR_REQUIRED'):
|
||||
execute()
|
||||
assert len(closes) == (1 if when == 'closing' else 0)
|
||||
assert not any(e['stage'] == 'diagnostic_complete' for e in events)
|
||||
|
||||
|
||||
def test_diagnostic_snapshot_is_before_launch(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import mentor_adapter as adapter
|
||||
job, events, execute = diagnostic_worker(tmp_path, monkeypatch)
|
||||
job['diagnostic_only'] = True
|
||||
def launch(*a):
|
||||
assert job.get('diagnostic_log_baseline', {}).get('started_ns')
|
||||
from types import SimpleNamespace
|
||||
return SimpleNamespace(pid=1)
|
||||
monkeypatch.setattr(adapter, 'launch_pcb_process', launch)
|
||||
assert execute()['status'] == 'PASS'
|
||||
assert len(observations) >= 2
|
||||
@@ -0,0 +1,185 @@
|
||||
"""Project Backup is reached only after a current, released PCB startup fault."""
|
||||
from dataclasses import replace
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from test_maintenance_entry import case, no_native_launch, run_legacy_maintenance
|
||||
|
||||
|
||||
def fault_text(database):
|
||||
return ("The last server session on different server machine lost the connection to the database. "
|
||||
"Please use iCDB Project Backup 'Repair project' functionality to fix this issue. "
|
||||
f"Machine:[fixture-server] Path:[{database}] session:[fixture-current-session]")
|
||||
|
||||
|
||||
def install_probe(monkeypatch, result, calls):
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
def probe(request, **kwargs):
|
||||
assert request.diagnostic_only and not request.maintenance and not request.auto_repair
|
||||
assert not request.native_lm_verify and request.post_repair_proof is None
|
||||
calls.append('open')
|
||||
return result
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', probe)
|
||||
|
||||
|
||||
def forbid_backup(monkeypatch):
|
||||
from cbb_refresh_verify import native_repair
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair',
|
||||
lambda *a, **k: pytest.fail('Project Backup launched without a current matching startup fault'))
|
||||
|
||||
|
||||
def test_healthy_startup_skips_project_backup_even_with_old_address(case, monkeypatch):
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
request, _, address = case
|
||||
calls = []
|
||||
install_probe(monkeypatch, runner.VerifyResult('PASS', safe_to_continue=True), calls)
|
||||
forbid_backup(monkeypatch)
|
||||
result = run_legacy_maintenance(replace(request, native_lm_verify=True))
|
||||
assert calls == ['open']
|
||||
assert result.status == 'CHECKED' and result.library_flag == 'UNKNOWN'
|
||||
assert result.recovery_attempts == () and result.safe_to_continue
|
||||
assert address.read_bytes() == b'old server address - preserved'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('message', ['License unavailable', 'Could not run server',
|
||||
'COM 已连接,尚无目标文档', 'ICDB_REPAIR_REQUIRED',
|
||||
'PCB 文件损坏', 'Lost connection to server'])
|
||||
def test_generic_startup_errors_remain_failures_without_backup(case, monkeypatch, message):
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
request, _, _ = case
|
||||
calls = []
|
||||
failed = runner.VerifyResult('FAIL', stderr=message, safe_to_continue=True)
|
||||
install_probe(monkeypatch, failed, calls)
|
||||
forbid_backup(monkeypatch)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert calls == ['open'] and result == failed
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reason', ['shared', 'other_project', 'no_session', 'unreleased', 'timeout', 'cancelled'])
|
||||
def test_unmatched_or_unreleased_icdb_fault_never_enters_backup(case, monkeypatch, reason):
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
request, project, _ = case
|
||||
database = (project.parent/'database' if reason not in ('shared', 'other_project') else
|
||||
request.lmc_file.parent/('SymbolLibs/__ReusableBlocksSymb' if reason == 'shared'
|
||||
else 'ReusableBlocksLP/Other/Work/database'))
|
||||
if not database.exists(): database.mkdir(parents=True); (database/'icdb.dat').touch()
|
||||
text = fault_text(database)
|
||||
if reason == 'no_session': text = text.replace('session:[fixture-current-session]', '')
|
||||
failed = runner.VerifyResult('TIMEOUT' if reason == 'timeout' else
|
||||
'CANCELLED' if reason == 'cancelled' else 'FAIL', stderr=text,
|
||||
error_category='ICDB_REPAIR_REQUIRED', safe_to_continue=reason != 'unreleased')
|
||||
calls = []
|
||||
install_probe(monkeypatch, failed, calls)
|
||||
forbid_backup(monkeypatch)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert calls == ['open'] and result.status == failed.status
|
||||
assert not result.recovery_attempts
|
||||
assert result.safe_to_continue is failed.safe_to_continue
|
||||
|
||||
|
||||
def test_only_current_matching_fault_enters_native_maintenance(case, monkeypatch):
|
||||
from cbb_refresh_verify import verify_runner as runner, maintenance_entry as entry
|
||||
request, project, _ = case
|
||||
calls = []
|
||||
failed = runner.VerifyResult('FAIL', stderr=fault_text(project.parent/'database'),
|
||||
error_category='ICDB_REPAIR_REQUIRED', safe_to_continue=True)
|
||||
install_probe(monkeypatch, failed, calls)
|
||||
def maintain(req, *, diagnosed_target, startup_result, **kwargs):
|
||||
assert diagnosed_target.project == project and diagnosed_target.database == project.parent/'database'
|
||||
assert startup_result == failed
|
||||
calls.append('maintenance')
|
||||
return runner.VerifyResult('REPAIRED')
|
||||
monkeypatch.setattr(entry, 'run_existing_address_maintenance', maintain)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert calls == ['open', 'maintenance'] and result.status == 'REPAIRED'
|
||||
|
||||
|
||||
def test_old_saved_diagnosis_does_not_turn_generic_startup_failure_into_repair(case, monkeypatch):
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
request, project, _ = case
|
||||
root = request.evidence_dir/'old'; (root/'diagnostics').mkdir(parents=True)
|
||||
(root/'diagnostics/icdb-recovery.json').write_text(json.dumps({
|
||||
'error_code': 'ICDB_REPAIR_REQUIRED', 'native_message': fault_text(project.parent/'database')}))
|
||||
calls = []
|
||||
failure = runner.VerifyResult('FAIL', stderr='License unavailable', evidence_path=root/'result.json')
|
||||
install_probe(monkeypatch, failure, calls)
|
||||
forbid_backup(monkeypatch)
|
||||
assert run_legacy_maintenance(request) == failure
|
||||
assert calls == ['open']
|
||||
|
||||
|
||||
def test_native_admission_cannot_switch_the_diagnosed_database(case, monkeypatch):
|
||||
from cbb_refresh_verify import maintenance_entry as entry, native_repair
|
||||
from test_maintenance_entry import startup_failure
|
||||
request, project, _ = case
|
||||
forbid_backup(monkeypatch)
|
||||
result = entry.run_existing_address_maintenance(request,
|
||||
diagnosed_target=native_repair.RepairTarget(project, project.parent/'other'),
|
||||
startup_result=startup_failure(request))
|
||||
assert result.status == 'FAIL' and result.safe_to_continue
|
||||
assert result.error_category == 'ICDB_TARGET_MISMATCH'
|
||||
|
||||
|
||||
def test_equivalent_diagnosed_path_keeps_the_native_launch_path(case, monkeypatch):
|
||||
from cbb_refresh_verify import maintenance_entry as entry, native_repair
|
||||
from test_maintenance_entry import startup_failure
|
||||
from test_maintenance_diagnosis import inspection
|
||||
request, project, _ = case
|
||||
seen = []
|
||||
def inspect(target, *args, **kwargs):
|
||||
assert kwargs['inspection_only'] is True
|
||||
seen.append(target.project)
|
||||
return inspection(target)
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', inspect)
|
||||
alias = project.parent/'unused/..'
|
||||
result = entry.run_existing_address_maintenance(request,
|
||||
diagnosed_target=native_repair.RepairTarget(alias/project.name, alias/'database'),
|
||||
startup_result=startup_failure(request))
|
||||
assert result.status == 'CHECKED' and result.safe_to_continue, result
|
||||
assert seen == [project]
|
||||
|
||||
|
||||
def test_unsafe_startup_success_is_not_reported_as_healthy(case, monkeypatch):
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
request, _, _ = case
|
||||
install_probe(monkeypatch, runner.VerifyResult('PASS', safe_to_continue=False), [])
|
||||
forbid_backup(monkeypatch)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status == 'FAIL' and not result.safe_to_continue
|
||||
|
||||
|
||||
def test_report_write_failure_does_not_block_a_released_healthy_project(case, monkeypatch):
|
||||
from pathlib import Path
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
request, _, _ = case
|
||||
evidence = request.evidence_dir/'result.json'; evidence.parent.mkdir(); evidence.write_text('{}')
|
||||
install_probe(monkeypatch, runner.VerifyResult('PASS', evidence_path=evidence), [])
|
||||
forbid_backup(monkeypatch)
|
||||
write = Path.write_text
|
||||
def unavailable(path, *args, **kwargs):
|
||||
if path.name == 'maintenance-result.json': raise PermissionError('report unavailable')
|
||||
return write(path, *args, **kwargs)
|
||||
monkeypatch.setattr(Path, 'write_text', unavailable)
|
||||
result = run_legacy_maintenance(request)
|
||||
assert result.status == 'CHECKED' and result.safe_to_continue
|
||||
assert result.evidence_path == evidence and evidence.read_text() == '{}'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('before_open', [True, False])
|
||||
def test_cancelled_startup_diagnosis_never_requests_repair(case, monkeypatch, before_open):
|
||||
from threading import Event
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
from test_maintenance_entry import startup_failure
|
||||
request, _, _ = case
|
||||
stop = Event()
|
||||
if before_open: stop.set()
|
||||
calls = []
|
||||
def probe(req, **kw):
|
||||
calls.append('open'); stop.set()
|
||||
return startup_failure(req)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', probe)
|
||||
forbid_backup(monkeypatch)
|
||||
result = run_legacy_maintenance(request, stop=stop)
|
||||
assert result.status == 'CANCELLED' and result.safe_to_continue
|
||||
assert calls == ([] if before_open else ['open'])
|
||||
+75
-111
@@ -1,111 +1,75 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
|
||||
|
||||
def test_only_confirmed_maintenance_sets_explicit_flag(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
calls = []
|
||||
window = load_window(qtbot, tmp_path, monkeypatch,
|
||||
verifier=lambda req: (calls.append(req) or VerifyResult('FAIL', safe_to_continue=True)),
|
||||
status_refresher=lambda names, path: {name: 'PENDING' for name in names})
|
||||
window.search_edit.setText('Beta')
|
||||
window.verify_all(); qtbot.waitUntil(lambda: not window.busy)
|
||||
assert calls and calls[-1].maintenance is False
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.No)
|
||||
window.repair_icdb_all(); assert len(calls) == 1
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
|
||||
window.repair_icdb_all(); qtbot.waitUntil(lambda: not window.busy)
|
||||
assert len(calls) == 2 and calls[-1].maintenance is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize('marker_kind', ['valid', 'foreign', 'malformed'])
|
||||
def test_blocked_library_recovery_view_is_filesystem_only_and_maintenance_only(qtbot, tmp_path, monkeypatch, marker_kind):
|
||||
from cbb_refresh_verify.library_lock import LibraryLock, blocker_path, _owners, _guard
|
||||
from cbb_refresh_verify.ui.main_window import MainWindow
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
import cbb_refresh_verify.ui.main_window as ui
|
||||
library = tmp_path/'library/mentor.lmc'; library.parent.mkdir(); library.touch()
|
||||
(library.parent/'ReusableBlocksLP/IP101GR').mkdir(parents=True)
|
||||
with LibraryLock(library, safe_to_release=lambda: False) as lock: pass
|
||||
with _guard: _owners.pop(lock.key)['handle'].Close()
|
||||
marker = blocker_path(library)
|
||||
if marker_kind == 'malformed': marker.write_text('{}')
|
||||
if marker_kind == 'foreign':
|
||||
record = json.loads(marker.read_text()); record['library'] = str(tmp_path/'foreign/mentor.lmc')
|
||||
marker.write_text(json.dumps(record))
|
||||
monkeypatch.setattr(ui, 'preflight_skip_reason', lambda *a: None)
|
||||
calls = []
|
||||
window = MainWindow(reader=lambda *a: pytest.fail('blocked view called native reader'),
|
||||
verifier=lambda req: (calls.append(req) or VerifyResult('BLOCKED', safe_to_continue=False)),
|
||||
status_refresher=lambda *a: pytest.fail('unsafe view refreshed native status'), data_root=tmp_path/'data')
|
||||
qtbot.addWidget(window)
|
||||
window.lmc_edit.setText(str(library)); window.load_library()
|
||||
qtbot.waitUntil(lambda: not window.busy)
|
||||
assert window.release_library_button.isEnabled()
|
||||
if marker_kind != 'valid':
|
||||
assert window.loaded_path is None and not window.icdb_repair_button.isEnabled()
|
||||
return
|
||||
assert window.visible_records()[0].name == 'IP101GR'
|
||||
assert window.visible_records()[0].status == 'UNKNOWN'
|
||||
assert '未确认' in window.status_label.text()
|
||||
assert 'ICDB' in window.management_capability_label.text()
|
||||
assert '会话' in window.add_button.toolTip()
|
||||
window.select_visible_button.click()
|
||||
assert window.icdb_repair_button.isEnabled()
|
||||
assert not any(button.isEnabled() for button in (window.batch_button, window.selected_batch_button,
|
||||
window.backup_restore_button, window.add_button, window.update_button, window.remove_button))
|
||||
window.verify_all(); window.verify_selected(); window.restore_backup(); window.manage_cbb('remove')
|
||||
assert window.refresh_affected_records(['IP101GR']) is False
|
||||
assert calls == [] and not window.busy
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
|
||||
window.repair_icdb_all(); qtbot.waitUntil(lambda: not window.busy)
|
||||
assert len(calls) == 1 and calls[0].maintenance is True
|
||||
|
||||
|
||||
def test_maintenance_summary_exposes_first_failure_reason(qtbot, tmp_path):
|
||||
from cbb_refresh_verify.ui.main_window import MainWindow
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
window = MainWindow(data_root=tmp_path)
|
||||
qtbot.addWidget(window)
|
||||
window._global_icdb_run = True
|
||||
detail = 'MAINTENANCE_TARGET_UNCONFIRMED: PCB 引用与当前工程不一致'
|
||||
window._batch_done(([VerifyResult('BLOCKED', stderr=detail, safe_to_continue=False)], tmp_path/'batch.log'))
|
||||
assert detail in window.summary.text()
|
||||
assert detail in window.status_label.text()
|
||||
|
||||
|
||||
def test_safe_maintenance_reloads_authoritative_catalog_after_worker_finishes(qtbot, tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify.library_lock import LibraryLock, blocker_path, _owners, _guard
|
||||
from cbb_refresh_verify.ui.main_window import MainWindow
|
||||
from cbb_refresh_verify.models import LibraryReadResult, CbbRecord
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
import cbb_refresh_verify.ui.main_window as ui
|
||||
library = tmp_path/'library/mentor.lmc'; library.parent.mkdir(); library.touch()
|
||||
(library.parent/'ReusableBlocksLP/IP101GR').mkdir(parents=True)
|
||||
with LibraryLock(library, safe_to_release=lambda: False) as lease: pass
|
||||
with _guard: _owners.pop(lease.key)['handle'].Close()
|
||||
reads = []
|
||||
def reader(path):
|
||||
reads.append(path)
|
||||
return LibraryReadResult((CbbRecord('IP101GR', 'Reusable Blocks', status='READY'),))
|
||||
def verify(req):
|
||||
assert req.maintenance
|
||||
blocker_path(library).unlink() # Simulate normal cleanup at the injected boundary.
|
||||
return VerifyResult('PASS', library_flag='GREEN')
|
||||
monkeypatch.setattr(ui, 'preflight_skip_reason', lambda *a: None)
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
|
||||
window = MainWindow(reader=reader, verifier=verify, data_root=tmp_path/'data',
|
||||
status_refresher=lambda *a: pytest.fail('recovery view must reload after worker completion'))
|
||||
qtbot.addWidget(window)
|
||||
window.lmc_edit.setText(str(library)); window.load_library(); qtbot.waitUntil(lambda: not window.busy)
|
||||
assert reads == []
|
||||
window.search_edit.setText('IP101')
|
||||
window.repair_icdb_all()
|
||||
qtbot.waitUntil(lambda: not window.busy and bool(reads))
|
||||
assert window.visible_records()[0].status == 'READY'
|
||||
assert not window._maintenance_recovery_view and window.search_edit.text() == 'IP101'
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
|
||||
|
||||
def test_only_confirmed_maintenance_sets_explicit_flag(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
calls = []
|
||||
window = load_window(qtbot, tmp_path, monkeypatch,
|
||||
verifier=lambda req: (calls.append(req) or VerifyResult('FAIL', safe_to_continue=True)),
|
||||
status_refresher=lambda names, path: {name: 'PENDING' for name in names})
|
||||
window.search_edit.setText('Beta')
|
||||
window.verify_all(); qtbot.waitUntil(lambda: not window.busy)
|
||||
assert calls and calls[-1].maintenance is False
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.No)
|
||||
window.repair_icdb_all(); assert len(calls) == 1
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
|
||||
window.repair_icdb_all(); qtbot.waitUntil(lambda: not window._icdb_active())
|
||||
assert len(calls) == 2 and calls[-1].maintenance is True
|
||||
|
||||
|
||||
|
||||
|
||||
def test_maintenance_summary_exposes_first_failure_reason(qtbot, tmp_path):
|
||||
from cbb_refresh_verify.ui.main_window import MainWindow
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
window = MainWindow(data_root=tmp_path)
|
||||
qtbot.addWidget(window)
|
||||
window._global_icdb_run = True
|
||||
detail = 'MAINTENANCE_TARGET_UNCONFIRMED: PCB 引用与当前工程不一致'
|
||||
window._batch_done(([VerifyResult('BLOCKED', stderr=detail, safe_to_continue=False)], tmp_path/'batch.log'))
|
||||
assert detail in window.summary.detailedText()
|
||||
assert detail in window.output.toPlainText()
|
||||
assert detail not in window.summary.text()
|
||||
assert str(tmp_path) not in window.summary.text()
|
||||
assert detail not in window.status_label.text()
|
||||
assert '无法确认 1' in window.summary.text()
|
||||
|
||||
|
||||
def test_open_check_preserves_verify_state_without_starting_an_extra_catalog_read(qtbot, tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify.library_lock import LibraryLock, blocker_path, _owners, _guard
|
||||
from cbb_refresh_verify.ui.main_window import MainWindow
|
||||
from cbb_refresh_verify.models import LibraryReadResult, CbbRecord
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
import cbb_refresh_verify.ui.main_window as ui
|
||||
library = tmp_path/'library/mentor.lmc'; library.parent.mkdir(); library.touch()
|
||||
(library.parent/'ReusableBlocksLP/IP101GR').mkdir(parents=True)
|
||||
with LibraryLock(library, safe_to_release=lambda: False) as lease: pass
|
||||
with _guard:
|
||||
owner = _owners.pop(lease.key, None)
|
||||
if owner: owner['handle'].Close()
|
||||
reads = []
|
||||
def reader(path):
|
||||
reads.append(path)
|
||||
return LibraryReadResult((CbbRecord('IP101GR', 'Reusable Blocks', status='PENDING'),))
|
||||
def verify(req):
|
||||
assert req.maintenance
|
||||
blocker_path(library).unlink() # Simulate normal cleanup at the injected boundary.
|
||||
return VerifyResult('CHECKED')
|
||||
monkeypatch.setattr(ui, 'preflight_skip_reason', lambda *a: None)
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
|
||||
window = MainWindow(reader=reader, verifier=verify, data_root=tmp_path/'data',
|
||||
status_refresher=lambda *a: pytest.fail('An open check must not start a second native status read'))
|
||||
qtbot.addWidget(window)
|
||||
window.lmc_edit.setText(str(library)); window.load_library(); qtbot.waitUntil(lambda: not window.busy)
|
||||
assert len(reads) == 1
|
||||
window.search_edit.setText('IP101')
|
||||
window.repair_icdb_all()
|
||||
qtbot.waitUntil(lambda: not window._icdb_active())
|
||||
assert window.visible_records()[0].status == 'PENDING' and len(reads) == 1
|
||||
assert not window._maintenance_recovery_view and window.search_edit.text() == 'IP101'
|
||||
@@ -162,7 +162,7 @@ def test_update_failed_readd_keeps_removed_checkpoint_and_baseline(setup):
|
||||
request, adapter, source = setup
|
||||
adapter.fail_add = True
|
||||
result = execute(replace(request, operation='update', source=source), adapter)
|
||||
assert result.status == 'RECOVERY_REQUIRED' and not result.safe_to_continue
|
||||
assert result.status == 'RECOVERY_REQUIRED' and result.safe_to_continue
|
||||
assert adapter.records == []
|
||||
history = json.loads(result.evidence_path.read_text(encoding='utf-8'))['history']
|
||||
assert 'removed' in [x['stage'] for x in history]
|
||||
@@ -177,7 +177,7 @@ def test_lying_native_output_does_not_report_success(setup, operation):
|
||||
request = replace(request, operation=operation, source=source,
|
||||
name='New' if operation == 'add' else 'Block')
|
||||
result = execute(request, adapter)
|
||||
assert result.status == 'RECOVERY_REQUIRED' and not result.safe_to_continue
|
||||
assert result.status == 'RECOVERY_REQUIRED' and result.safe_to_continue
|
||||
|
||||
|
||||
def test_unreleased_native_owner_prevents_postread_and_verification(setup):
|
||||
@@ -265,7 +265,7 @@ def test_replaced_source_bytes_fail_identity_even_with_same_name(setup):
|
||||
return result
|
||||
adapter.add = wrong_source
|
||||
result = execute(replace(request, operation='add', name='New', source=source), adapter)
|
||||
assert result.status == 'RECOVERY_REQUIRED' and not result.safe_to_continue
|
||||
assert result.status == 'RECOVERY_REQUIRED' and result.safe_to_continue
|
||||
|
||||
|
||||
def test_update_success_requires_same_identity_and_no_implicit_partition_move(setup):
|
||||
|
||||
@@ -107,7 +107,8 @@ def test_native_registered_but_asset_mismatch_retains_recovery(transaction, corr
|
||||
root, request, state = transaction
|
||||
state['corrupt'] = corrupt
|
||||
result = execute(root, request)
|
||||
assert result.status == 'RECOVERY_REQUIRED' and not result.safe_to_continue
|
||||
assert result.status == 'RECOVERY_REQUIRED' and result.safe_to_continue
|
||||
assert execute(root, request).status == 'BLOCKED'
|
||||
|
||||
|
||||
def test_update_readd_failure_preserves_baseline_and_removed_checkpoint(transaction):
|
||||
@@ -115,7 +116,8 @@ def test_update_readd_failure_preserves_baseline_and_removed_checkpoint(transact
|
||||
assert execute(root, request).status == 'UPLOADED'
|
||||
state['fail_add'] = True
|
||||
result = execute(root, replace(request, operation='update'))
|
||||
assert result.status == 'RECOVERY_REQUIRED' and not result.safe_to_continue
|
||||
assert result.status == 'RECOVERY_REQUIRED' and result.safe_to_continue
|
||||
assert execute(root, replace(request, operation='update')).status == 'BLOCKED'
|
||||
assert (result.evidence_path.parent/'library-baseline-manifest.json').exists()
|
||||
assert not (result.evidence_path.parent/'library-before').exists()
|
||||
assert 'removed' in [entry['stage'] for entry in json.loads(result.evidence_path.read_text())['history']]
|
||||
|
||||
@@ -0,0 +1,571 @@
|
||||
"""Retry boundaries use fake native outcomes and temporary libraries only."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from test_management import setup, execute
|
||||
from test_management_native_transaction import transaction
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def isolated_mutex(monkeypatch):
|
||||
import win32event
|
||||
from uuid import uuid4
|
||||
original = win32event.CreateMutex
|
||||
suffix = uuid4().hex
|
||||
monkeypatch.setattr(win32event, 'CreateMutex', lambda security, owned, name:
|
||||
original(security, owned, name + suffix))
|
||||
|
||||
|
||||
def test_released_catalog_failure_does_not_retain_management_lease(setup, monkeypatch):
|
||||
from cbb_refresh_verify.native_management import NativeManagementAdapter
|
||||
from cbb_refresh_verify.library_lock import LibraryLock, blocker_path
|
||||
request, _, _ = setup
|
||||
adapter = NativeManagementAdapter(mentor_home=request.library.parent)
|
||||
monkeypatch.setattr(adapter, 'capabilities', lambda: {'remove': SimpleNamespace(supported=True)})
|
||||
monkeypatch.setattr(adapter, '_worker', lambda *_: {
|
||||
'success': False, 'safe_to_continue': True, 'detail': 'catalog read failed after exit'})
|
||||
result = execute(request, adapter)
|
||||
assert result.safe_to_continue
|
||||
assert not blocker_path(request.library).exists()
|
||||
with LibraryLock(request.library):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.mark.parametrize('busy', [False, True])
|
||||
def test_legacy_blocker_is_rechecked_before_management_without_inventing_new_owner(setup, monkeypatch, isolated_mutex, busy):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
request, adapter, _ = setup
|
||||
marker = locks.blocker_path(request.library)
|
||||
legacy = {'protocol': 'cbb-refresh-verify-library-lease', 'version': 1,
|
||||
'lease_id': 'eae80a06f23e4664b00c70b6bf81b01d', 'library': str(request.library),
|
||||
'status': 'OWNER_RELEASE_UNCONFIRMED', 'pid': 57076, 'time': '2026-11-04T09:43:50.830958+00:00'}
|
||||
marker.write_text(json.dumps(legacy), encoding='utf-8')
|
||||
before = marker.read_bytes()
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
|
||||
address = request.library.parent/'database/cdbsvr/sAddress.adr'
|
||||
if busy:
|
||||
address.parent.mkdir(parents=True); address.write_bytes(b'actual address')
|
||||
result = execute(request, adapter)
|
||||
assert result.safe_to_continue, 'No new native session was started by a blocked release check'
|
||||
assert result.evidence_path and result.evidence_path.is_file()
|
||||
if busy:
|
||||
assert result.status == 'BLOCKED' and adapter.calls == []
|
||||
assert marker.read_bytes() == before and address.read_bytes() == b'actual address'
|
||||
assert '地址' in result.detail
|
||||
else:
|
||||
assert result.status == 'REMOVED' and adapter.calls == ['remove']
|
||||
assert result.release_proof['status'] == 'RELEASE_CONFIRMED'
|
||||
archive = Path(result.release_proof['evidence_path']).with_name('blocker-before-0.json')
|
||||
assert archive.read_bytes() == before and not marker.exists()
|
||||
|
||||
|
||||
def test_busy_execution_channel_does_not_create_unreleased_management_owner(setup, monkeypatch):
|
||||
import win32con, win32event
|
||||
request, adapter, _ = setup
|
||||
monkeypatch.setattr(win32event, 'WaitForSingleObject', lambda *_: win32con.WAIT_TIMEOUT)
|
||||
result = execute(request, adapter)
|
||||
assert result.status == 'BLOCKED' and result.safe_to_continue and not adapter.calls
|
||||
assert result.evidence_path.is_file()
|
||||
|
||||
|
||||
|
||||
|
||||
def test_management_worker_prelaunch_failure_is_safe(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
job = tmp_path/'request.json'
|
||||
job.write_text(json.dumps({'operation': 'catalog', 'desktop': 'CbbManagement_test',
|
||||
'library': str(tmp_path/'lib.lmc')}), encoding='utf-8')
|
||||
monkeypatch.setattr(native, '_current_desktop', lambda: (None, 'wrong desktop'))
|
||||
assert native.management_worker_main(job) == 2
|
||||
result = json.loads((tmp_path/'result.json').read_text('utf-8'))
|
||||
assert result['safe_to_continue'] is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize('code,busy', [(5, False), (32, True), (33, True)])
|
||||
def test_coordination_open_error_preserves_access_failure(tmp_path, monkeypatch, code, busy):
|
||||
import pywintypes
|
||||
import win32file
|
||||
from cbb_refresh_verify.library_lock import LibraryLock, LibraryBusy
|
||||
def denied(*_):
|
||||
raise pywintypes.error(code, 'CreateFile', 'test failure')
|
||||
monkeypatch.setattr(win32file, 'CreateFile', denied)
|
||||
with pytest.raises((OSError, pywintypes.error)) as error:
|
||||
with LibraryLock(tmp_path/'lib.lmc'):
|
||||
pass
|
||||
assert isinstance(error.value, LibraryBusy) is busy
|
||||
|
||||
|
||||
def test_retained_checkpoint_lease_can_reprobe_exact_release(tmp_path):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
released = False
|
||||
lease = locks.LibraryLock(library, safe_to_release=lambda: released)
|
||||
try:
|
||||
with lease:
|
||||
pass
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
with locks.LibraryLock(library):
|
||||
pass
|
||||
released = True
|
||||
with locks.LibraryLock(library):
|
||||
pass
|
||||
assert not locks.blocker_path(library).exists()
|
||||
finally:
|
||||
owner = locks._owners.pop(lease.key, None)
|
||||
if owner:
|
||||
owner['handle'].Close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure', ['enumerate', 'cancel'])
|
||||
def test_owned_mapping_close_retries_after_transient_failure(monkeypatch, failure):
|
||||
from test_network_path import FakeWNet
|
||||
from cbb_refresh_verify.network_path import LibraryPathLease, NetworkPathError
|
||||
backend = FakeWNet()
|
||||
lease = LibraryPathLease.acquire(r'\\server\share\lib.lmc', backend=backend)
|
||||
method = 'mappings' if failure == 'enumerate' else 'cancel_mapping'
|
||||
original = getattr(backend, method)
|
||||
def broken(*_):
|
||||
raise OSError('temporary disconnect')
|
||||
monkeypatch.setattr(backend, method, broken)
|
||||
with pytest.raises(NetworkPathError):
|
||||
lease.close()
|
||||
monkeypatch.setattr(backend, method, original)
|
||||
lease.close()
|
||||
assert backend.cancelled == [lease.drive]
|
||||
|
||||
|
||||
def test_batch_mismatch_isolated_to_item(tmp_path):
|
||||
from cbb_refresh_verify.batch_status import BatchStatusSession
|
||||
from cbb_refresh_verify.status_bridge import BridgeResponseError, BridgeResult
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
class Bridge:
|
||||
def __init__(self): self.calls = []; self.restarts = 0
|
||||
def start(self): pass
|
||||
def close(self): pass
|
||||
def restart(self): self.restarts += 1
|
||||
def query(self, library, name, **kwargs):
|
||||
self.calls.append(name)
|
||||
if name == 'Bad': raise BridgeResponseError('CBB mismatch')
|
||||
return BridgeResult('PENDING', 'test')
|
||||
bridge = Bridge()
|
||||
results = BatchStatusSession(bridge).scan(['Bad', 'Good'], library, tmp_path/'scan.jsonl')
|
||||
assert [result.status for result in results] == ['MALFORMED', 'PENDING']
|
||||
assert bridge.calls == ['Bad', 'Good'] and bridge.restarts == 1
|
||||
|
||||
|
||||
def test_batch_cache_binds_exact_library_identity(tmp_path):
|
||||
from cbb_refresh_verify.batch_status import fingerprint_library
|
||||
first = tmp_path/'a/lib.lmc'; first.parent.mkdir(); first.write_bytes(b'same')
|
||||
second = tmp_path/'b/lib.lmc'; second.parent.mkdir(); second.write_bytes(b'same')
|
||||
stat = first.stat(); os.utime(second, ns=(stat.st_atime_ns, stat.st_mtime_ns))
|
||||
assert fingerprint_library(first).sha256 != fingerprint_library(second).sha256
|
||||
|
||||
|
||||
def test_timed_out_management_worker_releases_only_after_its_result(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
state = {'exit': None}
|
||||
worker = SimpleNamespace(poll=lambda: state['exit'], close=lambda: None)
|
||||
adapter = native.NativeManagementAdapter(mentor_home=tmp_path, worker_factory=lambda *_: worker)
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
evidence = tmp_path/'run'; evidence.mkdir()
|
||||
result = adapter._launch_worker({'library': str(library), 'operation': 'catalog',
|
||||
'desktop': 'CbbManagement_test', 'timeout_seconds': 0}, evidence)
|
||||
try:
|
||||
assert result['safe_to_continue'] is False
|
||||
assert adapter.release_confirmed(library) is False
|
||||
state['exit'] = 2
|
||||
assert adapter.release_confirmed(library) is False
|
||||
(evidence/'result.json').write_text(json.dumps({'success': False, 'safe_to_continue': True}))
|
||||
assert adapter.release_confirmed(tmp_path/'other.lmc') is False
|
||||
assert adapter.release_confirmed(library) is True
|
||||
assert worker not in native._retained_workers
|
||||
finally:
|
||||
if worker in native._retained_workers:
|
||||
native._retained_workers.remove(worker)
|
||||
|
||||
|
||||
def test_existing_library_manager_refusal_preserves_prelaunch_release(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
monkeypatch.setattr(native, '_current_desktop', lambda: (None, 'CbbManagement_test'))
|
||||
monkeypatch.setattr('cbb_refresh_verify.mentor_adapter._process_details', lambda *_: [(123, 'other')])
|
||||
with pytest.raises(RuntimeError) as error:
|
||||
native._catalog_native({'operation': 'catalog', 'desktop': 'CbbManagement_test'}, tmp_path)
|
||||
assert error.value.safe_to_continue is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize('stage,expected', [('catalog_before', 'REMOVED'), ('native_remove', 'BLOCKED')])
|
||||
def test_prewrite_failure_evidence_does_not_permanently_prevent_retry(setup, stage, expected):
|
||||
request, adapter, _ = setup
|
||||
checkpoint = request.evidence_dir/'interrupted/checkpoint.json'
|
||||
checkpoint.parent.mkdir(parents=True)
|
||||
checkpoint.write_text(json.dumps({'library': str(request.library), 'stage': 'complete',
|
||||
'status': 'BLOCKED', 'safe_to_continue': False, 'history': [{'stage': stage}]}), encoding='utf-8')
|
||||
result = execute(request, adapter)
|
||||
assert result.status == expected
|
||||
|
||||
|
||||
def test_scoped_release_includes_shared_database_addresses(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
address = tmp_path/'SymbolLibs/__ReusableBlocksSymb/cdbsvr/sAddress.adr'
|
||||
address.parent.mkdir(parents=True); address.write_bytes(b'preserve shared native address')
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
with locks._prove_library_released(library, block_name='Target'):
|
||||
pass
|
||||
assert address.read_bytes() == b'preserve shared native address'
|
||||
|
||||
|
||||
def test_valid_relocated_pending_checkpoint_does_not_block_snapshot(tmp_path):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
library = tmp_path/'copy/lib.lmc'; library.parent.mkdir(); library.touch()
|
||||
pending = locks.blocker_path(library).with_suffix('.pending')
|
||||
pending.write_text(json.dumps({'protocol': 'cbb-refresh-verify-library-lease', 'version': 1,
|
||||
'library': str(tmp_path/'source/lib.lmc'), 'pid': os.getpid(),
|
||||
'status': 'OPERATION_IN_PROGRESS', 'lease_id': 'a'*32, 'time': '2026-11-05'}))
|
||||
assert not locks.has_blocker(library)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('content', ['{torn json', '{"unrecognized":"metadata"}'])
|
||||
def test_unknown_checkpoint_release_archives_only_after_full_fresh_proof(tmp_path, monkeypatch, content):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_engineering_identity._process_snapshot', lambda: [])
|
||||
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
|
||||
marker = locks.blocker_path(library); marker.write_text(content)
|
||||
result = locks.release_retained_library(library, tmp_path/'evidence', block_name='Target')
|
||||
assert result['status'] == 'RELEASE_CONFIRMED'
|
||||
assert Path(result['evidence_path']).with_name('blocker-before-0.json').read_text() == content
|
||||
assert not marker.exists()
|
||||
assert library.with_name('.lib.cbb-upload.lock').exists()
|
||||
|
||||
|
||||
def test_unknown_checkpoint_cannot_use_selected_target_to_ignore_other_owners(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_engineering_identity._process_snapshot', lambda: [])
|
||||
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
|
||||
marker = locks.blocker_path(library); marker.write_bytes(b'{torn checkpoint')
|
||||
address = library.parent/'ReusableBlocksLP/Other/Work/database/cdbsvr/sAddress.adr'
|
||||
address.parent.mkdir(parents=True); address.write_bytes(b'preserve owner record')
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
locks.release_retained_library(library, tmp_path/'evidence', block_name='Target')
|
||||
assert marker.read_bytes() == b'{torn checkpoint'
|
||||
assert address.read_bytes() == b'preserve owner record'
|
||||
|
||||
|
||||
def test_status_cache_does_not_reuse_a_different_block_type(tmp_path):
|
||||
from cbb_refresh_verify.batch_status import BatchStatusSession
|
||||
from cbb_refresh_verify.status_bridge import BridgeResult
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
calls = []
|
||||
class Bridge:
|
||||
def query(self, library, name, **kwargs):
|
||||
calls.append(kwargs['block_type'])
|
||||
return BridgeResult('READY', 'test')
|
||||
session = BatchStatusSession(Bridge())
|
||||
session.scan(['Block'], library, tmp_path/'scan.jsonl', block_type='RULP')
|
||||
session.scan(['Block'], library, tmp_path/'scan.jsonl', block_type='Other', resume=True)
|
||||
assert calls == ['RULP', 'Other']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('case,relevant', [('other', False), ('prefix', False),
|
||||
('target', True), ('shared', True), ('worker_target', True), ('worker_other', False)])
|
||||
def test_release_owner_scope_uses_exact_paths_and_bound_worker_request(tmp_path, monkeypatch, case, relevant):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
|
||||
target = library.parent/'ReusableBlocksLP/Target/Work'
|
||||
locations = {'other': tmp_path/'other/Other.prj', 'prefix': target.with_name('WorkOld')/'Other.prj',
|
||||
'target': target/'Target.prj', 'shared': library.parent/'SymbolLibs/shared/database'}
|
||||
if case.startswith('worker_'):
|
||||
job = tmp_path/'worker.json'
|
||||
job.write_text(json.dumps({'library': str(library if case == 'worker_target' else tmp_path/'other/lib.lmc')}))
|
||||
name, command = 'python.exe', f'python.exe --management-worker "{job}"'
|
||||
else:
|
||||
name, command = 'ExpeditionPCB.exe', f'ExpeditionPCB.exe -project="{locations[case]}"'
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [
|
||||
{'pid': 123456, 'name': name, 'command': command, 'parent': 0}])
|
||||
if relevant:
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
with locks._prove_library_released(library, block_name='Target'):
|
||||
pass
|
||||
else:
|
||||
with locks._prove_library_released(library, block_name='Target'):
|
||||
pass
|
||||
|
||||
|
||||
def test_release_ignores_retained_management_worker_for_other_library(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import cbb_refresh_verify.native_management as native
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
other = SimpleNamespace(poll=lambda: None, cbb_library=str(tmp_path/'other.lmc'))
|
||||
monkeypatch.setattr(native, '_retained_workers', [other])
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
|
||||
with locks._prove_library_released(library):
|
||||
pass
|
||||
|
||||
|
||||
def test_retained_mapping_can_close_after_exact_release_proof():
|
||||
from test_network_path import FakeWNet
|
||||
from cbb_refresh_verify.network_path import LibraryPathLease
|
||||
backend = FakeWNet()
|
||||
lease = LibraryPathLease.acquire(r'\\server\share\lib.lmc', backend=backend)
|
||||
lease.retain_for_recovery()
|
||||
lease.close()
|
||||
assert backend.cancelled == []
|
||||
assert not lease.release_after_recovery({'status': 'RELEASE_CONFIRMED', 'library': r'\\other\share\lib.lmc'})
|
||||
assert lease.release_after_recovery({'status': 'RELEASE_CONFIRMED', 'library': r'\\server\share\lib.lmc'})
|
||||
lease.close()
|
||||
assert backend.cancelled == [lease.drive]
|
||||
|
||||
|
||||
def test_target_mapping_query_ignores_unrelated_enumeration_failure():
|
||||
from test_network_path import FakeWNet
|
||||
from cbb_refresh_verify.network_path import ensure_mapped_drive_visible
|
||||
class Backend(FakeWNet):
|
||||
def mapping(self, drive):
|
||||
assert drive == 'S:'
|
||||
return r'\\server\share'
|
||||
def mappings(self):
|
||||
raise OSError('unrelated drive enumeration failed')
|
||||
result = ensure_mapped_drive_visible('S:', r'\\server\share', backend=Backend())
|
||||
assert result['created'] is False
|
||||
|
||||
|
||||
def test_windows_mapping_enumeration_reserves_unavailable_drive():
|
||||
from cbb_refresh_verify.network_path import WindowsWNetBackend
|
||||
backend = WindowsWNetBackend.__new__(WindowsWNetBackend)
|
||||
def connection(drive, buffer, size):
|
||||
if drive == 'D:': return 5
|
||||
if drive == 'Y:':
|
||||
buffer.value = r'\\server\share'
|
||||
return 0
|
||||
return 2250
|
||||
backend._mpr = SimpleNamespace(WNetGetConnectionW=connection)
|
||||
backend._kernel32 = SimpleNamespace(GetLogicalDrives=lambda: 0)
|
||||
assert backend.mappings() == {'Y:': r'\\server\share'}
|
||||
assert 'D:' in backend.used_drives()
|
||||
|
||||
|
||||
def test_postnative_idle_failure_preserves_known_release(setup, isolated_mutex):
|
||||
from cbb_refresh_verify.management import run_management
|
||||
from cbb_refresh_verify.library_lock import LibraryLock
|
||||
request, adapter, _ = setup
|
||||
checks = []
|
||||
def idle(*_):
|
||||
checks.append(1)
|
||||
if len(checks) == 3:
|
||||
raise OSError('passive owner query unavailable after native exit')
|
||||
result = run_management(request, adapter=adapter, idle_check=idle)
|
||||
assert result.status == 'RECOVERY_REQUIRED' and result.safe_to_continue
|
||||
with LibraryLock(request.library):
|
||||
pass
|
||||
|
||||
|
||||
def test_final_report_failure_does_not_discard_release_result(setup, monkeypatch, isolated_mutex):
|
||||
import cbb_refresh_verify.management as management
|
||||
request, adapter, _ = setup
|
||||
original = management._write_json
|
||||
def write(path, record):
|
||||
if record.get('stage') == 'complete':
|
||||
raise OSError('evidence volume unavailable')
|
||||
return original(path, record)
|
||||
monkeypatch.setattr(management, '_write_json', write)
|
||||
result = execute(request, adapter)
|
||||
assert result.status == 'REMOVED' and result.safe_to_continue
|
||||
assert 'evidence volume unavailable' in result.detail
|
||||
|
||||
|
||||
def test_legacy_checkpoint_cannot_clear_other_target_owner(tmp_path, monkeypatch, isolated_mutex):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
|
||||
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
|
||||
marker = locks.blocker_path(library)
|
||||
locks._persist_blocker(library, lease_id='b'*32)
|
||||
original = marker.read_bytes()
|
||||
address = library.parent/'ReusableBlocksLP/Other/Work/database/cdbsvr/sAddress.adr'
|
||||
address.parent.mkdir(parents=True); address.write_bytes(b'keep actual owner address')
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
locks.release_retained_library(library, tmp_path/'evidence', block_name='Target')
|
||||
assert marker.read_bytes() == original
|
||||
assert address.read_bytes() == b'keep actual owner address'
|
||||
|
||||
|
||||
def test_release_proof_recovers_old_mapping_lease_and_transfers_shared_drive():
|
||||
import cbb_refresh_verify.network_path as network
|
||||
from test_network_path import FakeWNet
|
||||
backend = FakeWNet()
|
||||
old = network.LibraryPathLease.acquire(r'\\server\share\A\lib.lmc', backend=backend)
|
||||
current = network.LibraryPathLease.acquire(r'\\server\share\B\lib.lmc', backend=backend)
|
||||
old.retain_for_recovery(); old.close()
|
||||
proof = {'status': 'RELEASE_CONFIRMED', 'library': r'\\server\share\A\lib.lmc'}
|
||||
assert network.release_retained_path_leases(proof, current_lease=current) == 1
|
||||
assert backend.cancelled == [] and current.created
|
||||
current.close()
|
||||
assert backend.cancelled == [current.drive]
|
||||
|
||||
|
||||
def test_clean_failed_mutation_keeps_recovery_requirement_and_released_owner(setup, isolated_mutex):
|
||||
from dataclasses import replace
|
||||
from cbb_refresh_verify.management import run_management
|
||||
request, adapter, source = setup
|
||||
adapter.fail_add = True
|
||||
failed = execute(replace(request, operation='update', source=source, auto_verify=False), adapter)
|
||||
assert failed.status == 'RECOVERY_REQUIRED' and failed.safe_to_continue
|
||||
adapter.fail_add = False
|
||||
same = execute(replace(request, operation='add', source=source, auto_verify=False), adapter)
|
||||
assert same.status == 'BLOCKED'
|
||||
other = execute(replace(request, operation='add', name='Independent', source=source, auto_verify=False), adapter)
|
||||
assert other.status == 'UPLOADED' and other.safe_to_continue
|
||||
|
||||
|
||||
@pytest.mark.parametrize('history', [None, [], [{'stage': 'native_remove'}, {'stage': 'prepare_identity'}]])
|
||||
def test_prewrite_stage_alone_does_not_override_unknown_or_mutated_history(history):
|
||||
from cbb_refresh_verify.management import _may_have_mutated
|
||||
record = {'stage': 'prepare_identity', 'history': history, 'status': 'RUNNING'}
|
||||
assert _may_have_mutated(record)
|
||||
|
||||
|
||||
def test_library_checkpoint_binds_supervisor_creation_identity(tmp_path):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
locks._persist_blocker(library, lease_id='c'*32)
|
||||
record = json.loads(locks.blocker_path(library).read_text())
|
||||
assert record.get('supervisor_created')
|
||||
assert locks._recorded_supervisor_alive(record) is True
|
||||
assert locks._recorded_supervisor_alive({**record, 'supervisor_created': 'other process'}) is False
|
||||
legacy = {key: value for key, value in record.items() if key not in ('machine', 'supervisor_created')}
|
||||
assert locks._recorded_supervisor_alive(legacy) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('proof,safe', [
|
||||
({'safe_to_continue': True, 'process_created': False, 'worker_exited': True, 'remaining_pids': []}, True),
|
||||
({'safe_to_continue': True, 'process_created': True, 'worker_exited': True, 'remaining_pids': []}, False),
|
||||
({'safe_to_continue': True, 'process_created': False, 'worker_exited': False, 'remaining_pids': []}, False),
|
||||
(None, False)])
|
||||
def test_management_worker_launch_exception_uses_explicit_release_protocol(tmp_path, proof, safe):
|
||||
from cbb_refresh_verify.native_management import NativeManagementAdapter
|
||||
error = OSError('private desktop creation failed')
|
||||
error.worker_launch_release = proof
|
||||
def fail(*_): raise error
|
||||
adapter = NativeManagementAdapter(mentor_home=tmp_path, worker_factory=fail)
|
||||
with pytest.raises(OSError) as caught:
|
||||
adapter._launch_worker({'library': str(tmp_path/'lib.lmc'), 'operation': 'catalog',
|
||||
'desktop': 'CbbManagement_test', 'timeout_seconds': 1}, tmp_path)
|
||||
assert getattr(caught.value, 'safe_to_continue', None) is safe
|
||||
|
||||
|
||||
def test_native_add_passive_postcheck_failure_preserves_release(transaction, monkeypatch, isolated_mutex):
|
||||
from test_management_native_transaction import execute as execute_transaction
|
||||
root, request, state = transaction
|
||||
def unavailable(*_): raise OSError('passive target check unavailable')
|
||||
monkeypatch.setattr('cbb_refresh_verify.backup_recovery._idle_check', unavailable)
|
||||
result = execute_transaction(root, request)
|
||||
assert result.status == 'RECOVERY_REQUIRED' and result.safe_to_continue
|
||||
|
||||
|
||||
@pytest.mark.parametrize('case,safe', [('exit_output_error', True), ('popen_missing', True),
|
||||
('popen_denied', True), ('popen_unknown', False), ('timeout', False)])
|
||||
def test_remove_worker_preserves_exit_and_known_creation_rejection(tmp_path, monkeypatch, case, safe):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
job = tmp_path/'request.json'
|
||||
job.write_text(json.dumps({'operation': 'remove', 'desktop': 'CbbManagement_test',
|
||||
'mentor_home': str(tmp_path), 'library': str(tmp_path/'lib.lmc'), 'name': 'Block',
|
||||
'partition': 'Logical-Physical', 'timeout_seconds': 1}), encoding='utf-8')
|
||||
monkeypatch.setattr(native, '_current_desktop', lambda: (None, 'CbbManagement_test'))
|
||||
monkeypatch.setattr(native.NativeManagementAdapter, 'capabilities', lambda _: {
|
||||
'remove': SimpleNamespace(supported=True)})
|
||||
observed = {'waited': False}
|
||||
def wait(timeout):
|
||||
if case == 'timeout':
|
||||
raise native.subprocess.TimeoutExpired('fake CleanWGLib', timeout)
|
||||
observed['waited'] = True
|
||||
return 0
|
||||
def popen(*args, **kwargs):
|
||||
failures = {'popen_missing': FileNotFoundError('native binary disappeared'),
|
||||
'popen_denied': PermissionError('native creation denied'),
|
||||
'popen_unknown': OSError('unconfirmed process creation')}
|
||||
if case in failures:
|
||||
raise failures[case]
|
||||
return SimpleNamespace(pid=123456, wait=wait)
|
||||
monkeypatch.setattr(native.subprocess, 'Popen', popen)
|
||||
original_read = Path.read_bytes
|
||||
def read(path):
|
||||
if path.name == 'native-output.txt' and case == 'exit_output_error':
|
||||
assert observed['waited']
|
||||
raise OSError('native output storage unavailable after exit')
|
||||
return original_read(path)
|
||||
monkeypatch.setattr(Path, 'read_bytes', read)
|
||||
assert native.management_worker_main(job) == 2
|
||||
result = json.loads((tmp_path/'result.json').read_text('utf-8'))
|
||||
assert result['safe_to_continue'] is safe
|
||||
if case == 'exit_output_error':
|
||||
assert result['exit_code'] == 0 and 'storage unavailable' in result['detail']
|
||||
|
||||
|
||||
def test_add_source_missing_central_library_fails_before_capture_without_retaining(setup, monkeypatch, isolated_mutex):
|
||||
from dataclasses import replace
|
||||
import cbb_refresh_verify.native_management as native
|
||||
from cbb_refresh_verify.management import Catalog
|
||||
from cbb_refresh_verify.library_lock import LibraryLock, blocker_path
|
||||
request, _, source = setup
|
||||
adapter = native.NativeManagementAdapter(mentor_home=source.parent)
|
||||
monkeypatch.setattr(adapter, 'capabilities', lambda: {'add': SimpleNamespace(supported=True)})
|
||||
monkeypatch.setattr(adapter, 'catalog', lambda library, evidence: Catalog(library, 1, ()))
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_engineering_identity.capture_identity',
|
||||
lambda *_a, **_kw: pytest.fail('incomplete source reached native capture'))
|
||||
result = execute(replace(request, operation='add', name='New', source=source, auto_verify=False), adapter)
|
||||
assert result.status == 'UPLOAD_FAILED' and result.safe_to_continue
|
||||
assert 'CentralLibrary' in result.detail
|
||||
assert not blocker_path(request.library).exists()
|
||||
with LibraryLock(request.library):
|
||||
pass
|
||||
|
||||
|
||||
def test_prepared_transaction_storage_failure_preserves_capture_release(transaction, monkeypatch, isolated_mutex):
|
||||
from test_management_native_transaction import execute as execute_transaction
|
||||
root, request, _ = transaction
|
||||
def unavailable(*_a, **_kw): raise OSError('prepared transaction storage unavailable')
|
||||
monkeypatch.setattr('cbb_refresh_verify.management_transaction.prepare_transaction', unavailable)
|
||||
result = execute_transaction(root, request)
|
||||
assert result.status == 'UPLOAD_FAILED' and result.safe_to_continue
|
||||
assert 'prepared transaction storage unavailable' in result.detail
|
||||
|
||||
|
||||
@pytest.mark.parametrize('flag,relevant', [('-icdb', False), ('-icdb=', False),
|
||||
('-ICDB', True), ('-icdb=', True)])
|
||||
def test_release_owner_scope_parses_actual_edif_database_argument(tmp_path, flag, relevant):
|
||||
from cbb_refresh_verify.library_lock import _owner_matches_scope
|
||||
library = tmp_path/'Target/lib.lmc'
|
||||
database = library.parent/'Work/database'
|
||||
selected = database if relevant else tmp_path/'Other project/database'
|
||||
argument = flag + ('' if flag.endswith('=') else ' ') + f'"{selected}"'
|
||||
item = {'command': f'edifExporter.exe -schematic {argument} -isnap DxD'}
|
||||
assert _owner_matches_scope(item, library, (database,)) is relevant
|
||||
|
||||
|
||||
def test_release_owner_scope_does_not_match_edif_database_prefix(tmp_path):
|
||||
from cbb_refresh_verify.library_lock import _owner_matches_scope
|
||||
database = tmp_path/'Target/database'
|
||||
item = {'command': f'edifExporter.exe -schematic -icdb "{database}_old" -isnap DxD'}
|
||||
assert _owner_matches_scope(item, tmp_path/'Target/lib.lmc', (database,)) is False
|
||||
|
||||
|
||||
def test_same_target_recovery_gate_preserves_release_and_batch_continues(setup, isolated_mutex):
|
||||
from dataclasses import replace
|
||||
from cbb_refresh_verify.management import run_management_batch
|
||||
request, adapter, source = setup
|
||||
adapter.fail_add = True
|
||||
failed = execute(replace(request, operation='update', source=source, auto_verify=False), adapter)
|
||||
assert failed.status == 'RECOVERY_REQUIRED' and failed.safe_to_continue
|
||||
adapter.fail_add = False
|
||||
results = run_management_batch([
|
||||
replace(request, operation='add', source=source, auto_verify=False),
|
||||
replace(request, operation='add', name='Independent', source=source, auto_verify=False)],
|
||||
adapter=adapter, idle_check=lambda *_: None)
|
||||
assert [result.status for result in results] == ['BLOCKED', 'UPLOADED']
|
||||
assert all(result.safe_to_continue for result in results)
|
||||
+31
-20
@@ -80,23 +80,34 @@ def test_restart_shows_unfinished_without_starting_worker(qtbot, tmp_path):
|
||||
assert 'Block' in window.output.toPlainText()
|
||||
|
||||
|
||||
def test_persistent_owner_blocker_prevents_native_load_and_offers_checked_release(qtbot, tmp_path, monkeypatch):
|
||||
import pytest
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
from cbb_refresh_verify.ui.main_window import MainWindow
|
||||
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
|
||||
locks.blocker_path(library).write_text('{}', encoding='utf-8')
|
||||
window = MainWindow(reader=lambda _: pytest.fail('unconfirmed owner reopened'), data_root=tmp_path/'data')
|
||||
qtbot.addWidget(window)
|
||||
window.lmc_edit.setText(str(library)); window.load_library()
|
||||
qtbot.waitUntil(lambda: not window.busy)
|
||||
assert window.loaded_path is None
|
||||
assert window.release_library_button.isEnabled()
|
||||
assert '释放检查' in window.status_label.text()
|
||||
calls = []
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
|
||||
monkeypatch.setattr(locks, 'release_retained_library', lambda *a:
|
||||
(calls.append(a) or {'status': 'RELEASE_CONFIRMED', 'evidence_path': 'proof.json'}))
|
||||
window.release_library_button.click()
|
||||
qtbot.waitUntil(lambda: not window.busy)
|
||||
assert len(calls) == 1 and 'proof.json' in window.output.toPlainText()
|
||||
def test_previous_unsafe_result_allows_retry_and_requires_matching_release_proof(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
from cbb_refresh_verify.management import Capability, ManagementResult
|
||||
adapter = SimpleNamespace(capabilities=lambda: {op: Capability(True, 'available')
|
||||
for op in ('add', 'update', 'remove')})
|
||||
window = load_window(qtbot, tmp_path, monkeypatch, management_adapter=adapter)
|
||||
library = Path(window.mentor_lmc_path or window.loaded_path)
|
||||
from cbb_refresh_verify.network_path import LibraryPathLease
|
||||
current = LibraryPathLease(library, library)
|
||||
current.retain_for_recovery()
|
||||
window.library_lease = current
|
||||
window._management_unsafe = True
|
||||
window._management_unsafe_library = library
|
||||
window.select_visible_button.click()
|
||||
assert window.remove_button.isEnabled(), 'A historical flag must not disable the fresh release check'
|
||||
window.remove_button.click()
|
||||
requests = window.management_dialog.requests()
|
||||
assert requests and all(r.check_previous_release for r in requests)
|
||||
result = ManagementResult('remove', library, 'Beta', 'Logical-Physical', None,
|
||||
False, 'complete', 'BLOCKED', True, 'prelaunch failure')
|
||||
window._management_completed([result])
|
||||
assert window._management_library_unsafe(library), 'An input failure does not prove the previous session released'
|
||||
assert current._retained_for_recovery
|
||||
proof = {'status': 'RELEASE_CONFIRMED', 'library': str(library), 'evidence_path': 'proof.json'}
|
||||
window._management_completed([replace(result, release_proof=proof)])
|
||||
qtbot.waitUntil(lambda: window._mapping_busy == 0)
|
||||
assert not window._management_library_unsafe(library)
|
||||
assert not current._retained_for_recovery
|
||||
window.management_dialog.reject()
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ def test_management_prompts_for_manual_backup_and_cancel_starts_nothing(qtbot, t
|
||||
assert '完整备份与检查点' not in seen[0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('action', ['verify_all', 'verify_selected', 'repair_icdb_all'])
|
||||
@pytest.mark.parametrize('action', ['verify_all', 'verify_selected'])
|
||||
def test_batch_prompts_once_for_manual_backup_and_cancel_does_not_start(qtbot, tmp_path, monkeypatch, action):
|
||||
from cbb_refresh_verify.ui.main_window import MainWindow
|
||||
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
|
||||
|
||||
@@ -46,7 +46,8 @@ def test_add_timeout_publishes_cancellation_without_killing_native_owner(tmp_pat
|
||||
def poll(self): return None
|
||||
def close(self): pytest.fail('live worker must not be killed')
|
||||
adapter=native.NativeManagementAdapter(worker_factory=Running)
|
||||
result=adapter._launch_worker({'operation':'add','desktop':'CbbManagement_test','timeout_seconds':0},tmp_path)
|
||||
result=adapter._launch_worker({'operation':'add','desktop':'CbbManagement_test','timeout_seconds':0,
|
||||
'library':str(tmp_path/'library.lmc')},tmp_path)
|
||||
assert not result['safe_to_continue'] and (tmp_path/'cancel-native-add.signal').exists()
|
||||
assert len(native._retained_workers)==1
|
||||
|
||||
|
||||
Loaded 100 of 126 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user