Compare commits

..
Author SHA1 Message Date
阿白叔 a7df105616 fix: recreate batch resume action after release summary retirement 2026-11-09 14:34:28 +08:00
阿白叔 363a279157 Merge branch 'codex/review-ui-integration' into codex/review-residual-release
# Conflicts:
#	src/cbb_refresh_verify/ui/main_window.py
2026-11-09 14:10:30 +08:00
阿白叔 0fca6abb4e Merge branch 'codex/review-native-backend' into codex/review-ui-integration 2026-11-09 14:02:14 +08:00
阿白叔 342a7266c7 fix: retire result dialogs and clarify batch lifecycle 2026-11-09 13:51:32 +08:00
阿白叔 e8a1714d95 fix: clarify backend status freshness and scoped copy evidence 2026-11-09 13:50:04 +08:00
阿白叔 14c9a74bbf fix: show confirmed scope beside actual residual release results 2026-11-09 13:45:53 +08:00
阿白叔 651b539d0e fix: isolate unreadable residual sessions and bound release evidence 2026-11-09 10:39:16 +08:00
阿白叔 35daa77118 Merge branch 'codex/review-ui-integration' into codex/review-residual-release 2026-11-09 10:26:20 +08:00
阿白叔 e73f9c6edc Merge branch 'codex/review-native-backend' into codex/review-ui-integration 2026-11-09 10:26:13 +08:00
阿白叔 b7baa24b5e fix: identify foreign CBB checkpoints in release evidence 2026-11-09 10:26:09 +08:00
阿白叔 5eb4b2d7ed fix: persist release outcomes and guard active native backup sessions 2026-11-06 12:08:54 +08:00
阿白叔 d40192ee58 Merge branch 'codex/review-ui-integration' into codex/review-residual-release 2026-11-06 11:41:05 +08:00
阿白叔 3c1998f2ef Merge branch 'codex/review-native-backend' into codex/review-ui-integration 2026-11-06 11:41:03 +08:00
阿白叔 807aa26baf test: guard actual reads of unrelated CBB content 2026-11-06 11:41:00 +08:00
阿白叔 71029b19a2 Merge branch 'codex/review-ui-integration' into codex/review-residual-release 2026-11-06 11:36:21 +08:00
阿白叔 8c2c60fab1 fix: distinguish native outcomes from report and item recovery status 2026-11-06 11:36:19 +08:00
阿白叔 5b22787418 Merge branch 'codex/review-native-backend' into codex/review-ui-integration 2026-11-06 11:34:27 +08:00
阿白叔 679f33b8cc fix: keep prelaunch release-probe failures from stopping independent work 2026-11-06 11:34:25 +08:00
阿白叔 746e5b5145 Merge branch 'codex/review-native-backend' into codex/review-ui-integration 2026-11-06 11:21:21 +08:00
阿白叔 8eefecd9f0 fix: reconcile historical leases and record scoped native changes 2026-11-06 11:21:15 +08:00
阿白叔 d8156c57f0 Merge remote-tracking branch 'origin/main' into codex/review-native-backend 2026-11-06 11:14:58 +08:00
abaishu0730 959399b974 Merge pull request '审查拆分 1/4:只读占用探测与可取消任务队列' (#9) from codex/review-infrastructure into main 2026-11-06 10:25:10 +08:00
abaishu0730 46dae81190 Merge pull request 'docs: CBB Verify 全量扫描与阻塞分析(关联 #4)' (#5) from docs/scan-20261104-blockers into main 2026-11-06 10:20:23 +08:00
阿白叔 dc536da555 docs: record published review chain and completed verification 2026-11-05 23:33:46 +08:00
阿白叔 173dee1980 feat: add confirmed client release with durable consent and server protection 2026-11-05 23:31:36 +08:00
阿白叔 282be7be7f feat: integrate independent background checks and native management UI 2026-11-05 23:25:25 +08:00
阿白叔 da67de026f feat: integrate native diagnostics and coordinated CBB transactions 2026-11-05 23:18:00 +08:00
阿白叔 9e230e1a46 feat: add bounded read-only owner probes and cooperative native queue 2026-11-05 23:04:35 +08:00
abaishu0730 3dbfca0f44 docs: record full project scan and blocker analysis (#4) 2026-11-04 15:20:37 +08:00
45 changed files with 2277 additions and 195 deletions

No files matched your search

+2
View File
@@ -4,6 +4,8 @@
当前开发版本:**[v0.2.4-beta.1](docs/releases/v0.2.4-beta.1.md)(待评审、待现场验收)**。ICDB 批量检查在后台逐项运行,普通校验、管理和恢复可排队;READY 工程在实际执行前再次排除。检查不自动 Repair、Restore 或选择历史版本,也不代表中心库 READY。
历史释放记录会触发实际占用复核,确认释放后归档继续;会话释放不等于历史数据恢复。释放结果逐项保存;记录保存失败会单独显示,不把已确认释放的会话重新标成占用。可查看后台窗口的原生提示;仅对当前可识别的原生取消按钮提供确认操作。
自动流程不强杀原生会话;释放入口默认正常关闭。另有单独确认的“强制结束客户端”操作,仅限属于当前 Windows 用户和会话、归属及进程身份已确认的 PCB、Library Manager、DxDesigner/viewdraw、iCDB Project Backup 客户端。**ICDB 数据库服务器、后台导入器和归属未知的进程不允许强制结束**,即使命令指向当前库也不例外。客户端中其他已打开工程可能一并退出、未保存更改可能丢失;必须先记录确认名单,结束后重新证明库已释放,不能宣称数据库已修复。详见 [操作规程](SOP.md) 与 [版本说明](docs/releases/v0.2.4-beta.1.md)。下方日期记录为历史行为,以本说明为准。
本目录是独立的 CBB 中心库上传后校验工具,不属于 Part Replacement,也不负责 CBB 工程复制或中心库上传。
+10 -2
View File
@@ -12,13 +12,21 @@
新增拒绝同名冲突;更新先原生移除再导入,失败可能需要人工备份恢复;移除后重新读取目录确认。版本回退由操作员在原生界面选择,核对工程内容后单独校验。
## 历史记录、操作结果与报告
校验和管理遇到历史释放记录时,先复核实际进程、地址、独占文件及导出副本。确认释放后归档记录再继续,不以历史 JSON 本身判定真实占用;同目标未完成写入仍需核对,不自动重放。释放证明在管理首次原生调用前写入检查点,并在结果中保留。
管理操作生成目标工程、库配置和共享依赖的写前/写后主要文件清单及新增、删除、修改差分;不增加自动全库备份,也不声称检查了其他 CBB 内容。报告不可用与原生操作失败分别记录;本任务已释放时可继续独立项。
## 默认释放与单独确认的强制客户端操作
1. 停止新任务,预览当前库的工程、程序、PID 和历史记录。默认“确认释放”仅正常关闭作用域及当前身份已确认的客户端。未保存更改由操作员选择保存、放弃或保留;未知提示保持现场。
2. 数据库服务器可能服务同库其他用户。本工具不允许强制结束服务器,命令行指向本库也不构成独占授权;由库管理员核对用户和服务器状态。
3. “强制结束客户端”是另行确认的异常处理,只允许属于当前 Windows 用户和会话、已确认作用域和精确进程身份的 Expedition PCB、Library Manager、viewdraw、iCDB Project Backup 客户端。后台导入器、脚本宿主和归属未知的进程同样不在强制名单。
4. 警告明确告知客户端中其他已打开工程可能一并退出、未保存更改会丢失、写入中的工程可能需要恢复。执行前持久保存库外 `consent.json`,包含目标库、名单、创建身份和排除项;写入失败不执行。派发与最终进程句柄两处重新核对,PID 复用、用户/Windows 会话或范围变化时拒绝。
5. 客户端退出仅证明进程结束,不表示修复成功或 READY。服务器仍活跃或库状态未知时保留 PARTIAL、检查点和映射。只有完整的独立释放证明才解除匹配的历史记录;空进程列表本身不是释放证明。
4. 警告明确告知客户端中其他已打开工程可能一并退出、未保存更改会丢失、写入中的工程可能需要恢复。执行前持久保存库外 `consent.json`,包含目标库、名单、创建身份和排除项;写入失败不执行。派发处核对快照身份和原预览范围,最终句柄处核对创建时间、完整映像、用户 SID、Windows 会话和原生活动;变化时拒绝。
5. 预览和执行前检查进度与本轮 Output。Backup/Restore/Repair 进行中或状态无法确认时,不强制结束。可查看后台窗口的标题、输出和所在桌面;仅当当前窗口唯一存在已识别的 Cancel/取消按钮时,提供单独确认的原生取消。核对身份、用户会话和按钮快照后发送请求,再重新检查实际结果;没有识别到按钮时不猜菜单参数,不抢占前台。
6. 每项动作前后持久记录实际结果,异常保留已完成/未执行项。若最终记录保存失败但独立库释放证明已确认,界面明确提示记录失败并接受释放事实,不伪造新的占用。
7. 客户端退出仅证明进程结束,不表示修复成功或 READY。服务器仍活跃或库状态未知时保留 PARTIAL、检查点和映射。只有完整的独立释放证明才解除匹配的历史记录;空进程列表本身不是释放证明。
## 失败、证据和回退
+4
View File
@@ -16,6 +16,10 @@ ICDB 数据库服务器即使命令行指向当前中心库,也可能服务其
强制客户端动作必须先在库外证据目录持久写入确认名单、库和进程创建身份,再核对当前进程句柄、用户 SID 和 Windows 会话;记录失败或身份变化时不执行。客户端结束后仍需独立证明库已释放,重新打开工程并核对版本,必要时从人工一致备份或原生历史版本恢复。不能把“进程已结束”解释为“ICDB 已修复”。具体步骤见 [操作规程](../SOP.md)。
原生 Backup/Restore/Repair 进行中时不强制结束。释放预览可查看后台桌面上的原生输出;只有当前窗口唯一可识别的取消按钮才提供确认请求,发送后仍需重新检查是否停止。输出或取消按钮无法确认时保留现场,不猜测原生命令。
## 原生工程数据库 Repair
1. 启动本机的 iCDB Project Backup,并打开实际报错工程对应的 `.prj`。本机可用 PowerShell 命令形式如下,工程路径需替换为自己的隔离副本:
@@ -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,75 @@
{
"date": "2026-11-06",
"review_comments": [
275,
283,
286
],
"tests": {
"backend_full": {
"tests": 1385,
"errors": 0,
"failures": 0,
"skipped": 0,
"xml_file": "cbb-refresh-verify-795-backend-fixes-fixes.xml",
"xml_sha256": "b1af9d0025abbbbcf25fe134b02da980c9402dd22c0fa39e1f96b9f8124183ee"
},
"backend_read_guard": {
"tests": 9,
"errors": 0,
"failures": 0,
"skipped": 0,
"xml_file": "cbb-refresh-verify-795-backend-fixes-fixes-focused.xml",
"xml_sha256": "25dac539945d9ba71f2f9dafeb342e8f6110e094c62364369013e16e551b1f94"
},
"ui_integration": {
"tests": 29,
"errors": 0,
"failures": 0,
"skipped": 0,
"xml_file": "cbb-refresh-verify-795-ui-fixes-fixes.xml",
"xml_sha256": "9eeeff28c6fcd31d8f2e6d7fb38e0bdf01b0058ba7b7f9e5df2f173f71a4fca0"
},
"final_integrated": {
"tests": 1631,
"errors": 0,
"failures": 0,
"skipped": 0,
"xml_file": "cbb-refresh-verify-795-review-stack-fixes-full.xml",
"xml_sha256": "7d75049e4feecb4a6026062321d4a0fcb1c92e30f8f1ba23d11a4ea28ee19c9c"
},
"final_release_focused": {
"tests": 63,
"errors": 0,
"failures": 0,
"skipped": 0,
"xml_file": "cbb-refresh-verify-795-review-stack-fixes-focused.xml",
"xml_sha256": "469923faf0919ab2e3dffac183f2cb44a6b606aa15edacce92a88da1bde81424"
}
},
"compileall": "passed",
"git_diff_check": "passed",
"source_and_tests_sha256": "6fe6f02a3e0e731c4c9d2ff2f2c5e86e537139ef5e59f15441a9059522109526",
"post_full_suite_change": "GUI proof path comparison now uses lexical absolute paths, with no filesystem resolution; final 63 release regressions cover this one-line change. No further full-suite run was performed for this isolated UI comparison.",
"ui_preview": {
"file": "2026-11-06-release-preview.png",
"sha256": "e13645ed6b8234a2d46f6c462a262c7ef2092459c8e94f60a9fa273fd02c3613",
"mode": "offscreen simulated sessions; local Windows fonts loaded for visual inspection"
},
"red_regressions": {
"initial_backend": 6,
"initial_release": 12,
"ui_outcomes": 2,
"additional": "report storage, prelaunch evidence/probe timeout, cancel release propagation"
},
"scope": "Historical records trigger actual ownership proof; no automatic repair, server termination, native lock/address deletion or library backup.",
"native_cancel": "Only a unique enabled standard Cancel/取消 (IDCANCEL=2) on a current matching Project Backup window; identity, user/session, title, desktop and button rechecked; request does not prove cancellation.",
"not_verified": [
"actual Mentor native cancellation",
"actual Mentor force termination",
"field ICDB recovery",
"new frozen package",
"Windows 10",
"cross-machine shared-library concurrency"
]
}
@@ -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,21 @@
# PR #12 comment 313
## Behavior
Window inspection takes a Windows thread snapshot for the requested processes, finds the desktops assigned to those threads, and opens only those desktops. Failures are recorded per affected PID outside the real window list. Unrelated inaccessible desktops no longer disable healthy rows. Preview, cooperative close, forced close, native Cancel and save-prompt responses all use the same per-PID incomplete-read fact during their fresh action-time observation.
Unknown or active native writes still prohibit forced termination. The review's suggested blanket force override for unreadable windows is not implemented: exact identity and private-desktop ownership do not establish that Save/Repair has returned. A failed read names that session and can be retried, while other sessions remain actionable.
Disk evidence retains window identity and a UTF-8 output excerpt of at most 4,096 bytes, original output length and SHA-256. It omits child-control trees and duplicated native-activity output. The complete preview remains in memory for the existing details action.
Native Cancel carries the preview's `block_names` and checks the same Work + SymbolLibs scope before the exact-process/control checks. It no longer silently widens a scoped preview to the full library.
## Verification
The initial five regressions failed against the old implementation. After the fix, 116 residual/backend/UI/background-queue regressions passed; compileall and git diff --check passed. This includes a real controlled Windows window on a private CbbManagement desktop, read from another process, with clean fixture exit and no Mentor/native database actions.
The real fixture caught a platform limitation missed by API doubles: EnumThreadWindows silently omits windows on another desktop. The final implementation maps threads to desktop names and uses OpenDesktop/EnumDesktopWindows for only those mapped desktops. GetThreadDesktop's borrowed handle is never closed; owned OpenDesktop handles and the thread snapshot are closed.
Independent review and the full integrated-chain run are recorded at the final PR #13 tip. Older deep-review comments #297-#300 remain outside this explicitly selected scope. No candidate was rebuilt; real Mentor, Windows 10 and shared/network release scenarios remain unverified.
Review: https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/pulls/12#issuecomment-313
@@ -0,0 +1,7 @@
# PR #12 comment 348 follow-up
The review's process-isolation and oversized-output findings target the earlier `5eb4b2d` tree; both are addressed by `651b539` and remain covered by the real private-desktop and bounded-evidence regressions.
The remaining consent/result presentation gap is fixed here. The residual table retains its original six columns and adds confirmation scope and actual result. A row that was allowed at confirmation but rejected after a fresh activity/identity check now shows both facts beside its reason. The result message also counts confirmation-allowed rows and how many remain unreleased; it does not reinterpret preview consent as successful execution or bypass an active-write guard.
The new regression failed before the change. The release-dialog, residual follow-up and private-desktop regression group passed 35 tests. No production/native database action was performed. Integrated full validation is recorded at the PR #13 tip; no candidate build, merge or field acceptance is implied.
+9 -1
View File
@@ -12,7 +12,7 @@
## 强制客户端操作的契约
支持 Expedition PCB、Library Manager、viewdraw 和 iCDB Project Backup。操作员须知晓客户端中其他工程可能一并退出、未保存更改可能丢失、写入中的工程可能需要恢复。确认名单先持久记录为库外 `consent.json`,失败则不执行;派发与进程句柄两处复核,PID 复用、用户或 Windows 会话变化时拒绝。
支持 Expedition PCB、Library Manager、viewdraw 和 iCDB Project Backup。操作员须知晓客户端中其他工程可能一并退出、未保存更改可能丢失、写入中的工程可能需要恢复。确认名单先持久记录为库外 `consent.json`,失败则不执行;派发处复核身份和预览范围,句柄处复核创建时间、完整映像、用户 SID、Windows 会话与原生活动;变化时拒绝。
数据库服务器可能服务同库其他用户,命令行归属不构成独占授权。本工具不会强制结束任何 ICDB 服务器;它仍活跃或库状态未知时保留 PARTIAL,不能通过结束客户端伪造释放或修复成功。
@@ -29,3 +29,11 @@ PR #3 comment 249 的修复通过服务器排除、确认记录失败、PID 复
此前 r10 的原生隔离检查与界面排队证据只证明该候选包已记录的打开/释放行为,不能当成新强制客户端功能的现场验收。现场服务器失联恢复、ICDB 自动修复、Windows 10 和共享库跨机器并发仍未验收。
规范:[SOP](../../SOP.md)、[ICDB 手动修复手册](../ICDB-MANUAL-REPAIR-AND-UPDATE.md)。依赖和拆分顺序见 PR #3 的独立审查链。
## 2026-11-06 审查修正
- 校验和管理统一复核历史占用,释放经过先留证;PASS 不再重复计入无法确认。
- 管理增加目标工程及共享依赖的写后差分,明确不覆盖其他 CBB 内容;报告失败不制造未完成原生事务。
- 释放逐项持久保存,快照异常保留已完成/未执行项;报告保存失败与独立释放证明分别展示。
- 预览与强制执行前读取原生活动,正在 Backup/Restore/Repair 或无法确认的备份客户端不可强制结束;显示后台提示、映像路径与桌面,并对唯一已识别的 Cancel/取消按钮提供确认请求。取消后的实际状态仍需复核。
- 本轮自动测试不包含真实 Mentor 的强制结束或原生取消验收;ICDB 自动修复继续暂停。
@@ -9,3 +9,12 @@ Dependency rationale: library release imports native engineering identity and re
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 @@
# 评论 275:占用复核与变更报告
校验和管理共用历史释放记录复核:旧 JSON/内存租约触发实际进程、地址、独占文件和导出副本证明,不直接视为真实占用,不结束进程或执行 Repair。确认释放后归档旧记录并继续;失败且本项尚未启动时保留原记录,结果不会把本项标成未释放。校验结果兼容新增 release_proof,管理首次原生调用前保存释放经过;进程释放不等于历史数据已恢复。
写后仅对原先的目标 Work/Cert、中心库配置和共享依赖范围生成 SHA-256 差分,报告新增、删除、修改路径,并保存写后清单。范围沿用原有 ManifestScope.library,不增加整库备份或其他 CBB 内容哈希,不声称已证明所有其他 CBB 未被波及。已释放的部分失败也保留差分;仍有原生所有者时不为报告读取数据库。报告失败单独标为 UNCONFIRMED 并返回原因,不伪造未完成事务、不制造永久占用。
PASS 不再重复计入 unconfirmed。未改变实际原生写操作、人工备份政策或服务器保护,也没有恢复自动修复。
回归覆盖历史记录无占用/真实地址占用、首次原生调用前留证、目标及共享依赖差分、失败后差分、报告保存失败后可继续。完整回归和限制以最终验证记录及 PR 描述为准;真实 Mentor、Win10、跨机器共享库尚未因此取得新验收结论。
@@ -0,0 +1,11 @@
# 评论 286:释放留证与原生活动
释放前持久保存 NOT_STARTED 检查点,动作前保存 REQUESTING,动作后逐项保存实际状态,快照超时/中途异常也保留已执行和未执行项。保存失败停止继续发出动作;最终保存失败明确标为 PARTIAL/evidence_error,但独立且匹配当前库的释放证明仍被界面接受,不伪造占用。确认意图 consent_allowed 与实际 release_status 分别记录。
强制结束预览及精确句柄处重新读取原生窗口、进度和 Output;备份客户端进行中或状态无法确认时拒绝强制结束。普通客户端的保存模态窗口不直接等同于正在写库。服务器、导入器和未知身份仍排除。
窗口快照记录桌面,预览展示完整映像路径并提供原生提示/输出查看,支持原有保存选择。仅在当前用户/会话、精确进程身份匹配,且当前备份窗口唯一存在启用的 Cancel/取消(标准 IDCANCEL=2)控件时,提供单独确认的取消请求;执行前再次匹配标题、桌面、窗口和按钮并校验 PID。该请求复用串行准入和库外留证,不能当作已取消/已释放/已修复,也没有未知菜单或前台鼠标回退。没有可识别控件时入口禁用,保留状态供重新检查。
回归覆盖初次/末次快照超时、逐项记录、报告落盘失败、活动状态变化、原生取消按钮变化、确认与取消选择、已释放事实不被报告错误覆盖。测试使用临时文件和 fake 原生边界,没有终止或取消真实 Mentor 事务。原生取消在具体 Mentor 版本/现场窗口上的效果仍待隔离实机验收;ICDB 自动修复继续暂停。
回退代码不恢复已结束进程或原生事务;工程数据恢复仍需一致人工备份或明确选择的原生历史,不自动重放写操作。
+7
View File
@@ -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.
@@ -39,10 +39,18 @@ Files: `pyproject.toml`, `README.md`, `SOP.md`, `docs/ICDB-MANUAL-REPAIR-AND-UPD
- [x] Inventory final files against main and assign each file to the smallest dependency-closed review stage. Keep UI/release hooks unavailable until their backend exists; do not publish branches with broken normal operation.
- [x] Create ordered branches with one concrete feature commit per review unit, no rewriting the existing umbrella history.
- [x] Test each review stage using appropriate unit/full checks; preserve all final regressions and verify the final source tree against the umbrella snapshot.
- [ ] Push branches without force and create draft PRs with explicit base dependencies. Link them from #3 and record the splitting rationale.
- [x] Push branches without force and create draft PRs with explicit base dependencies. Link them from #3 and record the splitting rationale.
## Task 4: Delivery
- [ ] Commit and push the safety fixes and validation record to #3.
- [ ] Verify remote heads, PR descriptions and clean review worktrees. Keep #3 and issues open and do not merge #5.
- [ ] Report PR links, passing tests and remaining field-acceptance limits to the user.
- [x] Commit and push the safety fixes and validation record to #3.
- [x] Verify remote heads, PR descriptions and clean review worktrees. Keep #3 and issues open and do not merge #5.
- [x] Prepare the final user report with PR links, passing tests and remaining field-acceptance limits.
## Delivery evidence
- Review chain: [#9](https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/pulls/9) → [#10](https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/pulls/10) → [#11](https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/pulls/11) → [#12](https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/pulls/12). Each base/head was read back from the API and matched local branches; all remain Draft and open.
- #3 is the unmerged umbrella with the review chain linked. #5 was not merged; issues #2/#4 remain open.
- Complete suites: 491 / 1,376 / 1,545 / 1,601 passed for the four review stages; umbrella 1,601; focused release tests 43. Validation hashes and limits: `docs/releases/2026-11-05-pr249-review-validation.json`.
- Final implementation files match byte for byte; compile and diff checks pass. Only review worktrees were committed; the original running r10 test workspace was preserved.
- No new frozen package or field ICDB recovery acceptance is claimed. No actual Mentor client/server termination or production-library operation was performed.
@@ -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 启动一个桥进程”的启动开销。
+26 -2
View File
@@ -46,6 +46,16 @@ 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)
@@ -57,6 +67,7 @@ def main(argv: Sequence[str] | None = None) -> int:
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)
@@ -110,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,
@@ -117,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))
+10 -3
View File
@@ -107,7 +107,7 @@ 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'))
@@ -186,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:
@@ -196,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)
@@ -291,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 -1
View File
@@ -21,7 +21,7 @@ def maintenance_counts(results):
'checked_without_repair': sum(r.status == 'CHECKED' for r in results),
'issues_found': sum(r.error_category == 'ICDB_REPAIR_REQUIRED' for r in results),
'in_use': sum(r.error_category == 'ICDB_DATABASE_IN_USE' for r in results),
'unconfirmed': sum(r.status not in ('CHECKED', 'SKIPPED', 'CANCELLED')
'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),
+36 -1
View File
@@ -82,6 +82,28 @@ def has_retained_library(library):
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)
@@ -499,7 +521,7 @@ def _prove_library_released(library, block_name=None, *, allow_unknown_checkpoin
def release_retained_library(library, evidence_dir, *, block_name=None):
"""Explicit user-requested release, after fresh owner/address/access proof.
"""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.
@@ -537,6 +559,16 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
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))
@@ -548,6 +580,9 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
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')
+36 -6
View File
@@ -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)
@@ -73,6 +73,7 @@ class ManagementResult:
detail: str = ''
evidence_path: Path | None = None
release_proof: dict | None = None
change_report: dict | None = None
def validate_name(value):
@@ -186,6 +187,8 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
mutex = None
acquired = False
release_proof = None
original = None
change_report = None
def invoke(callback, *args):
nonlocal owner_safe
owner_safe = False
@@ -206,8 +209,33 @@ 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, release_proof)
request.source, request.auto_verify, 'complete', status, safe, detail, report, release_proof, change_report)
if report:
try:
_write_json(report, {**asdict(result), 'history': history, 'backup_policy': 'manual'})
@@ -256,10 +284,12 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired:
return finish('BLOCKED', '已有 CBB 校验/管理/恢复任务运行;本次未启动。')
from .library_lock import has_blocker, has_retained_library, release_retained_library
if (has_blocker(library) or has_retained_library(library) or request.check_previous_release
or unfinished_target and unfinished_target.get('safe_to_continue') is not True):
release_proof = release_retained_library(library, root/'previous-release')
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'):
-15
View File
@@ -160,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 退出均已确认。'}
+339 -91
View File
@@ -1,6 +1,7 @@
"""Preview and cooperatively close the exact native sessions a user confirms."""
from contextlib import contextmanager
import json
import hashlib
import os
from pathlib import Path
import re
@@ -31,9 +32,33 @@ def force_block_reason(row):
if (row.get('force_user_confirmed') is not True or not row.get('owner_sid')
or not isinstance(row.get('session_id'), int)):
return '未确认属于当前用户和 Windows 会话,不允许强制结束'
activity = row.get('native_activity', {})
if activity.get('status') in ('ACTIVE', 'UNCONFIRMED'):
return activity.get('detail', '原生操作状态未确认')+';请查看进展或请求原生取消后重新检查'
if name == 'icdbprojectbackup.exe' and activity.get('status') != 'IDLE':
return '备份/恢复/修复状态未确认,请重新检查'
return ''
def native_activity(name, windows, *, incomplete=None):
if incomplete or any(w['class'] == 'UNCONFIRMED' for w in windows):
return {'status': 'UNCONFIRMED', 'detail': '原生窗口读取不完整'}
if any((name.casefold() == 'icdbprojectbackup.exe' and not w['enabled'])
or any(c['class'].casefold() == 'msctls_progress32' for c in w['children']) for w in windows):
return {'status': 'ACTIVE', 'detail': '原生窗口显示操作进行中'}
if name.casefold() == 'icdbprojectbackup.exe':
main = [w for w in windows if w['class'].startswith('Afx:')
and w['title'].startswith('iCDB Project Backup')]
output = main[0].get('output') if len(main) == 1 else None
if not isinstance(output, str) or not output.strip():
return {'status': 'UNCONFIRMED', 'detail': '无法确认备份/恢复/修复输出'}
active = list(re.finditer(r'(?i)repairing|restoring|backing up|creating (?:a )?backup', output))
if active and max(output.rfind('Backup information loaded correctly.'),
output.rfind('Repair project error [')) < active[-1].start():
return {'status': 'ACTIVE', 'detail': '原生备份/恢复/修复尚未确认结束', 'output': output}
return {'status': 'IDLE', 'detail': '未观察到进行中的原生操作'}
@contextmanager
def _process_handle(pid, *, terminate=False):
import win32api, win32con
@@ -88,16 +113,85 @@ def _force_ownership(handle, pid):
and session == win32ts.ProcessIdToSessionId(os.getpid())}
class _WindowSnapshot(dict):
def __init__(self, pids):
super().__init__((pid, []) for pid in pids)
self.incomplete = {}
def _process_threads(pids):
import ctypes
from ctypes import wintypes
class ThreadEntry(ctypes.Structure):
_fields_ = [('size', wintypes.DWORD), ('usage', wintypes.DWORD), ('tid', wintypes.DWORD),
('pid', wintypes.DWORD), ('base', wintypes.LONG), ('delta', wintypes.LONG),
('flags', wintypes.DWORD)]
kernel = ctypes.WinDLL('kernel32', use_last_error=True)
kernel.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD]
kernel.CreateToolhelp32Snapshot.restype = wintypes.HANDLE
kernel.CloseHandle.argtypes = [wintypes.HANDLE]
for name in ('Thread32First', 'Thread32Next'):
function = getattr(kernel, name)
function.argtypes = [wintypes.HANDLE, ctypes.POINTER(ThreadEntry)]
function.restype = wintypes.BOOL
snapshot = kernel.CreateToolhelp32Snapshot(4, 0) # TH32CS_SNAPTHREAD
if snapshot == ctypes.c_void_p(-1).value:
raise ctypes.WinError(ctypes.get_last_error())
result = {pid: [] for pid in pids}
try:
entry = ThreadEntry(); entry.size = ctypes.sizeof(entry)
more = kernel.Thread32First(snapshot, ctypes.byref(entry))
while more:
if entry.pid in result:
result[entry.pid].append(int(entry.tid))
entry.size = ctypes.sizeof(entry)
more = kernel.Thread32Next(snapshot, ctypes.byref(entry))
if ctypes.get_last_error() != 18: # ERROR_NO_MORE_FILES
raise ctypes.WinError(ctypes.get_last_error())
finally:
kernel.CloseHandle(snapshot)
return result
def _thread_desktop_name(tid):
import ctypes
from ctypes import wintypes
user = ctypes.WinDLL('user32', use_last_error=True)
user.GetThreadDesktop.argtypes = [wintypes.DWORD]
user.GetThreadDesktop.restype = wintypes.HANDLE
user.GetUserObjectInformationW.argtypes = [wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID,
wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)]
user.GetUserObjectInformationW.restype = wintypes.BOOL
ctypes.set_last_error(0)
desktop = user.GetThreadDesktop(tid)
if not desktop:
if error := ctypes.get_last_error():
raise ctypes.WinError(error)
return None # A non-GUI thread need not have an assigned desktop.
# GetThreadDesktop returns a borrowed handle; never CloseDesktop it.
name, needed = ctypes.create_unicode_buffer(512), wintypes.DWORD()
if not user.GetUserObjectInformationW(desktop, 2, name, ctypes.sizeof(name), ctypes.byref(needed)):
raise ctypes.WinError(ctypes.get_last_error())
return name.value
def _window_error(snapshot, pid):
return getattr(snapshot, 'incomplete', {}).get(pid)
def _process_windows(pids):
if not pids: return {}
result = _WindowSnapshot(pids)
if not pids: return result
import win32api, win32con, win32gui, win32process, win32service
from .native_repair_ui import _native_output
result = {pid: [] for pid in pids}
observed = set()
def capture(hwnd, _=None):
pid = win32process.GetWindowThreadProcessId(hwnd)[1]
if pid not in result or hwnd in observed or not win32gui.IsWindowVisible(hwnd):
def capture(hwnd, _, *, pid, desktop_name):
if win32process.GetWindowThreadProcessId(hwnd)[1] != pid:
raise ValueError('窗口所属进程已变化')
if hwnd in observed or not win32gui.IsWindowVisible(hwnd):
return
if desktop_name is None:
raise ValueError('窗口所属桌面无法读取')
observed.add(hwnd)
children, documents = [], []
def child(handle, _):
@@ -111,36 +205,52 @@ def _process_windows(pids):
win32api.SetLastError(0)
win32gui.EnumChildWindows(hwnd, child, None)
window = {'hwnd': int(hwnd), 'title': win32gui.GetWindowText(hwnd),
'desktop': desktop_name,
'class': win32gui.GetClassName(hwnd), 'enabled': bool(win32gui.IsWindowEnabled(hwnd)),
'children': children, 'documents': documents, 'rect': list(win32gui.GetWindowRect(hwnd))}
if any(c['class'].casefold().startswith('richedit') for c in children):
window['output'] = _native_output([window])
result[pid].append(window)
win32api.SetLastError(0)
def incomplete():
for pid in result:
result[pid].append({'hwnd': 0, 'title': '窗口状态读取不完整', 'class': 'UNCONFIRMED',
'enabled': False, 'children': []})
try:
win32gui.EnumWindows(capture, None)
except Exception:
incomplete()
try:
desktops = win32service.GetProcessWindowStation().EnumDesktops()
except Exception:
incomplete()
threads = _process_threads(pids)
except Exception as error:
result.incomplete = {pid: str(error)[:500] for pid in pids}
return result
for name in desktops:
if name != 'Default' and not name.startswith(('CbbVerify_', 'CbbRepair_', 'CbbManagement_', 'CbbStatusRead_', 'CbbFlagRead_')):
continue
desktops = {}
for pid in pids:
if not threads.get(pid):
result.incomplete[pid] = '进程线程已退出或暂时无法读取'
for tid in threads.get(pid, ()):
try:
desktop = _thread_desktop_name(tid)
if desktop:
desktops.setdefault(desktop, set()).add(pid)
except Exception as error:
result.incomplete.setdefault(pid, str(error)[:500])
if not any(pid in members for members in desktops.values()):
result.incomplete.setdefault(pid, '窗口所属桌面暂时无法确认')
# EnumThreadWindows silently omits windows on other desktops. Enumerate
# only desktops actually assigned to the target processes' threads.
for name, members in desktops.items():
desktop = None
try:
desktop = win32service.OpenDesktop(name, 0, False, win32con.DESKTOP_READOBJECTS)
for hwnd in desktop.EnumDesktopWindows(): capture(int(hwnd))
except Exception:
incomplete()
win32api.SetLastError(0)
for hwnd in desktop.EnumDesktopWindows():
pid = None
try:
pid = win32process.GetWindowThreadProcessId(hwnd)[1]
if pid in members:
capture(hwnd, None, pid=pid, desktop_name=name)
except Exception as error:
for affected in (members if pid is None else {pid} & members):
result.incomplete.setdefault(affected, str(error)[:500])
except Exception as error:
for pid in members:
result.incomplete.setdefault(pid, str(error)[:500])
finally:
if desktop is not None: desktop.CloseDesktop()
if desktop is not None:
desktop.CloseDesktop()
return result
@@ -156,8 +266,10 @@ def _project_name(row, library):
return '当前库关联会话'
def close_target(name, windows):
def close_target(name, windows, *, incomplete=None):
"""No save/restore approval and no close against an unknown modal/window."""
if incomplete:
return None, '该会话窗口读取不完整,请重新检查:'+str(incomplete)
main = [w for w in windows if w['class'].startswith('Afx:') and (
name.casefold() == 'icdbprojectbackup.exe' and w['title'].startswith('iCDB Project Backup')
or name.casefold() == 'librarymanager.exe' and w['title'].startswith('Library Manager')
@@ -187,22 +299,46 @@ def close_target(name, windows):
return window, ('将正常关闭工程;未保存时等待确认' if window.get('documents') else '可正常关闭')
def _save_question(windows):
def _save_question(windows, *, incomplete=None):
if incomplete:
return None
for window in windows:
text = '\n'.join(c['text'] for c in window['children'] if c['class'] == 'Static')
buttons = {c['id']: c for c in window['children'] if c['class'] == 'Button' and c['enabled']}
if (window['class'] == '#32770' and 'Expedition' in window['title']
and re.search(r'\bsave\b', text, re.I) and re.search(r'changes|modified', text, re.I)
and set(buttons) == {6, 7, 2}):
return {'hwnd': window['hwnd'], 'text': text, 'buttons': buttons}
return {'hwnd': window['hwnd'], 'text': text, 'buttons': buttons,
'desktop': window.get('desktop', '')}
return None
def _cancel_question(name, windows, *, incomplete=None):
if (name.casefold() != 'icdbprojectbackup.exe'
or native_activity(name, windows, incomplete=incomplete)['status'] != 'ACTIVE'):
return None
candidates = []
for window in windows:
if not (window['class'].startswith('Afx:') or window['class'] == '#32770'):
continue
if not window['title'].startswith('iCDB Project Backup') or not window['enabled']:
continue
for button in window['children']:
if (button['class'] == 'Button' and button.get('id') == 2 and button.get('enabled')
and button.get('text', '').replace('&', '').strip() in ('Cancel', '取消')):
candidates.append({'hwnd': window['hwnd'], 'button': button,
'title': window['title'],
'desktop': window.get('desktop', '')})
return candidates[0] if len(candidates) == 1 else None
def inspect_residual_sessions(library, *, block_names=()):
from .library_lock import _owner_matches_scope, blocker_path, checkpoint_record, has_retained_library
library = Path(library).resolve()
if library.suffix.casefold() != '.lmc' or not library.is_file():
raise ValueError('请选择有效的中心库 .lmc 文件')
if library.suffix.casefold() != '.lmc':
raise ValueError('请选择中心库 .lmc 文件')
if not library.is_file():
raise ValueError('中心库路径当前不可见,请检查文件是否存在及网络盘映射后重新检查')
blocks = tuple(dict.fromkeys(str(name) for name in block_names))
if any(not name or name in ('.', '..') or any(c in name for c in '\\/:*?"<>|') for name in blocks):
raise ValueError('残留检查的工程名称无效')
@@ -222,15 +358,26 @@ def inspect_residual_sessions(library, *, block_names=()):
sessions = []
for row in candidates:
item = dict(row)
item['block_names'] = list(blocks)
error = _window_error(windows, row['pid'])
item.update(windows_incomplete=bool(error), window_read_error=error)
try:
item.update(_process_identity(row))
target, detail = close_target(row['name'], windows.get(row['pid'], [])) if row['scope_confirmed'] else (
target, detail = close_target(row['name'], windows.get(row['pid'], []), incomplete=error) if row['scope_confirmed'] else (
None, '归属未确认,请在原生窗口确认工程并关闭后重新检查')
item.update(can_close=target is not None, detail=detail)
except Exception as error:
item.update(can_close=False, detail=f'进程已变化或暂时无法确认:{error}')
except Exception as identity_error:
item.update(can_close=False, detail=f'进程已变化或暂时无法确认:{identity_error}')
item['project'] = _project_name(row, library) if row['scope_confirmed'] else '归属未确认'
item['prompt'] = _save_question(windows.get(row['pid'], [])) if row['scope_confirmed'] else None
item['prompt'] = _save_question(windows.get(row['pid'], []), incomplete=error) if row['scope_confirmed'] else None
observed = windows.get(row['pid'], [])
item['windows'] = observed
item['desktops'] = sorted({w.get('desktop', '') for w in observed if w.get('desktop')})
item['native_activity'] = native_activity(row['name'], observed, incomplete=error)
item['cancel_prompt'] = (_cancel_question(row['name'], observed, incomplete=error)
if row['scope_confirmed'] and item.get('force_user_confirmed') is True else None)
if any(name.startswith('Cbb') for name in item['desktops']) and not item['can_close']:
item['detail'] += ';窗口在后台,可查看原生提示并使用已提供的保存/取消操作'
item['force_block_reason'] = force_block_reason(item)
item['force_allowed'] = not item['force_block_reason']
if item['force_block_reason']:
@@ -260,7 +407,10 @@ def _request_close(row, *, stop=None):
identity = _handle_identity(handle)
if identity != {key: row.get(key) for key in ('created_handle', 'image')}:
return {'release_status': 'IDENTITY_CHANGED', 'detail': '进程身份已变化,未关闭'}
windows = _process_windows({row['pid']}).get(row['pid'], [])
snapshot = _process_windows({row['pid']})
windows, error = snapshot.get(row['pid'], []), _window_error(snapshot, row['pid'])
if error:
return {'release_status': 'WAITING', 'detail': '该会话窗口读取不完整,请重新检查:'+error}
if row['name'].casefold() == 'expeditionpcb.exe':
from .failed_session import _startup_snapshot, _cancel_target
for window in windows:
@@ -274,10 +424,13 @@ def _request_close(row, *, stop=None):
return {'release_status': 'RELEASED', 'detail': '已取消启动并退出'}
if stop is not None and stop.is_set():
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
windows = _process_windows({row['pid']}).get(row['pid'], [])
snapshot = _process_windows({row['pid']})
windows, error = snapshot.get(row['pid'], []), _window_error(snapshot, row['pid'])
if error:
break
if close_target(row['name'], windows)[0] is not None: break
break
target, detail = close_target(row['name'], windows)
target, detail = close_target(row['name'], windows, incomplete=error)
if target is None: return {'release_status': 'WAITING', 'detail': detail}
if stop is not None and stop.is_set():
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
@@ -308,6 +461,13 @@ def _force_close(row, *, stop=None):
if (not ownership['force_user_confirmed'] or
any(ownership[k] != row.get(k) for k in ('owner_sid', 'session_id'))):
return {'release_status': 'IDENTITY_CHANGED', 'detail': '用户或 Windows 会话已变化,未结束'}
snapshot = _process_windows({row['pid']})
activity = native_activity(row['name'], snapshot.get(row['pid'], []),
incomplete=_window_error(snapshot, row['pid']))
if reason := force_block_reason({**row, 'native_activity': activity}):
return {'release_status': 'WAITING', 'detail': reason, 'native_activity': activity}
if stop is not None and stop.is_set():
return {'release_status': 'CANCELLED', 'detail': '已停止释放,未强制结束'}
win32api.TerminateProcess(handle, 1)
exited = win32event.WaitForSingleObject(handle, 3000) == win32con.WAIT_OBJECT_0
return {'release_status': 'RELEASED' if exited else 'WAITING',
@@ -319,75 +479,162 @@ def _finish_library_release(library, evidence):
return release_retained_library(library, evidence)
def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False):
def _request_native_cancel(row, *, stop=None):
"""Only click the exact currently visible Cancel control the user confirmed."""
import win32con, win32gui, win32process
if row.get('scope_confirmed') is not True:
raise ValueError('取消目标归属未确认,请重新检查')
fresh = next((r for r in query_process_snapshot() if r['pid'] == row['pid']), None)
if fresh is None or any(fresh.get(k) != row.get(k) for k in ('created', 'command', 'executable', 'name')):
raise ValueError('取消目标身份已变化,请重新检查')
with _process_handle(row['pid']) as handle:
if _handle_identity(handle) != {k: row.get(k) for k in ('created_handle', 'image')}:
raise ValueError('取消目标身份已变化,请重新检查')
owner = _force_ownership(handle, row['pid'])
if not owner['force_user_confirmed'] or any(owner[k] != row.get(k) for k in ('owner_sid', 'session_id')):
raise ValueError('取消目标用户/会话已变化')
snapshot = _process_windows({row['pid']})
prompt = _cancel_question(row['name'], snapshot.get(row['pid'], []),
incomplete=_window_error(snapshot, row['pid']))
if not prompt or prompt != row.get('cancel_prompt'):
raise ValueError('原生取消按钮已变化,请重新检查')
button = prompt['button']
if win32process.GetWindowThreadProcessId(button['hwnd'])[1] != row['pid']:
raise ValueError('原生取消按钮归属已变化')
if stop is not None and stop.is_set():
return {'release_status': 'CANCELLED', 'detail': '已停止,未请求原生取消'}
win32gui.PostMessage(button['hwnd'], win32con.BM_CLICK, 0, 0)
return {'release_status': 'WAITING', 'detail': '已请求原生取消,需重新检查实际结果;未强制结束'}
def request_native_cancel(row, library, evidence_dir, *, stop=None):
# Reuse serialized admission, consent and incremental evidence for cancellation.
plan = {'library': str(library), 'sessions': [row], 'block_names': row.get('block_names', [])}
return release_residual_sessions(plan, evidence_dir, stop=stop, cancel_native=True)
def _session_evidence(row):
"""Keep the full preview in memory, but bound repeatedly written Output."""
value = dict(row)
if 'native_activity' in value:
value['native_activity'] = {k: v for k, v in value['native_activity'].items() if k != 'output'}
if 'windows' in value:
value['windows'] = []
for window in row['windows']:
saved = {k: window[k] for k in ('hwnd', 'title', 'class', 'desktop', 'enabled') if k in window}
output = window.get('output')
if isinstance(output, str):
data = output.encode('utf-8')
saved.update(output_excerpt=data[:4096].decode('utf-8', errors='ignore'),
output_bytes=len(data), output_sha256=hashlib.sha256(data).hexdigest(),
output_truncated=len(data) > 4096)
value['windows'].append(saved)
return value
def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, cancel_native=False):
library = Path(plan['library']).resolve()
root = Path(evidence_dir).resolve()/('sessions-'+uuid4().hex[:12])
if root.is_relative_to(library.parent) or library.parent.is_relative_to(root):
raise ValueError('释放记录需位于中心库之外')
root.mkdir(parents=True)
result = {'status': 'PARTIAL', 'library': str(library), 'sessions': [], 'force': force,
result = {'status': 'PARTIAL', 'library': str(library), 'sessions': [
{**row, 'release_status': 'NOT_STARTED', 'detail': '尚未执行',
'consent_allowed': not force_block_reason(row) if force else row.get('scope_confirmed') is True}
for row in plan['sessions']], 'force': force, 'cancel_native': cancel_native,
'evidence_path': str(root/'result.json'), 'previous_records': plan.get('previous_records', [])}
if force:
consent_path = root/'consent.json'
consent = {'version': 1, 'mode': 'force_document_clients', 'library': str(library),
'time_ns': time.time_ns(), 'sessions': [
{**row, 'force_allowed': not force_block_reason(row),
'force_block_reason': force_block_reason(row)} for row in plan['sessions']]}
with consent_path.open('x', encoding='utf-8') as stream:
json.dump(consent, stream, ensure_ascii=False, indent=2)
stream.flush(); os.fsync(stream.fileno())
result['consent_path'] = str(consent_path)
fresh = {r['pid']: r for r in query_process_snapshot()}
# Close native children first, so their supervisors can finish and drop leases.
ordered = sorted(plan['sessions'], key=lambda r: r['name'].casefold() in _WORKER_NAMES)
for original in ordered:
current = fresh.get(original['pid'])
outcome = {'release_status': 'RELEASED', 'detail': '已退出'}
if stop is not None and stop.is_set():
outcome = {'release_status': 'CANCELLED', 'detail': '已停止释放'}
elif current is not None:
from .library_lock import _owner_matches_scope
scoped = _owner_matches_scope(current, library, (library.parent,)) is True
if original.get('scope_confirmed') is not True or not scoped or original['pid'] == os.getpid():
outcome = {'release_status': 'WAITING', 'detail': '未在确认名单中证明属于当前库,未关闭;请重新检查'}
elif any(current.get(key) != original.get(key) for key in ('created', 'executable', 'command', 'name')):
outcome = {'release_status': 'IDENTITY_CHANGED', 'detail': '确认后进程身份已变化,未关闭'}
elif force and (reason := force_block_reason(original)):
outcome = {'release_status': 'WAITING', 'detail': reason, 'force_allowed': False}
else:
try: outcome = (_force_close if force else _request_close)(original, stop=stop)
except Exception as error:
outcome = {'release_status': 'WAITING', 'detail': str(error)}
result['sessions'].append({**original, **outcome})
by_pid = {r['pid']: r for r in result['sessions']}
result['sessions'] = [by_pid[r['pid']] for r in plan['sessions']]
# Launchers may exit only after the GUI child processed its close request.
after = {r['pid']: r for r in query_process_snapshot()}
remaining_windows = _process_windows({r['pid'] for r in result['sessions']
if r['release_status'] == 'WAITING' and r['pid'] in after})
for row in result['sessions']:
if row['release_status'] == 'WAITING' and row['pid'] not in after:
row.update(release_status='RELEASED', detail='已退出')
elif row['release_status'] == 'WAITING':
row['prompt'] = _save_question(remaining_windows.get(row['pid'], []))
if all(row['release_status'] == 'RELEASED' for row in result['sessions']) and not (stop and stop.is_set()):
def save():
from .management import _write_json
try:
result['report_saved'] = True
_write_json(root/'result.json', {**result, 'sessions': [_session_evidence(row) for row in result['sessions']]})
return True
except OSError as error:
result.update(status='PARTIAL', report_saved=False, evidence_error=str(error))
return False
if not save():
return result # No native actions without the initial checkpoint.
if force or cancel_native:
consent_path = root/'consent.json'
consent = {'version': 1, 'mode': 'cancel_native' if cancel_native else 'force_document_clients', 'library': str(library),
'time_ns': time.time_ns(), 'sessions': [
{**_session_evidence(row), 'force_allowed': not force_block_reason(row),
'cancel_allowed': bool(row.get('cancel_prompt')) and row.get('scope_confirmed') is True,
'force_block_reason': force_block_reason(row)} for row in plan['sessions']]}
try:
with consent_path.open('x', encoding='utf-8') as stream:
json.dump(consent, stream, ensure_ascii=False, indent=2)
stream.flush(); os.fsync(stream.fileno())
except OSError as error:
result['detail'] = f'确认记录保存失败,未执行:{error}'
save()
raise
result['consent_path'] = str(consent_path)
try:
fresh = {r['pid']: r for r in query_process_snapshot()}
blocks = plan.get('block_names', ())
roots = (tuple(library.parent/'ReusableBlocksLP'/b/'Work' for b in blocks)
+ (library.parent/'SymbolLibs',)) if blocks else (library.parent,)
# Close native children first; keep output rows in the original preview order.
ordered = sorted(result['sessions'], key=lambda r: r['name'].casefold() in _WORKER_NAMES)
for row in ordered:
current = fresh.get(row['pid'])
outcome = {'release_status': 'RELEASED', 'detail': '已退出'}
if stop is not None and stop.is_set():
outcome = {'release_status': 'CANCELLED', 'detail': '已停止释放'}
elif current is not None:
from .library_lock import _owner_matches_scope
scoped = _owner_matches_scope(current, library, roots) is True
if row.get('scope_confirmed') is not True or not scoped or row['pid'] == os.getpid():
outcome = {'release_status': 'WAITING', 'detail': '未在确认名单中证明属于当前库,未关闭;请重新检查'}
elif not row.get('created') or any(current.get(key) != row.get(key)
for key in ('created', 'executable', 'command', 'name')):
outcome = {'release_status': 'IDENTITY_CHANGED', 'detail': '确认后进程身份已变化,未关闭'}
elif force and (reason := force_block_reason(row)):
outcome = {'release_status': 'WAITING', 'detail': reason, 'force_allowed': False}
else:
row.update(release_status='REQUESTING', detail='正在请求原生操作,结果待确认')
if not save():
return result
try:
outcome = (_request_native_cancel(row, stop=stop) if cancel_native else
(_force_close if force else _request_close)(row, stop=stop))
except Exception as error:
outcome = {'release_status': 'WAITING', 'detail': str(error)}
row.update(outcome)
if not save():
return result # Preserve completed facts; stop further actions on storage failure.
after = {r['pid']: r for r in query_process_snapshot()}
remaining_windows = _process_windows({r['pid'] for r in result['sessions']
if r['release_status'] == 'WAITING' and r['pid'] in after})
for row in result['sessions']:
if row['release_status'] == 'WAITING' and row['pid'] not in after:
row.update(release_status='RELEASED', detail='已退出')
elif row['release_status'] == 'WAITING':
windows = remaining_windows.get(row['pid'], [])
error = _window_error(remaining_windows, row['pid'])
row.update(prompt=_save_question(windows, incomplete=error), windows=windows,
windows_incomplete=bool(error), window_read_error=error,
cancel_prompt=(_cancel_question(row['name'], windows, incomplete=error)
if row.get('force_user_confirmed') is True else None),
native_activity=native_activity(row['name'], windows, incomplete=error))
if all(row['release_status'] == 'RELEASED' for row in result['sessions']) and not (stop and stop.is_set()):
result['proof'] = _finish_library_release(library, root/'library-proof')
proof = result['proof']
if (proof.get('status') != 'RELEASE_CONFIRMED'
or Path(proof.get('library', '')).resolve() != library):
raise ValueError('释放证明与当前库不一致')
result['status'] = 'RELEASE_CONFIRMED'
except Exception as error:
result['detail'] = str(error)
try:
(root/'result.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), 'utf-8')
except OSError as error:
result['evidence_error'] = str(error)
except BaseException as error:
result.update(status='PARTIAL', detail=f'{type(error).__name__}: {error}')
if not isinstance(error, Exception):
raise
finally:
save()
return result
def release_residual_sessions(plan, evidence_dir, *, stop=None, force=False):
def release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, cancel_native=False):
import win32con, win32event
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = False
@@ -401,7 +648,7 @@ def release_residual_sessions(plan, evidence_dir, *, stop=None, force=False):
return {'status': 'PARTIAL', 'library': plan['library'], 'sessions': [
{**r, 'release_status': 'WAITING', 'detail': '其它批次尚在执行;请停止该批次后重试'}
for r in plan['sessions']], 'detail': '未取得执行通道,未关闭任何进程。'}
return _release_residual_sessions(plan, evidence_dir, stop=stop, force=force)
return _release_residual_sessions(plan, evidence_dir, stop=stop, force=force, cancel_native=cancel_native)
finally:
if acquired: win32event.ReleaseMutex(mutex)
mutex.Close()
@@ -431,7 +678,8 @@ def _answer_save_question(row, choice):
with _process_handle(row['pid']) as handle:
if _handle_identity(handle) != {k: row.get(k) for k in ('created_handle', 'image')}:
raise ValueError('进程已变化,请重新检查')
prompt = _save_question(_process_windows({row['pid']}).get(row['pid'], []))
snapshot = _process_windows({row['pid']})
prompt = _save_question(snapshot.get(row['pid'], []), incomplete=_window_error(snapshot, row['pid']))
if not prompt or prompt != row.get('prompt'):
raise ValueError('原生提示已变化,请重新检查')
button = prompt['buttons'][choice]
+59 -11
View File
@@ -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:
@@ -271,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
@@ -329,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):
+46 -9
View File
@@ -99,7 +99,6 @@ class MainWindow(QWidget):
self._management_unsafe_libraries = set()
self._management_operation_library = None
self._maintenance_recovery_view = False
self._reload_after_maintenance = False
self._reimport_offers = ()
self._batch_requests = ()
self._batch_records = {}
@@ -133,6 +132,10 @@ class MainWindow(QWidget):
self._mapping_auto_idle = False
self._mapping_finish_waiters = []
self._closing = self._close_ready = False
self.close_wait_timer = QTimer(self)
self.close_wait_timer.setSingleShot(True)
self.close_wait_timer.setInterval(120_000)
self.close_wait_timer.timeout.connect(self._show_close_wait_notice)
from cbb_refresh_verify.operation_queue import NativeQueue
self.native_queue = NativeQueue()
self.icdb_task = None
@@ -463,6 +466,12 @@ class MainWindow(QWidget):
self._finished()
pending = getattr(self, '_resume_batch', None)
if pending and pending['released']:
if getattr(self, 'summary', None) is None:
self.summary = self._new_result_summary('_batch_summary')
self.summary.setWindowTitle('继续未执行项')
self._resume_batch_action = self.summary.addButton('继续未执行项', QMessageBox.ActionRole)
self._resume_batch_action.clicked.connect(self._resume_released_batch)
self._update()
self.summary.setText('会话已释放,可以继续未执行项。')
self.summary.show()
@@ -584,7 +593,6 @@ class MainWindow(QWidget):
mapped_drive=getattr(self.library_lease, 'drive', ''),
mapped_remote_root=getattr(self.library_lease, 'remote_root', '')))
previous[record.name] = str(result.evidence_path)
self._reload_after_maintenance = False
if getattr(self, 'summary', None): self.summary.close()
self._open_management_dialog(requests, recovery_from=previous)
@@ -760,7 +768,7 @@ class MainWindow(QWidget):
if hasattr(task, 'summary'):
prefix = '已更新的工程:'+', '.join(sorted(task.invalidated))+'。下列为此前检查记录。\n'
task.summary.setDetailedText(prefix+task.summary.detailedText())
if names & getattr(task, 'recovery_names', set()):
if names & getattr(task, 'recovery_names', set()) and hasattr(task, 'recovery_action'):
task.recovery_action.setEnabled(False)
task.recovery_action.setToolTip('工程已有后续管理操作,请重新检查。')
self._reimport_offers = tuple(offer for offer in self._reimport_offers if offer[0].block_name not in names
@@ -860,7 +868,7 @@ class MainWindow(QWidget):
self.icdb_phase.setText(text)
if not self.busy: self.status_label.setText(text)
self.output.append(text+'\n'+str(task.report or task.report_error))
summary = QMessageBox(self); self.icdb_summary = summary
summary = self._new_result_summary('icdb_summary')
task.summary = summary
if not self.busy: self.summary = summary
summary.setWindowTitle('ICDB 批量检查结果'); summary.setText(text)
@@ -1398,6 +1406,30 @@ class MainWindow(QWidget):
if cell is not None:
cell.setBackground(QColor('#E8F5E9'))
def _new_result_summary(self, attribute):
previous = getattr(self, attribute, None)
if previous is not None:
previous.close()
summary = QMessageBox(self)
setattr(self, attribute, summary)
summary.setAttribute(Qt.WA_DeleteOnClose)
summary.finished.connect(lambda _: self._forget_result_summary(summary))
return summary
def _forget_result_summary(self, summary):
if getattr(self, '_batch_summary', None) is summary:
self._reimport_summary_action = None
self._residual_release_action = None
self._resume_batch_action = None
for attribute in ('summary', '_batch_summary', 'icdb_summary'):
if getattr(self, attribute, None) is summary:
setattr(self, attribute, None)
for task in self.icdb_tasks:
if getattr(task, 'summary', None) is summary:
del task.summary
if hasattr(task, 'recovery_action'):
del task.recovery_action
def _batch_done(self, outcome):
results, report = outcome[:2]
failure_report = failure_report_path(report) if report is not None else '未写入'
@@ -1459,7 +1491,7 @@ class MainWindow(QWidget):
text += guidance
status_text += guidance
self.status_label.setText(status_text.replace('\n', ' ')); self.output.append(text)
self.summary = QMessageBox(self)
self.summary = self._new_result_summary('_batch_summary')
self.summary.setWindowTitle('ICDB 批量检查结果' if self._global_icdb_run else 'CBB 校验结果')
self.summary.setText(status_text)
self.summary.setDetailedText(text)
@@ -1529,10 +1561,6 @@ class MainWindow(QWidget):
self.version_dialog.reject()
self.version_dialog = None
self.busy = False; self._update()
if self._reload_after_maintenance:
from PySide6.QtCore import QTimer
self._reload_after_maintenance = False
QTimer.singleShot(0, self.load_library)
def open_logs(self):
self.data_root.mkdir(parents=True, exist_ok=True); os.startfile(str(self.data_root))
@@ -1554,6 +1582,9 @@ class MainWindow(QWidget):
else:
self._closing = True
self.busy = True; self._update()
self.setWindowTitle('CBB 刷新校验 · 等待任务安全结束')
self.status_label.setText('正在等待当前操作安全结束,完成后关闭。')
self.close_wait_timer.start()
retained = None
if self._native_backup_session is not None:
self.native_backup_timer.stop()
@@ -1566,6 +1597,11 @@ class MainWindow(QWidget):
self._close_when_idle()
event.ignore()
def _show_close_wait_notice(self):
if self._closing and not self._close_ready:
self.setWindowTitle('CBB 刷新校验 · 仍在等待任务安全结束')
self.status_label.setText('当前操作尚未结束,仍在等待安全关闭。')
def _close_when_idle(self):
owners = [self, *self.icdb_tasks]
for name in ('management_dialog', 'backup_dialog', 'release_dialog'):
@@ -1580,5 +1616,6 @@ class MainWindow(QWidget):
if self._lease_pending or active:
QTimer.singleShot(20, self._close_when_idle)
return
self.close_wait_timer.stop()
self._close_ready = True
self.close()
+16 -1
View File
@@ -14,7 +14,7 @@ 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 = {
@@ -25,6 +25,9 @@ STAGE_LABELS = {
'verify': '正在校验上传结果', 'verified': '校验已返回', 'copy': '正在准备来源副本',
'hash': '正在校验主要文件',
'release_check': '正在检查工程是否被占用',
'previous_release_check': '正在复核历史占用',
'previous_release_confirmed': '历史会话已确认释放',
'previous_release_unconfirmed': '占用复核未通过',
}
@@ -203,6 +206,18 @@ class ManagementDialog(QDialog):
for result in results:
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'):
@@ -25,13 +25,13 @@ class ResidualReleaseDialog(QDialog):
self.pool = QThreadPool(self)
self.setWindowTitle('释放残留会话')
self.setModal(True)
self.resize(760, 350)
self.resize(1040, 400)
layout = QVBoxLayout(self)
self.message = QLabel('正在检查当前库关联的会话…')
self.message.setWordWrap(True)
layout.addWidget(self.message)
self.table = QTableWidget(0, 4)
self.table.setHorizontalHeaderLabels(['工程', '程序', 'PID', '状态'])
self.table = QTableWidget(0, 8)
self.table.setHorizontalHeaderLabels(['工程', '程序', 'PID', '状态', '窗口位置', '程序路径', '确认范围', '执行结果'])
self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
self.table.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch)
self.table.setEditTriggers(QTableWidget.NoEditTriggers)
@@ -40,17 +40,22 @@ class ResidualReleaseDialog(QDialog):
self.refresh_button = QPushButton('重新检查')
self.confirm_button = QPushButton('确认释放')
self.prompt_button = QPushButton('处理保存提示…')
self.details_button = QPushButton('查看原生提示…')
self.cancel_native_button = QPushButton('请求原生取消…')
self.force_button = QPushButton('强制结束客户端…')
self.force_button.setEnabled(False)
self.prompt_button.setEnabled(False)
self.close_button = QPushButton('关闭')
for button in (self.refresh_button, self.confirm_button, self.prompt_button, self.force_button, self.close_button): buttons.addWidget(button)
for button in (self.refresh_button, self.confirm_button, self.details_button, self.prompt_button,
self.cancel_native_button, self.force_button, self.close_button): buttons.addWidget(button)
layout.addLayout(buttons)
self.refresh_button.clicked.connect(self.refresh)
self.confirm_button.clicked.connect(self.confirm_release)
self.close_button.clicked.connect(self.close)
self.prompt_button.clicked.connect(self.answer_prompt)
self.force_button.clicked.connect(self.force_release)
self.details_button.clicked.connect(self.show_native_details)
self.cancel_native_button.clicked.connect(self.cancel_native)
self.table.itemSelectionChanged.connect(self._update_prompt)
self.refresh()
@@ -60,6 +65,7 @@ class ResidualReleaseDialog(QDialog):
self.refresh_button.setEnabled(False)
self.prompt_button.setEnabled(False)
self.force_button.setEnabled(False)
self.cancel_native_button.setEnabled(False)
self.close_button.setText('停止释放')
self.worker = ServiceWorker(action)
self.worker.signals.succeeded.connect(completed)
@@ -82,8 +88,14 @@ class ResidualReleaseDialog(QDialog):
def _rows(self, sessions):
self.table.setRowCount(len(sessions))
for index, session in enumerate(sessions):
allowed = session.get('consent_allowed')
permission = '允许' if allowed is True else '未允许' if allowed is False else '待确认'
outcome = {'RELEASED': '已释放', 'WAITING': '未释放', 'IDENTITY_CHANGED': '身份已变化',
'CANCELLED': '已停止', 'REQUESTING': '执行中', 'NOT_STARTED': '尚未执行'}.get(
session.get('release_status'), '待执行')
for column, value in enumerate((session.get('project', ''), session['name'],
session['pid'], session.get('detail', ''))):
session['pid'], session.get('detail', ''), ', '.join(session.get('desktops', [])),
session.get('image', session.get('executable', '')), permission, outcome)):
self.table.setItem(index, column, QTableWidgetItem(str(value)))
if sessions: self.table.setCurrentCell(0, 0)
@@ -91,6 +103,65 @@ class ResidualReleaseDialog(QDialog):
row = self.table.currentRow()
rows = self.plan['sessions'] if self.plan else []
self.prompt_button.setEnabled(not self.busy and 0 <= row < len(rows) and bool(rows[row].get('prompt')))
self.cancel_native_button.setEnabled(not self.busy and 0 <= row < len(rows)
and bool(rows[row].get('cancel_prompt')))
self.details_button.setEnabled(0 <= row < len(rows))
def show_native_details(self):
if not self.plan: return
row = self.table.currentRow()
if row < 0: return
session = self.plan['sessions'][row]
box = QMessageBox(self); self.native_details = box
box.setWindowTitle('原生会话状态')
box.setText(f'{session["name"]} (PID {session["pid"]})\n'+session.get('detail', ''))
details = ['程序路径:'+session.get('image', session.get('executable', '')),
'窗口位置:'+', '.join(session.get('desktops', [])),
session.get('native_activity', {}).get('detail', '')]
for window in session.get('windows', []):
details.extend(['', window.get('title', ''), window.get('output', '') or ''])
details.extend(c.get('text', '') for c in window.get('children', [])
if c.get('class') == 'Static')
box.setDetailedText('\n'.join(details))
box.show()
def cancel_native(self):
if self.busy or not self.plan: return
row = self.table.currentRow()
if row < 0: return
session = self.plan['sessions'][row]
if not session.get('cancel_prompt'): return
answer = QMessageBox.question(self, '请求原生取消',
f'请求 {session["name"]} (PID {session["pid"]}) 当前显示的取消按钮?\n'
'取消后的工程状态仍需核对;不会强制结束进程。',
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if answer != QMessageBox.Yes: return
from cbb_refresh_verify.residual_sessions import request_native_cancel
self.before_release.emit(); self.stop.clear()
def execute():
action = lambda: request_native_cancel(session, self.library, self.evidence_dir, stop=self.stop)
return self.native_queue.run(action, stop=self.stop) if self.native_queue is not None else action()
def done(result):
self.message.setText(result.get('detail') or '\n'.join(r.get('detail', '') for r in result['sessions']))
confirmed = self._accept_release_proof(result)
if confirmed:
self.message.setText('已确认原生会话结束,当前库已释放。')
if result.get('evidence_error'):
self.message.setText(self.message.text()+'\n记录保存失败:'+result['evidence_error'])
elif not confirmed:
self._refresh_after = True
self._start(execute, done)
def _accept_release_proof(self, result):
proof = result.get('proof', {})
# Both paths were canonicalized by the worker; GUI comparison must not touch SMB.
if (proof.get('status') != 'RELEASE_CONFIRMED'
or Path(proof.get('library', '')).absolute() != self.library.absolute()
or any(r.get('release_status') != 'RELEASED' for r in result['sessions'])):
return False
self.plan = None
self.released.emit(proof)
return True
def answer_prompt(self):
if self.busy or not self.plan: return
@@ -153,13 +224,16 @@ class ResidualReleaseDialog(QDialog):
self.plan = {**plan, 'sessions': result['sessions']}
self._rows(result['sessions'])
count = sum(row['release_status'] == 'RELEASED' for row in result['sessions'])
if result['status'] == 'RELEASE_CONFIRMED':
self.plan = None
self.message.setText(f'已释放 {count} 个会话,旧占用记录已解除。')
self.released.emit(result['proof'])
if self._accept_release_proof(result):
self.message.setText(f'已释放 {count} 个会话,旧占用记录已解除。'
+ ('\n记录保存失败:'+result['evidence_error'] if result.get('evidence_error') else ''))
else:
self.message.setText(f'已释放 {count} 个会话,其余会话或库状态仍待确认。'
+ ('\n'+result['detail'] if result.get('detail') else '请处理原生窗口后重新检查。'))
+ ('\n'+result['detail'] if result.get('detail') else '可查看原生提示、处理保存或请求取消后重新检查。')
+ ('\n记录保存失败:'+result['evidence_error'] if result.get('evidence_error') else ''))
allowed = [row for row in result['sessions'] if row.get('consent_allowed') is True]
pending = sum(row.get('release_status') != 'RELEASED' for row in allowed)
self.message.setText(self.message.text()+f'\n确认允许 {len(allowed)} 项,其中未释放 {pending} 项。')
def execute():
action = lambda: release_residual_sessions(plan, self.evidence_dir, stop=self.stop, force=force)
return self.native_queue.run(action, stop=self.stop) if self.native_queue is not None else action()
+10 -2
View File
@@ -102,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:
@@ -550,6 +551,7 @@ 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():
@@ -566,16 +568,18 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
if request.maintenance:
from .maintenance_entry import run_icdb_check
return run_icdb_check(request, progress=progress, stop=stop)
from .library_lock import LibraryLock, LibraryBusy
from .library_lock import LibraryLock, LibraryBusy, recheck_previous_release
import pywintypes
if Path(request.lmc_file).is_file():
try:
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('FAIL', stderr=str(error), error_category='LIBRARY_IN_USE')
except (OSError, pywintypes.error) as error:
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(
@@ -674,6 +678,10 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
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:
+21 -2
View File
@@ -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")
@@ -180,7 +199,7 @@ def test_retry_rechecks_failed_scan_without_library_changes(tmp_path):
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)
second = BatchStatusSession(bridge).scan(['A', 'B'], lmc, checkpoint, resume=True)
assert bridge.requests == ['A']
assert second[0].status == 'READY'
+1 -1
View File
@@ -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"]
+10 -4
View File
@@ -6,7 +6,7 @@ from test_maintenance_entry import case
def test_verify_defaults_to_no_repair_and_does_not_retain_a_failure_lock(tmp_path, monkeypatch):
from cbb_refresh_verify import verify_runner as runner, library_lock as locks, native_repair
library = tmp_path / 'library.lmc'; library.touch()
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)
@@ -16,11 +16,17 @@ def test_verify_defaults_to_no_repair_and_does_not_retain_a_failure_lock(tmp_pat
error_category='ICDB_REPAIR_REQUIRED', safe_to_continue=True)
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: (calls.append('verify') or result))
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **k: pytest.fail('verify requested Repair'))
assert runner.run_verify(req) is result
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 marker.read_text() == 'historical diagnostic record'
assert locks._key(tmp_path / '.library.cbb-upload.lock') not in locks._owners
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):
+1 -1
View File
@@ -283,7 +283,7 @@ def test_status_cache_does_not_reuse_a_different_block_type(tmp_path):
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')
session.scan(['Block'], library, tmp_path/'scan.jsonl', block_type='Other', resume=True)
assert calls == ['RULP', 'Other']
-18
View File
@@ -2,7 +2,6 @@ import pytest
from cbb_refresh_verify.pcb_bridge import (
PcbBridgeError,
execution_outcome,
require_document_identity,
wait_for_target_document,
)
@@ -74,23 +73,6 @@ def test_bridge_stops_if_pcb_exits_before_com_is_ready(tmp_path):
assert raised.value.error_code == 'PCB_EXITED_BEFORE_COM'
def test_fatal_dialog_overrides_successful_save_markers():
result = execution_outcome(
save_complete=True,
pcb_exited=True,
fatal_error='SAVE_REUSABLE_BLOCK_FAILED: Error saving the Reusable Block',
)
assert result['status'] == 'FAIL'
assert result['error_code'] == 'SAVE_REUSABLE_BLOCK_FAILED'
def test_success_requires_save_and_pcb_exit():
assert execution_outcome(save_complete=True, pcb_exited=True)['status'] == 'PASS'
assert execution_outcome(save_complete=False, pcb_exited=True)['status'] == 'FAIL'
assert execution_outcome(save_complete=True, pcb_exited=False)['status'] == 'FAIL'
def test_connected_com_without_document_remains_startup_and_checks_native_failure(tmp_path):
errors = iter(('', 'ICDB_REPAIR_REQUIRED: original lost session'))
events = []
+1
View File
@@ -149,6 +149,7 @@ def test_released_batch_can_resume_only_its_unexecuted_items(qtbot, tmp_path, mo
window.release_dialog.close()
qtbot.waitUntil(lambda: not window.busy)
assert window.summary.isVisible()
action = window._resume_batch_action
assert action.isEnabled()
calls = []
monkeypatch.setattr(window, '_run', lambda names, **kw: calls.append((names, kw)))
+6 -4
View File
@@ -147,7 +147,7 @@ def test_backup_intermediate_success_does_not_allow_cooperative_close(output):
def test_force_requires_separate_explicit_argument_and_rechecks_identity(tmp_path, monkeypatch):
from cbb_refresh_verify import residual_sessions as sessions
library = tmp_path/'lib.lmc'; library.touch()
process = row(10, tmp_path/'ReusableBlocksLP/A/Work/A.prj')
process = row(10, tmp_path/'ReusableBlocksLP/A/Work/A.prj', name='ExpeditionPCB.exe')
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [process.copy()])
monkeypatch.setattr(sessions, '_process_identity', lambda r: {**OWNERSHIP, 'created_handle': 'old', 'image': r['executable']})
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
@@ -311,6 +311,7 @@ def test_supported_force_revalidates_exact_handle_before_termination(monkeypatch
monkeypatch.setattr(win32event, 'WaitForSingleObject', lambda handle, timeout:
win32con.WAIT_OBJECT_0 if timeout else win32con.WAIT_TIMEOUT)
monkeypatch.setattr(sessions, '_force_ownership', lambda *args: dict(OWNERSHIP))
monkeypatch.setattr(sessions, '_process_windows', lambda _: {10: []})
calls = []
monkeypatch.setattr(win32api, 'TerminateProcess', lambda handle, code: calls.append((handle, code)))
assert sessions._force_close({**process, 'created_handle': 'reused'})['release_status'] == 'IDENTITY_CHANGED'
@@ -328,11 +329,12 @@ def test_partial_desktop_enumeration_never_offers_normal_close(monkeypatch):
def failed(*_): raise OSError('desktop disappeared')
monkeypatch.setattr(win32gui, 'EnumWindows', failed)
monkeypatch.setattr(win32service, 'GetProcessWindowStation', lambda: SimpleNamespace(EnumDesktops=lambda: []))
windows = _process_windows({10})[10]
assert any(w['class'] == 'UNCONFIRMED' for w in windows)
snapshot = _process_windows({10})
windows = snapshot[10]
assert snapshot.incomplete[10]
windows.append({'hwnd': 100, 'class': 'Afx:main', 'title': 'Design - Expedition PCB',
'children': [], 'enabled': True})
assert close_target('ExpeditionPCB.exe', windows)[0] is None
assert close_target('ExpeditionPCB.exe', windows, incomplete=snapshot.incomplete[10])[0] is None
@pytest.mark.parametrize('choice', [6, 7, 2])
+171
View File
@@ -0,0 +1,171 @@
from contextlib import nullcontext
import json
import sys
import time
from pathlib import Path
from types import SimpleNamespace
from uuid import uuid4
import pytest
from cbb_refresh_verify import residual_sessions as sessions
from test_residual_sessions import row, OWNERSHIP
def window():
return dict(hwnd=100, title='Design - Expedition PCB', desktop='Default',
**{'class': 'Afx:main'}, enabled=True, children=[], documents=[])
class PartialWindows(dict):
incomplete = {10: 'target thread inaccessible'}
def test_thread_read_failure_does_not_poison_another_process(monkeypatch):
import win32gui, win32process, win32service
def global_failure(*args):
raise OSError('an unrelated desktop is inaccessible')
monkeypatch.setattr(win32gui, 'EnumWindows', global_failure)
monkeypatch.setattr(win32service, 'GetProcessWindowStation',
lambda: SimpleNamespace(EnumDesktops=lambda: ['Default', 'CbbManagement_Unrelated']))
monkeypatch.setattr(sessions, '_process_threads', lambda _: {10: [100], 20: [200]}, raising=False)
monkeypatch.setattr(sessions, '_thread_desktop_name',
lambda tid: 'Default' if tid == 100 else 'CbbManagement_Broken', raising=False)
def open_desktop(name, *args):
if name == 'CbbManagement_Broken':
raise PermissionError('only process 20 is unreadable')
assert name == 'Default', 'an unrelated desktop must not be inspected'
return SimpleNamespace(EnumDesktopWindows=lambda: [1000], CloseDesktop=lambda: None)
monkeypatch.setattr(win32service, 'OpenDesktop', open_desktop)
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda _: (100, 10))
monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda _: True)
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda *args: None)
monkeypatch.setattr(win32gui, 'GetWindowText', lambda _: 'Design - Expedition PCB')
monkeypatch.setattr(win32gui, 'GetClassName', lambda _: 'Afx:main')
monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda _: True)
monkeypatch.setattr(win32gui, 'GetWindowRect', lambda _: (0, 0, 100, 100))
result = sessions._process_windows({10, 20})
assert [w['hwnd'] for w in result[10]] == [1000]
assert 10 not in result.incomplete and 'unreadable' in result.incomplete[20]
assert result[20] == [], 'a read error must not be represented as a native modal window'
assert sessions.close_target('ExpeditionPCB.exe', result[10])[0]
def test_preview_exposes_only_target_process_incomplete_state(tmp_path, monkeypatch):
library = tmp_path/'lib.lmc'; library.touch()
processes = [row(pid, tmp_path/f'ReusableBlocksLP/{pid}/Work/{pid}.prj', name='ExpeditionPCB.exe')
for pid in (10, 20)]
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: processes)
monkeypatch.setattr(sessions, '_process_identity', lambda r: dict(created_handle='creation',
image=r['executable'], **OWNERSHIP))
monkeypatch.setattr(sessions, '_process_windows', lambda _: PartialWindows({10: [window()], 20: [window()]}))
affected, healthy = sessions.inspect_residual_sessions(library)['sessions']
assert affected['windows_incomplete'] and not affected['can_close'] and not affected['force_allowed']
assert affected['native_activity']['status'] == 'UNCONFIRMED'
assert '读取' in affected['detail'] and '弹窗' not in affected['detail']
assert healthy['can_close'] and healthy['force_allowed']
def test_action_rechecks_incomplete_read_before_force_termination(monkeypatch):
import win32api, win32con, win32event
process = dict(row(10, 'C:/library/A.prj', name='ExpeditionPCB.exe'),
created_handle='creation', image='C:/Mentor/ExpeditionPCB.exe', scope_confirmed=True, **OWNERSHIP)
monkeypatch.setattr(sessions, '_process_handle', lambda *a, **kw: nullcontext(123))
monkeypatch.setattr(sessions, '_handle_identity', lambda _: {k: process[k] for k in ('created_handle', 'image')})
monkeypatch.setattr(sessions, '_force_ownership', lambda *args: dict(OWNERSHIP))
monkeypatch.setattr(win32event, 'WaitForSingleObject', lambda *args: win32con.WAIT_TIMEOUT)
monkeypatch.setattr(sessions, '_process_windows', lambda _: PartialWindows({10: [window()]}))
monkeypatch.setattr(win32api, 'TerminateProcess', lambda *args: pytest.fail('unreadable target was ended'))
result = sessions._force_close(process)
assert result['release_status'] == 'WAITING' and result['native_activity']['status'] == 'UNCONFIRMED'
def test_identity_read_failure_keeps_the_other_preview_row_available(tmp_path, monkeypatch):
library = tmp_path/'lib.lmc'; library.touch()
processes = [row(pid, tmp_path/f'ReusableBlocksLP/{pid}/Work/A.prj', name='ExpeditionPCB.exe')
for pid in (10, 20)]
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: processes)
def identity(process):
if process['pid'] == 10:
raise PermissionError('token inaccessible')
return dict(created_handle='creation', image=process['executable'], **OWNERSHIP)
monkeypatch.setattr(sessions, '_process_identity', identity)
monkeypatch.setattr(sessions, '_process_windows', lambda _: {pid: [window()] for pid in (10, 20)})
affected, healthy = sessions.inspect_residual_sessions(library)['sessions']
assert not affected['force_allowed'] and 'token inaccessible' in affected['detail']
assert healthy['force_allowed'] and healthy['can_close']
def test_native_cancel_retains_exact_preview_scope(tmp_path, monkeypatch):
from cbb_refresh_verify import library_lock
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
process = dict(row(10, library.parent/'ReusableBlocksLP/A/Work/A.prj'),
scope_confirmed=True, block_names=['A'], cancel_prompt={'hwnd': 100})
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [process])
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
expected = (library.parent/'ReusableBlocksLP/A/Work', library.parent/'SymbolLibs')
def scoped(actual, selected_library, roots):
assert roots == expected, 'Cancel widened the scope from its preview'
return True
monkeypatch.setattr(library_lock, '_owner_matches_scope', scoped)
monkeypatch.setattr(sessions, '_request_native_cancel', lambda *a, **kw:
dict(release_status='WAITING', detail='cancel requested'))
result = sessions.request_native_cancel(process, library, tmp_path/'evidence')
assert result['sessions'][0]['detail'] == 'cancel requested'
def test_persisted_release_evidence_is_bounded_without_changing_preview(tmp_path, monkeypatch):
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
output = '原生输出' * 100000
observed = dict(window(), output=output, children=[dict(text=output, **{'class': 'RichEdit'})])
process = dict(row(10, library.parent/'ReusableBlocksLP/A/Work/A.prj', name='ExpeditionPCB.exe'),
created_handle='creation', image='C:/Mentor/ExpeditionPCB.exe', scope_confirmed=True,
windows=[observed], native_activity={'status': 'IDLE', 'output': output}, **OWNERSHIP)
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [process])
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
monkeypatch.setattr(sessions, '_force_close', lambda *a, **kw: dict(release_status='RELEASED', detail='ended'))
monkeypatch.setattr(sessions, '_finish_library_release', lambda *args:
dict(status='RELEASE_CONFIRMED', library=str(library)))
result = sessions.release_residual_sessions(dict(library=str(library), sessions=[process]),
tmp_path/'evidence', force=True)
assert result['status'] == 'RELEASE_CONFIRMED'
for path in (Path(result['evidence_path']), Path(result['consent_path'])):
assert path.stat().st_size < 20000
saved = json.loads(path.read_text('utf-8'))['sessions'][0]
assert 'output' not in saved['native_activity']
assert 'children' not in saved['windows'][0] and 'output' not in saved['windows'][0]
assert len(saved['windows'][0]['output_excerpt'].encode('utf-8')) <= 4096
assert saved['windows'][0]['output_truncated'] is True
assert process['windows'][0]['output'] == output
def test_real_private_desktop_is_read_through_its_process_threads(tmp_path):
from cbb_refresh_verify.desktop_worker import DesktopWorker
ready, stop = tmp_path/'ready.json', tmp_path/'stop'
script = tmp_path/'window.py'
name = 'CbbManagement_Review_'+uuid4().hex[:10]
script.write_text('import json,time,win32api,win32con,win32gui\nfrom pathlib import Path\n'
'wc=win32gui.WNDCLASS()\nwc.hInstance=win32api.GetModuleHandle(None)\n'
'wc.lpszClassName="CbbReviewWindow"\nwc.lpfnWndProc=win32gui.DefWindowProc\n'
'atom=win32gui.RegisterClass(wc)\n'
'hwnd=win32gui.CreateWindow(atom,"Controlled review fixture",'
'win32con.WS_OVERLAPPEDWINDOW|win32con.WS_VISIBLE,0,0,300,200,0,0,wc.hInstance,None)\n'
f'Path({str(ready)!r}).write_text(json.dumps(dict(hwnd=hwnd)))\n'
f'while not Path({str(stop)!r}).exists():\n'
' win32gui.PumpWaitingMessages();time.sleep(.02)\n'
'win32gui.DestroyWindow(hwnd)\n', encoding='utf-8')
worker = DesktopWorker([sys.executable, str(script)], name)
try:
deadline = time.monotonic()+8
while not ready.exists() and worker.poll() is None and time.monotonic()<deadline:
time.sleep(.02)
assert ready.exists()
hwnd = json.loads(ready.read_text())['hwnd']
snapshot = sessions._process_windows({worker.pid})
assert worker.pid not in snapshot.incomplete, snapshot.incomplete
target = next(w for w in snapshot[worker.pid] if w['hwnd'] == hwnd)
assert target['desktop'] == name and target['title'] == 'Controlled review fixture'
finally:
stop.touch()
worker.wait(5)
worker.close()
+166
View File
@@ -0,0 +1,166 @@
from pathlib import Path
from threading import Event
from types import SimpleNamespace
import pytest
from PySide6.QtCore import QCoreApplication, QEvent
from PySide6.QtWidgets import QMessageBox
from shiboken6 import isValid
from cbb_refresh_verify.verify_runner import VerifyResult
def flush_deletes():
QCoreApplication.sendPostedEvents(None, QEvent.DeferredDelete)
def test_repeated_batch_results_retire_previous_dialog(qtbot, tmp_path):
from cbb_refresh_verify.ui.main_window import MainWindow
window = MainWindow(data_root=tmp_path)
qtbot.addWidget(window)
window._batch_done(([VerifyResult('FAIL')], tmp_path/'report.log'))
previous = window.summary
window._batch_done(([VerifyResult('PASS')], tmp_path/'report2.log'))
flush_deletes()
assert not isValid(previous)
assert len(window.findChildren(QMessageBox)) == 1
current = window.summary
current.close()
flush_deletes()
assert not isValid(current)
window._update() # No retained reference to deleted result actions.
def test_repeated_icdb_results_preserve_latest_recovery_task(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/'result.json', safe=True))
window._run(['Beta'], maintenance=True)
qtbot.waitUntil(lambda: not window._icdb_active())
first_task, previous = window.icdb_task, window.icdb_summary
window._run(['Gamma'], maintenance=True)
qtbot.waitUntil(lambda: not window._icdb_active())
flush_deletes()
assert not isValid(previous)
assert not hasattr(first_task, 'summary')
assert len(window.findChildren(QMessageBox)) == 1
assert window.icdb_task.summary is window.icdb_summary
action = next(b for b in window.icdb_summary.buttons() if '副本' in b.text())
action.click()
assert [request.name for request in window.management_dialog.requests()] == ['Gamma']
window.management_dialog.reject()
window._invalidate_check_targets('test.lmc', ['Beta', 'Gamma'])
window._update()
def test_batch_replacement_preserves_independent_icdb_result(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda _: VerifyResult('CHECKED'))
window._run(['Beta'], maintenance=True)
qtbot.waitUntil(lambda: not window._icdb_active())
icdb_summary = window.icdb_summary
window._batch_done(([VerifyResult('PASS')], tmp_path/'first.log'))
old_batch = window.summary
window._batch_done(([VerifyResult('PASS')], tmp_path/'second.log'))
flush_deletes()
assert not isValid(old_batch)
assert isValid(icdb_summary) and icdb_summary.isVisible()
assert window.icdb_task.summary is icdb_summary
assert len(window.findChildren(QMessageBox)) == 2
def test_close_wait_notice_remains_visible_and_timer_stops_on_idle(qtbot, tmp_path):
from cbb_refresh_verify.ui.main_window import MainWindow
entered, release = Event(), Event()
def close_lease():
entered.set()
release.wait(5)
window = MainWindow(data_root=tmp_path)
qtbot.addWidget(window)
window.library_lease = SimpleNamespace(close=close_lease)
window.show()
try:
window.close()
qtbot.waitUntil(entered.is_set)
assert window.isVisible() and '等待' in window.windowTitle()
timer = window.close_wait_timer
assert timer.isActive() and timer.interval() == 120_000
timer.start(10)
qtbot.waitUntil(lambda: '仍在等待' in window.windowTitle())
assert '仍在等待' in window.status_label.text()
window.close()
assert window.isVisible()
finally:
release.set()
qtbot.waitUntil(lambda: not window.isVisible())
assert not timer.isActive()
@pytest.fixture
def batch_cli(tmp_path, monkeypatch):
import cbb_refresh_verify.application as application
import cbb_refresh_verify.library_reader as reader
import cbb_refresh_verify.network_path as network
import cbb_refresh_verify.verify_runner as runner
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
log, requested, retained = [], [], []
def record(message, *args, **kwargs):
log.append(message % args if args else message)
logger = SimpleNamespace(info=record, warning=record, exception=record, handlers=())
monkeypatch.setattr(application, 'configure', lambda *_: SimpleNamespace(root=tmp_path, logger=logger))
class Lease:
display_path = Path(r'\\server\share\library')
mentor_path = tmp_path/'lib.lmc'
drive, remote_root, created = 'Z:', r'\\server\share', True
def __enter__(self): return self
def __exit__(self, *_): pass
def retain_for_recovery(self): retained.append(self.drive)
monkeypatch.setattr(network.LibraryPathLease, 'acquire', lambda _: Lease())
monkeypatch.setattr(network, 'select_library_file', lambda path: path)
monkeypatch.setattr(reader, 'read_library_fast', lambda *a, **kw: LibraryReadResult((
CbbRecord('Ready', 'LP', status='READY'), CbbRecord('One', 'LP'),
CbbRecord('Two', 'LP'), CbbRecord('Three', 'LP'))))
def run(requests):
requested.extend(request.block_name for request in requests)
return [VerifyResult('PASS') for _ in requests]
monkeypatch.setattr(runner, 'run_batch', run)
monkeypatch.setattr(runner, 'write_batch_report', lambda *a: tmp_path/'batch.log')
return application, runner, log, requested, retained
@pytest.mark.parametrize('extra, expected, counts', [
([], ['One', 'Two', 'Three'], (3, 3, 0)),
(['--limit', '2'], ['One', 'Two'], (2, 3, 1)),
(['--block', 'Three', '--block', 'One', '--limit', '1'], ['Three'], (1, 2, 1)),
])
def test_batch_cli_limit_is_optional_and_reports_selection(batch_cli, extra, expected, counts):
app, _, log, requested, _ = batch_cli
assert app.main(['--batch-lmc', 'lib.lmc', *extra]) == 0
assert requested == expected
assert any(all(f'{key}={value}' in line for key, value in zip(
('selected', 'total', 'remaining'), counts)) for line in log)
@pytest.mark.parametrize('value', ['0', '-1', 'no'])
def test_batch_cli_rejects_nonpositive_limit(batch_cli, value):
app, _, _, requested, _ = batch_cli
with pytest.raises(SystemExit) as error:
app.main(['--batch-lmc', 'lib.lmc', '--limit', value])
assert error.value.code == 2 and not requested
@pytest.mark.parametrize('raised', [False, True])
def test_retained_mapping_logs_context_and_confirmed_release_guidance(batch_cli, monkeypatch, raised):
app, runner, log, _, retained = batch_cli
def run(_):
if raised: raise RuntimeError('native writer status unknown')
return [VerifyResult('FAIL', safe_to_continue=False)]
monkeypatch.setattr(runner, 'run_batch', run)
assert app.main(['--batch-lmc', 'lib.lmc', '--block', 'One']) == (1 if raised else 2)
assert retained == ['Z:']
notice = next(line for line in log if 'batch_drive_retained' in line)
assert 'Z:' in notice and r'\\server\share' in notice
assert '释放残留会话' in notice and '确认' in notice
assert 'net use' not in notice.lower()
@@ -0,0 +1,40 @@
from cbb_refresh_verify import library_lock
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
def test_confirmed_scope_and_execution_divergence_are_visible(qtbot, tmp_path, monkeypatch):
library = tmp_path/'lib.lmc'
rows = [dict(name='ExpeditionPCB.exe', pid=pid, project=name, detail='可正常关闭')
for pid, name in ((10, 'A'), (20, 'B'))]
monkeypatch.setattr(library_lock, 'inspect_residual_sessions',
lambda *_: dict(library=str(library), sessions=rows))
monkeypatch.setattr(library_lock, 'release_residual_sessions', lambda *a, **kw:
dict(status='PARTIAL', sessions=[
dict(rows[0], consent_allowed=True, release_status='RELEASED', detail='已退出'),
dict(rows[1], consent_allowed=True, release_status='WAITING', detail='原生操作进行中')]))
dialog = ResidualReleaseDialog(library, tmp_path/'evidence')
qtbot.addWidget(dialog)
qtbot.waitUntil(lambda: not dialog.busy)
dialog.confirm_button.click()
qtbot.waitUntil(lambda: not dialog.busy)
assert dialog.table.columnCount() == 8
assert dialog.table.item(0, 6).text() == dialog.table.item(1, 6).text() == '允许'
assert dialog.table.item(0, 7).text() == '已释放'
assert dialog.table.item(1, 7).text() == '未释放'
assert '原生操作进行中' in dialog.table.item(1, 3).text()
assert '确认允许 2' in dialog.message.text() and '未释放 1' in dialog.message.text()
def test_retiring_batch_summary_forgets_enabled_release_actions(qtbot, tmp_path):
from cbb_refresh_verify.ui.main_window import MainWindow
from cbb_refresh_verify.verify_runner import VerifyResult
from test_review345_ui_cli import flush_deletes
window = MainWindow(data_root=tmp_path)
qtbot.addWidget(window)
window._batch_done(([VerifyResult('FAIL', safe_to_continue=False)], None))
assert window._residual_release_action is not None
window.summary.close(); flush_deletes()
window._update()
assert window._residual_release_action is None
window._resume_batch = dict(library=tmp_path/'lib.lmc', released=True)
window._release_dialog_finished()
+151
View File
@@ -0,0 +1,151 @@
import json
from dataclasses import replace
from pathlib import Path
import pytest
from test_management import setup, execute
def test_maintenance_totals_do_not_count_pass_as_unconfirmed():
from cbb_refresh_verify.icdb_maintenance import maintenance_counts
from cbb_refresh_verify.verify_runner import VerifyResult
counts = maintenance_counts([VerifyResult('PASS'), VerifyResult('CHECKED'),
VerifyResult('FAIL'), VerifyResult('SKIPPED')])
assert counts['passed'] == 1 and counts['unconfirmed'] == 1
assert sum(counts[k] for k in ('passed', 'checked_without_repair', 'unconfirmed',
'skipped', 'cancelled', 'issues_found', 'in_use')) == counts['total']
@pytest.mark.parametrize('occupied', [False, True])
def test_verify_rechecks_history_instead_of_ignoring_or_permanently_blocking_it(tmp_path, monkeypatch, occupied):
import cbb_refresh_verify.library_lock as locks
import cbb_refresh_verify.verify_runner as runner
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
locks._persist_blocker(library, lease_id='a'*32, block_name='Target')
before = locks.blocker_path(library).read_bytes()
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
address = library.parent/'ReusableBlocksLP/Target/Work/database/cdbsvr/sAddress.adr'
if occupied:
address.parent.mkdir(parents=True); address.touch()
called = []
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **kw:
called.append(1) or runner.VerifyResult('PASS', library_flag='GREEN'))
events = []
result = runner.run_verify(runner.VerifyRequest(library, 'Target', tmp_path/'evidence'), progress=events.append)
if occupied:
assert not called and result.safe_to_continue
assert result.error_category == 'LIBRARY_IN_USE'
assert locks.blocker_path(library).read_bytes() == before
else:
assert called == [1] and result.status == 'PASS'
assert result.release_proof['data_recovery_confirmed'] is False
assert not locks.blocker_path(library).exists()
assert any(e['stage'] == 'previous_release_confirmed' for e in events)
def test_management_preserves_release_context_before_first_native_call(setup, monkeypatch):
import cbb_refresh_verify.library_lock as locks
request, adapter, _ = setup
locks._persist_blocker(request.library, lease_id='b'*32)
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
catalog = adapter.catalog
def inspect(library, evidence):
checkpoint = next(request.evidence_dir.glob('*/checkpoint.json'))
history = json.loads(checkpoint.read_text('utf-8'))['history']
assert any(item.get('release_proof', {}).get('data_recovery_confirmed') is False for item in history)
return catalog(library, evidence)
monkeypatch.setattr(adapter, 'catalog', inspect)
result = execute(request, adapter)
assert result.status == 'REMOVED' and result.release_proof['status'] == 'RELEASE_CONFIRMED'
def test_management_records_scoped_changes_without_hashing_unrelated_cbb(setup, monkeypatch):
request, adapter, _ = setup
root = request.library.parent
target = root/'ReusableBlocksLP/Block/Work/Block.prj'
deleted = root/'ReusableBlocksLP/Block/Work/obsolete.dat'; deleted.write_bytes(b'old')
shared = root/'SymbolLibs/shared/icdb.dat'; shared.parent.mkdir(parents=True); shared.write_bytes(b'old')
foreign = root/'ReusableBlocksLP/Other/Work/private.dat'; foreign.parent.mkdir(parents=True); foreign.write_bytes(b'other')
original_open = Path.open
def opened(path, *args, **kwargs):
assert path != foreign, 'Post-write report must not add whole-library hashing'
return original_open(path, *args, **kwargs)
monkeypatch.setattr(Path, 'open', opened)
remove = adapter.remove
def mutate(req, evidence):
target.write_bytes(target.read_bytes()+b'# updated\n')
deleted.unlink(); (target.parent/'created.dat').write_bytes(b'new')
shared.write_bytes(b'changed')
return remove(req, evidence)
monkeypatch.setattr(adapter, 'remove', mutate)
result = execute(request, adapter)
report = json.loads((result.evidence_path.parent/'library-changes.json').read_text('utf-8'))
assert report['status'] == 'RECORDED' and report['unrelated_cbb_content_checked'] is False
assert report['added'] == ['ReusableBlocksLP/Block/Work/created.dat']
assert report['deleted'] == ['ReusableBlocksLP/Block/Work/obsolete.dat']
assert 'SymbolLibs/shared/icdb.dat' in report['modified']
assert 'ReusableBlocksLP/Block/Work/Block.prj' in report['modified']
assert result.change_report == report
assert report['rule_version'] == 1
assert report['scope'] == {'kind': 'library', 'block_name': 'Block',
'library_name': request.library.name}
from cbb_refresh_verify import scoped_manifest as manifests
assert report['excluded_categories'] == sorted(manifests._NONPRIMARY_DIRECTORIES)
assert report['excluded_suffixes'] == sorted(manifests._NONPRIMARY_SUFFIXES)
runtime = report['runtime_exclusions']
assert runtime['native_directory_names'] == ['dbcheck', 'dbrestore', 'log']
assert runtime['file_names'] == ['saddress.adr']
assert runtime['file_name_prefixes'] == ['~$']
assert runtime['relative_directories'] == ['projectbackup/backups']
assert runtime['directory_prefixes'] == ['work.before-restore-']
assert 'selected CBB Work/Cert root or its PCB child' in runtime['directory_name_positions']
assert 'SymbolLibs/<partition>/cdbsvr' in runtime['native_directory_positions']
def test_failed_mutation_still_records_changes_and_release_fact(setup):
request, adapter, source = setup
adapter.fail_add = True
result = execute(replace(request, operation='update', source=source), adapter)
assert result.status == 'RECOVERY_REQUIRED' and result.safe_to_continue
assert result.change_report['status'] == 'RECORDED'
def test_change_report_storage_failure_does_not_invent_unfinished_native_write(setup, monkeypatch):
import cbb_refresh_verify.management as management
request, adapter, _ = setup
original = management._write_json
def write(path, value):
if path.name == 'library-changes.json': raise PermissionError('report disk full')
return original(path, value)
monkeypatch.setattr(management, '_write_json', write)
result = execute(request, adapter)
assert result.safe_to_continue and result.status == 'REMOVED'
assert result.change_report['status'] == 'UNCONFIRMED'
assert 'report disk full' in result.detail
assert not management.unfinished_operations(request.evidence_dir)
def test_bad_history_evidence_location_does_not_turn_prelaunch_error_into_unreleased_session(tmp_path, monkeypatch):
from cbb_refresh_verify import library_lock as locks, verify_runner as runner
library=tmp_path/'lib.lmc';library.touch()
locks._persist_blocker(library,lease_id='c'*32)
monkeypatch.setattr(runner,'_run_verify_serialized',lambda *a,**kw:pytest.fail('invalid evidence launched native work'))
result=runner.run_verify(runner.VerifyRequest(library,'Target',tmp_path/'evidence'))
assert result.safe_to_continue and result.error_category=='LIBRARY_ACCESS_FAILED'
assert locks.blocker_path(library).exists()
def test_history_probe_timeout_does_not_stop_next_independent_library(tmp_path, monkeypatch):
from cbb_refresh_verify import library_lock as locks, verify_runner as runner
a=tmp_path/'A/lib.lmc';a.parent.mkdir();a.touch()
b=tmp_path/'B/lib.lmc';b.parent.mkdir();b.touch()
locks._persist_blocker(a,lease_id='d'*32)
def timeout(*args):raise RuntimeError('OWNER_QUERY_TIMEOUT')
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners',timeout)
calls=[]
monkeypatch.setattr(runner,'_run_verify_serialized',lambda req,**kw:
calls.append(req.lmc_file) or runner.VerifyResult('PASS'))
results=runner.run_batch([runner.VerifyRequest(p,'Target',tmp_path/'evidence') for p in (a,b)])
assert [r.status for r in results]==['FAIL','PASS']
assert results[0].safe_to_continue and calls==[b]
@@ -0,0 +1,52 @@
import json
from pathlib import Path
import pytest
from cbb_refresh_verify import library_lock as locks
@pytest.mark.parametrize('retained_owner', [False, True])
def test_releasing_another_blocks_checkpoint_names_its_owner(tmp_path, monkeypatch, retained_owner):
library = tmp_path/'library/lib.lmc'
library.parent.mkdir(); library.touch()
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
lease = None
if retained_owner:
with locks.LibraryLock(library, block_name='BlockB', safe_to_release=lambda: False) as lease:
pass
else:
locks._persist_blocker(library, lease_id='b'*32, block_name='BlockB')
before = locks.blocker_path(library).read_bytes()
try:
proof = locks.release_retained_library(library, tmp_path/'evidence', block_name='BlockA')
assert proof['requested_block_name'] == 'BlockA'
assert proof['proof_scope'] == 'LIBRARY'
assert proof['reconciled_foreign_blockers'] == ['BlockB']
assert proof['data_recovery_confirmed'] is False
checkpoint = next(r for r in proof['reconciled_checkpoints'] if r['kind'] == 'checkpoint')
assert checkpoint['block_name'] == 'BlockB' and checkpoint['status'] == 'OWNER_RELEASE_UNCONFIRMED'
assert checkpoint['lease_id']
proof_path = Path(proof['evidence_path'])
assert json.loads(proof_path.read_text('utf-8'))['reconciled_foreign_blockers'] == ['BlockB']
assert (proof_path.parent/'blocker-before-0.json').read_bytes() == before
assert not locks.blocker_path(library).exists()
if retained_owner:
assert any(r['kind'] == 'retained_owner' and r['block_name'] == 'BlockB'
for r in proof['reconciled_checkpoints'])
finally:
if lease:
with locks._guard:
owner = locks._owners.pop(lease.key, None)
if owner:
owner['handle'].Close()
def test_matching_checkpoint_uses_block_scope_without_foreign_targets(tmp_path, monkeypatch):
library = tmp_path/'library/lib.lmc'
library.parent.mkdir(); library.touch()
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
locks._persist_blocker(library, lease_id='a'*32, block_name='BlockA')
proof = locks.release_retained_library(library, tmp_path/'evidence', block_name='BlockA')
assert proof['proof_scope'] == 'BLOCK' and proof['proof_block_name'] == 'BlockA'
assert proof['reconciled_foreign_blockers'] == []
@@ -0,0 +1,45 @@
from dataclasses import replace
from test_management import setup
def test_released_item_failure_does_not_claim_entire_queue_stopped(qtbot, setup):
from cbb_refresh_verify.management import ManagementResult
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
request, _, _ = setup
dialog=ManagementDialog([request]);qtbot.addWidget(dialog)
result=ManagementResult(request.operation,request.library,request.name,request.partition,
None,False,'complete','RECOVERY_REQUIRED',True,'native add failed')
dialog._result([result])
assert '需要人工恢复' in dialog.status_label.text()
assert '队列已停止' not in dialog.status_label.text()
def test_report_failure_is_visible_without_inventing_native_failure(qtbot, setup):
from cbb_refresh_verify.management import ManagementResult
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
request, _, _=setup
dialog=ManagementDialog([request]);qtbot.addWidget(dialog)
result=ManagementResult(request.operation,request.library,request.name,request.partition,
None,False,'complete','REMOVED',True,'removed',release_proof={
'status':'RELEASE_CONFIRMED','data_recovery_confirmed':False},
change_report={'status':'UNCONFIRMED','detail':'report disk full'})
dialog._result([result])
assert '已移除' in dialog.status_label.text() and '变更清单待核对' in dialog.status_label.text()
assert '历史会话已释放' in dialog.output.toPlainText()
dialog._progress({'stage':'previous_release_check','block':request.name})
assert '正在复核历史占用' in dialog.status_label.text()
def test_recorded_counts_identify_compared_engineering_file_scope(qtbot, setup):
from cbb_refresh_verify.management import ManagementResult
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
request, _, _ = setup
dialog = ManagementDialog([request]); qtbot.addWidget(dialog)
result = ManagementResult(request.operation, request.library, request.name, request.partition,
None, False, 'complete', 'REMOVED', True, 'removed',
change_report={'status': 'RECORDED', 'added': ['a'], 'deleted': [], 'modified': ['b']})
dialog._result([result])
text = dialog.output.toPlainText()
assert '已比对的工程文件' in text
assert '新增 1' in text and '删除 0' in text and '修改 1' in text
+302
View File
@@ -0,0 +1,302 @@
import json
from contextlib import nullcontext
from pathlib import Path
import pytest
from test_residual_sessions import row, OWNERSHIP
@pytest.mark.parametrize('failure_stage', ['before_actions', 'after_actions'])
def test_snapshot_timeout_keeps_each_actual_release_result(tmp_path, monkeypatch, failure_stage):
from cbb_refresh_verify import residual_sessions as sessions
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
process = row(10, library.parent/'ReusableBlocksLP/A/Work/A.prj')
process.update(scope_confirmed=True, created_handle='creation', image=process['executable'], **OWNERSHIP)
snapshots = [0]
def snapshot():
snapshots[0] += 1
if snapshots[0] == (1 if failure_stage == 'before_actions' else 2):
raise TimeoutError('OWNER_QUERY_TIMEOUT')
return [process]
monkeypatch.setattr(sessions, 'query_process_snapshot', snapshot)
monkeypatch.setattr(sessions, '_request_close', lambda *a, **kw:
{'release_status': 'RELEASED', 'detail': 'closed'})
monkeypatch.setattr(sessions, '_finish_library_release', lambda *a: pytest.fail('snapshot failed'))
plan = {'library': str(library), 'sessions': [process]}
result = sessions._release_residual_sessions(plan, tmp_path/'evidence')
saved = json.loads(Path(result['evidence_path']).read_text('utf-8'))
assert saved['status'] == 'PARTIAL' and 'OWNER_QUERY_TIMEOUT' in saved['detail']
assert saved['sessions'][0]['release_status'] == ('NOT_STARTED' if failure_stage == 'before_actions' else 'RELEASED')
def test_first_outcome_is_durable_before_next_session_action(tmp_path, monkeypatch):
from cbb_refresh_verify import residual_sessions as sessions
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
processes = [dict(row(pid, library.parent/f'ReusableBlocksLP/{pid}/Work/a.prj'),
scope_confirmed=True) for pid in (10, 20)]
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: processes)
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
def close(process, **kwargs):
if process['pid'] == 20:
report = json.loads(next((tmp_path/'evidence').glob('sessions-*/result.json')).read_text('utf-8'))
assert report['sessions'][0]['release_status'] == 'RELEASED'
assert report['sessions'][1]['release_status'] == 'REQUESTING'
return {'release_status': 'RELEASED', 'detail': 'closed'}
monkeypatch.setattr(sessions, '_request_close', close)
monkeypatch.setattr(sessions, '_finish_library_release', lambda *a:
{'status': 'RELEASE_CONFIRMED', 'library': str(library)})
result = sessions._release_residual_sessions({'library': str(library), 'sessions': processes}, tmp_path/'evidence')
assert result['status'] == 'RELEASE_CONFIRMED'
def test_report_storage_failure_does_not_claim_complete_or_undo_release_proof(tmp_path, monkeypatch):
from cbb_refresh_verify import residual_sessions as sessions
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [])
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
monkeypatch.setattr(sessions, '_finish_library_release', lambda *a:
{'status': 'RELEASE_CONFIRMED', 'library': str(library)})
original = Path.open
writes = []
def deny(path, *args, **kwargs):
if path.name == 'result.pending':
writes.append(1)
if len(writes) > 1: raise PermissionError('disk full after release')
return original(path, *args, **kwargs)
monkeypatch.setattr(Path, 'open', deny)
result = sessions._release_residual_sessions({'library': str(library), 'sessions': []}, tmp_path/'evidence')
assert result['status'] == 'PARTIAL' and 'disk full' in result['evidence_error']
assert result['proof']['status'] == 'RELEASE_CONFIRMED'
@pytest.mark.parametrize('output', [None, 'Repairing project\nRepair backup created successfully.',
'Restoring project', 'Backing up project'])
def test_force_rechecks_native_backup_activity_before_termination(monkeypatch, output):
import win32api, win32con, win32event
from cbb_refresh_verify import residual_sessions as sessions
process = dict(row(10, 'C:/library/A.prj'), scope_confirmed=True,
created_handle='creation', image='C:/Mentor/iCDBProjectBackup.exe',
native_activity={'status': 'IDLE'}, **OWNERSHIP)
monkeypatch.setattr(sessions, '_process_handle', lambda *a, **kw: nullcontext(123))
monkeypatch.setattr(sessions, '_handle_identity', lambda _: {k:process[k] for k in ('created_handle','image')})
monkeypatch.setattr(sessions, '_force_ownership', lambda *a: dict(OWNERSHIP))
monkeypatch.setattr(win32event, 'WaitForSingleObject', lambda *a: win32con.WAIT_TIMEOUT)
monkeypatch.setattr(sessions, '_process_windows', lambda _: {10: [
{'hwnd': 100, 'class': 'Afx:main', 'title': 'iCDB Project Backup - A',
'enabled': True, 'children': [], 'output': output, 'desktop': 'CbbRepair_A'}]})
monkeypatch.setattr(win32api, 'TerminateProcess', lambda *a: pytest.fail('interrupted Backup/Repair'))
result = sessions._force_close(process)
assert result['release_status'] == 'WAITING'
assert result['native_activity']['status'] in ('ACTIVE', 'UNCONFIRMED')
def test_inspection_exposes_private_desktop_and_disables_force_for_active_backup(tmp_path, monkeypatch):
from cbb_refresh_verify import residual_sessions as sessions
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
process = row(10, library.parent/'ReusableBlocksLP/A/Work/A.prj')
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [process])
monkeypatch.setattr(sessions, '_process_identity', lambda r:
dict(created_handle='creation', image=r['executable'], **OWNERSHIP))
monkeypatch.setattr(sessions, '_process_windows', lambda _: {10:[
{'hwnd':100,'class':'Afx:main','title':'iCDB Project Backup - A','enabled':True,
'children':[],'output':'Repairing project','desktop':'CbbRepair_A'}]})
preview = sessions.inspect_residual_sessions(library)['sessions'][0]
assert preview['force_allowed'] is False
assert preview['desktops'] == ['CbbRepair_A']
assert preview['native_activity']['status'] == 'ACTIVE'
def test_saved_prompt_from_private_desktop_remains_actionable():
from cbb_refresh_verify.residual_sessions import _save_question
prompt = _save_question([{'hwnd':100,'class':'#32770','title':'Expedition PCB',
'desktop':'CbbVerify_A','children':[{'class':'Static','text':'Save changes to modified design?'},
*[{'class':'Button','id':code,'hwnd':code,'enabled':True} for code in (6,7,2)]]}])
assert prompt['desktop'] == 'CbbVerify_A' and set(prompt['buttons']) == {6,7,2}
def test_native_cancel_requires_same_current_control_and_exact_owned_process(monkeypatch):
import win32con, win32event, win32gui, win32process
from cbb_refresh_verify import residual_sessions as sessions
process = dict(row(10, 'C:/library/A.prj'), scope_confirmed=True,
created_handle='creation', image='C:/Mentor/iCDBProjectBackup.exe', **OWNERSHIP)
window = {'hwnd':100,'class':'Afx:main','title':'iCDB Project Backup - A','enabled':True,
'output':'Backing up project','desktop':'CbbRepair_A',
'children':[{'class':'Button','id':2,'text':'Cancel','enabled':True,'hwnd':102}]}
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [process])
monkeypatch.setattr(sessions, '_process_handle', lambda *a,**kw: nullcontext(123))
monkeypatch.setattr(sessions, '_handle_identity', lambda _: {k:process[k] for k in ('created_handle','image')})
monkeypatch.setattr(sessions, '_force_ownership', lambda *a: dict(OWNERSHIP))
monkeypatch.setattr(sessions, '_process_windows', lambda _: {10:[window]})
monkeypatch.setattr(win32event, 'WaitForSingleObject', lambda *a: win32con.WAIT_TIMEOUT)
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda _: (1,10))
clicked=[]; monkeypatch.setattr(win32gui, 'PostMessage', lambda *a: clicked.append(a))
process['cancel_prompt']={'hwnd':100,'button':dict(window['children'][0]),
'title':window['title'],'desktop':'CbbRepair_A'}
result = sessions._request_native_cancel(process)
assert result['release_status'] == 'WAITING' and clicked == [(102, win32con.BM_CLICK, 0, 0)]
window['children'][0]['text'] = 'Restore'
with pytest.raises(ValueError, match='取消'):
sessions._request_native_cancel(process)
assert len(clicked)==1
def test_ui_reports_missing_evidence_but_propagates_valid_library_release(qtbot, tmp_path, monkeypatch):
from cbb_refresh_verify import library_lock
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
library = tmp_path/'lib.lmc'
monkeypatch.setattr(library_lock, 'inspect_residual_sessions', lambda *_:
{'library':str(library),'sessions':[]})
proof = {'status':'RELEASE_CONFIRMED','library':str(library)}
monkeypatch.setattr(library_lock, 'release_residual_sessions', lambda *a,**kw:
{'status':'PARTIAL','sessions':[],'proof':proof,'evidence_error':'disk full'})
dialog = ResidualReleaseDialog(library, tmp_path/'evidence'); qtbot.addWidget(dialog)
released = []; dialog.released.connect(released.append)
qtbot.waitUntil(lambda: not dialog.busy)
dialog.confirm_button.click(); qtbot.waitUntil(lambda: not dialog.busy)
assert released == [proof]
assert '记录' in dialog.message.text() and 'disk full' in dialog.message.text()
def test_ui_native_cancel_is_explicit_and_details_are_readable(qtbot, tmp_path, monkeypatch):
from PySide6.QtWidgets import QMessageBox
from cbb_refresh_verify import library_lock, residual_sessions
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
library = tmp_path/'lib.lmc'
process = {'name':'iCDBProjectBackup.exe','pid':10,'detail':'备份进行中',
'image':'C:/Mentor/iCDBProjectBackup.exe','desktops':['CbbRepair_A'],
'native_activity':{'status':'ACTIVE','detail':'正在备份'},'cancel_prompt':{'hwnd':100},
'windows':[{'title':'iCDB Project Backup - A','output':'Backing up project','children':[]}]}
monkeypatch.setattr(library_lock, 'inspect_residual_sessions', lambda *_:
{'library':str(library),'sessions':[process]})
calls=[]
monkeypatch.setattr(residual_sessions,'request_native_cancel',lambda *a,**kw:
calls.append(a[0]) or {'status':'PARTIAL','sessions':[{'detail':'已请求取消'}]})
dialog=ResidualReleaseDialog(library,tmp_path/'evidence');qtbot.addWidget(dialog)
qtbot.waitUntil(lambda:not dialog.busy)
assert dialog.cancel_native_button.isEnabled() and not dialog.force_button.isEnabled()
dialog.details_button.click()
assert 'Backing up project' in dialog.native_details.detailedText()
assert 'CbbRepair_A' in dialog.native_details.detailedText()
dialog.native_details.close()
monkeypatch.setattr(QMessageBox,'question',lambda *a:QMessageBox.No)
dialog.cancel_native_button.click();assert calls==[]
monkeypatch.setattr(QMessageBox,'question',lambda *a:QMessageBox.Yes)
dialog.cancel_native_button.click();qtbot.waitUntil(lambda:not dialog.busy)
assert calls==[process]
def test_force_can_resume_after_backup_finishes_and_preview_is_refreshed(tmp_path, monkeypatch):
from cbb_refresh_verify import residual_sessions as sessions
library=tmp_path/'library/lib.lmc';library.parent.mkdir();library.touch()
process=row(10,library.parent/'ReusableBlocksLP/A/Work/A.prj')
monkeypatch.setattr(sessions,'query_process_snapshot',lambda:[process])
monkeypatch.setattr(sessions,'_process_identity',lambda r:
dict(created_handle='creation',image=r['executable'],**OWNERSHIP))
window={'hwnd':100,'class':'Afx:main','title':'iCDB Project Backup - A','enabled':True,
'children':[],'output':'Repairing project'}
monkeypatch.setattr(sessions,'_process_windows',lambda _:{10:[window]})
assert not sessions.inspect_residual_sessions(library)['sessions'][0]['force_allowed']
window['output']+='\nBackup information loaded correctly.'
assert sessions.inspect_residual_sessions(library)['sessions'][0]['force_allowed']
def test_native_cancel_records_consent_before_sending_any_message(tmp_path, monkeypatch):
from cbb_refresh_verify import residual_sessions as sessions
library=tmp_path/'library/lib.lmc';library.parent.mkdir();library.touch()
process=dict(row(10,library.parent/'ReusableBlocksLP/A/Work/A.prj'),
scope_confirmed=True,cancel_prompt={'hwnd':100})
evidence=tmp_path/'evidence'
monkeypatch.setattr(sessions,'query_process_snapshot',lambda:[process])
monkeypatch.setattr(sessions,'_process_windows',lambda _:{})
def cancel(actual, **kwargs):
record=json.loads(next(evidence.glob('sessions-*/consent.json')).read_text('utf-8'))
assert record['mode']=='cancel_native' and record['sessions'][0]['pid']==actual['pid']
return {'release_status':'WAITING','detail':'cancel requested'}
monkeypatch.setattr(sessions,'_request_native_cancel',cancel)
result=sessions.request_native_cancel(process,library,evidence)
assert result['cancel_native'] and Path(result['consent_path']).is_file()
assert result['sessions'][0]['detail']=='cancel requested'
def test_missing_initial_checkpoint_prevents_all_close_actions(tmp_path, monkeypatch):
from cbb_refresh_verify import residual_sessions as sessions
library=tmp_path/'library/lib.lmc';library.parent.mkdir();library.touch()
process=dict(row(10,library.parent/'A.prj'),scope_confirmed=True)
original=Path.open
def denied(path,*args,**kwargs):
if path.name=='result.pending':raise PermissionError('no storage')
return original(path,*args,**kwargs)
monkeypatch.setattr(Path,'open',denied)
monkeypatch.setattr(sessions,'_request_close',lambda *a,**kw:pytest.fail('unrecorded close'))
result=sessions._release_residual_sessions({'library':str(library),'sessions':[process]},tmp_path/'evidence')
assert result['status']=='PARTIAL' and result['sessions'][0]['release_status']=='NOT_STARTED'
def test_native_cancel_completion_propagates_actual_release_to_parent(qtbot,tmp_path,monkeypatch):
from PySide6.QtWidgets import QMessageBox
from cbb_refresh_verify import library_lock,residual_sessions
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
library=tmp_path/'lib.lmc'
process={'name':'iCDBProjectBackup.exe','pid':10,'cancel_prompt':{'hwnd':100}}
monkeypatch.setattr(library_lock,'inspect_residual_sessions',lambda *_:
{'library':str(library),'sessions':[process]})
proof={'status':'RELEASE_CONFIRMED','library':str(library)}
monkeypatch.setattr(residual_sessions,'request_native_cancel',lambda *a,**kw:
{'status':'RELEASE_CONFIRMED','sessions':[{**process,'release_status':'RELEASED'}],'proof':proof})
monkeypatch.setattr(QMessageBox,'question',lambda *a:QMessageBox.Yes)
dialog=ResidualReleaseDialog(library,tmp_path/'evidence');qtbot.addWidget(dialog)
released=[];dialog.released.connect(released.append)
qtbot.waitUntil(lambda:not dialog.busy)
dialog.cancel_native_button.click();qtbot.waitUntil(lambda:not dialog.busy)
assert released==[proof] and dialog.plan is None
def test_interruption_after_request_is_not_recorded_as_never_started(tmp_path,monkeypatch):
from cbb_refresh_verify import residual_sessions as sessions
library=tmp_path/'library/lib.lmc';library.parent.mkdir();library.touch()
process=dict(row(10,library.parent/'A.prj'),scope_confirmed=True)
evidence=tmp_path/'evidence'
monkeypatch.setattr(sessions,'query_process_snapshot',lambda:[process])
observed=[]
def interrupted(*a,**kw):
record=json.loads(next(evidence.glob('sessions-*/result.json')).read_text('utf-8'))
observed.append(record['sessions'][0]['release_status'])
raise KeyboardInterrupt()
monkeypatch.setattr(sessions,'_request_close',interrupted)
with pytest.raises(KeyboardInterrupt):
sessions._release_residual_sessions({'library':str(library),'sessions':[process]},evidence)
assert observed==['REQUESTING']
saved=json.loads(next(evidence.glob('sessions-*/result.json')).read_text('utf-8'))
assert saved['sessions'][0]['release_status']=='REQUESTING' and saved['status']=='PARTIAL'
def test_stop_during_native_activity_read_prevents_force_termination(monkeypatch):
from threading import Event
import win32api,win32con,win32event
from cbb_refresh_verify import residual_sessions as sessions
process=dict(row(10,'C:/library/A.prj',name='ExpeditionPCB.exe'),scope_confirmed=True,
created_handle='creation',image='C:/Mentor/ExpeditionPCB.exe',**OWNERSHIP)
stop=Event()
monkeypatch.setattr(sessions,'_process_handle',lambda *a,**kw:nullcontext(123))
monkeypatch.setattr(sessions,'_handle_identity',lambda _:{k:process[k] for k in ('created_handle','image')})
monkeypatch.setattr(sessions,'_force_ownership',lambda *a:dict(OWNERSHIP))
monkeypatch.setattr(win32event,'WaitForSingleObject',lambda *a:win32con.WAIT_TIMEOUT)
def windows(*args):stop.set();return {10:[]}
monkeypatch.setattr(sessions,'_process_windows',windows)
monkeypatch.setattr(win32api,'TerminateProcess',lambda *a:pytest.fail('force continued after stop'))
assert sessions._force_close(process,stop=stop)['release_status']=='CANCELLED'
def test_gui_release_proof_comparison_does_not_probe_network_filesystem(qtbot,tmp_path,monkeypatch):
from cbb_refresh_verify import library_lock
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
library=tmp_path/'lib.lmc'
monkeypatch.setattr(library_lock,'inspect_residual_sessions',lambda *_:
{'library':str(library),'sessions':[]})
dialog=ResidualReleaseDialog(library,tmp_path/'evidence');qtbot.addWidget(dialog)
qtbot.waitUntil(lambda:not dialog.busy)
with monkeypatch.context() as guard:
guard.setattr(Path,'resolve',lambda *a,**kw:pytest.fail('GUI tried filesystem resolution'))
assert dialog._accept_release_proof({'sessions':[],'proof':{
'status':'RELEASE_CONFIRMED','library':str(library)}})
+31 -6
View File
@@ -118,17 +118,42 @@ def test_corrupted_destination_bytes_are_rejected_and_evidence_is_preserved(tmp_
assert (destination/relative).exists()
def test_unlocked_primary_copy_reads_source_twice_and_target_once(tmp_path, monkeypatch):
from collections import Counter
source, destination = tmp_path/'source', tmp_path/'destination'
primary = put(source, 'A.prj', b'engineering' * 100000)
reads = Counter()
original_open = Path.open
def opened(path, mode='r', *args, **kwargs):
if mode == 'rb':
reads[path] += 1
return original_open(path, mode, *args, **kwargs)
monkeypatch.setattr(Path, 'open', opened)
hashes = Counter()
original_hash = recovery._hash
def hashed(path):
hashes[path] += 1
return original_hash(path)
monkeypatch.setattr(recovery, '_hash', hashed)
manifest = recovery._copy_verified(source, destination)
assert hashes[primary] == 1 # Only the final source rehash is a separate pass.
assert hashes[destination/'A.prj'] == 1
assert reads[primary] == 2 # Copy/hash stream, then final source content proof.
assert reads[destination/'A.prj'] == 1
assert manifest['files']['A.prj']['sha256'] == hashlib.sha256(primary.read_bytes()).hexdigest()
def test_source_byte_changes_with_preserved_metadata_are_rejected(tmp_path, monkeypatch):
source, destination = tmp_path/'source', tmp_path/'destination'
primary = put(source, 'A.prj')
real_copy = shutil.copy2
real_copy = shutil.copystat
def copy_then_change_source(src, dst, *args, **kwargs):
result = real_copy(src, dst, *args, **kwargs)
metadata = primary.stat()
primary.write_bytes(b'X' * metadata.st_size)
os.utime(primary, ns=(metadata.st_atime_ns, metadata.st_mtime_ns))
return result
monkeypatch.setattr(shutil, 'copy2', copy_then_change_source)
monkeypatch.setattr(shutil, 'copystat', copy_then_change_source)
with pytest.raises(OSError):
recovery._copy_verified(source, destination)
assert (destination/'A.prj').read_bytes() == b'engineering'
@@ -140,7 +165,7 @@ def test_complete_tree_metadata_must_stay_stable_during_copy(tmp_path, monkeypat
put(source, 'A.prj')
runtime = put(source, 'logs/session.log')
destination = tmp_path/'destination'
real_copy = shutil.copy2
real_copy = shutil.copystat
def copy_then_mutate(src, dst, *args, **kwargs):
result = real_copy(src, dst, *args, **kwargs)
if Path(src).name == 'A.prj':
@@ -151,7 +176,7 @@ def test_complete_tree_metadata_must_stay_stable_during_copy(tmp_path, monkeypat
else:
put(source, 'logs/added.log')
return result
monkeypatch.setattr(shutil, 'copy2', copy_then_mutate)
monkeypatch.setattr(shutil, 'copystat', copy_then_mutate)
with pytest.raises(OSError):
recovery._copy_verified(source, destination)
assert destination.exists()
@@ -277,7 +302,7 @@ def test_colliding_engineering_names_cannot_bypass_primary_copy_byte_checks(tmp_
scope = ManifestScope.library(block, 'target.lmc')
source, destination = tmp_path/'source', tmp_path/'destination'
put(source, relative)
real_copy = shutil.copy2
real_copy = shutil.copystat
def copy_then_corrupt(src, dst, *args, **kwargs):
result = real_copy(src, dst, *args, **kwargs)
corrupt = Path(src) if side == 'source' else Path(dst)
@@ -285,7 +310,7 @@ def test_colliding_engineering_names_cannot_bypass_primary_copy_byte_checks(tmp_
corrupt.write_bytes(b'X' * metadata.st_size)
os.utime(corrupt, ns=(metadata.st_atime_ns, metadata.st_mtime_ns))
return result
monkeypatch.setattr(shutil, 'copy2', copy_then_corrupt)
monkeypatch.setattr(shutil, 'copystat', copy_then_corrupt)
with pytest.raises(OSError):
recovery._copy_verified(source, destination, scope=scope)
assert (destination/relative).exists()