Compare commits
60
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9a9fbce9b2 | ||
|
|
1bd7589fef | ||
|
|
1acfbd6374 | ||
|
|
aea6192ef9 | ||
|
|
53118bae19 | ||
|
|
beb2b06fdf | ||
|
|
4ebe098ef0 | ||
|
|
00db1cf5f2 | ||
|
|
477a5a46e3 | ||
|
|
2587d33c5a | ||
|
|
223655fe00 | ||
|
|
29959e2988 | ||
|
|
e14a864b37 | ||
|
|
cb1326688b | ||
|
|
ef652f3ada | ||
|
|
8180a8a302 | ||
|
|
c902ffbe9a | ||
|
|
de952a68d6 | ||
|
|
c85696080d | ||
|
|
7527800128 | ||
|
|
d36b6bcad0 | ||
|
|
5eac654c36 | ||
|
|
b26e2f2f62 | ||
|
|
9ac2f91dde | ||
|
|
e915aaa865 | ||
|
|
f21781f170 | ||
|
|
55a82fdc5f | ||
|
|
89500cbb5f | ||
|
|
63f3417f19 | ||
|
|
ca84bce24f | ||
|
|
b97556dcc1 | ||
|
|
07a9c1eaaf | ||
|
|
f8f2dd53aa | ||
|
|
2085ec770f | ||
|
|
d76475a1d7 | ||
|
|
99a708b40c | ||
|
|
9806ef8f66 | ||
|
|
aa6684b588 | ||
|
|
5a758ee3b6 | ||
|
|
b635432cff | ||
|
|
4cbca0b5a6 | ||
|
|
e39dc63ded | ||
|
|
4f741cd176 | ||
|
|
122bafcc7a | ||
|
|
8e486c1097 | ||
|
|
bb98fe66dd | ||
|
|
1f69480ed8 | ||
|
|
ffa7e84d43 | ||
|
|
46c3e72364 | ||
|
|
dd1fcea7e2 | ||
|
|
797a79c30e | ||
|
|
3415e010ff | ||
|
|
29c154d2ca | ||
|
|
877e3b4c76 | ||
|
|
b90a9bbfab | ||
|
|
747ce1add2 | ||
|
|
c823a4b92d | ||
|
|
aa760c2839 | ||
|
|
44b808b8e2 | ||
|
|
ec78dd722c |
No files matched your search
@@ -1,19 +1,15 @@
|
||||
# CBB 中心库上传后校验工具
|
||||
|
||||
当前临时分支的备份策略(2026-11-03):应用不再自动备份中心库或 CBB 工程。新增、替换、移除、校验、ICDB 维护和恢复在执行前提示手动备份;请自行保留可用副本。导入暂存、恢复用隔离验证库和轻量操作证据仍会生成,Mentor 原生 Repair 自身的备份行为保持不变。详见[自动备份检查与调整](docs/releases/2026-11-03-manual-backup.md)。此条优先于下方历史版本的备份说明。
|
||||
|
||||
当前临时分支的备份策略(2026-11-03):应用不再自动备份中心库或 CBB 工程。新增、替换、移除、校验、ICDB 维护和恢复在执行前提示手动备份;请自行保留可用副本。导入暂存、恢复用隔离验证库和轻量操作证据仍会生成,Mentor 原生 Repair 自身的备份行为保持不变。详见[自动备份检查与调整](docs/releases/2026-11-03-manual-backup.md)。此条优先于下方历史版本的备份说明。
|
||||
|
||||
当前开发版本:**[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)。下方日期记录为历史行为,以本说明为准。
|
||||
当前补丁:**[v0.2.3-beta.1](docs/releases/v0.2.3-beta.1.md)(Beta 预发布,待现场验收)**,替代 0.2.2-beta.1。数据库所有权或关闭状态不确定时停止批次、保留现场;不自动移走地址文件、接管带锁设计或强杀 PCB 进程树。新增全库 ICDB 维护、同名 CBB 完整备份恢复弹窗及严格的原生复核流程。详见 [v0.2.3-beta.1 发布说明](docs/releases/v0.2.3-beta.1.md)。下方日期记录描述历史版本,以本补丁说明为准。
|
||||
|
||||
本目录是独立的 CBB 中心库上传后校验工具,不属于 Part Replacement,也不负责 CBB 工程复制或中心库上传。
|
||||
|
||||
针对 `The last server session ... lost the connection to the database`,修复分支增加
|
||||
`ICDB_REPAIR_REQUIRED` 专项识别、共享符号库路径诊断及停止批次处理。现场原生修复步骤及实现边界见
|
||||
[iCDB 旧服务器会话失联分析](docs/diagnostics/2026-10-27-icdb-lost-server-session.md)。
|
||||
当前应用入口仅检查工程打开情况,不自动 Repair。需要修复或回退时由用户在原生版本与备份界面选择,操作前请手动备份;共享符号库故障不得通过修复无关的 CBB 工程替代。
|
||||
当前分支会在目标明确、所有权释放和独占访问证据齐全时尝试一次同版本原生 Repair;操作前请手动备份,共享符号库没有 PRJ 入口时停止并要求人工处理。
|
||||
|
||||
## 功能边界
|
||||
|
||||
@@ -207,7 +203,7 @@ Mentor 桥耗时需在目标机器另行测量。
|
||||
- `save.log`:`LICENSE_OK / SAVE_OK / IS_SAVED / POST_SAVE_SYNCHRONIZED / CLOSE_OK / QUIT_OK`;
|
||||
- `result.json`:状态、中心库标志读取结果、阻断原因;
|
||||
- `image-status-map.json`:按中心库路径隔离的本机动态 `image_id` 校准快照(当前格式 `schema_version=2`);旧版本或无版本缓存会自动忽略并重新校准,日志会记录当前样本、缓存样本、Ready 主 ID、未映射 ID 和逐项决策原因;
|
||||
- `backup/`:历史版本的辅助文件副本;当前分支不再生成,所有路径记录 `backup_skipped / manual_backup_policy`。已有历史副本不由本轮改动清理。
|
||||
- `backup/`:历史版本的辅助文件副本;当前分支不再生成,所有路径记录 `backup_skipped / manual_backup_policy`。已有历史副本不由本轮改动清理。
|
||||
|
||||
超时采用无进展计时:界面和批量请求默认 600 秒无进展超时;它不是整个 CBB 的固定总时限,而是连续 600 秒没有可观察进展时才终止。PCB/COM 阶段切换、Project Integration 状态变化、保存标记变化和弹窗处理都会刷新计时器;重复的状态轮询不算进展。需要更快失败时仍可在界面将单项预算调低,但 30 秒只适合已确认 PCB 启动稳定的环境。
|
||||
|
||||
|
||||
@@ -1,40 +1,4 @@
|
||||
# CBB 检查、校验、管理与残留释放操作规程
|
||||
|
||||
适用开发版本:0.2.4b1。未完成现场验收,不自动发布或关闭工单。以下为当前规程,下方旧上传校验检查表保留为历史参考。
|
||||
|
||||
## 当前操作与队列
|
||||
|
||||
选择中心库 `.lmc`,核对 CBB 名称、分区及完整 PRJ/PCB 工程。写操作和人工修复前由操作员保存可用一致备份;应用不自动备份整个中心库,隔离验证/暂存副本不代替人工备份。
|
||||
|
||||
普通校验完成原生打开、身份确认、Project Integration、保存和关闭后,必须由权威状态 READY/raw=1 确认成功。ICDB 检查仅尝试打开并检查本次错误,不自动 Repair、Restore 或选择版本,CHECKED 不等于 READY。排队期间变成 READY 的工程在执行前跳过。
|
||||
|
||||
原生任务串行排队,检查每项结束后让出机会;缓存筛选保持可用。失败项确认释放后继续独立项目;实际未释放时停止后续原生操作。“停止检查”只取消检查,“取消当前任务并停止队列”同时取消前台任务及后续后台检查,已进行的写入等待安全结束,不强杀代替取消。
|
||||
|
||||
新增拒绝同名冲突;更新先原生移除再导入,失败可能需要人工备份恢复;移除后重新读取目录确认。版本回退由操作员在原生界面选择,核对工程内容后单独校验。
|
||||
|
||||
## 历史记录、操作结果与报告
|
||||
|
||||
校验和管理遇到历史释放记录时,先复核实际进程、地址、独占文件及导出副本。确认释放后归档记录再继续,不以历史 JSON 本身判定真实占用;同目标未完成写入仍需核对,不自动重放。释放证明在管理首次原生调用前写入检查点,并在结果中保留。
|
||||
|
||||
管理操作生成目标工程、库配置和共享依赖的写前/写后主要文件清单及新增、删除、修改差分;不增加自动全库备份,也不声称检查了其他 CBB 内容。报告不可用与原生操作失败分别记录;本任务已释放时可继续独立项。
|
||||
|
||||
## 默认释放与单独确认的强制客户端操作
|
||||
|
||||
1. 停止新任务,预览当前库的工程、程序、PID 和历史记录。默认“确认释放”仅正常关闭作用域及当前身份已确认的客户端。未保存更改由操作员选择保存、放弃或保留;未知提示保持现场。
|
||||
2. 数据库服务器可能服务同库其他用户。本工具不允许强制结束服务器,命令行指向本库也不构成独占授权;由库管理员核对用户和服务器状态。
|
||||
3. “强制结束客户端”是另行确认的异常处理,只允许属于当前 Windows 用户和会话、已确认作用域和精确进程身份的 Expedition PCB、Library Manager、viewdraw、iCDB Project Backup 客户端。后台导入器、脚本宿主和归属未知的进程同样不在强制名单。
|
||||
4. 警告明确告知客户端中其他已打开工程可能一并退出、未保存更改会丢失、写入中的工程可能需要恢复。执行前持久保存库外 `consent.json`,包含目标库、名单、创建身份和排除项;写入失败不执行。派发处核对快照身份和原预览范围,最终句柄处核对创建时间、完整映像、用户 SID、Windows 会话和原生活动;变化时拒绝。
|
||||
5. 预览和执行前检查进度与本轮 Output。Backup/Restore/Repair 进行中或状态无法确认时,不强制结束。可查看后台窗口的标题、输出和所在桌面;仅当当前窗口唯一存在已识别的 Cancel/取消按钮时,提供单独确认的原生取消。核对身份、用户会话和按钮快照后发送请求,再重新检查实际结果;没有识别到按钮时不猜菜单参数,不抢占前台。
|
||||
6. 每项动作前后持久记录实际结果,异常保留已完成/未执行项。若最终记录保存失败但独立库释放证明已确认,界面明确提示记录失败并接受释放事实,不伪造新的占用。
|
||||
7. 客户端退出仅证明进程结束,不表示修复成功或 READY。服务器仍活跃或库状态未知时保留 PARTIAL、检查点和映射。只有完整的独立释放证明才解除匹配的历史记录;空进程列表本身不是释放证明。
|
||||
|
||||
## 失败、证据和回退
|
||||
|
||||
保留原生错误、操作员、Mentor 版本、库/工程身份和证据目录;原生日志上传前脱敏。不得删除原生地址/锁文件或修改 LMC 伪造状态。强制客户端退出不可撤销;工程恢复依靠人工一致备份或原生历史版本,不自动回退共享库或重放写操作。
|
||||
|
||||
程序回退须先关闭当前客户端,再运行此前候选包;它不恢复丢失更改或被中断的原生事务。工程恢复另行在隔离副本验证,保留前后证据并重新校验。Windows 10、共享库跨机器并发和现场服务器失联恢复仍待验收,fake 测试和文件头损坏试验不代替现场验收。
|
||||
|
||||
## 历史上传校验检查表
|
||||
# CBB 中心库上传后校验操作规程
|
||||
|
||||
## 1. 输入与证据
|
||||
|
||||
|
||||
@@ -8,18 +8,6 @@
|
||||
|
||||
操作前正常关闭使用相同库的 PCB、Library Manager、原理图/符号编辑客户端,核对原服务器会话已结束,保留包含数据库、原备份和日志的完整一致副本。以下写入先在副本上进行。
|
||||
|
||||
## 残留客户端与共享服务器
|
||||
|
||||
0.2.4b1 的默认检查、校验、取消和释放流程不会强杀原生会话。操作员可以在独立确认界面强制结束属于当前 Windows 用户和会话、名单中的受支持客户端;这会影响该客户端内其他已打开工程,未保存更改可能丢失,属于异常退出处理,不能替代 Repair。
|
||||
|
||||
ICDB 数据库服务器即使命令行指向当前中心库,也可能服务其他用户,**本工具不允许强制结束服务器**。归属未知的进程、后台导入器和脚本宿主同样不允许强制结束;由库管理员核对用户和服务器状态后处理。
|
||||
|
||||
强制客户端动作必须先在库外证据目录持久写入确认名单、库和进程创建身份,再核对当前进程句柄、用户 SID 和 Windows 会话;记录失败或身份变化时不执行。客户端结束后仍需独立证明库已释放,重新打开工程并核对版本,必要时从人工一致备份或原生历史版本恢复。不能把“进程已结束”解释为“ICDB 已修复”。具体步骤见 [操作规程](../SOP.md)。
|
||||
|
||||
原生 Backup/Restore/Repair 进行中时不强制结束。释放预览可查看后台桌面上的原生输出;只有当前窗口唯一可识别的取消按钮才提供确认请求,发送后仍需重新检查是否停止。输出或取消按钮无法确认时保留现场,不猜测原生命令。
|
||||
|
||||
|
||||
|
||||
## 原生工程数据库 Repair
|
||||
|
||||
1. 启动本机的 iCDB Project Backup,并打开实际报错工程对应的 `.prj`。本机可用 PowerShell 命令形式如下,工程路径需替换为自己的隔离副本:
|
||||
|
||||
@@ -1,366 +0,0 @@
|
||||
# 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
|
||||
```
|
||||
@@ -1,90 +0,0 @@
|
||||
{
|
||||
"review_comment": "https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/pulls/3#issuecomment-249",
|
||||
"version": "0.2.4b1",
|
||||
"base_main": "a56fd17b60d9f67997d7f48c862f3367d4502f84",
|
||||
"tests": {
|
||||
"infrastructure": {
|
||||
"tests": 491,
|
||||
"errors": 0,
|
||||
"failures": 0,
|
||||
"skipped": 0,
|
||||
"xml_sha256": "12c2cd40542cb01d4fa374e98908c8a77a8deb83f95d0833645b1666ea5574e9",
|
||||
"xml_file": "codex-review-infrastructure-pytest.xml",
|
||||
"seconds": 52.986
|
||||
},
|
||||
"native_backend": {
|
||||
"tests": 1376,
|
||||
"errors": 0,
|
||||
"failures": 0,
|
||||
"skipped": 0,
|
||||
"xml_sha256": "8db65d11dd918d2a1b141d72627654a990ea903b68e20511e982dfb927d6be58",
|
||||
"xml_file": "codex-review-native-backend-pytest.xml",
|
||||
"seconds": 275.957
|
||||
},
|
||||
"ui_integration": {
|
||||
"tests": 1545,
|
||||
"errors": 0,
|
||||
"failures": 0,
|
||||
"skipped": 0,
|
||||
"xml_sha256": "5a3e6d58d611240c6e34cc9bd2350a8bf605516ef453240333836c1f88233af6",
|
||||
"xml_file": "codex-review-ui-integration-pytest.xml",
|
||||
"seconds": 325.065
|
||||
},
|
||||
"final_stack": {
|
||||
"tests": 1601,
|
||||
"errors": 0,
|
||||
"failures": 0,
|
||||
"skipped": 0,
|
||||
"xml_sha256": "bab74328facfbf512416b62a074fb5cb65ea39b04f0039d42083f96b5349c351",
|
||||
"xml_file": "codex-review-residual-release-pytest.xml",
|
||||
"seconds": 246.75
|
||||
},
|
||||
"umbrella": {
|
||||
"tests": 1601,
|
||||
"errors": 0,
|
||||
"failures": 0,
|
||||
"skipped": 0,
|
||||
"xml_sha256": "566f50b4ba537d4e54939946a5b48cad9ed6dbd8fb69c5ffbabcc5da0fbaf507",
|
||||
"xml_file": "r10-pr-pytest.xml",
|
||||
"seconds": 313.479
|
||||
},
|
||||
"force_boundary": {
|
||||
"tests": 43,
|
||||
"errors": 0,
|
||||
"failures": 0,
|
||||
"skipped": 0,
|
||||
"xml_sha256": "832425306b5fea3a150cc2188e00c97a771bb6d953e54b69c091d36e8062dca9",
|
||||
"xml_file": "pr249-force-focused.xml",
|
||||
"seconds": 3.231
|
||||
}
|
||||
},
|
||||
"compileall": "passed",
|
||||
"git_diff_check": "passed",
|
||||
"final_content": {
|
||||
"file_count": 195,
|
||||
"sha256": "2784b81ff0ae4d47f85ac8ea4b217292bbd9a1e716667e729863bfd4a6a372cd",
|
||||
"umbrella_equals_stack": true
|
||||
},
|
||||
"post_test_formatting": "MainWindow line endings aligned with UI review base (AST equality asserted); unchanged README lines retain main line endings",
|
||||
"regression_red": {
|
||||
"baseline": "e4266ae",
|
||||
"selected_new_ownership_tests": 3,
|
||||
"expected_failures": 3,
|
||||
"method": "in-memory baseline module; no production files or native processes modified"
|
||||
},
|
||||
"force_contract": {
|
||||
"clients_only": true,
|
||||
"same_user_sid_and_windows_session": true,
|
||||
"servers_never_terminated": true,
|
||||
"durable_consent_before_action": true,
|
||||
"independent_library_release_proof_required": true
|
||||
},
|
||||
"not_validated": [
|
||||
"field server-session loss recovery",
|
||||
"Windows 10",
|
||||
"cross-machine shared-library concurrency",
|
||||
"actual Mentor force termination",
|
||||
"new frozen package"
|
||||
],
|
||||
"delivery_policy": "Draft review only; no merge, publish, automatic issue closure or native production-library operation"
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
]
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
# 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
|
||||
@@ -1,38 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,21 +0,0 @@
|
||||
# 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
|
||||
@@ -1,7 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,39 +0,0 @@
|
||||
# v0.2.4-beta.1(0.2.4b1)开发候选说明
|
||||
|
||||
状态:待评审、待现场验收。不是自动发布指令,工单保持开放。
|
||||
|
||||
## 用户可见变化
|
||||
|
||||
- 检验、ICDB 维护、中心库管理为独立入口。ICDB 检查在后台逐项运行,其他原生任务可排队,搜索/筛选保持可用。
|
||||
- 检查以当前 PCB 打开情况和本次原生错误为依据,只有明确 ICDB 错误才标记问题;不自动 Repair、Restore 或选择版本,CHECKED 不等于 READY。
|
||||
- 停止队列同时停止后续后台检查;执行前再次排除 READY,校验排队不隐藏检查进度;释放失败显示实际原因。
|
||||
- 原生新增、同名替换、移除和备份恢复继续要求确认及人工备份,失败结果和未完成任务逐项保留。
|
||||
- 默认残留释放为正常关闭。单独确认的强制结束仅允许属于当前 Windows 用户和会话、已确认作用域和精确身份的受支持文档客户端;服务器、后台导入器和未知进程不可强制结束。
|
||||
|
||||
## 强制客户端操作的契约
|
||||
|
||||
支持 Expedition PCB、Library Manager、viewdraw 和 iCDB Project Backup。操作员须知晓客户端中其他工程可能一并退出、未保存更改可能丢失、写入中的工程可能需要恢复。确认名单先持久记录为库外 `consent.json`,失败则不执行;派发处复核身份和预览范围,句柄处复核创建时间、完整映像、用户 SID、Windows 会话与原生活动;变化时拒绝。
|
||||
|
||||
数据库服务器可能服务同库其他用户,命令行归属不构成独占授权。本工具不会强制结束任何 ICDB 服务器;它仍活跃或库状态未知时保留 PARTIAL,不能通过结束客户端伪造释放或修复成功。
|
||||
|
||||
## 安全状态和回退
|
||||
|
||||
单项失败且本任务确已释放时可继续独立项;未释放时保留现场、检查点、映射和证据。客户端强制结束不可撤销,恢复使用人工一致备份或原生历史版本;不会自动重新导入、回退共享库或重放未完成写操作。
|
||||
|
||||
程序回退:先关闭正在使用的客户端,再使用此前候选包;程序回退不恢复原生事务或丢失更改。工程恢复:保留故障现场、选择确认过的备份,在隔离副本验证后恢复并重新校验。
|
||||
|
||||
## 验证与限制
|
||||
|
||||
PR #3 comment 249 的修复通过服务器排除、确认记录失败、PID 复用、客户端/服务器混合名单等 fake 边界回归;没有为了验证本功能终止真实 Mentor 客户端或服务器。
|
||||
|
||||
此前 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 自动修复继续暂停。
|
||||
@@ -1,13 +0,0 @@
|
||||
# 独立审查 1:只读进程探测与原生任务准入队列
|
||||
|
||||
基于 main `a56fd17`,不叠加 PR #3 的历史提交。
|
||||
|
||||
**行为变化:** 增加有界、版本化、只读 owner-probe helper 和可取消的 FIFO 原生任务队列。应用仅新增隐藏的只读 helper 分派;现有 UI、验证和原生写操作保持原来的入口。
|
||||
|
||||
**失败安全:** 查询超时或协议/身份异常返回未确认;暂停或取消的队列票据不会运行其动作,也不阻止后面的可执行任务。不启动或终止 Mentor 进程。
|
||||
|
||||
**回滚方式:** 尚未合入下游时撤销本提交即可;下游接入后须按依赖从上层向下回退。
|
||||
|
||||
完整回归:491 passed,1 条既有 pywinauto STA 提示。编译和 diff 检查通过。
|
||||
|
||||
与原评论建议的差别:`management_transaction` 直接导入管理模型和库锁;`scoped_manifest` 的协调记录与独占快照依赖库锁协议。这两者在后端审查中一起交付,避免构造导入不完整的“纯工具”基线。
|
||||
@@ -1,20 +0,0 @@
|
||||
# Native backend review unit
|
||||
|
||||
Base: codex/review-infrastructure. This unit integrates ICDB open diagnostics, scoped content manifests, native CBB transactions and the library-release protocol; it does not expose the new UI or residual termination action. Verification and ICDB checks remain separate, READY items are excluded from maintenance, and a released single-item failure can continue independent targets.
|
||||
|
||||
Failure safety: no automatic Repair/version choice, no server termination, no direct LMC edits or native lock-file deletion. Native writes are serialized, uncertain ownership retains evidence and mappings, and unfinished writes are shown without replay.
|
||||
|
||||
Dependency rationale: library release imports native engineering identity and retained management workers; engineering identity imports management source models and scoped manifests. Separating these into nominally independent utilities would leave runtime imports unresolved. This PR therefore keeps the backend dependency closure together; UI and user-confirmed termination remain separate later PRs.
|
||||
|
||||
Rollback: before dependents are merged, revert this commit. After merging dependents, revert in reverse order or use the previous candidate package after closing the current app. Code rollback does not undo a native transaction; use a consistent manual backup or explicitly selected native history on an isolated copy.
|
||||
|
||||
Validation: full Python suite 1,376 passed (one existing pywinauto COM-threading warning); compileall and git diff --check passed. Native field recovery, Windows 10 and cross-machine shared-library acceptance remain pending.
|
||||
|
||||
Review comment 344 follow-up (2026-11-09):
|
||||
|
||||
- Production status scans continue to query fresh bridge results. The low-level session now also defaults to fresh scans; explicit checkpoint reuse is documented as a controlled read-only option with no production resume promise.
|
||||
- `library-changes.json` declares `rule_version`, the selected `scope`, excluded directory categories and suffixes, positional runtime rules, runtime filenames/prefixes, and recognized coordination checkpoints. Names, suffixes, prefixes and native database locations come from the same constants used by semantic classification. These are differences in participating engineering files; excluded content is not proven unchanged, and unrelated CBB content is not checked.
|
||||
- Removed the tests-only `pcb_bridge.execution_outcome` helper. Production release safety continues to come from observed release state and remaining clients.
|
||||
- Unlocked primary snapshots hash the copy stream, then independently hash the final source and destination. Source reads decrease from three to two. Rejected the suggestion to remove/threshold the final source hash: size and mtime cannot detect same-size, same-timestamp source edits. Locked LMC/icdb streams and owned lock snapshots retain their existing behavior; no source-rehash skip flag is added.
|
||||
|
||||
Validation for this follow-up: 287 targeted cases passed through the isolated mutex/PYTHONPATH wrapper (`test_batch_status`, `test_batch_status_faults`, `test_review_backend_followup`, `test_scoped_manifest`, `test_pcb_bridge`, `test_management_retry_blockers`, `test_backup_recovery`, `test_library_lock`, `test_management`). AST parsing, `git diff --check`, and original newline-style checks passed. No real Mentor, COM automation, shared library or process control was exercised; no full-suite run was requested.
|
||||
@@ -1,9 +0,0 @@
|
||||
# Residual release contract review unit
|
||||
|
||||
Base: codex/review-ui-integration. Behavior: expose the residual-session preview and cooperative close entry, plus a separately confirmed force action limited to recognized document clients of the current Windows user and session. Database servers, importers, unknown scope and unverified identities cannot be force ended. Version becomes 0.2.4b1, with README, SOP, manual and rollback notes aligned.
|
||||
|
||||
Failure safety: persist the exact allowed/excluded confirmation list before any native action, recheck scope/creation/executable/user/session at dispatch and the held handle, and require independent library-release proof after exit. Unreadable owner metadata disables force only. A terminated client is not a repaired/READY project; partial release retains evidence and mappings.
|
||||
|
||||
Rollback: reverse the dependent commits before reverting the backend, or close the current app and use the earlier candidate. Process termination cannot be undone, and code rollback does not restore native transactions or unsaved data. Use a consistent manual backup or an explicitly chosen native history version on a copy.
|
||||
|
||||
Validation: 1,601 passed for this final stack, 1,601 passed for the umbrella, and 43 focused release tests passed after the final UI wording change. Compileall, diff checks and byte-level final implementation equality passed. Detailed XML counts/hashes and content digest are recorded in ../releases/2026-11-05-pr249-review-validation.json. No real Mentor client/server was terminated for these checks. Field recovery, Windows 10, shared-library concurrency and the new frozen package remain unverified.
|
||||
@@ -1,9 +0,0 @@
|
||||
# Application integration review unit
|
||||
|
||||
Base: codex/review-native-backend. Behavior: verification, ICDB batch checking and CBB management have separate tabs; background checks yield between items, keep browsing responsive and let other native tasks queue. READY targets are excluded at execution, status refresh is scoped, and manual version/copy decisions remain explicit.
|
||||
|
||||
Failure safety: a released item failure can continue independent targets; uncertain native ownership retains evidence and mappings. There is no residual-session release backend in this review stage: its button and result actions are hidden, and its callback is inert. The next PR restores the complete release entry together with its tested backend, rather than exposing a button with a missing import. No automatic Repair or native version selection is added.
|
||||
|
||||
Rollback: revert this UI commit before its dependent release PR; after dependents, revert in reverse order or close the current program and use the prior candidate. This does not roll back library writes.
|
||||
|
||||
Validation: 1,545 passed (one existing pywinauto COM-threading warning), compileall and diff checks passed. Release-specific tests are introduced in the dependent PR, never discarded from the final tree. Windows 10, real shared-library concurrency and field ICDB recovery remain pending.
|
||||
@@ -1,9 +0,0 @@
|
||||
# 评论 275:占用复核与变更报告
|
||||
|
||||
校验和管理共用历史释放记录复核:旧 JSON/内存租约触发实际进程、地址、独占文件和导出副本证明,不直接视为真实占用,不结束进程或执行 Repair。确认释放后归档旧记录并继续;失败且本项尚未启动时保留原记录,结果不会把本项标成未释放。校验结果兼容新增 release_proof,管理首次原生调用前保存释放经过;进程释放不等于历史数据已恢复。
|
||||
|
||||
写后仅对原先的目标 Work/Cert、中心库配置和共享依赖范围生成 SHA-256 差分,报告新增、删除、修改路径,并保存写后清单。范围沿用原有 ManifestScope.library,不增加整库备份或其他 CBB 内容哈希,不声称已证明所有其他 CBB 未被波及。已释放的部分失败也保留差分;仍有原生所有者时不为报告读取数据库。报告失败单独标为 UNCONFIRMED 并返回原因,不伪造未完成事务、不制造永久占用。
|
||||
|
||||
PASS 不再重复计入 unconfirmed。未改变实际原生写操作、人工备份政策或服务器保护,也没有恢复自动修复。
|
||||
|
||||
回归覆盖历史记录无占用/真实地址占用、首次原生调用前留证、目标及共享依赖差分、失败后差分、报告保存失败后可继续。完整回归和限制以最终验证记录及 PR 描述为准;真实 Mentor、Win10、跨机器共享库尚未因此取得新验收结论。
|
||||
@@ -1,11 +0,0 @@
|
||||
# 评论 286:释放留证与原生活动
|
||||
|
||||
释放前持久保存 NOT_STARTED 检查点,动作前保存 REQUESTING,动作后逐项保存实际状态,快照超时/中途异常也保留已执行和未执行项。保存失败停止继续发出动作;最终保存失败明确标为 PARTIAL/evidence_error,但独立且匹配当前库的释放证明仍被界面接受,不伪造占用。确认意图 consent_allowed 与实际 release_status 分别记录。
|
||||
|
||||
强制结束预览及精确句柄处重新读取原生窗口、进度和 Output;备份客户端进行中或状态无法确认时拒绝强制结束。普通客户端的保存模态窗口不直接等同于正在写库。服务器、导入器和未知身份仍排除。
|
||||
|
||||
窗口快照记录桌面,预览展示完整映像路径并提供原生提示/输出查看,支持原有保存选择。仅在当前用户/会话、精确进程身份匹配,且当前备份窗口唯一存在启用的 Cancel/取消(标准 IDCANCEL=2)控件时,提供单独确认的取消请求;执行前再次匹配标题、桌面、窗口和按钮并校验 PID。该请求复用串行准入和库外留证,不能当作已取消/已释放/已修复,也没有未知菜单或前台鼠标回退。没有可识别控件时入口禁用,保留状态供重新检查。
|
||||
|
||||
回归覆盖初次/末次快照超时、逐项记录、报告落盘失败、活动状态变化、原生取消按钮变化、确认与取消选择、已释放事实不被报告错误覆盖。测试使用临时文件和 fake 原生边界,没有终止或取消真实 Mentor 事务。原生取消在具体 Mentor 版本/现场窗口上的效果仍待隔离实机验收;ICDB 自动修复继续暂停。
|
||||
|
||||
回退代码不恢复已结束进程或原生事务;工程数据恢复仍需一致人工备份或明确选择的原生历史,不自动重放写操作。
|
||||
@@ -1,7 +0,0 @@
|
||||
# 评论 275/283:结果口径接入
|
||||
|
||||
管理进度显示历史占用复核;结果分别呈现已确认的原生动作、变更清单完整性和历史会话释放事实。单项 RECOVERY_REQUIRED 但 safe_to_continue=True 时,不再声称整个队列停止;记录失败不伪装成原生上传/移除失败。
|
||||
|
||||
独立操作回归更新为实际历史记录归档流程:先证明当前占用已释放、保留归档字节,再进行普通验证;不自动 Repair,失败后不遗留新的占用锁。
|
||||
|
||||
本阶段相关 UI/独立操作/后端回归 29 passed。后端完整回归与最终集成回归另见验证记录。没有执行真实 Mentor 写操作;回退按依赖逆序,不代表恢复原生事务。
|
||||
@@ -1,7 +1,5 @@
|
||||
# CBB Batch Status Bridge Implementation Plan
|
||||
|
||||
Current behavior (2026-11-09): production status scans always query the bridge fresh and overwrite checkpoint evidence. `BatchStatusSession.scan` defaults to `resume=False`; `resume=True` remains an explicit low-level option for controlled read-only scans, not an exposed production resume feature. Its lightweight fingerprint cannot detect every native payload/database write, so saved READY/PENDING rows must not authorize production actions.
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Read 180 to 3000 CBB Verify states through one resilient x86 Mentor bridge session with checkpoint recovery and authoritative `READY/PENDING` results.
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
# PR #3 comment 249 implementation plan
|
||||
|
||||
**Goal:** Make the force-release contract explicit and keep shared native servers out of forced termination; replace the large PR as the merge entry with smaller, ordered review branches.
|
||||
|
||||
**Authorization:** The user requested implementation of comment 249. Earlier user decisions retain explicit user-confirmed residual release, manual backups and no release/issue closure before field acceptance. These decisions take precedence over changing Draft status merely to make a merge button available.
|
||||
|
||||
**Architecture:** Keep automatic verification and checking cooperative. A separate explicit force action can end supported document clients only after scope, exact process identity, current user SID and Windows session are checked. Native database servers and unknown processes remain observable and cannot be force terminated. Every force request must persist consent intent before any termination and still obtain independent library-release proof afterward.
|
||||
|
||||
**Review split:** Preserve #3 as an unmerged umbrella. Create a dependent review chain: (1) read-only owner probing and cooperative queue; (2) native backend, manifests, library coordination and transactions; (3) background checks and application UI integration; (4) residual-session release, its explicit contract, version and documentation. `management_transaction` imports management and lock APIs, and semantic manifests depend on recognized coordination checkpoints; they belong with the backend rather than pretending to be standalone read-only utilities. The existing #5 remains a prerequisite document review, not an automatically merged change.
|
||||
|
||||
## Global constraints
|
||||
|
||||
- Python/PySide6, Windows and Mentor EE7.9.5 remain the supported implementation stack.
|
||||
- Never kill native servers or operate production libraries in this development task.
|
||||
- No automatic Repair, Restore, version choice, issue closure, publishing or PR merge.
|
||||
- Each split PR states visible behavior, failure safety and rollback.
|
||||
- Preserve the current user test workspace; work in the PR worktree.
|
||||
|
||||
## Task 1: Force-release boundary
|
||||
|
||||
Files: `residual_sessions.py`, `ui/residual_release_dialog.py`, `tests/test_residual_sessions.py`, `tests/test_residual_release_dialog.py`.
|
||||
|
||||
- [x] Add failing tests: a scoped iCDB server cannot reach `_force_close`; direct force requests against server/unsupported names never obtain a terminate-capable handle; missing consent evidence causes zero termination calls; mixed client/server previews list only supported clients in the confirmation; rejected/reused process identities remain unchanged.
|
||||
- [x] Define one shared force-eligibility function allowing only recognized document clients with confirmed scope and matching captured executable identity. Enforce it again at dispatch and at the exact handle boundary.
|
||||
- [x] Persist `consent.json` with target library, exact preview identities and allowed/excluded targets before processing a force request. A write failure returns before native actions.
|
||||
- [x] Keep excluded servers in the release result and require the existing independent release proof; process exit never means repaired/READY.
|
||||
- [x] Run focused regressions and the complete suite with an isolated test mutex.
|
||||
|
||||
## Task 2: Version and operating contract
|
||||
|
||||
Files: `pyproject.toml`, `README.md`, `SOP.md`, `docs/ICDB-MANUAL-REPAIR-AND-UPDATE.md`, `docs/releases/v0.2.4-beta.1.md`.
|
||||
|
||||
- [x] Identify the actual tracked SOP before editing; update README, SOP and manual together.
|
||||
- [x] Set `0.2.4b1` and document the user-confirmed client-only exception to the automatic no-force contract. Explain server handling, evidence, failure states, manual recovery and rollback.
|
||||
- [x] Keep field ICDB recovery, Win10 and multiuser shared-library acceptance explicitly unverified.
|
||||
|
||||
## Task 3: Review branches
|
||||
|
||||
- [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.
|
||||
- [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
|
||||
|
||||
- [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.
|
||||
@@ -1,25 +0,0 @@
|
||||
# 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,7 +1,5 @@
|
||||
# CBB 批量状态桥设计
|
||||
|
||||
Current behavior (2026-11-09): production status scans always query the bridge fresh and overwrite checkpoint evidence. `BatchStatusSession.scan` defaults to `resume=False`; `resume=True` remains an explicit low-level option for controlled read-only scans, not an exposed production resume feature. Its lightweight fingerprint cannot detect every native payload/database write, so saved READY/PENDING rows must not authorize production actions.
|
||||
|
||||
## 目标
|
||||
|
||||
支持对 180 到 3000 个 CBB 进行 Mentor authoritative Verify 状态读取,要求单条失败隔离、过程可恢复、结果可审计,并避免现有“一条 CBB 启动一个桥进程”的启动开销。
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ requires = ["setuptools>=84.1.0"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
[project]
|
||||
name = "cbb-refresh-verify"
|
||||
version = "0.2.4b1"
|
||||
version = "0.2.3b1"
|
||||
requires-python = ">=3.12,<3.13"
|
||||
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<0.7", "Pillow>=13.0.0,<14"]
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
__version__ = "0.2.4b1"
|
||||
__version__ = "0.2.3b1"
|
||||
@@ -46,16 +46,6 @@ 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)
|
||||
@@ -67,7 +57,6 @@ 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)
|
||||
@@ -121,11 +110,6 @@ 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,
|
||||
@@ -133,21 +117,13 @@ 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:
|
||||
retain_mapping('batch_exception')
|
||||
lease.retain_for_recovery()
|
||||
raise
|
||||
if any(not result.safe_to_continue for result in results):
|
||||
retain_mapping('native_release_unconfirmed')
|
||||
lease.retain_for_recovery()
|
||||
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))
|
||||
|
||||
@@ -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 to invalidate changed LMC bytes; payload edits remain outside this key.
|
||||
# digest so a changed central library can never reuse an old status row.
|
||||
content_sha256 = _sha256_file(path)
|
||||
combined = hashlib.sha256()
|
||||
combined.update(str(path).casefold().encode('utf-8', errors='surrogatepass'))
|
||||
@@ -186,12 +186,7 @@ def _now() -> str:
|
||||
|
||||
|
||||
class BatchStatusSession:
|
||||
"""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.
|
||||
"""
|
||||
"""Supervised serial bridge session with checkpoint recovery."""
|
||||
|
||||
def __init__(self, bridge: StatusBridgeClient, *, timeout_seconds: float = 10.0,
|
||||
rotate_every: int = 500) -> None:
|
||||
@@ -201,7 +196,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 = False) -> list[BatchStatusRecord]:
|
||||
*, block_type: str = "RULP", resume: bool = True) -> list[BatchStatusRecord]:
|
||||
fingerprint = fingerprint_library(Path(lmc_file))
|
||||
if resume:
|
||||
checkpoint = BatchCheckpoint.load(checkpoint_path)
|
||||
@@ -296,8 +291,6 @@ 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``.
|
||||
"""
|
||||
|
||||
@@ -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 ('PASS', 'CHECKED', 'SKIPPED', 'CANCELLED')
|
||||
'unconfirmed': sum(r.status not in ('CHECKED', 'SKIPPED', 'CANCELLED')
|
||||
and r.error_category not in ('ICDB_REPAIR_REQUIRED', 'ICDB_DATABASE_IN_USE') for r in results),
|
||||
'cancelled': sum(r.status == 'CANCELLED' for r in results),
|
||||
'skipped': sum(r.status == 'SKIPPED' for r in results),
|
||||
|
||||
@@ -82,28 +82,6 @@ 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)
|
||||
@@ -521,7 +499,7 @@ def _prove_library_released(library, block_name=None, *, allow_unknown_checkpoin
|
||||
|
||||
|
||||
def release_retained_library(library, evidence_dir, *, block_name=None):
|
||||
"""Reconcile historical leases after fresh owner/address/access proof.
|
||||
"""Explicit user-requested release, after fresh owner/address/access proof.
|
||||
|
||||
The upload sidecar is never deleted. This acknowledges process release,
|
||||
not the correctness of a partially changed library or its recovery state.
|
||||
@@ -559,16 +537,6 @@ 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))
|
||||
@@ -580,9 +548,6 @@ 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')
|
||||
|
||||
@@ -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,
|
||||
comparison_rules, copy_verified, hash_file, scan_tree)
|
||||
copy_verified, hash_file, scan_tree)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -73,7 +73,6 @@ class ManagementResult:
|
||||
detail: str = ''
|
||||
evidence_path: Path | None = None
|
||||
release_proof: dict | None = None
|
||||
change_report: dict | None = None
|
||||
|
||||
|
||||
def validate_name(value):
|
||||
@@ -187,8 +186,6 @@ 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
|
||||
@@ -209,33 +206,8 @@ 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, change_report)
|
||||
request.source, request.auto_verify, 'complete', status, safe, detail, report, release_proof)
|
||||
if report:
|
||||
try:
|
||||
_write_json(report, {**asdict(result), 'history': history, 'backup_policy': 'manual'})
|
||||
@@ -284,12 +256,10 @@ 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 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)
|
||||
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')
|
||||
if unfinished_target:
|
||||
return finish('BLOCKED', f'存在未完成/需恢复任务,禁止自动重放:{unfinished_target["evidence_path"]}')
|
||||
if hasattr(adapter, 'bind_library_mapping'):
|
||||
|
||||
@@ -160,3 +160,18 @@ 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 退出均已确认。'}
|
||||
@@ -1,7 +1,6 @@
|
||||
"""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
|
||||
@@ -16,47 +15,6 @@ _NAMES = {'expeditionpcb.exe', 'librarymanager.exe', 'icdbprojectbackup.exe',
|
||||
'reuseblockimporter.exe', 'cleanwglib.exe', 'cscript.exe', 'wscript.exe'} | _OWNER_NAMES
|
||||
_WORKER_NAMES = {'python.exe', 'pythonw.exe', 'cbbrefreshverify.exe'}
|
||||
_WORKER_FLAGS = ('--verify-worker', '--repair-worker', '--management-worker', '--native-backup-worker')
|
||||
_FORCE_CLIENT_NAMES = {'expeditionpcb.exe', 'librarymanager.exe', 'viewdraw.exe', 'icdbprojectbackup.exe'}
|
||||
|
||||
|
||||
def force_block_reason(row):
|
||||
"""A library path proves scope, never exclusive ownership of a server."""
|
||||
if row.get('scope_confirmed') is not True:
|
||||
return '进程归属未确认,不允许强制结束'
|
||||
name = str(row.get('name', '')).casefold()
|
||||
if name not in _FORCE_CLIENT_NAMES:
|
||||
return '服务器或其他受保护进程仅供观察,不允许强制结束'
|
||||
if (not row.get('created_handle') or not row.get('image')
|
||||
or Path(row['image']).name.casefold() != name):
|
||||
return '客户端身份未确认,不允许强制结束'
|
||||
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
|
||||
@@ -87,111 +45,19 @@ def _handle_identity(handle):
|
||||
|
||||
def _process_identity(row):
|
||||
with _process_handle(row['pid']) as handle:
|
||||
identity = _handle_identity(handle)
|
||||
try:
|
||||
identity.update(_force_ownership(handle, row['pid']))
|
||||
except Exception as error:
|
||||
identity.update(force_user_confirmed=False, owner_error=str(error))
|
||||
return identity
|
||||
|
||||
|
||||
def _force_ownership(handle, pid):
|
||||
import win32api, win32con, win32process, win32security, win32ts
|
||||
if win32process.GetProcessId(handle) != pid:
|
||||
raise ValueError('进程身份已变化')
|
||||
def owner(process):
|
||||
token = win32security.OpenProcessToken(process, win32con.TOKEN_QUERY)
|
||||
try:
|
||||
return win32security.ConvertSidToStringSid(
|
||||
win32security.GetTokenInformation(token, win32security.TokenUser)[0])
|
||||
finally:
|
||||
token.Close()
|
||||
sid = owner(handle)
|
||||
session = win32ts.ProcessIdToSessionId(pid)
|
||||
return {'owner_sid': sid, 'session_id': session, 'force_user_confirmed':
|
||||
sid == owner(win32api.GetCurrentProcess())
|
||||
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)
|
||||
return _handle_identity(handle)
|
||||
|
||||
|
||||
def _process_windows(pids):
|
||||
result = _WindowSnapshot(pids)
|
||||
if not pids: return result
|
||||
if not pids: return {}
|
||||
import win32api, win32con, win32gui, win32process, win32service
|
||||
from .native_repair_ui import _native_output
|
||||
result = {pid: [] for pid in pids}
|
||||
observed = set()
|
||||
def capture(hwnd, _, *, pid, desktop_name):
|
||||
if win32process.GetWindowThreadProcessId(hwnd)[1] != pid:
|
||||
raise ValueError('窗口所属进程已变化')
|
||||
if hwnd in observed or not win32gui.IsWindowVisible(hwnd):
|
||||
def capture(hwnd, _=None):
|
||||
pid = win32process.GetWindowThreadProcessId(hwnd)[1]
|
||||
if pid not in result or hwnd in observed or not win32gui.IsWindowVisible(hwnd):
|
||||
return
|
||||
if desktop_name is None:
|
||||
raise ValueError('窗口所属桌面无法读取')
|
||||
observed.add(hwnd)
|
||||
children, documents = [], []
|
||||
def child(handle, _):
|
||||
@@ -205,52 +71,36 @@ 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:
|
||||
threads = _process_threads(pids)
|
||||
except Exception as error:
|
||||
result.incomplete = {pid: str(error)[:500] for pid in pids}
|
||||
win32gui.EnumWindows(capture, None)
|
||||
except Exception:
|
||||
incomplete()
|
||||
try:
|
||||
desktops = win32service.GetProcessWindowStation().EnumDesktops()
|
||||
except Exception:
|
||||
incomplete()
|
||||
return result
|
||||
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():
|
||||
for name in desktops:
|
||||
if name != 'Default' and not name.startswith(('CbbVerify_', 'CbbRepair_', 'CbbManagement_', 'CbbStatusRead_', 'CbbFlagRead_')):
|
||||
continue
|
||||
desktop = None
|
||||
try:
|
||||
desktop = win32service.OpenDesktop(name, 0, False, win32con.DESKTOP_READOBJECTS)
|
||||
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])
|
||||
for hwnd in desktop.EnumDesktopWindows(): capture(int(hwnd))
|
||||
except Exception:
|
||||
incomplete()
|
||||
finally:
|
||||
if desktop is not None:
|
||||
desktop.CloseDesktop()
|
||||
if desktop is not None: desktop.CloseDesktop()
|
||||
return result
|
||||
|
||||
|
||||
@@ -266,10 +116,8 @@ def _project_name(row, library):
|
||||
return '当前库关联会话'
|
||||
|
||||
|
||||
def close_target(name, windows, *, incomplete=None):
|
||||
def close_target(name, windows):
|
||||
"""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')
|
||||
@@ -299,46 +147,22 @@ def close_target(name, windows, *, incomplete=None):
|
||||
return window, ('将正常关闭工程;未保存时等待确认' if window.get('documents') else '可正常关闭')
|
||||
|
||||
|
||||
def _save_question(windows, *, incomplete=None):
|
||||
if incomplete:
|
||||
return None
|
||||
def _save_question(windows):
|
||||
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,
|
||||
'desktop': window.get('desktop', '')}
|
||||
return {'hwnd': window['hwnd'], 'text': text, 'buttons': buttons}
|
||||
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':
|
||||
raise ValueError('请选择中心库 .lmc 文件')
|
||||
if not library.is_file():
|
||||
raise ValueError('中心库路径当前不可见,请检查文件是否存在及网络盘映射后重新检查')
|
||||
if library.suffix.casefold() != '.lmc' or not library.is_file():
|
||||
raise ValueError('请选择有效的中心库 .lmc 文件')
|
||||
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('残留检查的工程名称无效')
|
||||
@@ -358,30 +182,15 @@ 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'], []), incomplete=error) if row['scope_confirmed'] else (
|
||||
target, detail = close_target(row['name'], windows.get(row['pid'], [])) if row['scope_confirmed'] else (
|
||||
None, '归属未确认,请在原生窗口确认工程并关闭后重新检查')
|
||||
item.update(can_close=target is not None, detail=detail)
|
||||
except Exception as identity_error:
|
||||
item.update(can_close=False, detail=f'进程已变化或暂时无法确认:{identity_error}')
|
||||
except Exception as error:
|
||||
item.update(can_close=False, detail=f'进程已变化或暂时无法确认:{error}')
|
||||
item['project'] = _project_name(row, library) if row['scope_confirmed'] else '归属未确认'
|
||||
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']:
|
||||
item['detail'] += ';'+item['force_block_reason']
|
||||
item['prompt'] = _save_question(windows.get(row['pid'], [])) if row['scope_confirmed'] else None
|
||||
sessions.append(item)
|
||||
previous = []
|
||||
marker = blocker_path(library)
|
||||
@@ -407,10 +216,7 @@ 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': '进程身份已变化,未关闭'}
|
||||
snapshot = _process_windows({row['pid']})
|
||||
windows, error = snapshot.get(row['pid'], []), _window_error(snapshot, row['pid'])
|
||||
if error:
|
||||
return {'release_status': 'WAITING', 'detail': '该会话窗口读取不完整,请重新检查:'+error}
|
||||
windows = _process_windows({row['pid']}).get(row['pid'], [])
|
||||
if row['name'].casefold() == 'expeditionpcb.exe':
|
||||
from .failed_session import _startup_snapshot, _cancel_target
|
||||
for window in windows:
|
||||
@@ -424,13 +230,10 @@ 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': '已停止释放'}
|
||||
snapshot = _process_windows({row['pid']})
|
||||
windows, error = snapshot.get(row['pid'], []), _window_error(snapshot, row['pid'])
|
||||
if error:
|
||||
break
|
||||
windows = _process_windows({row['pid']}).get(row['pid'], [])
|
||||
if close_target(row['name'], windows)[0] is not None: break
|
||||
break
|
||||
target, detail = close_target(row['name'], windows, incomplete=error)
|
||||
target, detail = close_target(row['name'], windows)
|
||||
if target is None: return {'release_status': 'WAITING', 'detail': detail}
|
||||
if stop is not None and stop.is_set():
|
||||
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
|
||||
@@ -450,28 +253,15 @@ def _force_close(row, *, stop=None):
|
||||
import win32api, win32con, win32event
|
||||
if stop is not None and stop.is_set():
|
||||
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
|
||||
if reason := force_block_reason(row):
|
||||
return {'release_status': 'WAITING', 'detail': reason}
|
||||
with _process_handle(row['pid'], terminate=True) as handle:
|
||||
if win32event.WaitForSingleObject(handle, 0) == win32con.WAIT_OBJECT_0:
|
||||
return {'release_status': 'RELEASED', 'detail': '已退出'}
|
||||
if _handle_identity(handle) != {k: row.get(k) for k in ('created_handle', 'image')}:
|
||||
return {'release_status': 'IDENTITY_CHANGED', 'detail': '进程身份已变化,未结束'}
|
||||
ownership = _force_ownership(handle, row['pid'])
|
||||
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',
|
||||
'detail': '已强制结束客户端,工程待检查,未执行修复' if exited else '已请求结束客户端,等待退出'}
|
||||
'detail': '已强制结束,工程需重新检查' if exited else '已请求结束,等待退出'}
|
||||
|
||||
|
||||
def _finish_library_release(library, evidence):
|
||||
@@ -479,162 +269,63 @@ def _finish_library_release(library, evidence):
|
||||
return release_retained_library(library, evidence)
|
||||
|
||||
|
||||
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):
|
||||
def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=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': [
|
||||
{**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,
|
||||
result = {'status': 'PARTIAL', 'library': str(library), 'sessions': [], 'force': force,
|
||||
'evidence_path': str(root/'result.json'), 'previous_records': plan.get('previous_records', [])}
|
||||
def save():
|
||||
from .management import _write_json
|
||||
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': '确认后进程身份已变化,未关闭'}
|
||||
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()):
|
||||
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 BaseException as error:
|
||||
result.update(status='PARTIAL', detail=f'{type(error).__name__}: {error}')
|
||||
if not isinstance(error, Exception):
|
||||
raise
|
||||
finally:
|
||||
save()
|
||||
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)
|
||||
return result
|
||||
|
||||
|
||||
def release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, cancel_native=False):
|
||||
def release_residual_sessions(plan, evidence_dir, *, stop=None, force=False):
|
||||
import win32con, win32event
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
acquired = False
|
||||
@@ -648,7 +339,7 @@ def release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, can
|
||||
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, cancel_native=cancel_native)
|
||||
return _release_residual_sessions(plan, evidence_dir, stop=stop, force=force)
|
||||
finally:
|
||||
if acquired: win32event.ReleaseMutex(mutex)
|
||||
mutex.Close()
|
||||
@@ -678,8 +369,7 @@ 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('进程已变化,请重新检查')
|
||||
snapshot = _process_windows({row['pid']})
|
||||
prompt = _save_question(snapshot.get(row['pid'], []), incomplete=_window_error(snapshot, row['pid']))
|
||||
prompt = _save_question(_process_windows({row['pid']}).get(row['pid'], []))
|
||||
if not prompt or prompt != row.get('prompt'):
|
||||
raise ValueError('原生提示已变化,请重新检查')
|
||||
button = prompt['buttons'][choice]
|
||||
|
||||
@@ -15,15 +15,6 @@ 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++',
|
||||
@@ -38,21 +29,22 @@ 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(_ROOT_RUNTIME_PREFIX)
|
||||
or directories[:len(_ROOT_RUNTIME_PATH)] == _ROOT_RUNTIME_PATH))
|
||||
or directories[0].startswith('work.before-restore-')
|
||||
or directories[:2] == ('projectbackup', 'backups')))
|
||||
|
||||
|
||||
def _native_runtime(directories, database_prefix):
|
||||
runtime_prefix = database_prefix + (_NATIVE_SERVER_DIRECTORY,)
|
||||
runtime_prefix = database_prefix + ('cdbsvr',)
|
||||
return (directories[:len(runtime_prefix)] == runtime_prefix
|
||||
and len(directories) > len(runtime_prefix)
|
||||
and directories[len(runtime_prefix)] in _NATIVE_RUNTIME_DIRECTORIES)
|
||||
and directories[len(runtime_prefix)] in ('log', 'dbcheck', 'dbrestore'))
|
||||
|
||||
|
||||
def _project_runtime(directories):
|
||||
return (_root_runtime(directories)
|
||||
or (directories[:1] == (_PROJECT_PCB_DIRECTORY,) and _root_runtime(directories[1:]))
|
||||
or any(_native_runtime(directories, prefix) for prefix in _PROJECT_DATABASE_PREFIXES))
|
||||
or (directories[:1] == ('pcb',) and _root_runtime(directories[1:]))
|
||||
or _native_runtime(directories, ('database',))
|
||||
or _native_runtime(directories, ('pcb', 'database')))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -93,8 +85,7 @@ class ManifestScope:
|
||||
"""
|
||||
directories = parts if directory else parts[:-1]
|
||||
if not directory and (Path(parts[-1]).suffix in _NONPRIMARY_SUFFIXES
|
||||
or parts[-1] in _NONPRIMARY_FILENAMES
|
||||
or parts[-1].startswith(_NONPRIMARY_FILENAME_PREFIXES)):
|
||||
or parts[-1] == 'saddress.adr' or parts[-1].startswith('~$')):
|
||||
return True
|
||||
if self.kind == 'project':
|
||||
return _project_runtime(directories)
|
||||
@@ -132,36 +123,6 @@ 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:
|
||||
@@ -310,10 +271,7 @@ 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. 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.
|
||||
hashing destination bytes. Failures retain the partial destination evidence.
|
||||
Progress receives one dict with stage, hashed_files/bytes and copied_files.
|
||||
"""
|
||||
import win32con
|
||||
@@ -371,15 +329,9 @@ 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):
|
||||
|
||||
+1584
-1621
File diff suppressed because it is too large.
Load diff
@@ -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,9 +25,6 @@ STAGE_LABELS = {
|
||||
'verify': '正在校验上传结果', 'verified': '校验已返回', 'copy': '正在准备来源副本',
|
||||
'hash': '正在校验主要文件',
|
||||
'release_check': '正在检查工程是否被占用',
|
||||
'previous_release_check': '正在复核历史占用',
|
||||
'previous_release_confirmed': '历史会话已确认释放',
|
||||
'previous_release_unconfirmed': '占用复核未通过',
|
||||
}
|
||||
|
||||
|
||||
@@ -206,18 +203,6 @@ 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'):
|
||||
|
||||
@@ -7,7 +7,6 @@ from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushB
|
||||
QTableWidget, QTableWidgetItem, QHeaderView, QMessageBox)
|
||||
|
||||
from .workers import ServiceWorker
|
||||
from ..residual_sessions import force_block_reason
|
||||
|
||||
|
||||
class ResidualReleaseDialog(QDialog):
|
||||
@@ -25,13 +24,13 @@ class ResidualReleaseDialog(QDialog):
|
||||
self.pool = QThreadPool(self)
|
||||
self.setWindowTitle('释放残留会话')
|
||||
self.setModal(True)
|
||||
self.resize(1040, 400)
|
||||
self.resize(760, 350)
|
||||
layout = QVBoxLayout(self)
|
||||
self.message = QLabel('正在检查当前库关联的会话…')
|
||||
self.message.setWordWrap(True)
|
||||
layout.addWidget(self.message)
|
||||
self.table = QTableWidget(0, 8)
|
||||
self.table.setHorizontalHeaderLabels(['工程', '程序', 'PID', '状态', '窗口位置', '程序路径', '确认范围', '执行结果'])
|
||||
self.table = QTableWidget(0, 4)
|
||||
self.table.setHorizontalHeaderLabels(['工程', '程序', 'PID', '状态'])
|
||||
self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
|
||||
self.table.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch)
|
||||
self.table.setEditTriggers(QTableWidget.NoEditTriggers)
|
||||
@@ -40,22 +39,17 @@ 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 = 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.details_button, self.prompt_button,
|
||||
self.cancel_native_button, self.force_button, self.close_button): buttons.addWidget(button)
|
||||
for button in (self.refresh_button, self.confirm_button, self.prompt_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()
|
||||
|
||||
@@ -65,7 +59,6 @@ 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)
|
||||
@@ -78,7 +71,7 @@ class ResidualReleaseDialog(QDialog):
|
||||
self.refresh_button.setEnabled(True)
|
||||
self.confirm_button.setEnabled(self.plan is not None)
|
||||
self.force_button.setEnabled(bool(self.plan and any(
|
||||
not force_block_reason(r) for r in self.plan['sessions'])))
|
||||
r.get('scope_confirmed', True) for r in self.plan['sessions'])))
|
||||
self.close_button.setText('关闭')
|
||||
self._update_prompt()
|
||||
if self._refresh_after:
|
||||
@@ -88,14 +81,8 @@ 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', ''), ', '.join(session.get('desktops', [])),
|
||||
session.get('image', session.get('executable', '')), permission, outcome)):
|
||||
session['pid'], session.get('detail', ''))):
|
||||
self.table.setItem(index, column, QTableWidgetItem(str(value)))
|
||||
if sessions: self.table.setCurrentCell(0, 0)
|
||||
|
||||
@@ -103,65 +90,6 @@ 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
|
||||
@@ -204,12 +132,11 @@ class ResidualReleaseDialog(QDialog):
|
||||
|
||||
def force_release(self):
|
||||
if self.busy or not self.plan or not self.plan['sessions']: return
|
||||
targets = [r for r in self.plan['sessions'] if not force_block_reason(r)]
|
||||
targets = [r for r in self.plan['sessions'] if r.get('scope_confirmed', True)]
|
||||
if not targets: return
|
||||
names = '\n'.join(f'{r.get("project", "")} — {r["name"]} (PID {r["pid"]})' for r in targets)
|
||||
answer = QMessageBox.warning(self, '强制结束客户端',
|
||||
'仅强制结束以下客户端。客户端中其他已打开工程也会退出;未保存的更改会丢失,正在写入的工程可能需要恢复。'
|
||||
'\n数据库服务器和归属未知的进程不会被强制结束。\n\n'+names+
|
||||
answer = QMessageBox.warning(self, '强制结束会话',
|
||||
'将强制结束以下进程,未保存的更改会丢失,正在写入的工程可能需要恢复。\n\n'+names+
|
||||
'\n\n仍要结束这些进程吗?', QMessageBox.Yes | QMessageBox.Cancel, QMessageBox.Cancel)
|
||||
if answer == QMessageBox.Yes: self.confirm_release(force=True)
|
||||
|
||||
@@ -224,16 +151,13 @@ 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 self._accept_release_proof(result):
|
||||
self.message.setText(f'已释放 {count} 个会话,旧占用记录已解除。'
|
||||
+ ('\n记录保存失败:'+result['evidence_error'] if result.get('evidence_error') else ''))
|
||||
if result['status'] == 'RELEASE_CONFIRMED':
|
||||
self.plan = None
|
||||
self.message.setText(f'已释放 {count} 个会话,旧占用记录已解除。')
|
||||
self.released.emit(result['proof'])
|
||||
else:
|
||||
self.message.setText(f'已释放 {count} 个会话,其余会话或库状态仍待确认。'
|
||||
+ ('\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} 项。')
|
||||
+ ('\n'+result['detail'] if result.get('detail') else '请处理原生窗口后重新检查。'))
|
||||
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()
|
||||
|
||||
@@ -102,7 +102,6 @@ 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:
|
||||
@@ -551,7 +550,6 @@ 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():
|
||||
@@ -568,18 +566,16 @@ 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, recheck_previous_release
|
||||
from .library_lock import LibraryLock, LibraryBusy
|
||||
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, ValueError, RuntimeError, pywintypes.error) as error:
|
||||
except (OSError, pywintypes.error) as error:
|
||||
return VerifyResult('FAIL', stderr=str(error), error_category='LIBRARY_ACCESS_FAILED')
|
||||
release_confirmed = False
|
||||
result = _run_verify_serialized(
|
||||
@@ -678,10 +674,6 @@ 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:
|
||||
|
||||
@@ -84,30 +84,11 @@ def test_scan_reuses_checkpoint_and_queries_only_missing(tmp_path):
|
||||
encoding="utf-8",
|
||||
)
|
||||
bridge = FakeBridge()
|
||||
records = BatchStatusSession(bridge).scan(["A", "B"], lmc, checkpoint, resume=True)
|
||||
records = BatchStatusSession(bridge).scan(["A", "B"], lmc, checkpoint)
|
||||
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")
|
||||
@@ -199,7 +180,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, resume=True)
|
||||
second = BatchStatusSession(bridge).scan(['A', 'B'], lmc, checkpoint)
|
||||
assert bridge.requests == ['A']
|
||||
assert second[0].status == 'READY'
|
||||
|
||||
|
||||
@@ -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, resume=True)
|
||||
BatchStatusSession(bridge).scan(["A"], lmc, checkpoint)
|
||||
assert bridge.requests == ["A"]
|
||||
@@ -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/library.lmc'; library.parent.mkdir(); library.touch()
|
||||
library = tmp_path / 'library.lmc'; library.touch()
|
||||
req = runner.VerifyRequest(library, 'CBB', tmp_path / 'evidence')
|
||||
assert req.auto_repair is False
|
||||
marker = locks.blocker_path(library)
|
||||
@@ -16,17 +16,11 @@ 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'))
|
||||
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 runner.run_verify(req) is result
|
||||
assert calls == ['verify', 'verify']
|
||||
assert not marker.exists()
|
||||
archive = Path(first.release_proof['evidence_path']).with_name('blocker-before-0.json')
|
||||
assert archive.read_text() == 'historical diagnostic record'
|
||||
assert locks._key(library.parent / '.library.cbb-upload.lock') not in locks._owners
|
||||
assert marker.read_text() == 'historical diagnostic record'
|
||||
assert locks._key(tmp_path / '.library.cbb-upload.lock') not in locks._owners
|
||||
|
||||
|
||||
def test_catalog_checkpoint_does_not_disable_ordinary_verify(qtbot, tmp_path, monkeypatch):
|
||||
|
||||
@@ -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', resume=True)
|
||||
session.scan(['Block'], library, tmp_path/'scan.jsonl', block_type='Other')
|
||||
assert calls == ['RULP', 'Other']
|
||||
|
||||
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
from threading import Event, Thread
|
||||
|
||||
from cbb_refresh_verify.operation_queue import NativeQueue, QueueCancelled
|
||||
|
||||
|
||||
def test_paused_ticket_yields_to_a_ready_native_task():
|
||||
queue=NativeQueue()
|
||||
ready, waiting, complete=Event(),Event(),Event()
|
||||
order=[]
|
||||
thread=Thread(target=lambda:queue.run(lambda:(order.append('resumed'),complete.set()),
|
||||
ready=ready.is_set,waiting=waiting.set))
|
||||
thread.start()
|
||||
try:
|
||||
assert waiting.wait(2)
|
||||
queue.run(lambda:order.append('ready'))
|
||||
assert order==['ready']
|
||||
ready.set();queue.wake()
|
||||
assert complete.wait(2)
|
||||
assert order==['ready','resumed']
|
||||
finally:
|
||||
ready.set();queue.wake();thread.join(2)
|
||||
assert not thread.is_alive()
|
||||
|
||||
|
||||
def test_cancelled_paused_ticket_does_not_hold_later_work():
|
||||
queue=NativeQueue()
|
||||
waiting,stop=Event(),Event()
|
||||
outcome=[]
|
||||
def wait():
|
||||
try:
|
||||
queue.run(lambda:outcome.append('unexpected'),ready=lambda:False,
|
||||
waiting=waiting.set,stop=stop)
|
||||
except QueueCancelled:outcome.append('cancelled')
|
||||
thread=Thread(target=wait);thread.start()
|
||||
try:
|
||||
assert waiting.wait(2)
|
||||
stop.set();queue.wake();thread.join(2)
|
||||
assert not thread.is_alive()
|
||||
queue.run(lambda:outcome.append('next'))
|
||||
assert outcome==['cancelled','next']
|
||||
finally:
|
||||
stop.set();queue.wake();thread.join(2)
|
||||
@@ -2,6 +2,7 @@ import pytest
|
||||
|
||||
from cbb_refresh_verify.pcb_bridge import (
|
||||
PcbBridgeError,
|
||||
execution_outcome,
|
||||
require_document_identity,
|
||||
wait_for_target_document,
|
||||
)
|
||||
@@ -73,6 +74,23 @@ 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 = []
|
||||
|
||||
@@ -81,8 +81,7 @@ def test_force_close_is_explicit_and_cancel_does_not_release(qtbot, tmp_path, mo
|
||||
from cbb_refresh_verify import library_lock
|
||||
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
|
||||
plan = {'library': str(tmp_path/'lib.lmc'), 'sessions': [
|
||||
{'project': 'A', 'name': 'ExpeditionPCB.exe', 'pid': 10, 'detail': '窗口无响应',
|
||||
'scope_confirmed': True, 'owner_sid': 'S-1-current', 'session_id': 1, 'force_user_confirmed': True, 'image': 'C:/Mentor/ExpeditionPCB.exe', 'created_handle': 'creation'}]}
|
||||
{'project': 'A', 'name': 'ExpeditionPCB.exe', 'pid': 10, 'detail': '窗口无响应'}]}
|
||||
monkeypatch.setattr(library_lock, 'inspect_residual_sessions', lambda *_: plan)
|
||||
calls = []
|
||||
def release(actual, *a, **kw):
|
||||
@@ -101,31 +100,6 @@ def test_force_close_is_explicit_and_cancel_does_not_release(qtbot, tmp_path, mo
|
||||
assert calls == [True]
|
||||
|
||||
|
||||
def test_force_confirmation_excludes_shared_servers(qtbot, tmp_path, monkeypatch):
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
from cbb_refresh_verify import library_lock
|
||||
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
|
||||
rows = [{'project': 'A', 'name': name, 'pid': pid, 'scope_confirmed': True, 'owner_sid': 'S-1-current', 'session_id': 1, 'force_user_confirmed': True,
|
||||
'image': 'C:/Mentor/'+name, 'created_handle': str(pid), 'detail': 'waiting'}
|
||||
for name, pid in [('icdbserver.exe', 10), ('ExpeditionPCB.exe', 20)]]
|
||||
monkeypatch.setattr(library_lock, 'inspect_residual_sessions', lambda *_: {
|
||||
'library': str(tmp_path/'lib.lmc'), 'sessions': rows})
|
||||
dialog = ResidualReleaseDialog(tmp_path/'lib.lmc', tmp_path/'evidence')
|
||||
qtbot.addWidget(dialog)
|
||||
qtbot.waitUntil(lambda: not dialog.busy)
|
||||
messages = []
|
||||
monkeypatch.setattr(QMessageBox, 'warning', lambda parent, title, text, *args:
|
||||
messages.append(text) or QMessageBox.Cancel)
|
||||
dialog.force_button.click()
|
||||
assert len(messages) == 1
|
||||
assert 'ExpeditionPCB.exe' in messages[0]
|
||||
assert 'icdbserver.exe' not in messages[0]
|
||||
assert '服务器' in messages[0]
|
||||
dialog.plan['sessions'] = [rows[0]]
|
||||
dialog._finished()
|
||||
assert not dialog.force_button.isEnabled()
|
||||
|
||||
|
||||
def test_released_batch_can_resume_only_its_unexecuted_items(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
@@ -149,7 +123,6 @@ 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)))
|
||||
|
||||
+14
-150
@@ -4,9 +4,6 @@ from types import SimpleNamespace
|
||||
import pytest
|
||||
|
||||
|
||||
OWNERSHIP = {"owner_sid": "S-1-current", "session_id": 1, "force_user_confirmed": True}
|
||||
|
||||
|
||||
def api():
|
||||
from cbb_refresh_verify import library_lock
|
||||
inspect = getattr(library_lock, 'inspect_residual_sessions', None)
|
||||
@@ -27,7 +24,7 @@ def test_preview_limits_to_selected_projects_and_keeps_process_identity(tmp_path
|
||||
a = library.parent/'ReusableBlocksLP/A/Work/A.prj'
|
||||
b = library.parent/'ReusableBlocksLP/B/Work/B.prj'
|
||||
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [row(10, a), row(20, b)])
|
||||
monkeypatch.setattr(sessions, '_process_identity', lambda r: {**OWNERSHIP, 'created_handle': r['created'], 'image': r['executable']})
|
||||
monkeypatch.setattr(sessions, '_process_identity', lambda r: {'created_handle': r['created'], 'image': r['executable']})
|
||||
monkeypatch.setattr(sessions, '_process_windows', lambda pids: {p: [] for p in pids})
|
||||
result = inspect(library, block_names=('A',))
|
||||
assert [r['pid'] for r in result['sessions']] == [10]
|
||||
@@ -41,7 +38,7 @@ def test_unknown_scope_is_visible_but_never_closed_even_with_force(tmp_path, mon
|
||||
process['name'] = 'LibraryManager.exe'
|
||||
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [process])
|
||||
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
|
||||
monkeypatch.setattr(sessions, '_process_identity', lambda r: {**OWNERSHIP, 'created_handle': 'old', 'image': r['executable']})
|
||||
monkeypatch.setattr(sessions, '_process_identity', lambda r: {'created_handle': 'old', 'image': r['executable']})
|
||||
plan = sessions.inspect_residual_sessions(library)
|
||||
assert plan['sessions'] and plan['sessions'][0]['scope_confirmed'] is False
|
||||
monkeypatch.setattr(sessions, '_request_close', lambda *a, **kw: pytest.fail('closed unknown scope'))
|
||||
@@ -77,7 +74,7 @@ def test_confirmation_rechecks_pid_reuse_and_never_posts_to_replacement(tmp_path
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
process = row(10, tmp_path/'ReusableBlocksLP/A/Work/A.prj')
|
||||
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_identity', lambda r: {'created_handle': 'old', 'image': r['executable']})
|
||||
monkeypatch.setattr(sessions, '_process_windows', lambda _: {10: []})
|
||||
plan = inspect(library)
|
||||
process['created'] = 'replacement'
|
||||
@@ -94,7 +91,7 @@ def test_close_requests_cover_whole_preview_and_failures_remain_per_item(tmp_pat
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
rows = [row(p, tmp_path/f'ReusableBlocksLP/{p}/Work/{p}.prj') for p in (10, 20)]
|
||||
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: rows)
|
||||
monkeypatch.setattr(sessions, '_process_identity', lambda r: {**OWNERSHIP, 'created_handle': r['created'], 'image': r['executable']})
|
||||
monkeypatch.setattr(sessions, '_process_identity', lambda r: {'created_handle': r['created'], 'image': r['executable']})
|
||||
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
|
||||
calls = []
|
||||
monkeypatch.setattr(sessions, '_request_close', lambda r, *_, **kw: calls.append(r['pid']) or
|
||||
@@ -147,9 +144,9 @@ 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', name='ExpeditionPCB.exe')
|
||||
process = row(10, tmp_path/'ReusableBlocksLP/A/Work/A.prj')
|
||||
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_identity', lambda r: {'created_handle': 'old', 'image': r['executable']})
|
||||
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
|
||||
monkeypatch.setattr(sessions, '_request_close', lambda *a, **k: {'release_status': 'WAITING', 'detail': 'hung'})
|
||||
forced = []
|
||||
@@ -166,125 +163,14 @@ def test_force_requires_separate_explicit_argument_and_rechecks_identity(tmp_pat
|
||||
assert forced == [10]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('name', ['icdbnetserver.exe', 'icdbserver.exe',
|
||||
'ReuseBlockImporter.exe', 'wscript.exe'])
|
||||
def test_force_preserves_servers_and_unsupported_processes_even_with_confirmed_scope(tmp_path, monkeypatch, name):
|
||||
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', name=name)
|
||||
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 _: {})
|
||||
monkeypatch.setattr(sessions, '_force_close', lambda *a, **kw: pytest.fail('protected process was force terminated'))
|
||||
plan = sessions.inspect_residual_sessions(library)
|
||||
assert plan['sessions'][0]['scope_confirmed']
|
||||
result = sessions.release_residual_sessions(plan, tmp_path.parent/'release-evidence'/tmp_path.name, force=True)
|
||||
assert result['status'] == 'PARTIAL'
|
||||
assert result['sessions'][0]['release_status'] == 'WAITING'
|
||||
assert result['sessions'][0]['force_allowed'] is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize('name', ['icdbserver.exe', 'cdbsvr.exe', 'python.exe'])
|
||||
def test_direct_force_cannot_request_a_terminate_handle_for_database_server(monkeypatch, name):
|
||||
from cbb_refresh_verify import residual_sessions as sessions
|
||||
process = {'pid': 10, 'name': name, 'scope_confirmed': True,
|
||||
'image': 'C:/Mentor/'+name, 'created_handle': 'creation'}
|
||||
monkeypatch.setattr(sessions, '_process_handle', lambda *a, **kw: pytest.fail('opened terminate-capable server handle'))
|
||||
assert sessions._force_close(process)['release_status'] == 'WAITING'
|
||||
|
||||
|
||||
def test_force_writes_exact_consent_before_any_native_action(tmp_path, monkeypatch):
|
||||
import json
|
||||
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', 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 _: {})
|
||||
evidence = tmp_path.parent/'release-evidence'/tmp_path.name
|
||||
def force(actual, **kwargs):
|
||||
consent = json.loads(next(evidence.glob('sessions-*/consent.json')).read_text(encoding='utf-8'))
|
||||
assert consent['library'] == str(library.resolve())
|
||||
assert consent['mode'] == 'force_document_clients'
|
||||
assert consent['sessions'][0]['pid'] == actual['pid']
|
||||
assert consent['sessions'][0]['created_handle'] == actual['created_handle']
|
||||
return {'release_status': 'WAITING', 'detail': 'not exited'}
|
||||
monkeypatch.setattr(sessions, '_force_close', force)
|
||||
plan = sessions.inspect_residual_sessions(library)
|
||||
result = sessions.release_residual_sessions(plan, evidence, force=True)
|
||||
assert Path(result['consent_path']).is_file()
|
||||
assert result['status'] == 'PARTIAL'
|
||||
|
||||
|
||||
def test_unwritable_force_consent_prevents_all_native_actions(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', 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 _: {})
|
||||
plan = sessions.inspect_residual_sessions(library)
|
||||
original = Path.open
|
||||
def deny(path, *args, **kwargs):
|
||||
if path.name == 'consent.json': raise PermissionError('cannot record consent')
|
||||
return original(path, *args, **kwargs)
|
||||
monkeypatch.setattr(Path, 'open', deny)
|
||||
monkeypatch.setattr(sessions, '_force_close', lambda *a, **kw: pytest.fail('termination preceded durable consent'))
|
||||
with pytest.raises(PermissionError, match='cannot record consent'):
|
||||
sessions.release_residual_sessions(plan, tmp_path.parent/'release-evidence'/tmp_path.name, force=True)
|
||||
|
||||
|
||||
def test_current_process_handle_identity_uses_real_windows_api():
|
||||
import os
|
||||
from cbb_refresh_verify.residual_sessions import _process_identity
|
||||
identity = _process_identity({'pid': os.getpid()})
|
||||
assert identity['created_handle'] and Path(identity['image']).is_file()
|
||||
assert identity['owner_sid'].startswith('S-1-')
|
||||
assert isinstance(identity['session_id'], int)
|
||||
assert identity['force_user_confirmed'] is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize('ownership', [{}, {'owner_sid': 'S-1-other', 'session_id': 1,
|
||||
'force_user_confirmed': False}])
|
||||
def test_force_never_opens_terminate_handle_without_current_user_and_session(monkeypatch, ownership):
|
||||
from cbb_refresh_verify import residual_sessions as sessions
|
||||
process = {'pid': 10, 'name': 'ExpeditionPCB.exe', 'scope_confirmed': True,
|
||||
'created_handle': 'creation', 'image': 'C:/Mentor/ExpeditionPCB.exe', **ownership}
|
||||
monkeypatch.setattr(sessions, '_process_handle', lambda *a, **kw: pytest.fail('opened unowned process'))
|
||||
assert sessions._force_close(process)['release_status'] == 'WAITING'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('other_user,other_session', [(True, False), (False, True), (False, False)])
|
||||
def test_force_ownership_checks_user_sid_and_windows_session(monkeypatch, other_user, other_session):
|
||||
import os
|
||||
import win32api, win32process, win32security, win32ts
|
||||
from cbb_refresh_verify import residual_sessions as sessions
|
||||
closed = []
|
||||
monkeypatch.setattr(win32process, 'GetProcessId', lambda _: 10)
|
||||
monkeypatch.setattr(win32api, 'GetCurrentProcess', lambda: 999)
|
||||
monkeypatch.setattr(win32security, 'OpenProcessToken', lambda process, access:
|
||||
SimpleNamespace(process=process, Close=lambda: closed.append(process)))
|
||||
monkeypatch.setattr(win32security, 'GetTokenInformation', lambda token, kind:
|
||||
('other' if other_user and token.process == 123 else 'current', 0))
|
||||
monkeypatch.setattr(win32security, 'ConvertSidToStringSid', lambda sid: 'S-1-'+sid)
|
||||
monkeypatch.setattr(win32ts, 'ProcessIdToSessionId', lambda pid:
|
||||
2 if other_session and pid != os.getpid() else 1)
|
||||
assert sessions._force_ownership(123, 10)['force_user_confirmed'] is (not other_user and not other_session)
|
||||
assert closed == [123, 999]
|
||||
|
||||
|
||||
def test_unreadable_force_ownership_does_not_hide_cooperative_identity(monkeypatch):
|
||||
from contextlib import nullcontext
|
||||
from cbb_refresh_verify import residual_sessions as sessions
|
||||
monkeypatch.setattr(sessions, '_process_handle', lambda _: nullcontext(123))
|
||||
monkeypatch.setattr(sessions, '_handle_identity', lambda _: {'created_handle': 'creation', 'image': 'pcb.exe'})
|
||||
def denied(*args): raise PermissionError('token inaccessible')
|
||||
monkeypatch.setattr(sessions, '_force_ownership', denied)
|
||||
identity = sessions._process_identity({'pid': 10})
|
||||
assert identity['created_handle'] == 'creation' and identity['force_user_confirmed'] is False
|
||||
|
||||
|
||||
def test_force_refuses_actual_unsupported_test_helper():
|
||||
def test_force_checks_exact_handle_before_ending_owned_test_helper():
|
||||
import subprocess
|
||||
import sys
|
||||
from cbb_refresh_verify.residual_sessions import _process_identity, _force_close
|
||||
@@ -292,49 +178,27 @@ def test_force_refuses_actual_unsupported_test_helper():
|
||||
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
try:
|
||||
process = {'pid': child.pid, **_process_identity({'pid': child.pid})}
|
||||
assert _force_close(process)['release_status'] == 'WAITING'
|
||||
changed = {**process, 'created_handle': 'different process'}
|
||||
assert _force_close(changed)['release_status'] == 'IDENTITY_CHANGED'
|
||||
assert child.poll() is None
|
||||
assert _force_close(process)['release_status'] == 'RELEASED'
|
||||
assert child.wait(3) == 1
|
||||
finally:
|
||||
if child.poll() is None:
|
||||
child.terminate(); child.wait(3) # This test's sleep-only helper.
|
||||
|
||||
|
||||
def test_supported_force_revalidates_exact_handle_before_termination(monkeypatch):
|
||||
from contextlib import nullcontext
|
||||
import win32api, win32con, win32event
|
||||
from cbb_refresh_verify import residual_sessions as sessions
|
||||
process = {'pid': 10, 'name': 'ExpeditionPCB.exe', 'scope_confirmed': True,
|
||||
'created_handle': 'creation', 'image': 'C:/Mentor/ExpeditionPCB.exe', **OWNERSHIP}
|
||||
monkeypatch.setattr(sessions, '_process_handle', lambda *a, **kw: nullcontext(123))
|
||||
monkeypatch.setattr(sessions, '_handle_identity', lambda _: {
|
||||
'created_handle': 'creation', 'image': 'C:/Mentor/ExpeditionPCB.exe'})
|
||||
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'
|
||||
assert not calls
|
||||
assert sessions._force_close({**process, 'session_id': 2})['release_status'] == 'IDENTITY_CHANGED'
|
||||
assert sessions._force_close({**process, 'owner_sid': 'S-1-other'})['release_status'] == 'IDENTITY_CHANGED'
|
||||
assert not calls
|
||||
assert sessions._force_close(process)['release_status'] == 'RELEASED'
|
||||
assert calls == [(123, 1)]
|
||||
|
||||
|
||||
def test_partial_desktop_enumeration_never_offers_normal_close(monkeypatch):
|
||||
import win32gui, win32service
|
||||
from cbb_refresh_verify.residual_sessions import _process_windows, close_target
|
||||
def failed(*_): raise OSError('desktop disappeared')
|
||||
monkeypatch.setattr(win32gui, 'EnumWindows', failed)
|
||||
monkeypatch.setattr(win32service, 'GetProcessWindowStation', lambda: SimpleNamespace(EnumDesktops=lambda: []))
|
||||
snapshot = _process_windows({10})
|
||||
windows = snapshot[10]
|
||||
assert snapshot.incomplete[10]
|
||||
windows = _process_windows({10})[10]
|
||||
assert any(w['class'] == 'UNCONFIRMED' for w in windows)
|
||||
windows.append({'hwnd': 100, 'class': 'Afx:main', 'title': 'Design - Expedition PCB',
|
||||
'children': [], 'enabled': True})
|
||||
assert close_target('ExpeditionPCB.exe', windows, incomplete=snapshot.incomplete[10])[0] is None
|
||||
assert close_target('ExpeditionPCB.exe', windows)[0] is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('choice', [6, 7, 2])
|
||||
|
||||
@@ -1,171 +0,0 @@
|
||||
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()
|
||||
@@ -1,166 +0,0 @@
|
||||
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()
|
||||
@@ -1,40 +0,0 @@
|
||||
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()
|
||||
@@ -1,151 +0,0 @@
|
||||
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]
|
||||
@@ -1,52 +0,0 @@
|
||||
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'] == []
|
||||
@@ -1,45 +0,0 @@
|
||||
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
|
||||
@@ -1,302 +0,0 @@
|
||||
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)}})
|
||||
@@ -118,42 +118,17 @@ 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.copystat
|
||||
real_copy = shutil.copy2
|
||||
def copy_then_change_source(src, dst, *args, **kwargs):
|
||||
result = real_copy(src, dst, *args, **kwargs)
|
||||
metadata = primary.stat()
|
||||
primary.write_bytes(b'X' * metadata.st_size)
|
||||
os.utime(primary, ns=(metadata.st_atime_ns, metadata.st_mtime_ns))
|
||||
return result
|
||||
monkeypatch.setattr(shutil, 'copystat', copy_then_change_source)
|
||||
monkeypatch.setattr(shutil, 'copy2', copy_then_change_source)
|
||||
with pytest.raises(OSError):
|
||||
recovery._copy_verified(source, destination)
|
||||
assert (destination/'A.prj').read_bytes() == b'engineering'
|
||||
@@ -165,7 +140,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.copystat
|
||||
real_copy = shutil.copy2
|
||||
def copy_then_mutate(src, dst, *args, **kwargs):
|
||||
result = real_copy(src, dst, *args, **kwargs)
|
||||
if Path(src).name == 'A.prj':
|
||||
@@ -176,7 +151,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, 'copystat', copy_then_mutate)
|
||||
monkeypatch.setattr(shutil, 'copy2', copy_then_mutate)
|
||||
with pytest.raises(OSError):
|
||||
recovery._copy_verified(source, destination)
|
||||
assert destination.exists()
|
||||
@@ -302,7 +277,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.copystat
|
||||
real_copy = shutil.copy2
|
||||
def copy_then_corrupt(src, dst, *args, **kwargs):
|
||||
result = real_copy(src, dst, *args, **kwargs)
|
||||
corrupt = Path(src) if side == 'source' else Path(dst)
|
||||
@@ -310,7 +285,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, 'copystat', copy_then_corrupt)
|
||||
monkeypatch.setattr(shutil, 'copy2', copy_then_corrupt)
|
||||
with pytest.raises(OSError):
|
||||
recovery._copy_verified(source, destination, scope=scope)
|
||||
assert (destination/relative).exists()
|
||||
|
||||
Reference in new issue
Block a user