fix: scope release proofs and bind PCB opening consent

This commit is contained in:
阿白叔 committed 2026-11-12 16:02:53 +08:00
1 parent 42d0cebc54
commit 466f400514
33 files changed
+1358 -61

No files matched your search

@@ -0,0 +1,233 @@
# 当前程序流程、阻塞点与错误节点
> 这是修改前 `42d0ceb` 的流程快照。后续修复及真实复测见 [占用范围验证](2026-11-12-scoped-release-validation.md)。
依据提交 `42d0cebc54191681b53dcecb120f53236c1963bb` 的代码及 2026-11-12 冻结程序原生验收记录。本文件只分析当前行为,没有实施下面建议的调整,也没有新增原生验收。
后续只读核查已用外部软件自身日志确认 E01 的两个未知阻塞进程来自 DxPartReplace 测试,创建时间、父进程和私有桌面交叉匹配;外部工程引用原库,本次 CBB 验收使用隔离库。详见 [进程来源核查](2026-11-12-process-origin-audit.md)。这进一步确认了并行软件触发本程序范围判定漏洞,不能将其解释成本程序自身客户端未退出。
红色 E 节点表示真实验收已经发生、仍未解决的问题;橙色 B 节点表示代码中确实存在的等待、拒绝或失败分支,但不表示每个条件都已复现;绿色 F 表示本轮修复并复测通过的位置。各入口在 UI 中独立,底层原生调用仍共享串行通道。
## 一、最需要处理的阻塞链
```mermaid
flowchart LR
A[单个 CBB 失败或被停止] --> B[PCB 或助手未确认退出]
B --> C[safe_to_continue 为 false]
C --> D[B02 同库后续项被跳过]
C --> E[B01 后续任务等待库可用]
E --> F[用户打开释放窗口]
F --> G[正常关闭本工具 PCB]
G --> H[E01 其他任务的未知会话也被纳入必须退出的集合]
H --> I[整库释放仍为 PARTIAL]
I --> E
classDef error fill:#fee2e2,stroke:#dc2626,color:#7f1d1d
classDef risk fill:#fff3cd,stroke:#d97706,color:#78350f
class H,I error
class D,E risk
```
这条链中的核心缺陷是:**当前项是否失败、当前项是否留下占用、整个库能否继续、其他工具是否正在运行,没有彻底分开。** 某项失败但 `safe_to_continue=true` 时,当前代码会继续处理下一项,真实多来源新增已验证这一点;`false` 则会阻止同库后续项,不能称为“所有失败都不会影响整批”。
## 二、阻塞与失败清单
| 标记 | 发生位置与触发条件 | 当前后果、影响范围 | 证据与处理方向 |
| --- | --- | --- | --- |
| **E01 已复现、未修复** | 释放集合包含 scope_confirmed=false 的其他任务进程;释放函数要求全部观察项 RELEASED;底层证明也把没有目标路径的进程作为可能占用 | 本工具 PCB 已退出,整库仍 PARTIAL;保留状态无法清除,同库后续任务继续等或被跳过 | R7 的 PCB 21856/21248 均退出;其他任务 viewdraw 29832 为 WAITING。必须区分观察项与本库目标,并用目标资源证明决定能否继续,不能直接结束其他任务 |
| **E02 已复现、未走通** | PCB 启动出现原生“确认无其他用户,以读写权限继续”提示 | 当前打开判为 DATABASE_SAFETY_STOP;普通校验未 READY,ICDB 检查无法确认,备份副本不安装。关闭成功时本项失败仍可安全继续 | 该正文不直接证明 ICDB 损坏。代码有受限的修复后授权分支,但不是普通打开时通用的用户确认入口 |
| **E03 已复现、未修复** | A/B 来源工程的原生 EDIF 导出器退出 0xC0000005 | 本项上传失败;退出及资源释放证明成功后下一项继续,不能跳过身份比对报告成功 | 相同批次 C 能新增成功。需进一步定位原生导出与输入兼容性 |
| **B01 可长期排队** | NativeQueue 没有排队总超时;等待 active=false 且本库 library_available=true | UI 线程保持运行,但普通校验、管理、刷新等任务可能一直显示等待;可取消排队。活动任务未返回时,即使不同库也不能使用同一个原生通道 | 属于后台任务等待,不等于界面卡死;不同库且条件满足的票据可以越过暂不可用票据。需要展示等待对象、阶段及下一步,而不是单一“忙” |
| **B02 失败传播到同库** | run_batch、run_management_batch、IcdbCheckTask 遇 safe_to_continue=false;未知异常也可能保守置 false | 同库后续项 SKIPPED;其他库不因这个集合被跳过;CANCELLED/QUEUE_STOP 或用户停止会停止余下队列 | 现有规则确实仍会让单项占用影响本库整批。后续需分辨仅此工程占用与共享库占用,不能盲目把 false 改 true |
| **B03 执行互斥与协调锁** | Windows 会话级 Local/CbbRefreshVerify795 被占用;库协调锁被持有;历史 blocked/pending 记录存在或身份不符 | 直接拒绝本次操作,或先复核旧记录;未确认时保留本库协调锁/记录 | 多个应用实例、独立上传工具、崩溃遗留均可能触发。历史记录本身不是仍在写库的证明 |
| **B04 地址、数据库、在途调用** | 存在 sAddress.adr;数据库/LMC/Layout 独占读失败;仍有本库原生写入或导出副本所有者 | 当前操作或释放证明失败;真实在途写入应继续保护。陈旧地址和不完整日志也可能导致无法确认 | 当前主要哈希排除地址文件,但占用判断仍会使用它们;不能用“哈希忽略了”推断“占用也已忽略” |
| **B05 原生调用未返回** | Add/Remove/COM 调用或原生进程超过监督时限 | 有些监督入口返回超时并保留真实 worker;真实写入继续观测;CleanWGLib 超时后仍等待其自然退出,不能把超时当释放 | 可能同时占着执行通道、库锁或保留状态。需要区分取消未开始项、请求原生取消、仍在写入、可以关闭的客户端 |
| **B06 原生版本窗口仍打开** | iCDB Project Backup 原生窗口尚未关闭,或关闭结果未确认 | 同库校验/恢复受到限制;同库 ICDB 后台检查会暂停,关闭并确认后恢复;不是自动修复失败 | 这是实际原生编辑会话的互斥。不能通过关闭应用或删除记录假装窗口已关闭 |
| **B07 格式、能力与来源校验** | 缺失/越界引用、不支持的版本或接口、目标分区不唯一、来源同名不匹配、未完成变更记录仍需恢复 | 本项拒绝;新增遇同名冲突明确失败;未完成写操作不会在重启后自动重放 | 这些多数属于输入/恢复边界;要给出具体原因和可纠正入口,不能混成 ICDB 问题 |
| **B08 来源/目标内容变化** | 暂存复制前后文件集合或主要哈希变化;基线后中心库更新;恢复前来源或目标变化 | 停止当前写入或恢复。更新已 Remove 但尚未 Add 成功时可能 RECOVERY_REQUIRED | 应保留阶段、原 Work 或人工备份路径;不能把部分成功视为整体成功 |
| **B09 权威状态与工程身份** | 保存/关闭失败;注册内容不符;中心库复读失败;校验后不是 GREEN/READY | 当前项不通过;是否影响后续取决于释放事实。上传成功可为 UPLOADED,但不等于 UPLOADED_VERIFIED | 不能仅以 PCB 窗口打开、COM 返回或文件目录存在判成功 |
| **B10 IO、路径与证据存储** | 网络盘不可见、路径映射失败、证据目录不可写、检查点变化、空间不足 | 读取/当前任务失败;关键写前检查点保存失败时不开始写入;某些辅助诊断写入失败只记录警告 | 网络/磁盘与原生数据库错误要分开报告;恢复需先复制验证库,因此有实际容量和耗时 |
| **B11 程序关闭等待** | 关闭时检查仍活动、当前任务仍忙、线程池或路径租约操作仍未结束 | 首次关闭可能只请求停止;进入关闭流程后等线程池/租约结束,代码没有统一关闭总超时 | R7 正常退出通过,不代表 COM 永久不返回场景也能退出;需要单独验收这一条件 |
| **F01 已修复复测** | 原生私有桌面 GetThreadDesktop 拒绝访问;重新 OpenDesktop 后 HWND 不可读 | 之前误报窗口归属变化,无法正常释放 | 已改为有界桌面枚举、映射窗口后再核对 PID,真实 PCB 正常取消退出通过 |
| **F02 已修复复测** | 状态刷新期间结果窗口的释放按钮仍可点击,函数因 busy 直接返回 | 之前按钮点击无窗口 | 已跟随 busy/排队目标更新,R7 先禁用后可用,点击能打开释放窗口;不等于 E01 已解决 |
另有 **P2 结果展示错误**:释放数量包含自然退出且未允许操作的观察项,因此出现“已释放 4 个,确认允许 2 个”。这是统计问题,不是解除占用的证明。
## 三、完整业务流程总图
下图按实际任务边界展开:所有菜单可以独立提交请求;排队串行的是 Mentor 原生操作。为保持图可读,把共享的 PCB 子流程和释放子流程放在后两张展开图中,节点 V、R 在各图中指向同一过程。
```mermaid
flowchart TD
START[启动桌面应用] --> INIT[配置日志、加载原生能力、异步发现未完成任务]
INIT --> LIB[选择中心库并建立路径映射 B10]
LIB --> READ[读取 CBB、工程文件及权威状态 B07 B09]
READ --> LIST[搜索、筛选、可见项勾选]
LIST --> OP{选择独立操作入口}
OP --> VERIFY[检验:只取可见非 READY 项]
OP --> CHECK[ICDB 批量检查:只取可见非 READY 项]
OP --> HISTORY[版本历史与备份:单个非 READY 项]
OP --> RECOVER[从完整工程备份恢复:非 READY 项]
OP --> MANAGE[中心库管理:READY 可更新或移除]
OP --> R[释放残留:进入释放子流程]
VERIFY --> CONFIRM[显示目标与确认;写操作提示人工备份]
CHECK --> CONFIRM
HISTORY --> ADMIT
RECOVER --> CONFIRM
MANAGE --> CONFIRM
CONFIRM --> ADMIT[原生队列准入 B01:可取消;按目标库保留状态判断]
ADMIT --> DISPATCH{任务类型}
DISPATCH -->|普通校验| V[共享 PCB 打开、弹窗、校验、关闭子流程 E02]
DISPATCH -->|检查| CITEM[每项重新判断 READY 和内容是否更新]
CITEM -->|应跳过| RESULT
CITEM -->|应检查| CV[调用 V;仅诊断打开,不保存校验、不 Repair]
CV --> CLASSIFY{本次错误正文含 ICDB 特征吗}
CLASSIFY -->|正常打开并关闭| CLEAN[CHECKED;不等于 READY]
CLASSIFY -->|含有特征| ICERR[报告 ICDB 问题;不执行自动修复]
CLASSIFY -->|其他弹窗或无法打开| UNCERTAIN[无法确认;保留原错误 E02]
CLEAN --> RESULT
ICERR --> RESULT
UNCERTAIN --> RESULT
DISPATCH -->|版本管理| HOPEN[绑定工程后打开原生备份窗口 B06]
HOPEN --> HUSER[用户查看、创建备份或选择版本回退]
HUSER --> HCLOSE[等待窗口正常关闭、释放结果及状态复读 B06 B09]
HCLOSE --> RESULT
DISPATCH -->|备份恢复| BVALID[来源身份、路径、文件、空间检查 B07 B10]
BVALID --> BCOPY[复制隔离验证库与备份工程 B08]
BCOPY --> BV[调用 V:在副本校验 E02]
BV --> BOK{PASS、GREEN 且安全释放}
BOK -->|否| BUNCHANGED[恢复失败;目标不安装]
BOK -->|是| BCOMPARE[复核来源和目标未变化 B08]
BCOMPARE --> INSTALL[旧 Work 改名保留,再安装副本 B08 B10]
INSTALL --> TV[调用 V:重新打开实际目标 B09]
TV --> RESULT
BUNCHANGED --> RESULT
DISPATCH -->|管理| MPRE[原生能力、来源、历史任务、库锁检查 B03 B07]
MPRE --> MCAT[原生目录复读并核对名称和分区 B09]
MCAT --> MBASE[记录内容基线;来源工程复制暂存 B08]
MBASE --> MOP{新增、更新或移除}
MOP -->|新增或更新| EXPORT[原生 ASCII、CSV、EDIF 身份导出 E03]
EXPORT --> MWRITE[新增 Add;更新 Remove 后 Add B05 B08]
MOP -->|移除| REMOVE[原生 Remove B05]
MWRITE --> MREAD[目录复读、内容身份及释放核对 B09]
REMOVE --> MREAD
MREAD --> AUTO{新增或更新启用自动校验吗}
AUTO -->|是| MV[调用 V 进行校验;上传成功与校验成功分别记录]
AUTO -->|否或移除| RESULT
MV --> RESULT
V --> RESULT[逐项记录结果、阶段、证据与释放事实]
RESULT --> SAFE{safe_to_continue}
SAFE -->|true| NEXT[继续下一项;ICDB 检查在每项之间让出原生队列]
SAFE -->|false| RETAIN[B02 保留本库会话状态;同库余项跳过]
RETAIN --> R
NEXT --> MORE{还有任务且未停止吗}
MORE -->|是| ADMIT
MORE -->|否| REFRESH[刷新受影响条目的权威状态 B09;生成报告 B10]
REFRESH --> LIST
R -->|证明成功| RESUME[清理本库保留状态;必要时用户继续未执行项]
R -->|未确认 E01| RETAIN
RESUME --> LIST
LIST -->|关闭应用| EXIT[停止当前任务并等待线程池、租约结束 B11]
EXIT --> END[程序退出]
classDef error fill:#fee2e2,stroke:#dc2626,color:#7f1d1d
classDef risk fill:#fff3cd,stroke:#d97706,color:#78350f
classDef good fill:#dcfce7,stroke:#16a34a,color:#14532d
class V,CV,UNCERTAIN,BV,EXPORT,R error
class LIB,READ,ADMIT,HOPEN,HCLOSE,BVALID,BCOPY,BCOMPARE,INSTALL,TV,MPRE,MCAT,MBASE,MWRITE,REMOVE,MREAD,RETAIN,REFRESH,EXIT risk
class CLEAN,RESUME good
```
图中的“回到队列”是下一次任务准入的概览:当前普通校验和管理批次在批次外围占用队列;ICDB 检查每完成一个 CBB 才释放并重新排队,不能理解为三种批次都已经逐项让出通道。读取/状态刷新也会使用原生队列,纯内存搜索与筛选不启动 Mentor。
## 四、共享 PCB 任务展开图 V
```mermaid
flowchart TD
V[开始:普通校验、检查或恢复副本校验] --> GATE[取得会话互斥、复核历史释放、取得库锁 B03 B04]
GATE --> PRE[检查 PRJ、PCB、依赖和证据目录 B07 B10]
PRE --> CONTENT{普通校验且配置了额外内容检查吗}
CONTENT -->|是| EXTRA[Importer 内容检查;失败结束本项]
CONTENT -->|否| LAUNCH
EXTRA -->|通过| LAUNCH[创建私有桌面与监督 worker;启动 PCB B05]
EXTRA -->|失败| FAILURE
LAUNCH --> OPEN{原生打开结果}
OPEN -->|读写确认提示| PERMISSION[E02 普通入口缺少通用授权交互;当前安全停止]
OPEN -->|可识别版本选择| VERSION[用户选最后手动保存、自动保存或取消;适用入口才提供]
OPEN -->|其他错误或未知弹窗| FAILURE[本项失败,记录实际文本或超时 B05]
OPEN -->|打开完成| MODE{仅诊断打开吗}
VERSION -->|可继续| OPEN
VERSION -->|取消| FAILURE
MODE -->|是| DIAG[证明目标已打开;请求关闭,不执行保存校验]
MODE -->|否| VERIFY[实际原生校验、保存、关闭 B05 B09]
VERIFY --> READY[中心库权威复读:必须 GREEN/READY B09]
PERMISSION --> CLOSE
FAILURE --> CLOSE
DIAG --> CLOSE[正常关闭、取消已知启动弹窗、释放 COM 和自动化助手]
READY --> CLOSE
CLOSE --> OWNERS[确认 worker、PCB、启动器和目标资源已释放 B04;桌面访问 F01 已修复]
OWNERS -->|成功| OUT[返回本项业务结果,safe_to_continue=true]
OWNERS -->|失败或无法确认| RETAIN[保留证据与会话,safe_to_continue=false,触发 B02]
classDef error fill:#fee2e2,stroke:#dc2626,color:#7f1d1d
classDef risk fill:#fff3cd,stroke:#d97706,color:#78350f
class PERMISSION error
class GATE,PRE,LAUNCH,FAILURE,VERIFY,READY,OWNERS,RETAIN risk
```
普通校验和检查都不默认启动自动 Repair。仓库中仍保留修复与修复后授权代码,但当前桌面批量检查路径明确关闭自动修复,不能把存在函数等同于产品入口已接通。
## 五、释放任务展开图 R
```mermaid
flowchart TD
R[主窗口或结果窗口点击释放] --> UI[校验当前目标与按钮可用状态 F02 已修复]
UI --> SCAN[异步枚举进程、线程桌面、窗口、历史会话]
SCAN --> GROUP{能证明属于本库吗}
GROUP -->|是| TARGET[可确认的目标客户端]
GROUP -->|否| OBSERVE[归属未知,只允许观察]
TARGET --> CONSENT[用户确认正常关闭;可查看原生提示]
CONSENT --> ACTION[重新核对 PID、创建时间、映像、窗口后正常关闭 F01 已修复]
ACTION --> PROMPT{还有原生提示吗}
PROMPT -->|保存提示| SAVE[用户保存、放弃或保留;真实分支尚未完整验收]
PROMPT -->|支持取消的活动窗口| CANCEL[确认后请求原生 Cancel;不当成取消已完成]
PROMPT -->|无| EXITCHECK
SAVE --> EXITCHECK[观察真实进程是否退出]
CANCEL --> EXITCHECK
EXITCHECK --> ALL{当前代码:所有观察项都 RELEASED 吗}
OBSERVE --> ALL
ALL -->|否| ERROR[E01 未归属本库的其他任务也会让整体 PARTIAL]
ALL -->|是| PROOF[持有证明句柄检查本库、共享库、地址、导出副本和在途调用 B04]
PROOF --> UNKNOWN[E01 底层仍可能把路径未知进程当候选占用]
UNKNOWN -->|不能证明| ERROR
UNKNOWN -->|证明成功| RECORD[归档匹配的历史记录,清理对应保留状态及映射]
RECORD --> RELEASED[RELEASE_CONFIRMED;允许重新尝试]
ERROR --> WAIT[B01 队列仍等或 B02 本库余项已跳过;显示残留原因]
WAIT -->|用户重新检查| SCAN
classDef error fill:#fee2e2,stroke:#dc2626,color:#7f1d1d
classDef risk fill:#fff3cd,stroke:#d97706,color:#78350f
classDef fixed fill:#dcfce7,stroke:#16a34a,color:#14532d
class ALL,ERROR,UNKNOWN error
class PROOF,WAIT,SAVE,CANCEL risk
class UI,ACTION,RELEASED fixed
```
强制结束是另一个需要确认的分支:只针对已确认归属、符合条件的客户端,不能结束数据库服务器或归属未知进程;本轮真实操作只验收了打开确认后取消,没有执行强制终止。它不会消除 E01,不能作为释放判断错误的替代方案。
## 六、代码位置与四层协调机制
| 机制 | 位置 | 控制范围 |
| --- | --- | --- |
| 原生队列 | `operation_queue.py:18`、`ui/main_window.py:844`、`ui/management_dialog.py:174` | 应用内一次执行一个原生任务;按库保留状态允许其他可运行票据越过等待项 |
| Windows 会话互斥 | `verify_runner.py:547`、`management.py:172`、`backup_recovery.py:145` | 同一 Windows 会话中的本工具原生调用;不是每工程独立互斥 |
| 库协调锁与历史阻止记录 | `library_lock.py:129`、`:443`、`:523` | 按中心库控制写入与释放;历史记录需复核,不能直接删除当成功 |
| 运行时保留状态 | `session_record.py:25`、`:236`、`:354`、`:443` | 原生队列准入、助手与客户端身份观测;日志阶段不等于真实进程状态 |
| 导出副本所有权 | `native_export_guard.py:10`、`native_engineering_identity.py:288` | 防止原生导出器仍持有分析副本时释放相关操作 |
关键传播代码:`verify_runner.py:1294`、`management.py:430`、`ui/icdb_check_task.py:55`。E01 的双重判定:`residual_sessions.py` 中 `_release_residual_sessions` 的全部行 RELEASED 条件,以及 `library_lock.py:443` 的 `_prove_library_released`。E02:`dialog_rules.py:222`、`verify_runner.py:895`。E03:`native_engineering_identity.py:288`。退出等待:`ui/main_window.py:1709`。
建议处理顺序:**E01 的本库释放判定 → B02 的工程/共享库影响范围 → E02 的明确用户确认路径 → B01/B05/B11 的等待及停止结果 → E03 输入兼容性与剩余条件按钮原生验收**。这些是后续工作建议,未在本次流程整理中实施。
@@ -0,0 +1,71 @@
# 误判复核与优化顺序
> 这是当天早期的复核与建议;后续实施结果见 [占用范围验证](2026-11-12-scoped-release-validation.md),不将早期未通过项追记为成功。
依据 `42d0ceb` 的六处修复记录、真实冻结程序验收,以及 13:44–13:46 的外部进程归属交叉核对。本轮只做分类和优化建议,没有修改业务代码。统计单位是已知问题根因,不能据此估算整个程序的缺陷率。
## 已修复的六处问题
| 问题 | 复核分类 | 依据 |
| --- | --- | --- |
| 导出器退出期间 OpenProcess 返回 5,立即认为释放失败 | 误判/过早得出失败结论 | 原生退出竞争;需要继续观察新快照与目标文件,而不是只看一次权限错误。已修复并有真实导入/更新复测 |
| 无工程参数的外部 viewdraw 阻止备份入口 | 跨工程占用误判 | 未证明目标被占用;恢复入口已改为结合路径、地址与目标文件实际探测 |
| 历史 sAddress_.adr 不一致导致报告工程内容不同 | 内容校验范围误判 | 地址元数据不等于工程内容;完整复制保留,但主要内容哈希排除 |
| 旧工程没有辅助 PCB/pcb.prj 被报告备份不完整 | 工程格式误判 | PCB 唯一关联主 PRJ 的旧格式本身可用;已复用同一身份检查并真实进入副本校验 |
| 私有桌面窗口不可读,不能正常取消 PCB | 真实 Windows 接入缺陷 | 正常进程查询权限不等于可读外部桌面 HWND;已修复并真实关闭客户端 |
| 释放按钮可点击但 busy 导致处理函数直接返回 | 真实 UI 状态缺陷 | R6 原包实际点击无窗口,R7 新包先禁用再可用,实际打开窗口 |
六处中四类属于误判/过严判断,两类属于真实功能缺陷。这里“误判”仍然是程序需要修复的缺陷,不表示可以撤销失败记录或补记验收成功。
## 当前剩余五类问题
| 类别 | 判定 | 是否仍需修改 |
| --- | --- | --- |
| 外部未知会话导致整库释放 PARTIAL | **已确认占用范围误判,1 个根因至少影响两道释放门禁** | 是,最高优先级;操作集合全退出判断与底层资源证明必须一起修正 |
| 显示释放 4 个,但确认允许操作只有 2 个 | **统计归因错误** | 是;区分本次请求关闭、实际退出、原已退出、外部只读观察,不混成主动释放数量 |
| PCB 读写确认挡住校验与备份恢复 | **原生提示真实发生,普通流程缺少相应确认路径;当前停止不等于检测错** | 是;明确用户授权、目标身份和实际占用核查;不能当 ICDB 损坏,也不能直接自动同意 |
| A/B 的原生 EDIF 导出崩溃 | **真实导出失败,输入/原生兼容性根因未定** | 是;保留错误码、输入及导出证据,独立复现,不绕过内容身份校验 |
| 条件按钮、现场失联副本、Win10 等未完成 | **验收缺口,不能记为已发生漏洞或误判** | 补真实覆盖;测试后再决定需要何种修改 |
此前“本程序遗留会话导致释放不了”的描述需细化:本程序在停止启动过程中确实留下过两个 PCB 客户端,属于真实清理问题;正常关闭后,继续挡住整库确认的是外部软件。不能用后半段的误判抹去前半段实际残留,也不能把两者当成同一种“锁”。
## 优化顺序与验收条件
### P1:统一占用归属和资源范围
当前备份入口与整库释放入口使用不同的判断强度;一处已经按目标资源探测,另一处仍能因未知进程直接停止。应复用统一的“来源、目标范围、活动阶段、资源证据”判断,避免每个入口再次发明一套锁规则。
- 来源记录:创建时保存 PID、创建时间、映像、任务号、私有桌面、目标工程/库和父子关系;重启后按身份核对,不能仅凭 PID。
- 范围判定:区分同工程、同库共享依赖、明确其他库、未知。由谁拉起与是否占用本库分别保存。
- 观察项不自动变成阻止项。明确属于其他库的进程不要求退出;未知项展示不确定原因,继续取本库在途调用、目标文件/数据库、地址、必要原生读取等证据。证据不足不能猜测安全。
- 不能只把 `scope is not False` 改成 `scope is True`,也不能只改“所有行退出”条件;否则可能放过真实打开同库的外部会话,或仍被底层第二道门禁挡住。
- 目标文件独占打开只是证据之一,不单独保证原生接口、共享依赖和检查期间的状态均安全。后续写入前还需重新核对。
验收至少包括:其他软件开其他库且持续运行时,本库能正常完成操作;其他软件确实持有本库数据库时,本库拒绝相关写入;外部进程来源不明但目标文件无占用时,不能单凭进程名永久阻止;PID 被复用时不得操作新进程。
### P1:把单项失败与批次停止分开
现有一个 `safe_to_continue` 同时承载多种情况:当前项失败、当前工程占用、共享库写入未结束、释放证据不足。因此某个工程的问题容易扩大为整库不可用。
逐项保留业务结果,再明确能否继续及影响范围:仅当前工程、整个共享库、原生执行通道、用户主动停止。安全释放的失败项继续下一项;仅当前工程问题是否可绕过,需要以共享资源证据决定;共享写入未返回则继续保护。不要全局放开 false 或直接删历史记录。
验收要使用同一批次“坏工程 → 好工程”以及“共享库真实占用 → 后续写入不得开始”两个方向。现有真实多来源新增已通过前一方向的一种安全失败场景,不代表所有占用场景都通过。
### P1/P2:接通原生读写提示与非阻塞操作
普通校验、检查、恢复副本按操作目的决定是否允许读写授权,不复用只适用于修复后的隐式授权。识别精确提示后展示目标和选项,用户可继续、跳过、取消;等待用户决定时保持 UI 可用,并明确后续任务是否仍需等当前原生会话。检查流程不能因用户点击而悄悄变成自动修复。
队列、原生执行和关闭分别展示等待对象与阶段。取消排队立即生效;已进入原生写入时说明是否正在等待返回或支持原生取消。普通校验/管理当前在批次外层持有队列,评估能否在完整单项事务结束后让出通道,不在 Remove→Add 中间插入另一写任务。
### P2:结果和性能
- UI 使用“检测结果、操作结果、释放状态”分别表达,避免将“待用户确认”写成工程损坏,或将“上传成功”写成 READY。
- 修正释放数字归因,报告观察项不增加本次主动释放数量。
- 来源、版本、依赖等便宜的输入检查先做;只复查本次受影响工程和实际依赖。避免每个按钮都全局扫描并读取无关窗口。
- 原生 EDIF 单独诊断;保存失败输入和退出码,让独立 CBB 继续,不能降低身份校验来消除报错。
### P2:真实并行与异常操作回归
保留其他软件测试作为并行验收条件,覆盖:外部独立工程持续打开、外部共享同库、检查中排队再取消、停止后立即释放、刷新时连续点击、版本窗口开关、断网、源文件变化、主程序关闭与重启后的 PID 复用。分别核查目标变更、真实进程退出、权威状态和剩余任务,而不是只看按钮恢复可用或 Python 测试通过。
当前最有价值的改动是修 E01 的作用范围与证据链,而不是继续增加更多全局拒绝条件。最终验收仍要求实际完整校验与恢复到 READY;本次分类没有补齐这一缺口。
@@ -0,0 +1,39 @@
# 阻塞进程来源核查
> 本文保留当时的只读归属结论;后续代码修改及试验见 [占用范围验证](2026-11-12-scoped-release-validation.md)。
2026-11-12 13:44–13:46 进行了只读核查。结论:此前阻止整库释放的两个未知会话来自 `dxdesigner-part-replacement` 测试,不是本 CBB 程序拉起;其他软件并行测试暴露了本程序的归属和释放判定漏洞。本次没有修改业务代码或关闭进程。
| 历史进程 | 归属证据 | 结论 |
| --- | --- | --- |
| viewdraw.exe,PID 29832,父进程 5940 | 外部工具 lifecycle.jsonl 记录 worker_started PID 5940;其 private-desktop.json 记录 cad_pid 29832、创建时间 2026-11-12 03:17:21.099 UTC、桌面 dx-f2b2947f8ab144e19760e4599fda3249,均与 CBB 残留快照一致;窗口工程位于外部工具 outputs 目录 | 外部工具创建的 DxDesigner |
| cscript.exe,PID 8652,父进程 5940 | 命令行运行外部工具 QuickPartReplace.vbs;对应任务 project-checkpoint.json 的工程和 cad_pid 29832 与窗口匹配 | 同一外部测试批次的脚本 |
| ExpeditionPCB.exe,PID 21856 / 21248 | 命令行明确为 CBB 隔离库 1GPHY_8212 的 PCB;父子链 30552 → 21856 → 21248;CBB 验收释放记录确认两项均 RELEASED | 本程序的客户端,已正常退出 |
外部工程 CentralLibrary 指向 `F:/Sync Tool Skyworth/Work Maps/Skyworth_CBB_Lib/Mentor_lib_EE7.9/mentor_lib.lmc`。CBB 验收目标为 `F:/CbbAccept-20261112/library/native-add/fixture/mentor_lib.lmc`,二者不同。
13:44 的实时快照中,历史 PID 29832、8652 均已不存在,没有把新进程当成旧残留。当前另有真实父子链:DxPartReplace.exe 29436 → DxPartReplace.exe 16540 → cscript.exe 21364;父进程创建时间均早于子进程,映像和脚本均位于外部工具目录。此快照仅代表当时状态,PID 不能作为长期身份。
13:46 对本次隔离库的 LMC、icdb.dat、LayoutDB.lyt 共 12 个实际文件同时执行 GENERIC_READ、共享模式 0、OPEN_EXISTING 的只读独占打开,全部成功并关闭句柄;库内未发现 sAddress.adr。这证明当时这些目标文件没有阻止独占读的占用,不能倒推 11:28 的全部句柄状态。
## 逻辑漏洞所在
1. `library_lock._owner_matches_scope` 主要读取命令行中的 PRJ/PCB/LMC/数据库引用。裸 viewdraw.exe 和外部 QuickPartReplace.vbs 命令没有这些路径,均返回 None(UNKNOWN)。它没有在这里利用父进程批次记录、私有桌面或窗口工程身份进一步归属。
2. `residual_sessions.inspect_residual_sessions` 的 `scope is not False` 将这两项 UNKNOWN 加入当前库残留观察列表;`scope_confirmed=false` 正确阻止关闭它们。
3. `_release_residual_sessions` 又要求列表中全部行均为 RELEASED。这使“不能确认归属、不能操作的观察项”成为“当前库必须退出的对象”,结果一直 PARTIAL。
4. 即使绕过上一层,`library_lock._prove_library_released` 仍将范围为 UNKNOWN 的候选进程加入 owners,可能在目标文件独占打开之前直接拒绝证明。
以历史真实命令行回放当前归属函数,两项均得到 UNKNOWN,和真实残留列表一致。不是用户并行测试不合规,而是程序把“未知来源”升级成了“目标库占用”。
修复需要分别保存**进程来源**和**资源范围**:本程序创建的进程未必仍占目标;其他软件创建的进程也可能实际打开同一个库。因此不能只按进程名、父 PID 或软件目录粗暴排除外部进程,最终应结合创建时间绑定的身份、实际工程/库引用、本库在途调用、目标资源与地址探测决定是否阻止。外部归属只读展示,不自动结束;真实共享目标占用仍需保护。
## 证据
- 本机完整核查:`F:\CbbAccept-20261112\process-origin-audit.json`。
- 身份交叉核对、外部证据 SHA-256、分类回放及只读资源探测:`F:\CbbAccept-20261112\process-origin-confirmed.json`。
- 外部工具自身记录根目录:`F:\Sync Tool Skyworth\Work Maps\dxdesigner-part-replacement\outputs\frozen-random-final-20261112-r4`。
- 父 worker 记录:`data/batch-resources/28182d59cb9d4e0087fa312baf11d804/lifecycle.jsonl` 第 2 行。
- 原生进程创建身份:该批次 `generation-1/private-desktop.json`。
- 对应工程:`data/tasks/4f49b13e-3603-4578-b7f2-c9fe88bca864/quick-run/project-checkpoint.json`。
这里只完成核查和归因,没有声称跨软件阻塞已修复。
@@ -0,0 +1,61 @@
{
"schema_version": 1,
"time": "2026-11-12T16:00:50.172809+08:00",
"bundle": {
"module_count": 64,
"source_and_frozen_code_equal": true,
"source_sha256_checked": true,
"packaged_assets_equal": true,
"exe_icon_images_equal": true,
"executable_sha256": "85ec649c18fefcf50d8b4caf0a66005f108713e7d5f170d1aecc82e3c5fcfe33"
},
"tests": {
"passed": 1880,
"failures": 0,
"errors": 0,
"xml": "F:\\CbbAccept-20261112\\full-scoped-final10.xml"
},
"recovery": {
"path": "F:\\CbbAccept-20261112\\scoped10-data\\evidence\\backup-restore-5f9b134ab83c\\recovery-result.json",
"installed": true,
"source_status": "PASS",
"target_status": "PASS",
"library_flag": "GREEN",
"safe_to_continue": true,
"retained_work": "F:\\CbbAccept-20261112\\field-lib-recovery\\ReusableBlocksLP\\1GPHY_8212\\Work.before-restore-5f9b134ab83c"
},
"release": {
"path": "F:\\CbbAccept-20261112\\scoped10-data\\release-checks\\sessions-fc23a2a2024f\\result.json",
"status": "RELEASE_CONFIRMED"
},
"original_integrity": {
"time": "2026-11-12T16:00:19",
"results": [
{
"scope": "A",
"source": "F:\\Sync Tool Skyworth\\Work Maps\\Skyworth_CBB_Lib\\CBB\\1GPHY_RTL8211F",
"checked": 187,
"changes": []
},
{
"scope": "B",
"source": "F:\\Sync Tool Skyworth\\Work Maps\\Skyworth_CBB_Lib\\CBB\\1GPHY_RTL8211F_A",
"checked": 185,
"changes": []
},
{
"scope": "field-library-originals",
"source": "F:\\Sync Tool Skyworth\\Work Maps\\Skyworth_CBB_Lib\\Mentor_lib_EE7.9",
"checked": 26887,
"changes": []
}
],
"originals_unchanged": true
},
"interaction_log": "F:\\CbbAccept-20261112\\scoped10-accept.log",
"known_limits": [
"Native shared-symbol server sometimes cannot remove its own address file after STOP; not bypassed.",
"Actual field server-session-loss recovery and Windows 10 acceptance remain unverified.",
"Automatic ICDB Repair remains disabled. No merge, release or issue closure."
]
}
@@ -0,0 +1,52 @@
# 占用范围、单项队列及原生确认验证
本次基于 `42d0ceb`,沿用 `codex/runtime-lifecycle-safety`。当天较早的进程归属、误判分析和完整流程图是修改前快照;本记录描述后续实现及验收,不追溯改写先前失败。
## 修改
- 未确认归属的外部客户端只作观察,不要求其退出、不发送关闭,也不增加主动释放数量。释放仍检查本库在途调用、目标数据库地址和实际独占只读文件句柄;自身请求身份缺失、共享写入未返回时继续保护。
- 旧 NATIVE_CALL/CLOSING/UNCONFIRMED 日志结合进程创建身份核实;已退出或 PID 被复用不会仅因日志阶段被认定仍在写入,读取失败保留未确认。
- 单项失败后只对绑定任务取得新的释放证明;证明成功才允许后续项,原业务失败和原证据保留。校验和管理在完整单项事务结束后让出原生队列,不在移除与重新导入之间穿插其他任务。排队取消保留已完成项和汇总。
- 普通校验、上传后的校验、备份副本/目标校验接通精确 PCB 读写提示和历史版本选择。用户可以继续、跳过、取消;绑定本任务 PCB 的创建身份、启动链、工程和私有桌面,临近点击重新检查。ICDB 诊断检查不借此执行 Repair 或隐式取得写入授权。
- 实测新增修复:同名更新自动校验不再把自己当前的事务当成历史未释放事务。仅允许同线程、同 lease、同 PID、同目标及无待处理导出/检查点的嵌套调用。取消批次后不再把刷新排进已经取消的队列而丢失结果。
- 第二轮真实试验暴露导出器进程链误判:CSV 导出器 PID 16068 创建于 14:56:19,却收录了 12:57:45 已创建的 OneDrive 服务 PID 23804。运行时追踪改为排除原有进程、绑定原生进程句柄创建时间、拒绝早于父进程的子进程及 PID 复用后的新进程链。旧记录复核也排除出生时间证明不可能属于导出任务的条目;仍需原生范围及分析副本数据库的全套释放证明,未发送退出请求给 OneDrive。
- 失败释放复核包含在单项原生队列内部,完成后才让出通道,避免下一项开始时前一项又来争取管理互斥。新增两项回归先失败后通过,相关 46 项通过。
- 普通读写确认比较真实控件的句柄、ID、类和正文,允许 UIA 后续增加已识别的标题栏辅助节点、重排控件及省略按钮快捷键标记;替换真实按钮仍拒绝。实际快照显示 Win32 的“是(&Y)”变成 UIA 的“是(Y)”,进程及窗口/按钮句柄均未变化;不能据此认定工程或窗口被替换。来自恢复副本真实失败的回归先失败后通过,相关 52 项通过。
## 冻结包和真实试验
当前候选程序:`F:\CbbAccept-20261112\candidate-scoped10\dist\CbbRefreshVerify-Background\CbbRefreshVerify.exe`。
SHA-256:`85ec649c18fefcf50d8b4caf0a66005f108713e7d5f170d1aecc82e3c5fcfe33`。64 个冻结模块逐个与当前源码编译结果一致,资源及 PE 图标一致;检查记录 `candidate-scoped10/bundle-verification.json`。较早的 scoped5 为 `4cf682130923c4534d3193a8b967ffc83d0cc519e580f6739a4861daed4f36c3`,scoped7 为 `e37b2601bb3851e9170ab8d552800547004b1a5b9882211f1180693dde76957c`,scoped9 为 `a59488dcbad72bdd7159772aabdb33b6411dea972babec33e64412a3406f810f`;各次动作日志绑定实际运行包哈希,不能混为同一版本。
原生写操作仅在 `F:\CbbAccept-20261112` 隔离库及工具生成的 `C:\Users\ABS_Windows\.cbb-restore` 校验副本中进行,环境为 Windows 11 build 26200、Mentor EE7.9.5 及私有桌面。操作驱动使用真实程序按钮和后台窗口消息,没有前台鼠标抢占、强杀原生客户端或手删地址文件。
| 试验 | 事实与证据 |
| --- | --- |
| 外部脚本持续存在,目标真实句柄被占用 | `scoped3-accept.log`:持有 LMC 的 Windows 独占句柄时拒绝释放,错误 32;外部脚本仍存活 |
| 目标句柄关闭,外部脚本继续运行 | 同一日志:RELEASE_CONFIRMED,主动释放 0、授权 0;外部行为保持 OBSERVED,脚本最后自行退出 |
| 同名更新并自动校验 | `management-38fdf8365d834a13ba7dca67111861ff/checkpoint.json`:UPLOADED_VERIFIED、safe=true;真实选择继续打开和最后手动保存版本;校验 InSynch、Save/IsSaved/Close、PCB EXITED,IsVerifiedReuseBlock=1/READY。校验约 91.6 秒 |
| 重复更新发现地址残留 | `management-0cee6b12e93b45918caf18101c603dc5/checkpoint.json`:RECOVERY_REQUIRED;原生移除已发生,重新导入未开始,不能记为成功 |
| 地址残留的原生证据 | 共享符号库服务器 PID 17344 日志记录 Database closed、defragmentation completed、Could not remove server address file、S: STOP;之后没有该服务器进程。`address-native-probe/result.json`:原生目录可复读,地址仍在、端点不可达;未将不可达视作无占用证明 |
| 早期空白库试验 | 读写和手动版本选择成功,但原生 PartPkg 报缺 PartsDB 分区;不作为校验成功 |
| 早期自动校验试验 | `management-cb85cb2b564d4778912df7accf85c109` 上传完成,校验被自身事务锁拒绝;已补回归后由上述真实完整成功试验复核 |
| 导出器错误收录 OneDrive | `scoped6-data/management/management-498258fe1e1541e9a135ca4117cb7344/source-identity/csv-process.json`:CSV 日志已完成、分析副本无地址,但历史父 PID 关联扩大至外部进程;后来进程查询超时,本次无原生移除/新增,不计上传成功。`scoped6-active-handle-attribution.json` 为只读 Windows 句柄归属诊断;新增失败回归 `export-lineage-red.xml`、`export-history-red.xml`,修复后两组 73 项通过 |
| 旧误判记录解除及更新重试 | scoped7 真实点击释放:RELEASE_CONFIRMED、主动关闭 0;保留旧证据。随后 `scoped7-data/management/management-d4017aaae47041b08dae6445858a7419/checkpoint.json` 完成原生更新及工程身份复读,UPLOADED、safe=true,关闭了本批次自动校验 |
| 恢复确认窗口误判 | scoped7 的 `evidence/backup-restore-f52ee9adc188/recovery-result.json` 和 scoped9 的 `evidence/backup-restore-22512e81160b/recovery-result.json` 都在副本阶段失败,installed=false。先处理控件辅助节点后,第二次实际差分又明确了快捷键标记差异;未将两次失败记为通过 |
| 快捷键表示差异的原生定位 | `open-identity-real-diff.json` 捕获同一 PID/创建时间、HWND、真实按钮句柄下的 Win32/UIA 差异。修正后 `identity-debug/verify-f34d9f72d4aa/result.json` 实际 PASS、GREEN/READY=1、Save COMMITTED、Close CLOSED、PCB EXITED、资源 RELEASED。这是定位与复测,不能替代完整恢复按钮验收 |
| 立即停止后的残留 | scoped7 的 `evidence/icdb-check-73cdeda6d163/pcb-open/verify-bb3bdc393b0b/result.json`:CANCELLED、safe=false;本任务启动器 12408、PCB 344 在扫描时尚无可关闭窗口。未以队列取消成功冒充原生退出成功 |
| 残留后的再次释放 | 后续读取发现原生 Tip of the Day;在精确绑定的私有桌面正常关闭此帮助窗口后,PCB 完成打开。scoped9 实际“确认释放”正常关闭 3 项并 RELEASE_CONFIRMED,应用正常退出。`cleanup-scoped7-stop*/startup-close.json` 保留早期未确认记录;未强杀进程、未把帮助窗口关闭本身记成数据库释放 |
| 最终包验收 | 事实与证据 |
| --- | --- |
| 最终包完整恢复按钮 | scoped10 真实执行空来源校验、取消确认、重新确认、运行期间重复点击,随后完成副本校验、目标变更检查、保留旧 Work、安装、目标再次原生校验。`scoped10-data/evidence/backup-restore-5f9b134ab83c/recovery-result.json`:installed=true,source_validation 和 result 都为 PASS、GREEN/READY=1、safe=true,Save COMMITTED、Close CLOSED、PCB/助手 EXITED、资源 RELEASED |
| 最终状态及退出 | scoped10 原生状态刷新后可见 READY 1;READY 项检查及恢复入口禁用。最终释放为 RELEASE_CONFIRMED,主动关闭 0/允许 0,主程序正常退出 0;未修改旧失败记录 |
| 原始文件复核 | 16:00:19 对 A/B 来源及原始中心库共 27,259 个文件重新检查大小、SHA-256,无变化;`originals-rechecked.json`。先前失败校验副本归档到 F 盘以保留证据并腾出系统盘空间,映射见 `archived-validation-copies/map.json` |
最终源码全量测试 **1,880 passed**(1 条既有 pywinauto STA 警告),记录 `F:\CbbAccept-20261112\full-scoped-final10.xml`;compileall、diff-check 通过。冻结代码和图标一致性、完整恢复、释放及原始文件复核的机器摘要见同目录 [验证 JSON](2026-11-12-scoped-release-validation.json)。历史版本是按此前选择偏好使用最后手动保存版本,READY 不表示已经人工核对版本内容或无数据回退。
## 保留限制
自动 ICDB Repair 继续关闭。现场服务器会话失联的一致故障副本、Windows 10、跨机共享库掉线尚未验收;不会自动合并、发布或关闭工单。共享符号数据库地址若原生工具自身无法删除,不能通过本程序删除文件或仅凭无进程放行。此前 A/B 输入 EDIF 导出崩溃与空白依赖库有关与否仍需独立复现,不绕过工程身份校验。
立即停止时的晚到窗口仍需要正常处理:本次 Tip of the Day 是在精确绑定的私有桌面关闭后才由应用完成会话释放,不能将此试验写成自动退出无缺口。未知/损坏检查点、尚未返回的真实共享写入继续保留未确认状态。
@@ -0,0 +1,13 @@
# 占用范围、释放及原生确认实施计划
按用户已确认的误判复核方案执行,沿用隔离分支 codex/runtime-lifecycle-safety;原工作区和其他软件会话不改动。
1. 先以真实外部命令回放补充失败测试:未知外部观察项不接收关闭请求,目标独占资源证明成功后不阻止本库释放;真实本库进程、在途助手、数据库句柄或地址仍阻止。统一库证明与维护入口的进程候选判断,保留观测证据。
2. 修正释放结果:观察项与可操作目标分开,未允许且自然退出不计主动释放;对绑定身份已退出的旧 UNCONFIRMED 日志不再认定调用仍在执行。覆盖 PID 复用和读取失败。
3. 单项失败后,先尝试本库/本工程新鲜释放证明;证明完成才解除相应保留状态并继续,无法证明的共享占用仍停止相关写入。普通校验/管理在完整单项事务结束后让出队列,支持等待及取消。
4. 普通 PCB 打开接通精确读写提示的用户确认;复用现有异步选择模型,绑定 PID、工程、私有桌面、当前提示,取消/跳过不自动写入。自动 Repair 保持关闭;恢复副本也传递用户选择。识别未知提示不猜测点击。
5. 每项先红后绿;全量回归、编译、冻结代码/图标一致性;其他软件独立工程持续运行、真实目标句柄占用、停止后重试、提示确认/取消、真实校验与备份恢复。EDIF 崩溃单独保留原生失败证据,不跳过身份校验。尚未达到 READY 不宣称验收通过。
主要代码:library_lock.py、residual_sessions.py、session_record.py、verify_runner.py、management.py、ui/icdb_check_task.py、ui/management_dialog.py、ui/main_window.py、ui/residual_release_dialog.py、backup_recovery.py;原生确认按现有 pcb_restore_prompt 和 dialog_agent 模式实现。
验证记录写入 docs/releases,原始运行证据放 F 盘独立验收目录。开发与原生验收串行执行,所有原生操作局限隔离副本。
+4 -3
View File
@@ -142,7 +142,7 @@ def _align_library(project, pcb, library):
ensure_project_central_library(path, library)
def recover_from_backup(request, source, *, progress=None, verifier=None, idle_check=None):
def recover_from_backup(request, source, *, progress=None, verifier=None, idle_check=None, version_prompt=None):
"""Validate in copies before changing Work; preserve all recovery evidence."""
import pythoncom, win32con, win32event
from .network_path import absolute_preserving_drive
@@ -241,7 +241,8 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
preflight(validation)
emit('validate_source', '正在副本中打开备份工程并执行原生校验…')
release_confirmed = False
source_result = verifier(validation, progress=progress, flag_reader=read_library_flag_if_available)
choice_options = {'version_prompt': version_prompt} if version_prompt is not None else {}
source_result = verifier(validation, progress=progress, flag_reader=read_library_flag_if_available, **choice_options)
release_confirmed = source_result.safe_to_continue
record['source_validation'] = asdict(source_result)
if (source_result.status != 'PASS' or source_result.library_flag != 'GREEN'
@@ -275,7 +276,7 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
release_confirmed = False
final = verifier(replace(request, lmc_file=library, evidence_dir=root/'target-verify',
auto_repair=False, native_lm_verify=False, interactive_input=False),
progress=progress, flag_reader=read_library_flag_if_available)
progress=progress, flag_reader=read_library_flag_if_available, **choice_options)
release_confirmed = final.safe_to_continue
if final.status == 'PASS' and (final.library_flag != 'GREEN' or not final.safe_to_continue):
final = replace(final, status='FAIL', stderr='目标工程恢复后的 Ready 状态未确认。')
+8
View File
@@ -236,6 +236,14 @@ class DialogActionExecutor:
def perform(self, snapshot: WindowSnapshot, action: dict) -> ActionResult:
channels = tuple(action.get("channels", ()))
action_name = action.get("action")
if action_name == 'user_confirmed_pcb_open':
try:
from .pcb_open_consent import validate_action_window
if channels != ('win32_button_click',):
raise ValueError('PCB_OPEN_ACTION_CHANNEL_CHANGED')
validate_action_window(snapshot, action)
except Exception as error:
return ActionResult(error_code='DATABASE_RECOVERY_REQUIRED', detail=str(error))
if action_name == 'user_selected_pcb_version':
try:
from .pcb_restore_prompt import validate_action_window
+40 -2
View File
@@ -84,6 +84,19 @@ def has_retained_library(library):
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:
with _guard:
owner = _owners.get(LibraryLock(library).key)
marker = blocker_path(library)
record = checkpoint_record(marker)
if (owner and owner['thread'] == threading.get_ident() and owner['depth'] > 0
and not owner['retained'] and not marker.with_suffix('.pending').exists()
and record and record['lease_id'] == owner['lease_id']
and record['pid'] == os.getpid() and record['status'] == 'OPERATION_IN_PROGRESS'
and record.get('block_name') == owner.get('block_name')
and owner.get('block_name') in (None, block_name)
and 'export_analysis' not in record):
return None # Nested Verify belongs to this live transaction, not a past crash.
if not (required or has_blocker(library) or has_retained_library(library)):
return None
def notify(stage, **details):
@@ -362,6 +375,23 @@ def _owner_matches_scope(item, library, roots):
return False if candidates else None
def _owner_is_blocking(item, library, roots):
"""Unknown external clients need resource proof, not a global exit rule."""
scope = _owner_matches_scope(item, library, roots)
if scope is not None:
return scope
command = str(item.get('command') or '').casefold()
flags = ('--verify-worker', '--repair-worker', '--management-worker', '--native-backup-worker')
if any(flag in command for flag in flags):
return True # An unreadable in-flight request is not proof of another library.
from .failed_session import _command_args
try:
return any(Path(arg).name.casefold() in ('close_failed_block.vbs', 'save_verified_block.vbs')
for arg in _command_args(command)[1:])
except (OSError, ValueError):
return False
def _enter_maintenance(lease):
"""Transfer only a valid known lease, after project admission under lock."""
import win32con, win32event, win32file
@@ -466,14 +496,21 @@ def _prove_library_released(library, block_name=None, *, allow_unknown_checkpoin
shared_root = Path(library).resolve().parent/'SymbolLibs'
if allow_unknown_checkpoint and scope_root is not None:
raise LibraryBusy('未知检查点必须执行完整库释放证明。')
observed = []
def check_owners():
owners = []
observed.clear()
from .session_record import active_write_records
if active_write_records(library):
raise LibraryBusy('本库原生调用或助手尚未确认返回,请等待当前操作结束。')
for item in query_owners(names):
if item['pid'] == os.getpid():
continue
if not allow_unknown_checkpoint:
roots = (scope_root, shared_root) if scope_root is not None else (Path(library).parent,)
if _owner_matches_scope(item, library, roots) is False:
if not _owner_is_blocking(item, library, roots):
if _owner_matches_scope(item, library, roots) is None:
observed.append(item)
continue
automation = item['name'].casefold() in ('python.exe', 'pythonw.exe', 'cbbrefreshverify.exe')
command = item['command'].casefold()
@@ -513,7 +550,8 @@ def _prove_library_released(library, block_name=None, *, allow_unknown_checkpoin
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
stack.callback(handle.Close)
owners = check_owners()
yield {'native_owners': owners, 'addresses': addresses, 'export_copies': export_copies,
yield {'native_owners': owners, 'observed_owners': list(observed),
'addresses': addresses, 'export_copies': export_copies,
'unknown_checkpoint_recovery': allow_unknown_checkpoint,
'exclusive_files': [str(path) for path in native]}
finally:
+18 -4
View File
@@ -169,7 +169,7 @@ def _may_have_mutated(record):
or any(not isinstance(item, dict) or item.get('stage') not in prewrite for item in history))
def run_management(request, *, adapter=None, verifier=None, idle_check=None, progress=None, stop=None):
def run_management(request, *, adapter=None, verifier=None, idle_check=None, progress=None, stop=None, version_prompt=None):
from .verify_runner import VerifyRequest, run_verify
from .backup_recovery import _idle_check
import win32con, win32event
@@ -402,8 +402,10 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
# Adapter catalog cannot return until its exact native owner exits.
checkpoint('verify')
owner_safe = False
options = {'version_prompt': version_prompt} if version_prompt is not None else {}
verified = verifier(VerifyRequest(library, request.name, root/'verify',
mapped_drive=request.mapped_drive, mapped_remote_root=request.mapped_remote_root), progress=progress, stop=stop)
mapped_drive=request.mapped_drive, mapped_remote_root=request.mapped_remote_root),
progress=progress, stop=stop, **options)
owner_safe = verified.safe_to_continue
checkpoint('verified', verification=asdict(verified))
good = verified.status == 'PASS' and verified.library_flag == 'GREEN' and owner_safe
@@ -427,7 +429,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
uninitialize_com(initialized)
def run_management_batch(requests, *, stop=None, progress=None, **kwargs):
def run_management_batch(requests, *, stop=None, progress=None, item_executor=None, **kwargs):
results = []
retained_libraries = set()
for request in requests:
@@ -442,7 +444,19 @@ def run_management_batch(requests, *, stop=None, progress=None, **kwargs):
if progress:
progress({'stage': result.status, 'block': result.name, 'detail': result.detail})
continue
result = run_management(request, progress=progress, stop=stop, **kwargs)
def action():
result = run_management(request, progress=progress, stop=stop, **kwargs)
if not result.safe_to_continue:
from .operation_lifecycle import recheck_failed_release
result = recheck_failed_release(request.library, request.name, result)
return result
from .operation_queue import QueueCancelled
try:
result = item_executor(request, action) if item_executor is not None else action()
except QueueCancelled as error:
results.append(ManagementResult(request.operation, request.library, request.name, request.partition,
request.source, request.auto_verify, 'complete', 'CANCELLED', True, str(error)))
break
results.append(result)
if progress:
progress({'stage': result.status, 'block': result.name, 'detail': result.detail,
@@ -285,9 +285,54 @@ def _database_released(project_root):
return True
def _process_birth(value):
from datetime import datetime, timezone, timedelta
if not value:
return None
if isinstance(value, datetime):
return value.astimezone(timezone.utc)
if re.fullmatch(r'\d{14}\.\d{6}[+-]\d{3}', value):
zone = timezone(timedelta(minutes=int(value[21:])))
return datetime.strptime(value[:21], '%Y%m%d%H%M%S.%f').replace(tzinfo=zone).astimezone(timezone.utc)
try:
parsed = datetime.fromisoformat(value)
if parsed.tzinfo is not None:
return parsed.astimezone(timezone.utc)
except ValueError:
pass
return value
def _export_descendants(snapshot, tracked, existing):
"""A historical parent PID is not evidence of current parentage."""
from datetime import datetime
rows = {row['pid']: row for row in snapshot}
def matches(row):
birth = _process_birth(row.get('created'))
return tracked[row['pid']] is None or birth is None or tracked[row['pid']] == birth
changed = True
while changed:
changed = False
for row in snapshot:
if row['pid'] in tracked or row['parent'] not in tracked:
continue
birth = _process_birth(row.get('created'))
if (row['pid'], birth) in existing:
continue
parent = rows.get(row['parent'])
parent_birth = tracked[row['parent']]
if parent is not None and not matches(parent):
continue
if isinstance(birth, datetime) and isinstance(parent_birth, datetime) and birth < parent_birth:
continue
tracked[row['pid']] = birth
changed = True
return [row for row in snapshot if row['pid'] in tracked and matches(row)]
def _run_exports(project, root, mentor_home, timeout_seconds):
"""Observe exact exporter/descendant handles; never kill a database owner."""
import win32api, win32con, win32event, pywintypes
import win32api, win32con, win32event, win32process, pywintypes
root = Path(root)
try:
_write_json(root/'export-launch.json', {'started': False})
@@ -338,16 +383,17 @@ def _run_exports(project, root, mentor_home, timeout_seconds):
creationflags=subprocess.CREATE_NO_WINDOW)
record['native_started'] = True
record['pid'] = process.pid
descendants = {process.pid}
handle = getattr(process, '_handle', None)
birth = _process_birth(win32process.GetProcessTimes(handle)['CreationTime']) if handle is not None else None
descendants = {process.pid: birth}
existing = {(p['pid'], _process_birth(p.get('created'))) for p in before}
if birth is not None:
record['root_created'] = birth.isoformat()
_write_json(root/(kind+'-process.json'), record)
while time.monotonic() < deadline:
snapshot = _process_snapshot()
changed = True
while changed:
previous = len(descendants)
descendants.update(p['pid'] for p in snapshot if p['parent'] in descendants)
changed = len(descendants) != previous
owners = [p for p in snapshot if p['pid'] in descendants or (
owned = {p['pid'] for p in _export_descendants(snapshot, descendants, existing)}
owners = [p for p in snapshot if p['pid'] in owned or (
p['name'].casefold() in _OWNER_NAMES and _native_scope_match(
p.get('command', ''), roots=(project.parent,)) is True)]
for owner in owners:
@@ -359,10 +405,10 @@ def _run_exports(project, root, mentor_home, timeout_seconds):
# owners until a fresh snapshot proves it absent.
record.setdefault('process_observation_errors', {})[str(owner['pid'])] = {
'winerror': error.winerror, 'detail': str(error)}
record['observed_pids'] = sorted(descendants | handles.keys())
identities.update({owner['pid']:
{key: owner.get(key, '') for key in ('pid', 'created', 'executable')}
for owner in owners})
record['observed_pids'] = sorted(descendants.keys() | handles.keys())
for owner in owners:
identities.setdefault(owner['pid'],
{key: owner.get(key, '') for key in ('pid', 'created', 'executable')})
record['process_identities'] = list(identities.values())
if (process.poll() is not None and not owners
and all(win32event.WaitForSingleObject(h, 0) == win32con.WAIT_OBJECT_0 for h in handles.values())):
+28 -2
View File
@@ -7,6 +7,19 @@ from uuid import uuid4
from .management import _write_json
def _preexisting_export_pids(record):
from datetime import datetime
from .native_engineering_identity import _process_birth
identities = record.get('process_identities', [])
root = next((p for p in identities if p.get('pid') == record.get('pid')), {})
birth = _process_birth(record.get('root_created') or root.get('created'))
if not isinstance(birth, datetime):
return set()
return {p['pid'] for p in identities if p.get('pid') != record.get('pid')
and isinstance(_process_birth(p.get('created')), datetime)
and _process_birth(p['created']) < birth}
def assert_retained_exports_idle(library=None):
import win32con, win32event
from .native_engineering_identity import _retained_exports
@@ -17,8 +30,18 @@ def assert_retained_exports_idle(library=None):
if (library is not None and scope.get('library')
and Path(scope['library']).resolve() != Path(library).resolve()):
continue
if process.poll() is None or any(win32event.WaitForSingleObject(handle, 0) != win32con.WAIT_OBJECT_0
for handle in handles.values()):
excluded = set()
if scope.get('analysis_root') and getattr(process, 'pid', None):
try:
for path in Path(scope['analysis_root']).glob('*-process.json'):
record = json.loads(path.read_text('utf-8'))
if record.get('pid') == process.pid:
excluded.update(_preexisting_export_pids(record))
except (OSError, ValueError, KeyError, TypeError):
excluded.clear()
if process.poll() is None or any(pid not in excluded
and win32event.WaitForSingleObject(handle, 0) != win32con.WAIT_OBJECT_0
for pid, handle in handles.items()):
raise LibraryBusy('Native identity exporter or descendant has not released.')
@@ -119,7 +142,10 @@ def prove_export_copies_released(library, *, allow_unknown_checkpoint=False, uns
if any(not isinstance(pid, int) or pid <= 0 for pid in pids):
raise ValueError('Invalid export process identity.')
identities = {p['pid']: p for p in process.get('process_identities', [])}
excluded = _preexisting_export_pids(process)
def original_alive(pid):
if pid in excluded:
return False
recorded = identities.get(pid, {})
current = next((p for p in snapshot if p['pid'] == pid), None)
if recorded.get('created') and current and current.get('created'):
@@ -2,6 +2,52 @@
from collections.abc import Sequence
def recheck_failed_release(library, block, result):
"""Refresh resource facts after a late exit; keep the original business failure."""
if result.safe_to_continue or not result.evidence_path:
return result
from pathlib import Path
from dataclasses import replace
import json
from .session_record import read_session_record, inspect_session_record
from .library_lock import release_retained_library
evidence = Path(result.evidence_path)
try:
session = Path(getattr(result, 'session_record_path', None) or evidence.with_name('session.json'))
if session.is_file():
record = read_session_record(session, evidence_root=evidence.parent)
if record.get('block') != block or Path(record.get('library', '')).resolve() != Path(library).resolve():
return result
if inspect_session_record(session, evidence_root=evidence.parent).get('status') == 'ACTIVE':
return result
else:
record = json.loads(evidence.read_text('utf-8'))
if (record.get('name') != block or record.get('operation') not in ('add', 'update', 'remove')
or Path(record.get('library', '')).resolve() != Path(library).resolve()):
return result
bound = []
for phase in ('before', 'remove', 'after-remove', 'add', 'after-add'):
candidate = evidence.parent/phase/'session.json'
if candidate.is_file():
owned = read_session_record(candidate, evidence_root=evidence.parent)
if Path(owned.get('library', '')).resolve() != Path(library).resolve():
return result
if inspect_session_record(candidate, evidence_root=evidence.parent).get('status') == 'ACTIVE':
return result
bound.append(candidate)
if not bound:
return result # A generic timeout without a bound owner is not an exit fact.
proof = release_retained_library(library, evidence.parent/'late-release', block_name=block)
if proof.get('status') != 'RELEASE_CONFIRMED' or Path(proof.get('library', '')).resolve() != Path(library).resolve():
return result
evidence.with_name('late-release-result.json').write_text(json.dumps(dict(
business_status=result.status, safe_to_continue=True, release_proof=proof),
ensure_ascii=False, default=str, indent=2), 'utf-8')
return replace(result, safe_to_continue=True, release_proof=proof)
except Exception:
return result
def classify_save_state(markers: Sequence[str], *, helper_exited: bool | None,
native_released: bool | None, forced: bool = False) -> dict:
names = {line.strip().split('|', 1)[0] for line in markers}
+154
View File
@@ -0,0 +1,154 @@
"""Explicit user answers to the owned PCB's exact read/write question."""
from contextlib import contextmanager, ExitStack
from pathlib import Path
from threading import Lock
import time
from .post_repair_consent import exact_prompt
def _prompt_identity(snapshot):
# UIA adds chrome/reorders controls and omits Win32 caption accelerator marks.
return tuple(sorted((c.handle, c.control_id, c.class_name,
c.name.replace('&', '') if c.class_name == 'Button' else c.name)
for c in snapshot.controls if c.handle and c.handle != snapshot.hwnd))
class OpenChoice:
def __init__(self, block, library):
self.block, self.library = block, library
self.decision = None
self._lock = Lock()
def choose(self, decision):
if decision not in ('continue', 'skip', 'cancel'):
raise ValueError('无效的打开工程选择')
with self._lock:
if self.decision is None:
self.decision = decision
def validate_owner(job, target_pid, launcher_pid, worker_pid):
from .owner_probe import query_process_snapshot
from .session_record import process_identity
from .mentor_adapter import is_reusable_circuit_pcb
rows = {r['pid']: r for r in query_process_snapshot()}
target, launcher = rows.get(target_pid), rows.get(launcher_pid)
if (not target or not launcher or target['parent'] != launcher_pid or launcher['parent'] != worker_pid
or not str(job.get('desktop', '')).startswith('CbbVerify_')
or job.get('interactive_input') or job.get('native_lm_verify') or job.get('diagnostic_only')):
raise ValueError('PCB_OPEN_OWNER_UNCONFIRMED')
for row in (target, launcher):
if not is_reusable_circuit_pcb(row['executable'], row['command'], job['pcb']):
raise ValueError('PCB_OPEN_TARGET_CHANGED')
return {'target': process_identity(target_pid), 'launcher': process_identity(launcher_pid)}
@contextmanager
def resource_guard(job, allowed_pids):
import win32con, win32file
from .icdb_ownership import database_directories, unreleased_addresses
from .owner_probe import query_process_snapshot
from .library_lock import _owner_is_blocking
from .verify_runner import preflight, VerifyRequest
library = Path(job['lmc_file'])
project, pcb = preflight(VerifyRequest(library, job['block_name'], Path(job['root'])))
if project.resolve() != Path(job['project']).resolve() or pcb.resolve() != Path(job['pcb']).resolve():
raise ValueError('PCB_OPEN_PROJECT_CHANGED')
roots = (project.parent, library.parent/'SymbolLibs')
def check():
if unreleased_addresses(library, project, pcb):
raise ValueError('目标仍有数据库地址记录,暂不能确认读写打开。')
for row in query_process_snapshot():
if row['pid'] not in allowed_pids and _owner_is_blocking(row, library, roots):
raise ValueError(f'目标还有其他会话,PID={row["pid"]};未确认读写打开。')
check()
paths = [library, pcb.parent/'Layout/LayoutDB.lyt',
*(d/'icdb.dat' for d in database_directories(library, project, pcb) if (d/'icdb.dat').is_file())]
with ExitStack() as stack:
for path in dict.fromkeys(paths):
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
stack.callback(handle.Close)
check()
yield
class OpenController:
def __init__(self, job):
self.job = job
self.choice = None
self.original = self.owner = None
self.sent = False
self.sent_at = 0.0
def handle(self, snapshot, snapshots, *, target_pid, launcher_pid, worker_pid, show, perform):
from .dialog_supervisor import DialogPollResult
from .management import _write_json
try:
if not exact_prompt(snapshot) or snapshot.pid != target_pid or len(snapshots) != 1:
raise ValueError('PCB_OPEN_PROMPT_CHANGED')
owner = validate_owner(self.job, target_pid, launcher_pid, worker_pid)
if self.choice is None:
self.owner, self.original = owner, snapshot
self.choice = OpenChoice(self.job['block_name'], self.job['lmc_file'])
show(self.choice)
if (owner != self.owner or snapshot.hwnd != self.original.hwnd
or _prompt_identity(snapshot) != _prompt_identity(self.original)):
raise ValueError('PCB_OPEN_IDENTITY_CHANGED')
if self.sent:
if time.monotonic()-self.sent_at < 2:
return DialogPollResult(observed_snapshots=tuple(snapshots))
raise ValueError('PCB_OPEN_ANSWER_NOT_COMPLETED')
if self.choice.decision is None:
return DialogPollResult(activity=True, observed_snapshots=tuple(snapshots))
control = 6 if self.choice.decision == 'continue' else 7
action = {'action': 'user_confirmed_pcb_open', 'channels': ['win32_button_click'],
'target': {'control_id': control}, 'desktop': self.job['desktop'],
'pid': target_pid, 'owner': owner, 'choice': self.choice.decision}
def send():
self.sent, self.sent_at = True, time.monotonic()
_write_json(Path(self.job['root'])/'pcb-open-user-choice.json', dict(
choice=self.choice.decision, project=self.job['project'], pcb=self.job['pcb'],
library=self.job['lmc_file'], owner=owner, snapshot=snapshot.to_record()))
return perform(snapshot, action, snapshot.phase)
if control == 6:
allowed = {target_pid, launcher_pid, worker_pid, self.job.get('supervisor_pid')}
with resource_guard(self.job, allowed):
result = send()
else:
result = send()
error = result.error_code
if not error and result.accepted_controls != (control,):
error = 'PCB_OPEN_ANSWER_FAILED'
if not error and control == 7:
error = 'PCB_OPEN_SKIPPED' if self.choice.decision == 'skip' else 'USER_CANCELLED'
return DialogPollResult(activity=True, action_sent=True, snapshot=snapshot,
error_code=error, detail=result.detail or ('用户跳过本项。' if control == 7 else ''),
accepted_controls=result.accepted_controls, channel=result.channel,
action=action['action'], observed_snapshots=tuple(snapshots))
except Exception as error:
return DialogPollResult(error_code='DATABASE_RECOVERY_REQUIRED', detail=str(error),
snapshot=snapshot, observed_snapshots=tuple(snapshots))
def validate_action_window(snapshot, action):
from dataclasses import replace
import win32gui, win32process
from .native_repair_ui import _current_desktop_name
from .dialog_models import ControlSnapshot
from .session_record import process_identity
if (not exact_prompt(snapshot) or action.get('target', {}).get('control_id') not in (6, 7)
or snapshot.pid != action.get('pid') or _current_desktop_name() != action.get('desktop')
or not str(action.get('desktop', '')).startswith('CbbVerify_')
or win32process.GetWindowThreadProcessId(snapshot.hwnd)[1] != snapshot.pid
or process_identity(snapshot.pid) != action.get('owner', {}).get('target')):
raise ValueError('PCB_OPEN_LIVE_OWNER_CHANGED')
children = []
win32gui.EnumChildWindows(snapshot.hwnd, lambda h, _: children.append(int(h)), None)
controls = tuple(ControlSnapshot(h, win32gui.GetDlgCtrlID(h) & 0xffff,
win32gui.GetClassName(h), win32gui.GetWindowText(h), enabled=bool(win32gui.IsWindowEnabled(h))) for h in children)
if not exact_prompt(replace(snapshot, controls=controls)) or any(
c.handle != next(x.handle for x in snapshot.controls if x.control_id == c.control_id)
for c in controls if c.class_name == 'Button'):
raise ValueError('PCB_OPEN_LIVE_PROMPT_CHANGED')
+23 -9
View File
@@ -37,10 +37,11 @@ def _choice(snapshot):
class RestoreController:
def __init__(self, job):
def __init__(self, job, *, user_open=False):
from .post_repair_consent import _validate_grant
self.job = job
self.grant = _validate_grant(job)
self.grant = None if user_open else _validate_grant(job)
self.owner = None
self.prompt = None
self.original = None
self.selection_sent = self.confirm_sent = self.failed = False
@@ -60,13 +61,20 @@ class RestoreController:
or snapshot.pid != self.original.pid
or _candidate_key(choice['candidates']) != _candidate_key(self.prompt.candidates)):
raise ValueError('PCB_VERSION_CANDIDATES_CHANGED')
pre = json.loads((Path(self.job['root'])/'post-repair-prelaunch.json').read_text(encoding='utf-8'))
if (pre.get('nonce') != self.grant['nonce'] or pre.get('desktop') != self.job['desktop']
or pre.get('worker_pid') != worker_pid or pre.get('supervisor_pid') != self.job['supervisor_pid']
or pre.get('addresses') != []
or not all(consent._same(pre[key], self.grant[key]) for key in ('project', 'pcb', 'library'))):
raise ValueError('PCB_VERSION_PRELAUNCH_PROOF_INVALID')
consent._validate_current_processes(self.job, pre, target_pid, launcher_pid, worker_pid, companion_pids)
if self.grant is None:
from .pcb_open_consent import validate_owner
owner = validate_owner(self.job, target_pid, launcher_pid, worker_pid)
if self.owner is not None and owner != self.owner:
raise ValueError('PCB_VERSION_OWNER_CHANGED')
self.owner = owner
else:
pre = json.loads((Path(self.job['root'])/'post-repair-prelaunch.json').read_text(encoding='utf-8'))
if (pre.get('nonce') != self.grant['nonce'] or pre.get('desktop') != self.job['desktop']
or pre.get('worker_pid') != worker_pid or pre.get('supervisor_pid') != self.job['supervisor_pid']
or pre.get('addresses') != []
or not all(consent._same(pre[key], self.grant[key]) for key in ('project', 'pcb', 'library'))):
raise ValueError('PCB_VERSION_PRELAUNCH_PROOF_INVALID')
consent._validate_current_processes(self.job, pre, target_pid, launcher_pid, worker_pid, companion_pids)
if self.prompt is None:
self.original = snapshot
self.prompt = RestoreChoice(self.job['block_name'], self.job['lmc_file'], choice['candidates'])
@@ -91,6 +99,8 @@ class RestoreController:
action = {'action': 'user_selected_pcb_version', 'channels': ['win32_button_click'],
'target': {'control_id': control}, 'desktop': self.job['desktop'], 'pid': target_pid,
'choice': selected['kind'], 'candidates': list(self.prompt.candidates)}
if self.owner is not None:
action['owner'] = self.owner
self.selection_sent = True
self.confirm_sent = confirming
self.sent_at = time.monotonic()
@@ -119,6 +129,10 @@ def validate_action_window(snapshot, action):
import win32gui, win32process
from .native_repair_ui import _current_desktop_name
from .dialog_models import ControlSnapshot
if action.get('owner') is not None:
from .session_record import process_identity
if process_identity(snapshot.pid) != action['owner']['target']:
raise ValueError('PCB_VERSION_LIVE_PROCESS_CHANGED')
if (not str(action.get('desktop', '')).startswith('CbbVerify_')
or _current_desktop_name() != action.get('desktop') or snapshot.pid != action.get('pid')
or win32process.GetWindowThreadProcessId(snapshot.hwnd)[1] != snapshot.pid
+12 -2
View File
@@ -447,7 +447,7 @@ def inspect_residual_sessions(library, *, block_names=()):
try:
item.update(_process_identity(row))
target, detail = close_target(row['name'], windows.get(row['pid'], []), incomplete=error) if row['scope_confirmed'] else (
None, '归属未确认,请在原生窗口确认工程并关闭后重新检查')
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}')
@@ -616,6 +616,11 @@ def _session_evidence(row):
return value
def release_targets_complete(rows):
return all(row.get('release_status') == 'RELEASED' or (
row.get('scope_confirmed') is False and row.get('release_status') == 'OBSERVED') for row in rows)
def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, cancel_native=False):
library = Path(plan['library']).resolve()
root = Path(evidence_dir).resolve()/('sessions-'+uuid4().hex[:12])
@@ -666,6 +671,11 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca
outcome = {'release_status': 'RELEASED', 'detail': '已退出'}
if stop is not None and stop.is_set():
outcome = {'release_status': 'CANCELLED', 'detail': '已停止释放'}
elif row.get('scope_confirmed') is False:
from .library_lock import _owner_is_blocking
outcome = ({'release_status': 'WAITING', 'detail': '当前归属已变化,请重新检查确认;未关闭'}
if current is not None and _owner_is_blocking(current, library, roots) else
{'release_status': 'OBSERVED', 'detail': '仅观察,未关闭;由目标资源检查确认是否影响当前库'})
elif current is not None:
from .library_lock import _owner_matches_scope
scoped = _owner_matches_scope(current, library, roots) is True
@@ -702,7 +712,7 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca
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()):
if release_targets_complete(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'
+6 -5
View File
@@ -449,13 +449,13 @@ def active_write_records(library):
for path in paths:
try:
session, state, processes = _session(path, path.parent)
if state.get('phase') in ('NATIVE_CALL', 'CLOSING', 'UNCONFIRMED'):
result.append({**session, 'phase': state['phase']})
else:
if processes:
from .residual_sessions import _process_handle, _handle_identity, _force_ownership
import win32con, win32event
for identity in processes:
if identity.get('role') not in ('worker', 'helper'):
if identity.get('role') == 'supervisor' or (
state.get('phase') not in ('NATIVE_CALL', 'CLOSING', 'UNCONFIRMED')
and identity.get('role') not in ('worker', 'helper')):
continue
try:
with _process_handle(identity['pid']) as handle:
@@ -465,7 +465,8 @@ def active_write_records(library):
if any(actual[k] != identity[k] for k in IDENTITY_KEYS if k != 'pid'):
continue
# A retained caller may be inside Close after the last journal write failed.
result.append({**session, 'phase': 'UNCONFIRMED'})
result.append({**session, 'phase': state['phase'] if state.get('phase') in (
'NATIVE_CALL', 'CLOSING', 'UNCONFIRMED') else 'UNCONFIRMED'})
break
except Exception as error:
if getattr(error, 'winerror', None) != 87:
@@ -12,6 +12,7 @@ from .backup_notice import MANUAL_BACKUP_NOTICE
class RecoverySignals(QObject):
progress = Signal(object)
choice = Signal(object)
class BackupRecoveryDialog(QDialog):
@@ -31,6 +32,8 @@ class BackupRecoveryDialog(QDialog):
self.pool.setMaxThreadCount(1)
self.signals = RecoverySignals(self)
self.signals.progress.connect(self._progress)
if parent is not None and hasattr(parent, '_show_version_choice'):
self.signals.choice.connect(parent._show_version_choice)
self.block_combo = QComboBox()
self.block_combo.addItems(list(names))
self.source_edit = QLineEdit()
@@ -96,7 +99,8 @@ class BackupRecoveryDialog(QDialog):
self.status_label.setText('正在准备恢复…')
self.started.emit(name)
def execute():
action = lambda: recoverer(request, source, progress=self.signals.progress.emit)
options = {'version_prompt': self.signals.choice.emit} if self.recoverer is None else {}
action = lambda: recoverer(request, source, progress=self.signals.progress.emit, **options)
if self.native_queue is None: return action()
from ..operation_queue import QueueCancelled
def restore():
+5 -1
View File
@@ -73,7 +73,11 @@ class IcdbCheckTask(QObject):
if request.block_name in self.invalidated:
return VerifyResult('SKIPPED', stderr='目标已有后续管理操作,请重新检查。')
self.event.emit({'stage': 'icdb_check_start', 'block': request.block_name})
return self.verifier(request)
result = self.verifier(request)
if not result.safe_to_continue:
from ..operation_lifecycle import recheck_failed_release
result = recheck_failed_release(request.lmc_file, request.block_name, result)
return result
return self.queue.run(execute, stop=self.stop,
wait_state=lambda: (self.paused, library_wait_reason(request.lmc_file)),
ready=lambda: not self.paused and library_available(request.lmc_file),
+16 -7
View File
@@ -832,10 +832,10 @@ class MainWindow(QWidget):
path = QFileDialog.getOpenFileName(self, '选择中心库', '', 'LMC (*.lmc)')[0]
if path: self.lmc_edit.setText(path); self.load_library()
def _start(self, action, callback):
def _start(self, action, callback, *, queued=True):
self.stop.clear()
self.busy = True; self._update()
self.worker = ServiceWorker(self._queued_action(action))
self.worker = ServiceWorker(self._queued_action(action) if queued else action)
self.worker.signals.succeeded.connect(callback)
self.worker.signals.failed.connect(self._failed)
self.worker.signals.finished.connect(self._finished)
@@ -1370,6 +1370,7 @@ class MainWindow(QWidget):
self.signals.event.emit({'block': req.block_name, 'stage': 'icdb_check_start'})
return verify(req)
results = run_batch(requests, verifier=verifier, stop=self.stop,
item_executor=lambda req, action: self._queued_action(action)(),
progress=lambda name, result: self.signals.event.emit({'block': name, 'stage': result.status,
'error_category': result.error_category, 'evidence': str(result.evidence_path or ''),
'detail': result.stderr or result.stdout}))
@@ -1383,9 +1384,9 @@ class MainWindow(QWidget):
self.signals.event.emit({'stage': 'report_failed', 'detail': str(error)})
affected = [req.block_name for req, result in zip(requests, results) if result.status != 'SKIPPED']
safe = all(result.safe_to_continue for result in results)
refresh = self._read_affected_records(affected) if safe else None
refresh = self._queued_action(lambda: self._read_affected_records(affected))() if safe and not self.stop.is_set() else None
return results, report, affected, refresh
self._start(action, self._batch_done)
self._start(action, self._batch_done, queued=False)
def _read_affected_records(self, names):
"""Worker-only read; never derive library state from action outcomes."""
@@ -1655,9 +1656,17 @@ class MainWindow(QWidget):
if not self.busy or self.stop.is_set():
choice.choose('cancel')
return
self.version_dialog = PcbRestoreDialog(choice, self)
self.status_label.setText(f'{choice.block}:等待选择 PCB 恢复版本。')
self.icdb_phase.setText(f'{choice.block} · 等待选择 PCB 恢复版本')
from ..pcb_open_consent import OpenChoice
from .pcb_open_dialog import PcbOpenDialog
parent = self
backup = getattr(self, 'backup_dialog', None)
if backup is not None and backup.isVisible(): parent = backup
management = getattr(self, 'management_dialog', None)
if management is not None and management.isVisible(): parent = management
self.version_dialog = (PcbOpenDialog if isinstance(choice, OpenChoice) else PcbRestoreDialog)(choice, parent)
detail = '等待读写打开确认' if isinstance(choice, OpenChoice) else '等待选择 PCB 恢复版本'
self.status_label.setText(f'{choice.block}:{detail}。')
self.icdb_phase.setText(f'{choice.block} · {detail}')
self.version_dialog.show()
def request_stop(self):
@@ -33,6 +33,7 @@ STAGE_LABELS = {
class ManagementSignals(QObject):
progress = Signal(object)
choice = Signal(object)
class ManagementDialog(QDialog):
@@ -60,6 +61,8 @@ class ManagementDialog(QDialog):
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1)
self.signals = ManagementSignals(self)
self.signals.progress.connect(self._progress)
if parent is not None and hasattr(parent, '_show_version_choice'):
self.signals.choice.connect(parent._show_version_choice)
self.setWindowTitle({'add': '新增 CBB', 'update': '同名更新 CBB', 'remove': '移除 CBB'}[self.operation])
self.resize(850, 450)
self.table = QTableWidget(0, 4)
@@ -178,6 +181,17 @@ class ManagementDialog(QDialog):
from ..operation_queue import QueueCancelled
from ..session_record import library_available, library_wait_reason
try:
if self.runner is run_management_batch:
def item(request, action):
return self.native_queue.run(action, stop=self.stop,
ready=lambda: library_available(request.library),
wait_state=lambda: library_wait_reason(request.library),
waiting=lambda: self.signals.progress.emit({'stage': 'waiting_native_slot',
'retained': not library_available(request.library),
'detail': library_wait_reason(request.library) or '已排队,等待当前原生操作结束'}))
return self.runner(requests, adapter=self.adapter, stop=self.stop,
progress=self.signals.progress.emit, item_executor=item,
version_prompt=self.signals.choice.emit)
return self.native_queue.run(action, stop=self.stop, waiting=lambda: self.signals.progress.emit(
{'stage': 'waiting_native_slot',
'retained': not library_available(self.template.library),
@@ -0,0 +1,21 @@
from PySide6.QtWidgets import QMessageBox
class PcbOpenDialog(QMessageBox):
def __init__(self, choice, parent=None):
super().__init__(parent)
self.choice = choice
self.setWindowTitle('确认打开 PCB 工程')
self.setIcon(QMessageBox.Question)
self.setText(f'CBB:{choice.block}\n中心库:{choice.library}\n\n'
'PCB 提示上次可能未正常关闭,或工程仍被其他用户打开。\n'
'请确认没有其他用户打开此工程,再选择继续以读写权限打开。')
self.continue_button = self.addButton('确认无人使用,继续打开', QMessageBox.ActionRole)
self.skip_button = self.addButton('跳过本项', QMessageBox.ActionRole)
self.cancel_button = self.addButton('取消本批次', QMessageBox.RejectRole)
self.setDefaultButton(self.cancel_button)
self.setEscapeButton(self.cancel_button)
self.setModal(True)
self.buttonClicked.connect(lambda b: choice.choose('continue' if b is self.continue_button else
'skip' if b is self.skip_button else 'cancel'))
self.finished.connect(lambda _: choice.choose('cancel'))
@@ -7,7 +7,7 @@ from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushB
QTableWidget, QTableWidgetItem, QHeaderView, QMessageBox)
from .workers import ServiceWorker
from ..residual_sessions import force_block_reason
from ..residual_sessions import force_block_reason, release_targets_complete
class ResidualReleaseDialog(QDialog):
@@ -95,6 +95,7 @@ class ResidualReleaseDialog(QDialog):
allowed = session.get('consent_allowed')
permission = '允许' if allowed is True else '未允许' if allowed is False else '待确认'
outcome = {'RELEASED': '已释放', 'WAITING': '未释放', 'IDENTITY_CHANGED': '身份已变化',
'OBSERVED': '仅观察,未关闭',
'CANCELLED': '已停止', 'REQUESTING': '执行中', 'NOT_STARTED': '尚未执行'}.get(
session.get('release_status'), '待执行')
for column, value in enumerate((session.get('project', ''), session['name'],
@@ -162,7 +163,7 @@ class ResidualReleaseDialog(QDialog):
# 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'])):
or not release_targets_complete(result['sessions'])):
return False
self.plan = None
self.runtime_label.clear()
@@ -174,7 +175,7 @@ class ResidualReleaseDialog(QDialog):
proof = result.get('proof', {})
if (self.release_finalizer is not None and proof.get('status') == 'RELEASE_CONFIRMED'
and Path(proof.get('library', '')).absolute() == self.library.absolute()
and all(row.get('release_status') == 'RELEASED' for row in result['sessions'])):
and release_targets_complete(result['sessions'])):
self.release_finalizer(proof)
return {**result, 'proof': {**proof, 'mapping_cleanup_complete': True}}
return result
@@ -203,7 +204,7 @@ class ResidualReleaseDialog(QDialog):
self.library = Path(plan['library'])
self.plan = plan
self._rows(plan['sessions'])
text = ('确认后逐项正常关闭下列会话;有未保存更改时,可选择保存或保留。'
text = ('确认后正常关闭已确认属于当前库的会话,并复查库占用;其他会话仅作观察。'
if plan['sessions'] else '未发现活跃会话。')
records = plan.get('previous_records', [])
if records:
@@ -248,7 +249,8 @@ class ResidualReleaseDialog(QDialog):
def done(result):
self.plan = {**plan, 'sessions': result['sessions']}
self._rows(result['sessions'])
count = sum(row['release_status'] == 'RELEASED' for row in result['sessions'])
count = sum(row['release_status'] == 'RELEASED' and row.get('scope_confirmed') is not False
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 ''))
+27 -6
View File
@@ -940,6 +940,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
last_activity_key = None
phase = DialogPhase.PCB_STARTING
restore_controller = None
open_controller = None
dialog_agent = None
latest_snapshots = ()
if dialog_supervisor_factory is None:
@@ -1038,6 +1039,17 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
dialog_result = dialog_supervisor.poll()
else:
dialog_result = dialog_supervisor.poll()
if (version_prompt is not None and consent is None and dialog_agent is not None
and not request.diagnostic_only and not request.native_lm_verify
and dialog_result.error_code == 'DATABASE_RECOVERY_REQUIRED'
and dialog_result.snapshot is not None):
from .pcb_open_consent import OpenController, exact_prompt
if exact_prompt(dialog_result.snapshot):
if open_controller is None:
open_controller = OpenController(job)
dialog_result = open_controller.handle(dialog_result.snapshot, dialog_result.observed_snapshots,
target_pid=target_pid, launcher_pid=launcher_pid, worker_pid=process.pid,
show=version_prompt, perform=dialog_supervisor.backend.perform)
if (consent is not None and dialog_agent is not None
and dialog_result.error_code == 'DATABASE_RECOVERY_REQUIRED'
and dialog_result.snapshot is not None and exact_prompt(dialog_result.snapshot)):
@@ -1050,11 +1062,11 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
from .dialog_rules import archive_version_choice
choice_path = archive_version_choice(dialog_result.snapshot, root)
dialog_result = replace(dialog_result, detail=dialog_result.detail + f'\n版本候选与原生窗口证据:{choice_path}')
if (version_prompt is not None and consent is not None and dialog_agent is not None
if (version_prompt is not None and not request.diagnostic_only and dialog_agent is not None
and dialog_result.snapshot.hwnd in {int(h) for h in process.desktop.EnumDesktopWindows()}):
from .pcb_restore_prompt import RestoreController
if restore_controller is None:
restore_controller = RestoreController(job)
restore_controller = RestoreController(job, user_open=consent is None)
dialog_result = restore_controller.handle(dialog_result.snapshot,
dialog_result.observed_snapshots, target_pid=target_pid, launcher_pid=launcher_pid,
worker_pid=process.pid, companion_pids=tuple(process.companion_pids),
@@ -1089,7 +1101,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
# recovery checks for remaining native database clients.
_stop_worker(process, timeout=40)
return finish(VerifyResult(
'FAIL',
'CANCELLED' if dialog_result.error_code == 'USER_CANCELLED' else
'SKIPPED' if dialog_result.error_code == 'PCB_OPEN_SKIPPED' else 'FAIL',
stderr=f'{dialog_result.error_code}: {dialog_result.detail}',
error_stage=phase.value,
safe_to_continue=False,
@@ -1291,7 +1304,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
return finish(result)
def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=None):
def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=None, item_executor=None):
"""Run serially and stop when database/session safety is unconfirmed."""
if max_workers != 1:
raise ValueError('Only serial Verify is supported for the shared Library Manager session')
@@ -1308,10 +1321,18 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
result = VerifyResult('SKIPPED', stderr='同库原生会话尚未释放,未启动新的写入')
else:
try:
result = verifier(request)
def execute():
result = verifier(request)
if not result.safe_to_continue:
from .operation_lifecycle import recheck_failed_release
result = recheck_failed_release(request.lmc_file, request.block_name, result)
return result
result = item_executor(request, execute) if item_executor is not None else execute()
except Exception as error:
from .operation_queue import QueueCancelled
# An unexpected exception cannot establish database safety.
result = VerifyResult('FAIL', stderr=str(error), safe_to_continue=False)
result = VerifyResult('CANCELLED' if isinstance(error, QueueCancelled) else 'FAIL',
stderr=str(error), safe_to_continue=isinstance(error, QueueCancelled))
results.append(result)
# Never start another writer after an unconfirmed native shutdown.
if not result.safe_to_continue:
+100
View File
@@ -0,0 +1,100 @@
from threading import Event,Thread
def test_normal_verify_batch_yields_after_complete_item(qtbot,tmp_path,monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify.verify_runner import VerifyResult
started,release,waiting=Event(),Event(),Event()
order=[]
def verify(request):
order.append(request.block_name)
if request.block_name=='Beta':started.set();release.wait(5)
return VerifyResult('FAIL',stderr='independent failed item',safe_to_continue=True)
window=load_window(qtbot,tmp_path,monkeypatch,verifier=verify)
window._run(['Beta','Gamma'])
qtbot.waitUntil(started.is_set)
other=Thread(target=lambda:window.native_queue.run(lambda:order.append('other'),waiting=waiting.set))
other.start()
try:
assert waiting.wait(1)
release.set()
qtbot.waitUntil(lambda:not window.busy,timeout=10000)
other.join(2)
assert order==['Beta','other','Gamma']
finally:release.set();other.join(5)
def test_management_cancel_between_items_keeps_completed_results(tmp_path,monkeypatch):
from cbb_refresh_verify import management
from cbb_refresh_verify.operation_queue import QueueCancelled
from dataclasses import replace
request=management.ManagementRequest('remove',tmp_path/'lib.lmc','A')
def run(req,**kwargs):
return management.ManagementResult(req.operation,req.library,req.name,req.partition,None,False,
'complete','REMOVED',True)
monkeypatch.setattr(management,'run_management',run)
def execute(req,action):
if req.name=='B':raise QueueCancelled('cancelled waiting for native slot')
return action()
results=management.run_management_batch([request,replace(request,name='B')],item_executor=execute)
assert [r.status for r in results]==['REMOVED','CANCELLED']
assert all(r.safe_to_continue for r in results)
def test_cancelled_verify_keeps_summary_without_queueing_cancelled_refresh(qtbot,tmp_path,monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify.verify_runner import VerifyResult
calls=[]
def verify(req):
calls.append(req.block_name)
window.stop.set()
return VerifyResult('CANCELLED',safe_to_continue=True)
window=load_window(qtbot,tmp_path,monkeypatch,verifier=verify)
window._run(['Beta','Gamma'])
qtbot.waitUntil(lambda:not window.busy,timeout=5000)
assert calls==['Beta']
assert window.summary is not None
assert '队列未执行 1' in window.summary.detailedText()
def test_verify_failure_recheck_finishes_before_yielding_native_queue(qtbot,tmp_path,monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify.verify_runner import VerifyResult
from cbb_refresh_verify import operation_lifecycle
from dataclasses import replace
window=load_window(qtbot,tmp_path,monkeypatch,
verifier=lambda req:VerifyResult('FAIL',safe_to_continue=False))
active=[];seen=[]
def queued(action):
def run():
active.append(True)
try:return action()
finally:active.pop()
return run
def recheck(library,block,result):
seen.append(bool(active))
return replace(result,safe_to_continue=True)
monkeypatch.setattr(window,'_queued_action',queued)
monkeypatch.setattr(operation_lifecycle,'recheck_failed_release',recheck)
window._run(['Beta'])
qtbot.waitUntil(lambda:not window.busy,timeout=5000)
assert seen==[True]
def test_management_failure_recheck_finishes_before_yielding_native_queue(tmp_path,monkeypatch):
from cbb_refresh_verify import management,operation_lifecycle
from dataclasses import replace
request=management.ManagementRequest('remove',tmp_path/'lib.lmc','A')
monkeypatch.setattr(management,'run_management',lambda req,**kw:management.ManagementResult(
req.operation,req.library,req.name,req.partition,None,False,'complete','BLOCKED',False))
active=[];seen=[]
def item(req,action):
active.append(True)
try:return action()
finally:active.pop()
def recheck(library,block,result):
seen.append(bool(active))
return replace(result,safe_to_continue=True)
monkeypatch.setattr(operation_lifecycle,'recheck_failed_release',recheck)
management.run_management_batch([request],item_executor=item)
assert seen==[True]
+54
View File
@@ -0,0 +1,54 @@
from contextlib import nullcontext
from pathlib import Path
import pytest
import win32con,win32file
from cbb_refresh_verify import library_lock as locks, residual_sessions as sessions
from test_residual_sessions import row, OWNERSHIP
@pytest.mark.parametrize('command', ['viewdraw.exe', 'cscript.exe C:/other/QuickPartReplace.vbs'])
def test_unknown_external_owner_requires_resources_not_process_exit(tmp_path, monkeypatch, command):
library=tmp_path/'lib.lmc';library.touch()
owner=dict(pid=998877,name=command.split()[0],command=command)
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners',lambda *_:[owner])
with locks._prove_library_released(library) as proof:
assert proof['exclusive_files']==[str(library)]
assert proof['observed_owners']==[owner]
handle=win32file.CreateFile(str(library),win32con.GENERIC_READ,0,None,win32con.OPEN_EXISTING,0,None)
try:
with pytest.raises(Exception) as denied:
with locks._prove_library_released(library):pass
assert denied.value.winerror == 32
finally:handle.Close()
def test_unknown_observation_is_never_closed_or_counted_as_target(tmp_path,monkeypatch):
library=tmp_path/'lib/lib.lmc';library.parent.mkdir();library.touch()
foreign=dict(row(20,''),name='viewdraw.exe',command='viewdraw.exe',scope_confirmed=False)
target=dict(row(10,library.parent/'A.prj'),scope_confirmed=True)
monkeypatch.setattr(sessions,'query_process_snapshot',lambda:[target,foreign])
monkeypatch.setattr(sessions,'_process_windows',lambda _: {})
closed=[]
monkeypatch.setattr(sessions,'_request_close',lambda r,**kw:closed.append(r['pid']) or
dict(release_status='RELEASED',detail='closed'))
monkeypatch.setattr(sessions,'_finish_library_release',lambda *_:dict(status='RELEASE_CONFIRMED',library=str(library)))
result=sessions.release_residual_sessions(dict(library=str(library),sessions=[target,foreign]),tmp_path/'evidence')
assert result['status']=='RELEASE_CONFIRMED',result
assert closed==[10]
assert result['sessions'][1]['release_status']=='OBSERVED'
def test_explicit_target_owner_still_blocks_proof(tmp_path,monkeypatch):
library=tmp_path/'lib.lmc';library.touch()
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners',lambda *_:
[dict(pid=998877,name='viewdraw.exe',command=f'viewdraw.exe "{library}"')])
with pytest.raises(locks.LibraryBusy):
with locks._prove_library_released(library):pass
def test_our_unbound_worker_still_blocks_proof(tmp_path,monkeypatch):
library=tmp_path/'lib.lmc';library.touch()
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners',lambda *_:
[dict(pid=998877,name='CbbRefreshVerify.exe',command='CbbRefreshVerify.exe --verify-worker missing.json')])
with pytest.raises(locks.LibraryBusy):
with locks._prove_library_released(library):pass
+28
View File
@@ -0,0 +1,28 @@
import json
from dataclasses import asdict
from pathlib import Path
import pytest
from cbb_refresh_verify.verify_runner import VerifyRequest,VerifyResult,run_batch
@pytest.mark.parametrize('released',[True,False])
def test_batch_rechecks_owned_failure_before_skipping_next_item(tmp_path,monkeypatch,released):
from cbb_refresh_verify import library_lock,session_record
library=tmp_path/'lib.lmc';library.touch()
root=tmp_path/'failure';root.mkdir()
session_record.write_session_record(root/'session.json',dict(operation_id='test',library=str(library),block='A'))
outcome=VerifyResult('FAIL',stderr='original failure',safe_to_continue=False,
evidence_path=root/'result.json',session_record_path=root/'session.json')
calls=[]
monkeypatch.setattr(session_record,'inspect_session_record',lambda *a,**k:dict(status='UNCONFIRMED'))
def proof(*a,**k):
if not released:raise library_lock.LibraryBusy('shared database still occupied')
return dict(status='RELEASE_CONFIRMED',library=str(library),data_recovery_confirmed=False)
monkeypatch.setattr(library_lock,'release_retained_library',proof)
def verify(req):
calls.append(req.block_name)
return outcome if req.block_name=='A' else VerifyResult('PASS')
results=run_batch([VerifyRequest(library,n,tmp_path/'evidence') for n in ('A','B')],verifier=verify)
assert results[0].status=='FAIL' and results[0].stderr=='original failure'
assert results[0].safe_to_continue is released
assert calls==(['A','B'] if released else ['A'])
+24 -1
View File
@@ -70,6 +70,28 @@ def test_verification_refuses_uploader_exclusive_lock_before_native_work(tmp_pat
handle.Close()
@pytest.mark.parametrize('checkpoint_matches',[True,False])
def test_auto_verify_reuses_only_exact_active_parent_transaction(tmp_path,monkeypatch,checkpoint_matches):
import json
from cbb_refresh_verify import library_lock as locks,verify_runner as runner
library=tmp_path/'library/lib.lmc';library.parent.mkdir();library.touch()
calls=[]
monkeypatch.setattr(runner,'_run_verify_serialized',lambda *a,**k:
calls.append('verified') or runner.VerifyResult('PASS',library_flag='GREEN'))
with locks.LibraryLock(library,block_name='A'):
if not checkpoint_matches:
marker=locks.blocker_path(library)
value=json.loads(marker.read_text('utf-8'));value['lease_id']='b'*32
marker.write_text(json.dumps(value),'utf-8')
result=runner.run_verify(runner.VerifyRequest(library,'A',tmp_path/'evidence'))
assert (result.status=='PASS') is checkpoint_matches,result.stderr
assert calls==(['verified'] if checkpoint_matches else [])
if not checkpoint_matches:
# Restore only the fixture checkpoint so the enclosing test lease can exit.
owner=locks._owners[locks.LibraryLock(library).key]
value['lease_id']=owner['lease_id'];marker.write_text(json.dumps(value),'utf-8')
def test_unsafe_verify_records_failure_without_persistent_library_blocker(tmp_path, monkeypatch):
import json
import cbb_refresh_verify.verify_runner as runner
@@ -203,7 +225,8 @@ def test_release_rechecks_owners_after_database_handles_are_acquired(tmp_path, m
calls = []
def query(names):
calls.append(1)
return [] if len(calls) == 1 else [{'pid': 123456, 'name': 'cscript.exe', 'command': 'helper'}]
return [] if len(calls) == 1 else [{'pid': 123456, 'name': 'cscript.exe',
'command': 'cscript.exe close_failed_block.vbs'}]
monkeypatch.setattr(probe, 'query_owners', query)
with pytest.raises(locks.LibraryBusy, match='123456'):
with locks._prove_library_released(library): pass
+42
View File
@@ -221,6 +221,48 @@ def test_export_does_not_adopt_unrelated_existing_native_owner(project, tmp_path
assert len(started) == 3
def test_export_does_not_adopt_existing_child_of_reused_parent_pid(project, tmp_path, monkeypatch):
import cbb_refresh_verify.native_engineering_identity as identity
import win32api
source, _ = project
root = tmp_path/'exports'; root.mkdir()
# This process predates the exporter; its historical parent PID has been reused.
unrelated = dict(pid=888888, parent=987654, name='python.exe', executable='python.exe',
command='python other-tool.py', created='20261111120000.000000+480')
monkeypatch.setattr(identity, '_process_snapshot', lambda: [unrelated])
monkeypatch.setattr(identity, '_database_released', lambda _: True)
monkeypatch.setattr(identity, 'validate_export_output', lambda *_: None)
monkeypatch.setattr(win32api, 'OpenProcess', lambda *a: pytest.fail('adopted another tool'))
class Finished:
pid = 987654
returncode = 0
def __init__(self, *a, **k): pass
def poll(self): return 0
monkeypatch.setattr(identity.subprocess, 'Popen', Finished)
result = identity._run_exports(source, root, tmp_path, 1)
assert result['success'] and result['safe_to_continue']
def test_export_lineage_rejects_reused_owner_and_its_new_children():
from cbb_refresh_verify.native_engineering_identity import _export_descendants, _process_birth
old = '20261112120000.000000+480'
new = '20261112120100.000000+480'
tracked = {10: _process_birth(old), 20: _process_birth(old)}
rows = [dict(pid=20, parent=10, created=new), dict(pid=30, parent=20, created=new)]
assert _export_descendants(rows, tracked, set()) == []
assert 30 not in tracked
# An orphaned real child can outlive its exact original parent.
rows = [dict(pid=40, parent=10, created=new)]
assert _export_descendants(rows, tracked, set()) == rows
def test_export_lineage_rejects_child_older_than_native_handle_birth():
from cbb_refresh_verify.native_engineering_identity import _export_descendants, _process_birth
tracked = {10: _process_birth('20261112120000.000000+480')}
rows = [dict(pid=20, parent=10, created='20261111120000.000000+480')]
assert _export_descendants(rows, tracked, set()) == []
@pytest.mark.parametrize('remains_alive,database_busy', [(False, False), (True, False), (False, True)])
def test_export_reobserves_access_denied_child_before_deciding_release(
project, tmp_path, monkeypatch, remains_alive, database_busy):
+23
View File
@@ -161,6 +161,29 @@ def test_recorded_export_pid_reuse_requires_matching_creation_identity(export_ca
with prove_export_copies_released(library): pass
@pytest.mark.parametrize('in_memory', [False, True])
def test_preexisting_process_misrecorded_as_descendant_does_not_retain_copy(export_case, monkeypatch, in_memory):
import win32api, win32con
from cbb_refresh_verify import native_engineering_identity as identity
from cbb_refresh_verify.native_export_guard import prove_export_copies_released
library, root, *_ = export_case
record = dict(pid=123456, observed_pids=[123456, os.getpid()], process_identities=[
dict(pid=123456, created='20261112120000.000000+480', executable='native'),
dict(pid=os.getpid(), created='20261111120000.000000+480', executable='other')])
(root/'ascii-process.json').write_text(json.dumps(record),'utf-8')
monkeypatch.setattr(identity, '_process_snapshot', lambda: [dict(pid=os.getpid(), name='other.exe',
parent=123456, created='20261111120000.000000+480', executable='other', command='')])
handle = win32api.OpenProcess(win32con.SYNCHRONIZE, False, os.getpid())
try:
if in_memory:
monkeypatch.setattr(identity, '_retained_exports', [(SimpleNamespace(pid=123456,poll=lambda: 0),
{os.getpid(): handle}, dict(library=str(library),analysis_root=str(root)))])
with prove_export_copies_released(library) as copies:
assert copies == [str(root/'project')]
finally:
handle.Close()
@pytest.mark.parametrize('active', [False, True])
def test_unknown_checkpoint_requires_explicit_full_proof_and_no_native_export_owner(tmp_path, monkeypatch, active):
import cbb_refresh_verify.native_engineering_identity as identity
+114
View File
@@ -0,0 +1,114 @@
from contextlib import nullcontext
from types import SimpleNamespace
from dataclasses import replace
import pytest
from test_post_repair_consent import snapshot
@pytest.mark.parametrize('decision,control', [('continue',6),('skip',7),('cancel',7)])
def test_readwrite_requires_explicit_choice_and_consumes_once(tmp_path,monkeypatch,decision,control):
from cbb_refresh_verify import pcb_open_consent as consent
monkeypatch.setattr(consent,'validate_owner',lambda *a:('bound-owner',))
monkeypatch.setattr(consent,'resource_guard',lambda *a:nullcontext())
job=dict(root=str(tmp_path),block_name='A',lmc_file=str(tmp_path/'lib.lmc'),desktop='CbbVerify_test',
project=str(tmp_path/'A.prj'),pcb=str(tmp_path/'A.pcb'))
controller=consent.OpenController(job)
shown=[];sent=[]
def perform(s,p,phase):
sent.append(p);return SimpleNamespace(accepted_controls=(control,),error_code='',detail='',channel='win32_button_click')
kwargs=dict(target_pid=20,launcher_pid=10,worker_pid=5,show=shown.append,perform=perform)
first=controller.handle(snapshot(),(snapshot(),),**kwargs)
assert not first.error_code and len(shown)==1 and not sent
shown[0].choose(decision)
result=controller.handle(snapshot(),(snapshot(),),**kwargs)
assert len(sent)==1 and sent[0]['target']=={'control_id':control}
assert result.error_code==('' if decision=='continue' else 'PCB_OPEN_SKIPPED' if decision=='skip' else 'USER_CANCELLED')
controller.handle(snapshot(),(snapshot(),),**kwargs)
assert len(sent)==1
def test_no_consent_to_changed_window_or_database_owner(tmp_path,monkeypatch):
from cbb_refresh_verify import pcb_open_consent as consent
monkeypatch.setattr(consent,'validate_owner',lambda *a:('bound',))
def occupied(*a):raise ValueError('target database occupied')
monkeypatch.setattr(consent,'resource_guard',occupied)
controller=consent.OpenController(dict(root=str(tmp_path),block_name='A',lmc_file=str(tmp_path/'lib.lmc'),
desktop='CbbVerify_test',project=str(tmp_path/'A.prj'),pcb=str(tmp_path/'A.pcb')))
shown=[]
kwargs=dict(target_pid=20,launcher_pid=10,worker_pid=5,show=shown.append,perform=lambda *a:pytest.fail('unsafe Yes'))
controller.handle(snapshot(),(snapshot(),),**kwargs)
shown[0].choose('continue')
result=controller.handle(snapshot(),(snapshot(),),**kwargs)
assert result.error_code=='DATABASE_RECOVERY_REQUIRED' and 'occupied' in result.detail
def test_explicit_open_dialog_defaults_to_cancel(qtbot):
from cbb_refresh_verify.pcb_open_consent import OpenChoice
from cbb_refresh_verify.ui.pcb_open_dialog import PcbOpenDialog
choice=OpenChoice('A','lib.lmc')
dialog=PcbOpenDialog(choice);qtbot.addWidget(dialog)
assert dialog.defaultButton() is dialog.cancel_button
dialog.skip_button.click()
assert choice.decision=='skip'
def test_normal_open_can_request_a_version_without_automatic_repair(tmp_path,monkeypatch):
from cbb_refresh_verify import pcb_open_consent as consent
from cbb_refresh_verify.pcb_restore_prompt import RestoreController
from test_pcb_version_choice import captured
monkeypatch.setattr(consent,'validate_owner',lambda *a:('owned',))
job=dict(root=str(tmp_path),block_name='A',lmc_file=str(tmp_path/'lib.lmc'),
desktop='CbbVerify_test',project=str(tmp_path/'A.prj'),pcb=str(tmp_path/'A.pcb'))
controller=RestoreController(job,user_open=True)
snap=captured();shown=[];sent=[]
def perform(s,p,phase):
sent.append(p);return SimpleNamespace(accepted_controls=(p['target']['control_id'],),error_code='',detail='',channel='win32_button_click')
kwargs=dict(target_pid=snap.pid,launcher_pid=10,worker_pid=5,companion_pids=(),show=shown.append,perform=perform)
assert not controller.handle(snap,(snap,),**kwargs).error_code
assert len(shown)==1 and not sent
shown[0].choose('last_user_saved')
assert controller.handle(snap,(snap,),**kwargs).action_sent
selected=replace(snap,controls=tuple(replace(c,checked=c.control_id==6213,selected=c.control_id==6213)
if c.control_id in (6213,6206) else c for c in snap.controls))
assert controller.handle(selected,(selected,),**kwargs).action_sent
assert [p['target']['control_id'] for p in sent]==[6213,1]
def test_readwrite_choice_survives_uia_chrome_enrichment(tmp_path,monkeypatch):
from cbb_refresh_verify import pcb_open_consent as consent
from cbb_refresh_verify.dialog_models import ControlSnapshot
monkeypatch.setattr(consent,'validate_owner',lambda *a:('owned',))
monkeypatch.setattr(consent,'resource_guard',lambda *a:nullcontext())
controller=consent.OpenController(dict(root=str(tmp_path),block_name='A',lmc_file='lib.lmc',
project='A.prj',pcb='A.pcb',desktop='CbbVerify_test'))
original=snapshot();shown=[];sent=[]
original=replace(original,controls=tuple(replace(c,name='是(&Y)' if c.control_id==6 else '否(&N)')
if c.class_name=='Button' else c for c in original.controls))
def perform(s,p,phase):
sent.append(p)
return SimpleNamespace(accepted_controls=(6,),error_code='',detail='',channel='win32_button_click')
kwargs=dict(target_pid=20,launcher_pid=10,worker_pid=5,show=shown.append,perform=perform)
controller.handle(original,(original,),**kwargs)
shown[0].choose('continue')
chrome=(ControlSnapshot(original.hwnd,0,original.window_class,original.title,
control_type='Window',patterns=('Window',)),
ControlSnapshot(0,0,'','',control_type='TitleBar',patterns=('Value',)))
enriched=replace(original,controls=tuple(replace(c,name=c.name.replace('&',''))
if c.class_name=='Button' else c for c in reversed(original.controls))+chrome)
assert consent.exact_prompt(enriched)
result=controller.handle(enriched,(enriched,),**kwargs)
assert not result.error_code and len(sent)==1
def test_readwrite_choice_rejects_replaced_native_button(tmp_path,monkeypatch):
from cbb_refresh_verify import pcb_open_consent as consent
monkeypatch.setattr(consent,'validate_owner',lambda *a:('owned',))
controller=consent.OpenController(dict(root=str(tmp_path),block_name='A',lmc_file='lib.lmc'))
original=snapshot();shown=[]
kwargs=dict(target_pid=20,launcher_pid=10,worker_pid=5,show=shown.append,
perform=lambda *a:pytest.fail('changed native button accepted'))
controller.handle(original,(original,),**kwargs)
shown[0].choose('continue')
changed=replace(original,controls=tuple(replace(c,handle=c.handle+1) if c.control_id==6 else c
for c in original.controls))
assert controller.handle(changed,(changed,),**kwargs).error_code=='DATABASE_RECOVERY_REQUIRED'
+2 -1
View File
@@ -53,7 +53,8 @@ def test_unknown_scope_is_visible_but_never_closed_even_with_force(tmp_path, mon
monkeypatch.setattr(sessions, '_force_close', lambda *a, **kw: pytest.fail('ended unknown scope'))
for force in (False, True):
result = sessions.release_residual_sessions(plan, tmp_path.parent/'release-evidence'/tmp_path.name, force=force)
assert result['status'] == 'PARTIAL'
assert result['status'] == 'RELEASE_CONFIRMED'
assert result['sessions'][0]['release_status'] == 'OBSERVED'
# A request file becoming readable must not expand the user's consent list.
monkeypatch.setattr('cbb_refresh_verify.library_lock._owner_matches_scope', lambda *a: True)
result = sessions.release_residual_sessions(plan, tmp_path.parent/'release-evidence'/tmp_path.name, force=True)
+10
View File
@@ -38,6 +38,16 @@ def test_round_trip_and_exact_live_process(tmp_path, child):
assert child.poll() is None
@pytest.mark.parametrize('exited', [True, False])
def test_unconfirmed_journal_is_active_only_while_bound_native_is_alive(tmp_path, child, monkeypatch, exited):
path=record(tmp_path,[dict(role='native',**sessions.process_identity(child.pid))])
sessions.write_session_record(path.with_name('worker-state.json'),dict(operation_id='test-session',phase='UNCONFIRMED'))
monkeypatch.setattr(sessions,'_retained_libraries',{str(path):{sessions._library_key(tmp_path/'lib.lmc')}})
if exited:child.terminate();child.wait(5)
writes=sessions.active_write_records(tmp_path/'lib.lmc')
assert bool(writes) is not exited
@pytest.mark.parametrize('key,value', [('created_handle', 'old'), ('image', 'C:/old.exe'),
('owner_sid', 'S-1-old'), ('session_id', -1)])
def test_reused_pid_is_observed_never_acted_on(tmp_path, child, key, value):