Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
42898d33d2 | ||
|
|
b1c36e3ca6 | ||
|
|
ca39fb3517 | ||
|
|
96e179ba65 | ||
|
|
44bb734de8 | ||
|
|
1494dc260c | ||
|
|
8e946c6e7a | ||
|
|
5873b7146b | ||
|
|
051498ba57 | ||
|
|
d9a79b6535 | ||
|
|
cb11624b68 | ||
|
|
6278091f21 | ||
|
|
8d3eab1164 | ||
|
|
97a3de20c9 | ||
|
|
7bd7cd3966 | ||
|
|
3e7ae2b76f |
No files matched your search
@@ -1,3 +1,6 @@
|
||||
# Keep the verified Windows source and binary assets byte-for-byte.
|
||||
# Do not normalize the r4 baseline's line endings during add/checkout.
|
||||
* -text
|
||||
# Normalize only these two reviewed Python files at the chain tip.
|
||||
src/cbb_refresh_verify/application.py text eol=lf
|
||||
src/cbb_refresh_verify/ui/main_window.py text eol=lf
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
当前临时分支的备份策略(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。
|
||||
当前开发版本:**[0.2.4b2 生命周期候选](docs/releases/2026-11-06-runtime-lifecycle-candidate.md)(待评审、待现场验收)**。ICDB 批量检查在后台逐项运行,普通校验、管理和恢复可排队;READY 工程在实际执行前再次排除。检查不自动 Repair、Restore 或选择历史版本,也不代表中心库 READY。
|
||||
|
||||
停止、超时或应用失联只停止后续原生动作,不结束正在 Save/Close 的调用进程。普通停止等待 5 秒,可能正在写入时最多等待 120 秒后交给后台观察;这不是强制结束时限。保存结果、关闭结果和资源释放分别记录。相关库等待释放,独立库可以排队继续;界面、筛选和日志保持可用。重启只核对未完成会话,不重放管理写操作。legacy 状态读取只观察已打开且匹配库的 LM,不启动 LM 或回答弹窗;无法读取保持 UNKNOWN。
|
||||
|
||||
历史释放记录会触发实际占用复核,确认释放后归档继续;会话释放不等于历史数据恢复。释放结果逐项保存;记录保存失败会单独显示,不把已确认释放的会话重新标成占用。可查看后台窗口的原生提示;仅对当前可识别的原生取消按钮提供确认操作。
|
||||
|
||||
@@ -147,7 +149,7 @@ python -m cbb_refresh_verify
|
||||
- **不注入鼠标或键盘输入,不切换 Windows 桌面,不改写中心库源文件。** 生产路径在本次运行创建的私有桌面内启动中心库目录绑定的 ReusableCircuit PCB,随后用 COM 完成刷新、保存和关闭;只读状态桥在结束后确认 LMC 的 READY。Library Manager 菜单派发仅作为显式诊断路径保留。`tests/test_safety.py` 会在离线测试中阻止真实输入注入 API 重新进入生产代码。
|
||||
- 所有自动化都跑在本进程创建的**私有 Windows 桌面**上:用户看不到窗口,光标不会被移动。
|
||||
- 弹窗只认领本次运行的私有桌面/进程,依据已知规则投递 `BM_CLICK`。数据库恢复、会话失联和设计锁接管提示会阻断并保留现场;不会自动选择恢复或接管。未知弹窗也会阻断,Project Integration 进度窗保持观察。动作/错误弹窗和实际控件 ID 写入 `dialogs.jsonl`。
|
||||
- 超时或失败时停止自动化客户端,保留可能仍在写库的原生会话并停止批次。内容检查超时也不再强杀整个进程树;监督器核对进程是否退出,记录 `process_exit_confirmed` 或 `process_retained`;无法确认释放时输出 `recovery-required.json`,不以强杀代替数据库安全关闭。已确认身份且原生调用返回的失败文档会通过 32 位助手执行 `Close(False)`,再确认进程和 iCDB 地址释放。
|
||||
- 超时或失败时请求合作停止,保留可能正在原生调用的 worker 和保存/关闭助手,并交后台观察。内容检查超时同样不强杀进程树。保存结果未知时不再自动丢弃关闭;无保存助手且身份、空闲状态已确认的启动/集成失败仍可正常收尾。无法确认释放时保留 `recovery-required.json` 和相关库租约。
|
||||
|
||||
## 环境要求
|
||||
|
||||
@@ -174,7 +176,7 @@ Windows 版本判断以 Build 为准:`22000` 及以上归为 Win11,`10240–
|
||||
|
||||
## 批量策略
|
||||
|
||||
每个 CBB 独立执行并写入自己的 evidence 和结果行。可确认安全的单项失败允许继续;遇到 `ICDB_REPAIR_REQUIRED`、超时、原生会话释放未确认等情况,会停止整批并把后续项目标为 `SKIPPED`。点击“当前项完成后停止”或执行器返回 `QUEUE_STOP` 也会停止队列。
|
||||
每个 CBB 独立执行并写入自己的 evidence 和结果行。资源已释放的单项失败允许继续;未释放时跳过后续同库写入,独立库仍可运行。ICDB 错误本身不等于占用。用户取消或执行器明确返回 `QUEUE_STOP` 才停止本批次后续项,不自动恢复或重放该批次。
|
||||
|
||||
GUI 中状态为 `绿色 / Ready` 的条目不能勾选、也不会进入批量队列。
|
||||
|
||||
@@ -209,9 +211,9 @@ Mentor 桥耗时需在目标机器另行测量。
|
||||
- `image-status-map.json`:按中心库路径隔离的本机动态 `image_id` 校准快照(当前格式 `schema_version=2`);旧版本或无版本缓存会自动忽略并重新校准,日志会记录当前样本、缓存样本、Ready 主 ID、未映射 ID 和逐项决策原因;
|
||||
- `backup/`:历史版本的辅助文件副本;当前分支不再生成,所有路径记录 `backup_skipped / manual_backup_policy`。已有历史副本不由本轮改动清理。
|
||||
|
||||
超时采用无进展计时:界面和批量请求默认 600 秒无进展超时;它不是整个 CBB 的固定总时限,而是连续 600 秒没有可观察进展时才终止。PCB/COM 阶段切换、Project Integration 状态变化、保存标记变化和弹窗处理都会刷新计时器;重复的状态轮询不算进展。需要更快失败时仍可在界面将单项预算调低,但 30 秒只适合已确认 PCB 启动稳定的环境。
|
||||
超时采用无进展计时:界面和批量请求默认 600 秒没有可观察进展时进入停止与观察流程,不强杀正在进行的调用。PCB/COM 阶段切换、Project Integration 状态变化、保存标记变化和弹窗处理都会刷新计时器;重复的状态轮询不算进展。需要更快失败时仍可调低单项预算,但 30 秒只适合已确认 PCB 启动稳定的环境。
|
||||
|
||||
结果不会把“内容检查 PASS”冒充为中心库绿色状态:`library_flag` 只来自对条目状态的只读读取,读不到就是 `UNKNOWN`。Mentor 的树节点 `iImage` 是本机资源列表索引,不能跨安装固定写死为绿色;工具会在日志中为每个 CBB 记录 `image_id`,并从独立的 `Cert/Work` 持久化证据动态校准本机 ID。树 ID 可读时用于交叉核对,冲突不允许标记 Ready;LM 忙导致树 ID 暂时读不到时,完整的持久化证据仍可保留 Ready,缺少持久化证据的条目仍进入待校验。右键菜单文字(包括 `Unverify`)不参与状态判定。
|
||||
结果不会把“内容检查 PASS”冒充为中心库绿色状态。默认权威桥读取 READY/raw=1;桥失败保留未知/不可用。显式 legacy 模式只观察已有匹配 LM 的树图标,图标不可读时保持 UNKNOWN,不以 Cert/Work 文件直接推断 READY 或 PENDING,也不自动回答原生提示。右键菜单文字(包括 `Unverify`)不参与状态判定。
|
||||
|
||||
### 状态接口审计
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# CBB 检查、校验、管理与残留释放操作规程
|
||||
|
||||
适用开发版本:0.2.4b1。未完成现场验收,不自动发布或关闭工单。以下为当前规程,下方旧上传校验检查表保留为历史参考。
|
||||
适用开发版本:0.2.4b2。未完成现场验收,不自动发布或关闭工单。以下为当前规程,下方旧上传校验检查表保留为历史参考。
|
||||
|
||||
## 当前操作与队列
|
||||
|
||||
@@ -8,7 +8,11 @@
|
||||
|
||||
普通校验完成原生打开、身份确认、Project Integration、保存和关闭后,必须由权威状态 READY/raw=1 确认成功。ICDB 检查仅尝试打开并检查本次错误,不自动 Repair、Restore 或选择版本,CHECKED 不等于 READY。排队期间变成 READY 的工程在执行前跳过。
|
||||
|
||||
原生任务串行排队,检查每项结束后让出机会;缓存筛选保持可用。失败项确认释放后继续独立项目;实际未释放时停止后续原生操作。“停止检查”只取消检查,“取消当前任务并停止队列”同时取消前台任务及后续后台检查,已进行的写入等待安全结束,不强杀代替取消。
|
||||
原生任务串行排队,检查每项结束后让出机会;缓存筛选保持可用。失败项确认释放后继续独立项目;未释放会话转后台观察,只保留相关库的写入限制,独立库可继续。“停止检查”只取消检查,“取消当前任务并停止队列”取消当前批次后续动作;正在保存/关闭的调用只等待返回。普通等待 5 秒,可能正在写入时最多再等到 120 秒后交后台,这不是结束进程的期限。
|
||||
|
||||
保存已返回成功、关闭失败、资源仍占用可以同时出现。查看本轮保存/关闭标记和独立释放结果,不能因进程退出就认定工程已保存。管理更新若已经移除、尚未重新导入就取消,按“需恢复”核对,不自动补做下一次导入。重启发现未完成任务时只核对身份和资源,不自动重放。
|
||||
|
||||
权威状态桥不可用时保留未知/不可用;legacy 读取只观察已打开且库身份匹配的 Library Manager。没有匹配窗口、存在模态提示或树不可读时返回 UNKNOWN,不自动启动或应答窗口。
|
||||
|
||||
新增拒绝同名冲突;更新先原生移除再导入,失败可能需要人工备份恢复;移除后重新读取目录确认。版本回退由操作员在原生界面选择,核对工程内容后单独校验。
|
||||
|
||||
@@ -24,7 +28,7 @@
|
||||
2. 数据库服务器可能服务同库其他用户。本工具不允许强制结束服务器,命令行指向本库也不构成独占授权;由库管理员核对用户和服务器状态。
|
||||
3. “强制结束客户端”是另行确认的异常处理,只允许属于当前 Windows 用户和会话、已确认作用域和精确进程身份的 Expedition PCB、Library Manager、viewdraw、iCDB Project Backup 客户端。后台导入器、脚本宿主和归属未知的进程同样不在强制名单。
|
||||
4. 警告明确告知客户端中其他已打开工程可能一并退出、未保存更改会丢失、写入中的工程可能需要恢复。执行前持久保存库外 `consent.json`,包含目标库、名单、创建身份和排除项;写入失败不执行。派发处核对快照身份和原预览范围,最终句柄处核对创建时间、完整映像、用户 SID、Windows 会话和原生活动;变化时拒绝。
|
||||
5. 预览和执行前检查进度与本轮 Output。Backup/Restore/Repair 进行中或状态无法确认时,不强制结束。可查看后台窗口的标题、输出和所在桌面;仅当当前窗口唯一存在已识别的 Cancel/取消按钮时,提供单独确认的原生取消。核对身份、用户会话和按钮快照后发送请求,再重新检查实际结果;没有识别到按钮时不猜菜单参数,不抢占前台。
|
||||
5. 预览和执行前检查进度与本轮 Output。本工具登记的 Save/Close/原生调用尚未确认返回,或 Backup/Restore/Repair 进行中、状态无法确认时,不放行普通“强制结束客户端”。可查看后台窗口的标题、输出和所在桌面;仅当当前窗口唯一存在已识别的 Cancel/取消按钮时,提供单独确认的原生取消。核对身份、用户会话和按钮快照后发送请求,再重新检查实际结果;没有识别到按钮时不猜菜单参数,不抢占前台。
|
||||
6. 每项动作前后持久记录实际结果,异常保留已完成/未执行项。若最终记录保存失败但独立库释放证明已确认,界面明确提示记录失败并接受释放事实,不伪造新的占用。
|
||||
7. 客户端退出仅证明进程结束,不表示修复成功或 READY。服务器仍活跃或库状态未知时保留 PARTIAL、检查点和映射。只有完整的独立释放证明才解除匹配的历史记录;空进程列表本身不是释放证明。
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
## 残留客户端与共享服务器
|
||||
|
||||
0.2.4b1 的默认检查、校验、取消和释放流程不会强杀原生会话。操作员可以在独立确认界面强制结束属于当前 Windows 用户和会话、名单中的受支持客户端;这会影响该客户端内其他已打开工程,未保存更改可能丢失,属于异常退出处理,不能替代 Repair。
|
||||
0.2.4b2 的默认检查、校验、取消和释放流程保留正在原生调用中的 worker 和保存/关闭助手。停止只阻止后续动作,必要时转后台观察;保存、关闭、进程退出和资源释放分别记录。独立确认的“强制结束客户端”也不放行本工具尚未返回的 Save/Close。符合其他释放条件的受支持客户端仍可另行确认结束;这会影响其其他工程,属于异常退出处理,不能替代 Repair。
|
||||
|
||||
ICDB 数据库服务器即使命令行指向当前中心库,也可能服务其他用户,**本工具不允许强制结束服务器**。归属未知的进程、后台导入器和脚本宿主同样不允许强制结束;由库管理员核对用户和服务器状态后处理。
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
{
|
||||
"date": "2026-11-06T09:27:28.849706+00:00",
|
||||
"source_commit": "44bb734de80afbe3ff04ba72d52a465ff3b91684",
|
||||
"version": "0.2.4b2",
|
||||
"reason": "New user icon was uncommitted in original workspace and absent from isolated worktree; synchronize all three assets.",
|
||||
"assets": [
|
||||
{
|
||||
"name": "cbb_refresh_verify.ico",
|
||||
"sha256": "62d4472ebaa94f9b39aebae06459685d3322041d0e1a7ada9f368cfd816ba1d6",
|
||||
"bytes": 123139
|
||||
},
|
||||
{
|
||||
"name": "cbb_refresh_verify.png",
|
||||
"sha256": "840f657fd7c622d9afd78625a64ed8ad04c90a895dd3c9fd37eebae543cdebe8",
|
||||
"bytes": 1187049
|
||||
},
|
||||
{
|
||||
"name": "cbb_refresh_verify.svg",
|
||||
"sha256": "cbba5b3f339cbeb5eb43012709237359442ef67c69fc5b6679a8ee4c0a1b7328",
|
||||
"bytes": 1582896
|
||||
}
|
||||
],
|
||||
"exe_icon_frames_match_current_ico": true,
|
||||
"exe_icon_frame_count": 7,
|
||||
"qt_window_icon_matches_current_ico": true,
|
||||
"frozen_product_module_bytecode_matches_source": true,
|
||||
"module_count": 62,
|
||||
"packaging_tests": {
|
||||
"passed": 13
|
||||
},
|
||||
"frozen_smoke": "F:\\Sync Tool Skyworth\\Work Maps\\cbb-refresh-verify-795\\diagnostics\\runtime-lifecycle-b2-iconfix\\smoke-334dde93\\result.json",
|
||||
"exe": "F:\\Sync Tool Skyworth\\Work Maps\\cbb-refresh-verify-795\\diagnostics\\runtime-lifecycle-b2-iconfix\\dist\\CbbRefreshVerify-Background\\CbbRefreshVerify.exe",
|
||||
"exe_sha256": "7c4a78d9d2116f637c2a236a82979db2ce49b9b5fa6493a16e66fc803b38d999",
|
||||
"zip": "F:\\Sync Tool Skyworth\\Work Maps\\cbb-refresh-verify-795\\diagnostics\\runtime-lifecycle-b2-iconfix\\CbbRefreshVerify-0.2.4b2-iconfix-44bb734.zip",
|
||||
"zip_sha256": "4a0a96321801fdebf13fed0f850a0c4b32d6928480288fd35c2d36f534e6e5b5",
|
||||
"zip_bytes": 56846008,
|
||||
"runtime_changes": false,
|
||||
"full_runtime_suite_rerun": false,
|
||||
"prior_runtime_suite": {
|
||||
"passed": 1717,
|
||||
"source_commit": "5873b7146b61d0cdd0eb22f6f2941797b02f38fc"
|
||||
},
|
||||
"pr": 13,
|
||||
"draft": true
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
# 0.2.4b2 原生操作生命周期候选
|
||||
|
||||
本候选处理 PR #12 评论 297 的三条 P1 及直接相关的停止、释放记录问题。ICDB 自动 Repair 仍关闭,现场失联恢复尚未验收。本轮不合并、不发布正式版、不关闭工单。
|
||||
|
||||
差分审查入口:[Draft PR #13](https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/pulls/13),依赖 #12。
|
||||
|
||||
**当前图标修正版:** `44bb734` 将原工作区的新版蓝色对勾/环形箭头 ICO、PNG、SVG 同步进候选分支。已核对 EXE 内嵌的七个尺寸图标、Qt 窗口图标及三份打包资源一致,13 项打包测试和冻结入口冒烟通过。62 个产品模块字节码保持与当前源码一致,未为资源替换重跑业务全量。当前便携包为 `CbbRefreshVerify-0.2.4b2-iconfix-44bb734.zip`(56,846,008 字节),SHA-256:`4a0a96321801fdebf13fed0f850a0c4b32d6928480288fd35c2d36f534e6e5b5`。实际程序路径及验证明细见[图标修正记录](2026-11-06-icon-candidate-validation.json)。下文首次候选包哈希保留用于历史追溯。
|
||||
|
||||
## 行为
|
||||
|
||||
- 停止、超时、失败收尾和监督器失联只请求停止后续动作,不强杀可能正在 Save/Close 的 worker 或 cscript。保存助手先持久登记精确身份,再通过启动门进入 COM。保存返回、关闭返回和独立资源释放分别记录;进程消失不能把未知保存升级为成功。
|
||||
- 普通停止等待 5 秒;可能正在写入时最多等待 120 秒后转后台观察。相关库的租约、映射和精确进程观察继续保留,不占全局队列票据;独立库可以运行。用户取消的批次不自动恢复。
|
||||
- 管理 catalog/add/remove 使用统一监督器身份、取消信号、启动门和会话记录。更新在 remove 后停止,记录需恢复,不继续 add。异步 Add 提交前必须成功保存 NATIVE_CALL;提交后记录失败仍保留监督。未知 Add 结果不触发自动 Close/Quit,明确且已应答的原生失败可正常收尾。
|
||||
- 重启在后台核对受控记录,不执行记录中的命令或重放写操作。PID 复用只观察替代进程,继续独立资源核对;证明成立才解除对应等待。报告错误、损坏 JSON 本身不生成全局占用。
|
||||
- 权威状态桥保持默认;legacy 读取只观察已打开、匹配库且可读取的 LM,不启动程序、不回答提示、不关闭用户窗口。无法观察保持 UNKNOWN。
|
||||
|
||||
界面保持三个页签。新增说明写在本文和代码中;界面仅呈现当前状态和操作结果。原工作区、用户图标改动和已运行程序未替换。
|
||||
|
||||
## 实现与审查
|
||||
|
||||
基线为 `5eb4b2d`,独立分支为 `codex/runtime-lifecycle-safety`。保存与只读接线共用 mentor_adapter,审查顺序为:事实/会话协议 → 保存与停止 → 管理监督 → 界面交接 → 独立审查修正。共享文件的 A/C 接线合并在同一提交,候选仅在三单元联通后生成。
|
||||
|
||||
独立审查发现并修正:IDENTITY_CHANGED 提前结束观察、异步 Add 阶段不准确、权限 COM 查询后未再次检查取消,以及写入阶段记录失败后仍继续提交 Add。新增回归先复现失败,再验证修正。该审查不等于真实 Mentor 数据恢复验收。
|
||||
|
||||
## 验证口径
|
||||
|
||||
可机读结果、源码身份、XML 与候选包哈希见 [验证记录](2026-11-06-runtime-lifecycle-validation.json)。Python 全量回归、实际 32 位 cscript 的 FakeDoc Save/Close、真实 Windows 测试进程的父进程退出,以及冻结入口冒烟分别记录。
|
||||
|
||||
最终源码提交 `5873b71`:**1,717 passed**,编译与 diff 检查通过。正式候选 GUI 及四类 worker 入口冒烟通过;62 个产品模块的冻结字节码与当前源码一致。独立冻结夹具的保存/管理 × 用户取消/父进程退出共四个场景通过。唯一已知测试警告为 pywinauto 的 STA 模式提示。
|
||||
|
||||
首次候选便携 ZIP 为 `CbbRefreshVerify-0.2.4b2-runtime-lifecycle-5873b71.zip`,54,227,147 字节;SHA-256:`5983a4e99884d9551d1dba3d81af88f754ce876c19a780fe82e8ea9fd58a566b`。未上传为正式 Release。构建、XML 和各专项结果文件的实际路径保存在验证 JSON。
|
||||
|
||||
冻结测试夹具是独立测试程序,使用同一批产品模块并替换外部原生边界;不随候选交付,也不是应用实际按钮操作或真实数据库修复。冻结产品的 GUI、启动前取消、拒绝错误桌面的管理入口、进程探针及仅观察的弹窗代理单独冒烟。
|
||||
|
||||
可复现脚本在 `tests/support/runtime_lifecycle_frozen_*.py`。它们是实际执行脚本的逐字节副本,最终套件完成后归档,未改变产品源码或 pytest 收集范围。先按现有 spec 构建产品,再以 `runtime_lifecycle_frozen_fixture.py` 为独立 PyInstaller onedir/console 入口、产品 `src` 为搜索路径构建夹具;`runtime_lifecycle_frozen_smoke.py <worktree> <artifact-root>` 和 `runtime_lifecycle_frozen_boundaries.py <worktree> <artifact-root>` 分别验证产品与夹具。产物目录结构见验证 JSON,不应将测试夹具放入便携包。
|
||||
|
||||
本轮没有在生产库执行原生写入、删除地址/锁文件、强杀 Mentor、选择历史版本或重放旧管理任务。下列项仍为 **未验收**:
|
||||
|
||||
- 使用本候选实际按钮完成真实 Mentor 隔离副本的 Save 中停止、延迟 Close、管理失联及独立库继续。
|
||||
- Windows 10、共享网络库和跨机器并发。
|
||||
- 现场故障一致副本上的 ICDB 失联恢复、数据版本和 READY 验收。
|
||||
|
||||
原生 COM 调用本身可能不可取消。后台观察提供状态与资源保护,不承诺把任意卡死进程自动安全结束。回退程序不撤销数据库事务;工程恢复仍依靠人工一致备份或明确选择的原生历史版本。
|
||||
@@ -0,0 +1,387 @@
|
||||
{
|
||||
"date": "2026-11-06T08:53:02.058981+00:00",
|
||||
"version": "0.2.4b2",
|
||||
"base_commit": "5eb4b2d7ed09947f19310ba80ba3b9a2a09b6f7d",
|
||||
"source_commit": "5873b7146b61d0cdd0eb22f6f2941797b02f38fc",
|
||||
"src_tree": "ef5ef877665fff179dd6d21d8d6f86e8de0a7e5b",
|
||||
"pytest_tests_tree": "35f5ad42f2c6150bf5762a46cdeb9880d1fc0d0c",
|
||||
"environment": {
|
||||
"platform": "Windows-11-10.0.26200-SP0",
|
||||
"python": "3.12.10",
|
||||
"mentor_library_manager_file_version": "2012.0.522.442",
|
||||
"mentor_library_manager_sha256": "a9c4c3d806794dbdc56d2bc4c637a1cf25e87e98644a7d5fd4eb0067ca5845e0",
|
||||
"mentor_home": "D:\\Mentor\\7.9.5EE\\SDD_HOME",
|
||||
"matches_validated_mentor_library_manager_binary": true
|
||||
},
|
||||
"tests": {
|
||||
"final_full": {
|
||||
"status": "passed",
|
||||
"tests": 1717,
|
||||
"failures": 0,
|
||||
"errors": 0,
|
||||
"skipped": 0,
|
||||
"xml": "F:\\Sync Tool Skyworth\\Work Maps\\cbb-refresh-verify-795\\diagnostics\\runtime-lifecycle-final-1717.xml",
|
||||
"xml_sha256": "1d427f97dd04afbf8912bbdf787b0b9dfd1ed383d32bfe07f7a94cc24f9c5292"
|
||||
},
|
||||
"known_warning": "pywinauto: Revert to STA COM threading mode",
|
||||
"compileall": "passed",
|
||||
"git_diff_check": "passed",
|
||||
"independent_review": "important findings resolved through 051498b"
|
||||
},
|
||||
"frozen_product": {
|
||||
"build": "passed",
|
||||
"smoke": {
|
||||
"gui": {
|
||||
"status": "passed",
|
||||
"exit_code": 0
|
||||
},
|
||||
"verify-worker": {
|
||||
"exit_code": 1,
|
||||
"status": "passed",
|
||||
"evidence": "F:\\Sync Tool Skyworth\\Work Maps\\cbb-refresh-verify-795\\diagnostics\\runtime-lifecycle-b2\\smoke-74da6fd5\\verify-worker"
|
||||
},
|
||||
"management-worker": {
|
||||
"exit_code": 2,
|
||||
"status": "passed",
|
||||
"evidence": "F:\\Sync Tool Skyworth\\Work Maps\\cbb-refresh-verify-795\\diagnostics\\runtime-lifecycle-b2\\smoke-74da6fd5\\management-worker"
|
||||
},
|
||||
"owner-probe": {
|
||||
"exit_code": 0,
|
||||
"status": "passed",
|
||||
"evidence": "F:\\Sync Tool Skyworth\\Work Maps\\cbb-refresh-verify-795\\diagnostics\\runtime-lifecycle-b2\\smoke-74da6fd5\\owner-probe"
|
||||
},
|
||||
"dialog-agent": {
|
||||
"status": "passed",
|
||||
"exit_code": 0,
|
||||
"scope": "empty PID set, observe only"
|
||||
},
|
||||
"module_origins": {
|
||||
"status": "passed",
|
||||
"module_count": 62,
|
||||
"source_root": "F:\\Sync Tool Skyworth\\Work Maps\\cbb-refresh-verify-795-review-stack\\src"
|
||||
},
|
||||
"version": "0.2.4b2"
|
||||
},
|
||||
"evidence": "F:\\Sync Tool Skyworth\\Work Maps\\cbb-refresh-verify-795\\diagnostics\\runtime-lifecycle-b2\\smoke-74da6fd5\\result.json",
|
||||
"evidence_sha256": "4f354f3700d09e299e6437d36492fd8b380440eae7e5ec859c90645f16004ac2",
|
||||
"module_bytecode_matches_source": true,
|
||||
"module_count": 62,
|
||||
"modules": [
|
||||
{
|
||||
"module": "cbb_refresh_verify",
|
||||
"source_sha256": "dd960394d88657820dba858792abf0de258e05efceb08ae2f0b39c6ad78bc469"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.application",
|
||||
"source_sha256": "433c22b01df8376651c43cc9fe7f9551b531dcd3b3e590b77cb3ec1bfbfd2de6"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.backup_recovery",
|
||||
"source_sha256": "ea7bb90151e825efb6163e43ed344b62407565005f0a0459c423ba2205539373"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.batch_status",
|
||||
"source_sha256": "918c80dd4f75146baa6b7616ce415ac89ee28f6c1f46b2bfda77bacc998b5b62"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.com_runtime",
|
||||
"source_sha256": "f0f3802d16c791a8bf9dfef44a94917072bfbe8fb3a927d76be8ef0341c7ed35"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.content_check",
|
||||
"source_sha256": "8239c17b6e2452917ed573a7deb3e4c8583eaef91bf3630eff5f424d2e398aa9"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.defaults",
|
||||
"source_sha256": "a1c03192f4a61ad0924b24bb635705b1ee4811d35483a02864200f95edbbebe3"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.desktop_worker",
|
||||
"source_sha256": "1dd449e9885b32cb479970ddb9d1e3b580bc6339f9b491be0a414a1de8054efa"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.diagnostic_open",
|
||||
"source_sha256": "d6c49ffe5a9969d95edbbc896d47a7e100f248380a287f99ba7bb8b92dbb3072"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.dialog_agent",
|
||||
"source_sha256": "6a9b9802912afc4dd670ee9b28845d97bd64fe55fd577815ef729850fcff78db"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.dialog_models",
|
||||
"source_sha256": "f68cee01d927b48364276d3c1f79e63ce8af231878db0b907d292780cfbafb56"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.dialog_probe",
|
||||
"source_sha256": "d61f0c955c961980c9635940eefb9c7947c1fe90b4b6fd844720df41ddb0aa0e"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.dialog_rules",
|
||||
"source_sha256": "3189b476f7ff4678b59212ed7b4081164e038a7cf7662cd895f9019cb3c1edc5"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.dialog_supervisor",
|
||||
"source_sha256": "15c415c2d2e916f0b64ba04416164ff3b50996d70b22d3b4ac2226b5547ac247"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.failed_session",
|
||||
"source_sha256": "7e6f7fa5ebcf2d49f00c5efc5f5d26412704b68e9122e476ac1f672009a98c09"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.icdb_maintenance",
|
||||
"source_sha256": "e81d253d8b4d3e7c1000c45335a392c72b110748675c2c3324ebe524a7252e98"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.icdb_ownership",
|
||||
"source_sha256": "7bf2342c1efa34a2ebcbf27964a40a490220f7146fbb6ef957b8d8dd1e511f03"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.icdb_recovery",
|
||||
"source_sha256": "358c0e9a004f1e0b2127513286e1dffd94b0180a8b7314aa9655462f570b6360"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.integration",
|
||||
"source_sha256": "f188856af69ba25e265988c51db7a6d4263326440d972ca78378b733b891c1ed"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.library_lock",
|
||||
"source_sha256": "eea9021300410cc810eaa0e18aac546c94139f89528f5d68784ef3f943b65ce4"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.library_manager_verify",
|
||||
"source_sha256": "71e16a8581ad44b646be78b480f9812d596a6d162b3eec03d078bf4ea4503195"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.library_reader",
|
||||
"source_sha256": "d4007caa361edd467773e49f721e02671d5a9bcb30741769a57349850b12c438"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.maintenance_entry",
|
||||
"source_sha256": "3b93c25f69d7a961facd8004e20e155a84cc18f06d57b741a9055786ed058990"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.management",
|
||||
"source_sha256": "3d6e2505ce6e21acdea88d59b920229ba1ce2cee6c914ac1b0b8267cf0d34ffc"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.management_transaction",
|
||||
"source_sha256": "32c53caaead05d5db3a31d3e30721e65434e5837095dc0a7812f825603aa37a0"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.mentor_adapter",
|
||||
"source_sha256": "15bde6706c6533d839646b894896237921b89a8a3ce3016aa8161c591dab314f"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.mentor_paths",
|
||||
"source_sha256": "ba48c0003b3eacc88906497b2e43b299ca4536a9f7dae44bbacf6a6ec694c116"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.models",
|
||||
"source_sha256": "9e8209a8b006df923f1d07ccab64bbcfe5d674c4fc5f5426bfbc9b11da4ee105"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.native_add_failures",
|
||||
"source_sha256": "192202732423dc624c5548c75e80bb20973e5087c21d4798c9637f25b6de7e94"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.native_backup",
|
||||
"source_sha256": "7276fa3d9298e85550151cf0c7191d84bd08a18a72df5d854a3c38f1a88b001d"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.native_engineering_identity",
|
||||
"source_sha256": "a241bc3be7dc5a922ce728f1febd3684e79e6e45935589c80a4b1a5933e05df5"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.native_export_guard",
|
||||
"source_sha256": "5120c13e4ef1255d4c61316eb40005c4039c23e41edca4437bd0ef28b543a959"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.native_management",
|
||||
"source_sha256": "27a835bc31cfe0e1a09d767977e5c348d40e246c58d58ce1ef085411afe6d56e"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.native_occupancy",
|
||||
"source_sha256": "7d686079d12217382adace6361cd343d977b91075e3b157cf410ca92d07ffc49"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.native_repair",
|
||||
"source_sha256": "9f024dcb5e3a76369191033474fefd30787b6ae350c315f3cf38e92e5a1f3e98"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.native_repair_ui",
|
||||
"source_sha256": "3eb2af181befea94af8b3b3131edff09589f340bcba777abbe3b67fd31b80393"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.network_path",
|
||||
"source_sha256": "6b5b159502d42a46bf4ee26d5698fd2c6498b359088e2138eae46e9065b13c6f"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.operation_lifecycle",
|
||||
"source_sha256": "28b6cdebd22caaf369eeb8b7236e258b8160a8fa7c7d8bfbf0980979e9eba3ae"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.operation_queue",
|
||||
"source_sha256": "57ad9da8aeedd9cd75a8c5b5fda44044bcb457670a4a323e9e8bb247198074ab"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.owner_probe",
|
||||
"source_sha256": "8dcfd60246cb2979db34d02e0a2d605c334b6f7e2666f22daa2f50c0408bc903"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.pcb_bridge",
|
||||
"source_sha256": "745ef117e984021e8a3d9087a2783c1efe19bed97edcfbcfae7703a291cc6eaa"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.pcb_restore_prompt",
|
||||
"source_sha256": "5342612ad666e3faf5a9a4ce4710e9af458d357c44037135f2837dad436d5cf7"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.post_repair_consent",
|
||||
"source_sha256": "3b1eaff1db58fd311a9dbc5fdcd850911b04cc5afd4e747f70a62b721b8fafa4"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.post_verify_diagnostics",
|
||||
"source_sha256": "2442de485bc0d6a34c4b2d9b10bc5f323ea38f9ff66674119a50f5c6043bac63"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.reimport_recovery",
|
||||
"source_sha256": "66b2ba8f8c2ec9ae8c386d6b1aa74a1fbb6bfb509c4df0a262f8d7a0ca48469e"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.residual_sessions",
|
||||
"source_sha256": "69d39648a2f3c98a297847baf51373632acd881f034a2a011d0c3d27dbec3dfc"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.runtime_logging",
|
||||
"source_sha256": "44ac25430a89c5ffc9e48e88c227e88052f4c815365e8556f67918f3edaba39e"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.runtime_timing",
|
||||
"source_sha256": "c4ed4057b5000e0b86ccc7dd1fe2004d6e0dae29f397fec77b01ad41a81c6367"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.scoped_manifest",
|
||||
"source_sha256": "54cf4288e7850e220b394ae971ea98785eba631f80784a3f9354209e649f6498"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.session_record",
|
||||
"source_sha256": "394719d125b91ff124d707229f4599dcca9229d2c6e653840ef7e02f48c642b6"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.status_bridge",
|
||||
"source_sha256": "05d627d02934a14f5de409472c291d37565a95b836f9c130111aae80612e9196"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.ui",
|
||||
"source_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.ui.backup_notice",
|
||||
"source_sha256": "1a3fa5ac18a267907faf95f36d61b9f08bcbb939eef4d480dd06af1391a81599"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.ui.backup_recovery_dialog",
|
||||
"source_sha256": "621ea2efea85367b0c9bb9790040860a1ac001f40f8834289cb67c96ea0648d1"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.ui.icdb_check_task",
|
||||
"source_sha256": "01985644641ec623ed440433248d9445ab5b9f37d27a843ec7f26267895de397"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.ui.main_window",
|
||||
"source_sha256": "a625b2934a34c86ff30eaf115e50b0560cbb24f3dccf15bbb51574a9808c660d"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.ui.management_dialog",
|
||||
"source_sha256": "93b7a7464161e7448aa78c42ca8742c970e80387f9c6c1b9b4b6a07532da3ebf"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.ui.pcb_restore_dialog",
|
||||
"source_sha256": "b7228d828df235ac51502dc68760d28c4896af02c780e9806e11c32dba7f62da"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.ui.residual_release_dialog",
|
||||
"source_sha256": "ca0e18886457800cae7b543286395f05db1a74eb41e53fc54cfee57f93294368"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.ui.workers",
|
||||
"source_sha256": "4cc9360a4820ded27a7d5ef709fc9f04b1d4804cb1e7a614f6c357ed547da888"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.verify_diagnostics",
|
||||
"source_sha256": "041b77d7d49e4c86338ed5e5741d0d27a2c42bc358f4da54b3efe64af847e9b8"
|
||||
},
|
||||
{
|
||||
"module": "cbb_refresh_verify.verify_runner",
|
||||
"source_sha256": "2c7c37d2b510ab5735cd4a71cb834768c711e31b0ce5dd28b23acb8dcfe22ffb"
|
||||
}
|
||||
],
|
||||
"exe": "F:\\Sync Tool Skyworth\\Work Maps\\cbb-refresh-verify-795\\diagnostics\\runtime-lifecycle-b2\\dist\\CbbRefreshVerify-Background\\CbbRefreshVerify.exe",
|
||||
"exe_sha256": "9051ab52acb67d0d291ae230e7d55d1ce6f580f653d58a82d463b7c42cebb90f",
|
||||
"zip": "F:\\Sync Tool Skyworth\\Work Maps\\cbb-refresh-verify-795\\diagnostics\\runtime-lifecycle-b2\\CbbRefreshVerify-0.2.4b2-runtime-lifecycle-5873b71.zip",
|
||||
"zip_sha256": "5983a4e99884d9551d1dba3d81af88f754ce876c19a780fe82e8ea9fd58a566b",
|
||||
"zip_bytes": 54227147
|
||||
},
|
||||
"frozen_native_boundaries": {
|
||||
"scope": "separate frozen fixture; fake native COM/management boundary",
|
||||
"product_native_database_recovery_validated": false,
|
||||
"results": [
|
||||
{
|
||||
"mode": "save",
|
||||
"stop_kind": "cancel",
|
||||
"status": "passed"
|
||||
},
|
||||
{
|
||||
"mode": "save",
|
||||
"stop_kind": "supervisor-loss",
|
||||
"status": "passed"
|
||||
},
|
||||
{
|
||||
"mode": "management",
|
||||
"stop_kind": "cancel",
|
||||
"status": "passed"
|
||||
},
|
||||
{
|
||||
"mode": "management",
|
||||
"stop_kind": "supervisor-loss",
|
||||
"status": "passed"
|
||||
}
|
||||
],
|
||||
"evidence": "F:\\Sync Tool Skyworth\\Work Maps\\cbb-refresh-verify-795\\diagnostics\\runtime-lifecycle-b2\\frozen-boundaries-cdb9d884\\result.json",
|
||||
"evidence_sha256": "9cdc149a6fa545206c361aaba278ef54c9ee2529e9a09b440c5fcf9378fc8529",
|
||||
"module_bytecode_matches_source": true,
|
||||
"module_count": 47,
|
||||
"validation_helpers": [
|
||||
{
|
||||
"file": "tests\\support\\runtime_lifecycle_frozen_fixture.py",
|
||||
"sha256": "b87761c06a300f0d93bce864d3d31e045f2135324b2a9a42f8682ccbff09ad22"
|
||||
},
|
||||
{
|
||||
"file": "tests\\support\\runtime_lifecycle_frozen_boundaries.py",
|
||||
"sha256": "bf98533a1c06ccf4453d20b3804323779719e697141b8dc64fa679960a979cfd"
|
||||
},
|
||||
{
|
||||
"file": "tests\\support\\runtime_lifecycle_frozen_smoke.py",
|
||||
"sha256": "b11e0aac71c1079625ac9832dc5c38197bc80110478c4d9e02c2a3bc58a2a2d0"
|
||||
}
|
||||
],
|
||||
"helpers_copied_after_full_suite": true,
|
||||
"note": "Tracked helper files are byte-identical copies of the scripts executed from diagnostics. Not shipped; do not replace real application-button acceptance."
|
||||
},
|
||||
"not_run": [
|
||||
"Real Mentor isolated-copy application-button Save/Close and management-loss scenarios",
|
||||
"Windows 10 and cross-machine shared-library concurrency",
|
||||
"Field ICDB disconnected-session recovery and data-version/READY acceptance"
|
||||
],
|
||||
"auto_repair_enabled": false,
|
||||
"production_native_writes_performed": false,
|
||||
"merged_or_published": false,
|
||||
"issues_closed": false,
|
||||
"pull_request": {
|
||||
"number": 13,
|
||||
"url": "https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/pulls/13",
|
||||
"draft": true,
|
||||
"base": "codex/review-residual-release",
|
||||
"creation_head": "8e946c6e7a115a1ac22101b97df9b3fc6e2862f0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
{
|
||||
"date": "2026-11-09",
|
||||
"scope": "Latest comments #309/#310/#313 only; older deep-review backlog excluded by user",
|
||||
"integration_head_before_validation_commit": "b1c36e3ca6d6680d0b656a725a1db871d5ffabbd",
|
||||
"branch_heads": {
|
||||
"codex/review-native-backend": "b7baa24b5ed87256fb846236b08c75ff02887e9c",
|
||||
"codex/review-ui-integration": "e73f9c6edcb36a18fdd8a17b565cc1fb7c97f26b",
|
||||
"codex/review-residual-release": "651b539d0ef491b3fd410031b9f981d71272aac9",
|
||||
"codex/runtime-lifecycle-safety": "b1c36e3ca6d6680d0b656a725a1db871d5ffabbd"
|
||||
},
|
||||
"environment": {
|
||||
"python": "3.12.10",
|
||||
"windows": "10.0.26200"
|
||||
},
|
||||
"full_suite": {
|
||||
"tests": 1742,
|
||||
"failures": 0,
|
||||
"errors": 0,
|
||||
"skipped": 0,
|
||||
"duration_seconds": 293.056,
|
||||
"xml": "F:\\Sync Tool Skyworth\\Work Maps\\cbb-refresh-verify-795\\diagnostics\\2026-11-09-latest-stack-full-1742.xml",
|
||||
"source_xml": "F:\\Sync Tool Skyworth\\Work Maps\\cbb-refresh-verify-795\\diagnostics\\cbb-refresh-verify-795-review-stack-fixes-full.xml",
|
||||
"xml_sha256": "e00376d01fa26dd8e62d065d700f8cc200000665a6958536d109336119f8a0c0"
|
||||
},
|
||||
"focused_suites": {
|
||||
"cbb-refresh-verify-795-backend-fixes": {
|
||||
"tests": 94,
|
||||
"failures": 0,
|
||||
"errors": 0,
|
||||
"skipped": 0,
|
||||
"duration_seconds": 41.802,
|
||||
"xml": "F:\\Sync Tool Skyworth\\Work Maps\\cbb-refresh-verify-795\\diagnostics\\2026-11-09-cbb-refresh-verify-795-backend-fixes-latest-focused-94.xml",
|
||||
"source_xml": "F:\\Sync Tool Skyworth\\Work Maps\\cbb-refresh-verify-795\\diagnostics\\cbb-refresh-verify-795-backend-fixes-fixes-focused.xml",
|
||||
"xml_sha256": "d8580bcc766c7ad6d3ce1d9de7d44b496afaaa8c3489cf01245f1d8a7d15500c"
|
||||
},
|
||||
"cbb-refresh-verify-795-ui-fixes": {
|
||||
"tests": 43,
|
||||
"failures": 0,
|
||||
"errors": 0,
|
||||
"skipped": 0,
|
||||
"duration_seconds": 5.554,
|
||||
"xml": "F:\\Sync Tool Skyworth\\Work Maps\\cbb-refresh-verify-795\\diagnostics\\2026-11-09-cbb-refresh-verify-795-ui-fixes-latest-focused-43.xml",
|
||||
"source_xml": "F:\\Sync Tool Skyworth\\Work Maps\\cbb-refresh-verify-795\\diagnostics\\cbb-refresh-verify-795-ui-fixes-fixes-focused.xml",
|
||||
"xml_sha256": "0ed470d756f0b387ca9fbf4f4891bd60abfc3faf535e67c06d6640557d627753"
|
||||
},
|
||||
"cbb-refresh-verify-795-review-stack": {
|
||||
"tests": 136,
|
||||
"failures": 0,
|
||||
"errors": 0,
|
||||
"skipped": 0,
|
||||
"duration_seconds": 16.117,
|
||||
"xml": "F:\\Sync Tool Skyworth\\Work Maps\\cbb-refresh-verify-795\\diagnostics\\2026-11-09-cbb-refresh-verify-795-review-stack-latest-focused-136.xml",
|
||||
"source_xml": "F:\\Sync Tool Skyworth\\Work Maps\\cbb-refresh-verify-795\\diagnostics\\cbb-refresh-verify-795-review-stack-fixes-focused.xml",
|
||||
"xml_sha256": "2087bfa02a0251deee535acda7454c0967b1f11aa5c7125296efc78c141fec59"
|
||||
}
|
||||
},
|
||||
"compileall": "passed",
|
||||
"diff_check": "passed",
|
||||
"independent_review": "No important introduced findings before or after integration",
|
||||
"controlled_private_desktop_fixture": "passed",
|
||||
"tested_files_sha256": {
|
||||
".gitattributes": "a68c9f317ed6e4131c72269b98403c7a3f9c08d5d03e710425301bd50273e791",
|
||||
"src/cbb_refresh_verify/application.py": "b76ff891d77f0a7dba8feeb1f5ae5745ee83dee2fa46c585c187dbf9bb1c39d2",
|
||||
"src/cbb_refresh_verify/library_lock.py": "8b3286d36ad686f65ec7e30eded9c4d0f8a629ca214b39812dfba496292da976",
|
||||
"src/cbb_refresh_verify/residual_sessions.py": "b5d38a06cb2902c3612edb75b1ef83596524f02b6cf7890f6541f210d3e380ce",
|
||||
"tests/test_residual_sessions.py": "f34c77a11d2a2b08c5670a9809474afd84b212016a27b104249e5fddb4675f1f",
|
||||
"tests/test_review313_residual_isolation.py": "4052ca51c35787a8df9b63e79febd38b666da98c09976fffb34f4361381d8b4d",
|
||||
"tests/test_review_foreign_release_evidence.py": "cbf2af02418f6bd3ec720a7a7658cf97f06d1a6e12009fdff2a99f465711591e"
|
||||
},
|
||||
"icon_sha256": {
|
||||
"ico": "62d4472ebaa94f9b39aebae06459685d3322041d0e1a7ada9f368cfd816ba1d6",
|
||||
"png": "840f657fd7c622d9afd78625a64ed8ad04c90a895dd3c9fd37eebae543cdebe8",
|
||||
"svg": "cbba5b3f339cbeb5eb43012709237359442ef67c69fc5b6679a8ee4c0a1b7328"
|
||||
},
|
||||
"automatic_icdb_repair": false,
|
||||
"candidate_rebuilt": false,
|
||||
"not_verified": [
|
||||
"Real Mentor operations",
|
||||
"Frozen execution of this revision",
|
||||
"Windows 10",
|
||||
"Shared/network/cross-machine release"
|
||||
],
|
||||
"merged": false,
|
||||
"issue_closed": false
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
# Latest PR review follow-up: 2026-11-09
|
||||
|
||||
The user selected the November 9 latest re-review comments, excluding the older November 6 deep-review backlog.
|
||||
|
||||
| PR/comment | Result | Source/validation |
|
||||
| --- | --- | --- |
|
||||
| #10 / #309 | Proof names foreign CBB checkpoints and distinguishes requested block from effective BLOCK/LIBRARY scope. | `b7baa24`; 94 backend/lease regressions passed. See `2026-11-09-pr10-review309.md`. |
|
||||
| #11 / #310 | No new blocking finding; backend synchronized in `e73f9c6`. Existing pause semantics retained. | 43 UI/background/queue regressions passed on the UI branch. |
|
||||
| #12 / #313 | Incomplete window reads isolated by PID; bounded repeated evidence; native Cancel retains preview scope. | `651b539`; 116 relevant regressions passed, including a real controlled private desktop/window. See `2026-11-09-pr12-review313.md`. |
|
||||
| #13 integration | Both sides of the residual preview conflict retained: runtime write protection and per-PID read/scope metadata. | Integration merge `b1c36e3`; 136 focused integrated regressions passed. Full result and file hashes in the accompanying JSON. |
|
||||
|
||||
## Line endings
|
||||
|
||||
At the chain tip only, `application.py` is normalized from CRLF to LF. Replacing its LF bytes with CRLF reproduces its prior bytes exactly, and `git diff --ignore-space-at-eol` is empty for this file. `main_window.py` already uses LF. Two specific `.gitattributes` rules pin these files to LF; the global `* -text` rule and every other source file's line-ending policy remain unchanged. No repository-wide normalization or EditorConfig layer is added.
|
||||
|
||||
## Independent review
|
||||
|
||||
The reviewer found no important introduced P1/P2 in the backend/residual changes. Its focused check passed 45 tests with the private-desktop fixture excluded; the coordinator separately ran that actual fixture successfully. A second inspection of the integration confirmed that PR13's active-write, retained-session acknowledgment and durable release records coexist with the new evidence and window-read boundaries. No tests or native operations ran during that integration inspection.
|
||||
|
||||
## Reproduction
|
||||
|
||||
Use the existing `diagnostics/run_review_fixes.py` wrapper from the original workspace against each linked worktree; it isolates the test mutex and sets the intended source path/Qt offscreen. The final full run, compileall and git diff --check results are in `2026-11-09-latest-pr-stack-validation.json`, including evidence hashes and source/test file hashes.
|
||||
|
||||
Current ICO/PNG/SVG hashes match the previously corrected blue check/circular-arrow assets. No candidate executable or ZIP was rebuilt: the previous iconfix package does not contain these fixes. These are source/PR validations, not real Mentor/Windows 10/shared-network/cross-machine acceptance. ICDB automatic Repair remains OFF. PR #3 remains a historical umbrella already covered by #10–#13. The PRs stay Draft; no merge to main, formal release or issue closure is performed.
|
||||
@@ -0,0 +1,53 @@
|
||||
{
|
||||
"date": "2026-11-09",
|
||||
"review_url": "https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/pulls/13#issuecomment-319",
|
||||
"base_commit": "96e179ba6529eefd1401a012155cd7b7cbc0ffc3",
|
||||
"environment": {
|
||||
"python": "3.12.10",
|
||||
"windows": "10.0.26200"
|
||||
},
|
||||
"full_suite": {
|
||||
"tests": 1732,
|
||||
"failures": 0,
|
||||
"errors": 0,
|
||||
"skipped": 0,
|
||||
"duration_seconds": 501.166,
|
||||
"xml": "F:\\Sync Tool Skyworth\\Work Maps\\cbb-refresh-verify-795\\diagnostics\\cbb-refresh-verify-795-review-stack-fixes-full.xml",
|
||||
"xml_sha256": "578dd4b01db5c18ce657430ce3b2cd2dba8516d8191bdd31bf4e0df78187b3ba",
|
||||
"warnings": [
|
||||
"Existing pywinauto Revert to STA COM threading mode warning"
|
||||
]
|
||||
},
|
||||
"focused_suite": {
|
||||
"passed": 79
|
||||
},
|
||||
"compileall": "passed",
|
||||
"diff_check": "passed",
|
||||
"independent_review": "No remaining important findings in the scoped diff; durable completion feedback addressed",
|
||||
"tested_files_sha256": {
|
||||
"src/cbb_refresh_verify/desktop_worker.py": "173a951d510e78e088c439768ecfe31ab198723e7717b314b4a74a9d590a1fe0",
|
||||
"src/cbb_refresh_verify/library_lock.py": "391fb2f0b25f400676ba230472fb3bbd4a0d994ed5a8dfee46f8f32c7f198219",
|
||||
"src/cbb_refresh_verify/mentor_adapter.py": "1fc8c98d5508120e03bf001a42dd3e0da7b165eb18c90f1aed83147d17db8638",
|
||||
"src/cbb_refresh_verify/native_management.py": "96c2fe613a657d110302c8f7cc033b91ef256e168036f4794eb39be475e69de8",
|
||||
"src/cbb_refresh_verify/residual_sessions.py": "a19622be3e959a7e64bf9de953450203499fb82618da8537307e5f61ef4d793b",
|
||||
"src/cbb_refresh_verify/session_record.py": "c4c5771d11d7469980c02f2fb264b26e5ee26634a37daae008dbb65097ab4e0c",
|
||||
"src/cbb_refresh_verify/ui/main_window.py": "e46096ce784933f3ab47e4c316f3c84e3e5cf07242489323f6234b61aeb22f80",
|
||||
"src/cbb_refresh_verify/ui/residual_release_dialog.py": "ec7566bac6d92845f98933bffd4c06f31eeec42946e69699aff94e31f9a8baef",
|
||||
"tests/test_incident_safety.py": "52f3ccb04db8971bf38628c2bd334d4fd79795e97de6538f6f66cb35f7123ece",
|
||||
"tests/test_integration.py": "9e9d30692607c889e1e3744a63c79c68e3af7d4c86804e0bcebe48e68765086c",
|
||||
"tests/test_management_supervision.py": "107196ce8a00dd76e7e3e83fb47ae2e67c857fa234492ba593bf71a7d7e1c5e5",
|
||||
"tests/test_residual_release_dialog.py": "7d2bf95afc2f9112b9433c7d2fefde3b35b5e85a70a6bd506471c039e2505509",
|
||||
"tests/test_review_319.py": "831fd34d426abb4436b9132bfb7ed754994155a34ac60a59378dee0964b54d28"
|
||||
},
|
||||
"not_verified": [
|
||||
"Frozen execution of this revision",
|
||||
"Real Mentor native writes/save/close during supervisor loss",
|
||||
"Windows 10",
|
||||
"Shared network/cross-machine release",
|
||||
"ICDB field recovery"
|
||||
],
|
||||
"automatic_icdb_repair": false,
|
||||
"candidate_rebuilt": false,
|
||||
"merged": false,
|
||||
"issue_closed": false
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
# PR #13 review 319 validation
|
||||
|
||||
Review: https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/pulls/13#issuecomment-319
|
||||
|
||||
Baseline: `96e179ba6529eefd1401a012155cd7b7cbc0ffc3`.
|
||||
|
||||
## Changes
|
||||
|
||||
- Successful explicit resource proof acknowledges the retained queue entries captured before proof. The alias-set identity is a generation token: unrelated libraries and newer handoffs remain retained. Scoped proof acknowledges only the matching block.
|
||||
- Final observer outcomes remain available in the residual dialog after its observer ends. The existing refresh/confirm actions provide a running-session retry path. Successful release records a matching operation's RELEASED observation, so history refresh does not resurrect it as unconfirmed. Journal failure is reported separately from the established release fact.
|
||||
- Discovery observes process identities only. It never opens production databases exclusively, deletes coordination checkpoints, closes clients, or replays operations. Startup observers use the same read-only mode; only explicit release or already-authorized task reconciliation can establish resource release.
|
||||
- Supervisor loss sets cancellation independently of evidence-write success. An idle worker exits with code 75 only when its matching journal and synchronized in-memory phase both confirm no pending native write and every registered helper has exited. Missing/unknown/stale-active state retains the worker. The watchdog rechecks returned calls and cannot authorize a subsequent native write/helper. Native children are never terminated by this exit; worker exit is not database-release or Save-success evidence.
|
||||
- Worker phase persistence and watchdog journal reads share a gate to avoid a Windows sharing violation between reading the JSON and atomically replacing it. The dead `_terminate_pid` function is removed; cleanup tests observe actual process-termination boundaries.
|
||||
|
||||
## Verification
|
||||
|
||||
Commands run through the existing test wrapper with a dedicated mutex namespace and Qt offscreen; no user/native Mentor process is part of these fixtures.
|
||||
|
||||
```
|
||||
python -u -X utf8 diagnostics/run_review_fixes.py "F:/Sync Tool Skyworth/Work Maps/cbb-refresh-verify-795-review-stack"
|
||||
python -X utf8 -m compileall -q src tests
|
||||
git diff --check
|
||||
```
|
||||
|
||||
The focused session/watchdog/management/dialog/lease regression run passed 79 tests. The initial regressions were observed failing before the corresponding fixes: explicit proof left a library unavailable, history scan attempted release, orphan idle workers stayed alive, residual refresh omitted runtime records, and successful release reappeared as unconfirmed. Real harmless Windows subprocess fixtures cover PRECALL/POSTCALL, NATIVE_CALL/CLOSING, unknown/missing/stale journals, failed cancel/evidence writes, and rechecking after return.
|
||||
|
||||
Full-suite result is recorded in `2026-11-09-review-319-validation.json`. Independent review found no remaining P1/P2 in this scoped diff; its observation about durable completion was addressed and regression-tested.
|
||||
|
||||
## Limits
|
||||
|
||||
This is source/PR validation. The earlier `0.2.4b2-iconfix-44bb734` executable has not been rebuilt with these changes and must not be used as evidence for this revision. Its icon assets are preserved.
|
||||
|
||||
Not validated here: frozen execution of this revision, real Mentor Save/Close or library writes during supervisor loss, Windows 10, shared/network or cross-machine release. ICDB automatic Repair remains disabled. No field-recovery acceptance, merge, formal publication or issue closure is implied.
|
||||
@@ -0,0 +1,370 @@
|
||||
# CBB 原生操作生命周期与只读边界 Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. 本计划默认在当前会话逐项执行,不隐含授权创建额外代理。
|
||||
|
||||
**Goal:** 消除保存阶段的自动强杀、管理工作进程失联后的无监督写入,以及 legacy 状态读取的隐式弹窗操作,同时保持工具可用和独立任务可继续。
|
||||
|
||||
**Architecture:** 复用现有 NativeQueue、LibraryLock、私有桌面和库外证据体系,补充一个保存事实解析模块与一个会话记录模块。先实现保存/停止策略,再补管理监督与跨重启观察,最后收紧读取路径并联调 GUI/CLI;不重写调度框架。
|
||||
|
||||
**Tech Stack:** Python 3.12、PySide6、pywin32、Windows、Mentor EE7.9.5、现有 32 位 cscript/VBS 与状态桥;不增加运行时依赖。
|
||||
|
||||
**Spec:** [2026-11-06-runtime-lifecycle-safety-design.md](../specs/2026-11-06-runtime-lifecycle-safety-design.md)
|
||||
|
||||
**Status:** 用户已于 2026-11-06 授权按本计划实施,正在独立分支执行。基线为 `5eb4b2d7ed09947f19310ba80ba3b9a2a09b6f7d`;本文件没有修改生产行为。
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- 技术栈保持 Python 3.12、PySide6、pywin32、Mentor EE7.9.5,不增加运行时依赖。
|
||||
- 检验、ICDB 批量检查、中心库管理保持独立;ICDB 自动 Repair 继续关闭。
|
||||
- READY 条目继续排除维护;状态读取失败不伪造 READY,也不直接判定 ICDB 损坏。
|
||||
- 自动停止、超时、失败清理、监督器失联都不得强杀可能正在原生写入的进程或 COM 保存 helper。
|
||||
- UI、搜索、筛选、日志查看和只读浏览保持可用;一个未释放写入不得占着全局执行票据等待无限长时间。
|
||||
- 同库仍在进行的写入不可并发启动;已释放的单项失败不得阻止独立项,其他独立库可排队获得执行机会。
|
||||
- 历史 JSON 只触发身份及实际资源复核,不直接构成真实占用;报告错误不得伪造占用或永久禁用入口。
|
||||
- 不自动选择历史版本、重新导入、恢复备份、删除原生锁/地址文件或修改 LMC 伪造状态。
|
||||
- 不新增全库自动备份或全库内容哈希;此前确认的人工备份策略不变。
|
||||
- 确认结束客户端与正常停止分开;本轮不增加“放弃正在进行的保存”按钮,不自动放宽服务器保护。
|
||||
- 原生动作、证据读取、路径解析、进程查询和重启核对都放在非 GUI 线程;GUI 只更新视图和提交用户意图。
|
||||
- 保留 VerifyRequest / VerifyResult 的现有参数及 safe_to_continue 兼容性,只追加有默认值的事实字段。
|
||||
- 保持原有文件行尾,不进行与功能无关的整文件规范化。
|
||||
- 开发验证只使用临时数据、模拟原生边界或隔离副本;不在生产库制造保存中断。
|
||||
|
||||
## 实施起点与三个交付单元
|
||||
|
||||
执行前重新读取 PR #10/#11/#12、main 和本地工作树,不将旧评论当成新实现的批准。另开 `codex/runtime-lifecycle-safety` 临时分支,使用独立工作树;保留用户原始脏工作区与已运行程序,不 force-push。
|
||||
|
||||
- **A:保存与停止闭环。** Task 1–4 作为一个功能单元验收;前面的模型和 primitive 可以独立提交,接线未完成时不交付候选程序。
|
||||
- **B:管理失联与重启核对。** Task 5–6,在 A 的协议上扩展管理;不增加自动清除锁文件。
|
||||
- **C:只读边界与交付验证。** Task 7–9;最终创建仅含本轮差分的草稿 PR,按 A/B/C 给出审查顺序。
|
||||
|
||||
### Task 1:建立保存事实解析与停止判据
|
||||
|
||||
**Files:**
|
||||
- Create: `src/cbb_refresh_verify/operation_lifecycle.py`
|
||||
- Create: `tests/test_operation_lifecycle.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: 本轮 helper 的标记序列与独立进程/资源观察结果;不读取文件或调用 COM。
|
||||
- Produces: `classify_save_state(markers: Sequence[str], *, helper_exited: bool | None, native_released: bool | None, forced: bool = False) -> dict[str, str | bool]`。
|
||||
- Produces: `stop_disposition(*, call_started: bool | None, call_returned: bool | None, identity_confirmed: bool) -> str`,返回 CANCEL_BEFORE_CALL / WAIT_FOR_RETURN / CLEANUP_RETURNED / OBSERVE_UNCONFIRMED。
|
||||
- 返回字段固定为 save_state、close_state、helper_state、resource_state、interrupted、detail,取值见设计第 4 节;其他任务不得另造不兼容枚举。
|
||||
|
||||
- [x] **Step 1: 写失败测试,证明 Save/Close/释放不能互相替代。**
|
||||
|
||||
```python
|
||||
from cbb_refresh_verify.operation_lifecycle import classify_save_state, stop_disposition
|
||||
|
||||
def test_saved_but_not_closed_is_not_unsaved_or_fully_released():
|
||||
facts = classify_save_state(["SAVE_START", "SAVE_OK", "CLOSE_START"],
|
||||
helper_exited=False, native_released=False)
|
||||
assert facts["save_state"] == "COMMITTED"
|
||||
assert facts["close_state"] == "UNKNOWN"
|
||||
assert facts["resource_state"] == "RETAINED"
|
||||
|
||||
def test_process_exit_without_save_result_is_unknown():
|
||||
facts = classify_save_state(["SAVE_START"], helper_exited=True, native_released=True)
|
||||
assert facts["save_state"] == "UNKNOWN"
|
||||
assert facts["resource_state"] == "RELEASED"
|
||||
|
||||
def test_an_unreturned_call_requires_waiting():
|
||||
assert stop_disposition(call_started=True, call_returned=False,
|
||||
identity_confirmed=True) == "WAIT_FOR_RETURN"
|
||||
```
|
||||
|
||||
- [x] **Step 2: 运行并确认 RED。** `python -m pytest -q tests/test_operation_lifecycle.py`;预期缺少新模块/函数。再加取消前、SAVE_REJECTED、CLOSE_FAILED、日志截断/矛盾、forced=True 的行为断言,不把进程退出断言成保存完成。
|
||||
- [x] **Step 3: 实现纯判据。** 核心映射从明确证据出发:
|
||||
|
||||
```python
|
||||
save_state = ("COMMITTED" if "SAVE_OK" in markers else
|
||||
"REJECTED" if "SAVE_REJECTED" in markers else
|
||||
"NOT_STARTED" if "CANCELLED_BEFORE_SAVE" in markers else "UNKNOWN")
|
||||
resource_state = ("RELEASED" if native_released is True and helper_exited is True else
|
||||
"RETAINED" if native_released is False or helper_exited is False else "UNKNOWN")
|
||||
```
|
||||
|
||||
不把 UNKNOWN 当 False;矛盾标记降为 UNKNOWN 并记录原因。`forced=True` 不能把 UNKNOWN 的保存状态升级为成功。
|
||||
- [x] **Step 4: 运行该文件及 `tests/test_runtime_timing.py`,确认已有标记消费保持兼容。**
|
||||
- [x] **Step 5: 提交。** `git commit -m "feat: distinguish save close and resource release facts"`。
|
||||
|
||||
### Task 2:保存 helper 的启动门和完整返回事实
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/cbb_refresh_verify/save_verified_block.vbs`
|
||||
- Modify: `src/cbb_refresh_verify/desktop_worker.py:17`(launch_save_helper)
|
||||
- Modify: `src/cbb_refresh_verify/mentor_adapter.py:818`(保存启动和等待)
|
||||
- Modify: `tests/test_save_helper_runtime.py`
|
||||
- Modify: `tests/test_failure_lifecycle.py`
|
||||
- Create: `tests/test_save_helper_identity.py`(基线没有此文件,用于 helper 启动门和精确身份测试)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 1 的 `classify_save_state`。
|
||||
- Produces: VBS 标记 CANCELLED_BEFORE_SAVE / SAVE_START / SAVE_OK / SAVE_REJECTED / POST_SAVE_FAILED / CLOSE_START / CLOSE_OK / CLOSE_FAILED,以及既有 LICENSE_OK / IS_SAVED / QUIT_OK。
|
||||
- `launch_save_helper(command, **kwargs)` 保持原调用兼容;生产调用附加第 4 个 VBS 参数 `start_gate`,helper 未放行时不进入 COM;已有三参数 harness 保留兼容覆盖。
|
||||
- helper 启动门在 30 秒内未放行或取消时,以明确的启动前取消结果退出。门放行前记录精确 helper 身份,不靠事后按父 PID 猜测。
|
||||
|
||||
- [x] **Step 1: 扩展真实 cscript harness,先复现保存中取消和保存后关闭失败。** 继续使用 `tests/test_save_helper_runtime.py` 中实际 VBS 源码,仅替换 COM 创建。FakeDoc.Save 内创建取消文件后返回 True;FakeDoc.Close 返回 False 或延迟返回。断言:
|
||||
|
||||
```python
|
||||
assert "SAVE_OK" in completed.stdout
|
||||
assert "SAVE_REJECTED" not in completed.stdout
|
||||
assert "CLOSE_FAILED" in completed.stdout
|
||||
assert completed.returncode != 0
|
||||
```
|
||||
|
||||
另写门未打开的 harness,在 FakeDoc.Save 中写 `save-called.txt`;取消/门超时后该文件必须不存在。
|
||||
- [x] **Step 2: 运行 `python -m pytest -q tests/test_save_helper_runtime.py tests/test_failure_lifecycle.py -k "save or helper"`,确认新行为失败。** 不运行真实 Mentor 保存。
|
||||
- [x] **Step 3: 按调用边界写标记,取消只阻止尚未开始的写入。** 局部错误检查示例:
|
||||
|
||||
```vb
|
||||
CheckCancellationBeforeSave
|
||||
WScript.Echo "SAVE_START"
|
||||
On Error Resume Next
|
||||
operationOK = doc.Save()
|
||||
saveError = Err.Number
|
||||
saveDescription = Err.Description
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
If saveError <> 0 Then
|
||||
WScript.Echo "SAVE_RESULT_UNKNOWN|" & CStr(saveError) & "|" & saveDescription
|
||||
WScript.Quit 11
|
||||
End If
|
||||
If Not operationOK Then
|
||||
WScript.Echo "SAVE_REJECTED"
|
||||
WScript.Quit 4
|
||||
End If
|
||||
WScript.Echo "SAVE_OK"
|
||||
```
|
||||
|
||||
把 `saveError/saveDescription` 加入 Option Explicit 的 Dim。IsSaved/后置同步/Close 使用同样局部检查并写各自原因,不抹掉 SAVE_OK;取消后只在精确文档、已保存且没有未知模态提示时做既有正常关闭,不再次 Save、不自动放弃脏文档。
|
||||
- [x] **Step 4: 保存等待不再因取消文件出现就直接抛错丢弃监督。** 本任务先提供可观察的调用返回事实;Task 4 再统一所有生产停止入口,不能保留“保存脚本启动后随便 terminate”的中间交付。
|
||||
- [x] **Step 5: 重跑真实 cscript harness、身份核对和 runtime_timing 回归,通过后提交。** `git commit -m "fix: preserve native save results across cancellation"`。
|
||||
|
||||
### Task 3:受控会话记录和后台观察交接
|
||||
|
||||
**Files:**
|
||||
- Create: `src/cbb_refresh_verify/session_record.py`
|
||||
- Create: `tests/test_session_record.py`
|
||||
- Modify: `src/cbb_refresh_verify/desktop_worker.py`
|
||||
- Modify: `src/cbb_refresh_verify/library_lock.py`
|
||||
- Modify: `src/cbb_refresh_verify/network_path.py`
|
||||
- Test: `tests/test_network_release_safety.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: `write_session_record(path: Path, record: Mapping[str, object]) -> None`,原子 pending→replace,flush/fsync。
|
||||
- Produces: `read_session_record(path: Path, *, evidence_root: Path) -> dict`,协议 `cbb-runtime-session`、version=1,最大 64 KiB,拒绝重解析点/越界路径。
|
||||
- Produces: `reconcile_session_record(path: Path, *, evidence_root: Path) -> dict`,仅后台核对,返回 ACTIVE / RELEASED / IDENTITY_CHANGED / UNCONFIRMED、原因、匹配库及独立 release_proof;不终止进程、不执行写操作。
|
||||
- Produces: `observe_retained_session(path: Path, *, evidence_root: Path, stop=None, progress=None) -> dict`,1 秒为观察间隔,单次进程查询有界;退出观察不表示原生进程退出。
|
||||
- immutable `session.json`、单写者 `worker-state.json`、watchdog 的 `supervisor-lost.json`、观察者的 `observation-<observer_id>.json` 分开,不互相覆盖。
|
||||
- 等待循环只使用精确句柄的零等待观察,不持有 `_guard`/全局原生互斥,不循环扫描全库。退出后才尝试独立释放证明;通道忙只延后该观察,不把其他库也设为不可用。
|
||||
|
||||
- [x] **Step 1: 写协议/重启身份测试。** 使用临时 JSON 和本测试创建的 sleep 子进程;在记录上替换 created 或 executable,确保返回 IDENTITY_CHANGED 而不是结束新进程。损坏 JSON、超过 64 KiB 和越界目录返回 UNCONFIRMED。
|
||||
|
||||
```python
|
||||
def test_record_outside_controlled_root_is_observation_only(tmp_path):
|
||||
from cbb_refresh_verify.session_record import reconcile_session_record
|
||||
owned = tmp_path / "owned"
|
||||
owned.mkdir()
|
||||
external = tmp_path / "external-session.json"
|
||||
external.write_text("{}", encoding="utf-8")
|
||||
outcome = reconcile_session_record(external, evidence_root=owned)
|
||||
assert outcome["status"] == "UNCONFIRMED"
|
||||
assert outcome["release_proof"] is None
|
||||
```
|
||||
|
||||
PID 复用测试在本测试创建的进程身份记录上替换 created/image,再走同一个 reconcile 入口;只模拟外部进程观察边界,不用实现返回值代替被测流程。
|
||||
- [x] **Step 2: 运行 `python -m pytest -q tests/test_session_record.py`,确认 RED。**
|
||||
- [x] **Step 3: 实现精确身份、记录路径约束与独立释放证明。** 核对 supervisor/worker/helper/native 的创建时间、映像和当前用户/Windows 会话。PID 不在快照中不能直接生成 RELEASED;复用现有 `release_retained_library` 证明,不删 `.lock`/sAddress.adr。
|
||||
- [x] **Step 4: 增加后台交接测试。** A 库 helper 保持活跃,转观察后释放 NativeQueue action;同库写请求仍等待,B 库请求可运行。映射直到匹配库独立释放证明成立才归还;调用 `process.close()` 不得丢失观察所需的精确句柄。
|
||||
- [x] **Step 5: 验证报告写失败不终止活跃调用、不把记录存在本身当占用。** 内存观察保留,下一次可重新核对。通过后提交 `git commit -m "feat: persist and reconcile owned native sessions"`。
|
||||
|
||||
### Task 4:统一用户停止、超时、finally、kill 和 watchdog
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/cbb_refresh_verify/verify_runner.py:231`、`:951`、`:1067`、`:1090`、`:1128`
|
||||
- Modify: `src/cbb_refresh_verify/desktop_worker.py:25`、`:174`、`:182`、`:191`、`:224`
|
||||
- Modify: `src/cbb_refresh_verify/mentor_adapter.py:830`、`:888`、`:1005`
|
||||
- Modify: `src/cbb_refresh_verify/verify_runner.py`(VerifyResult 默认字段与兼容 auto_repair 停止传播)
|
||||
- Modify: `src/cbb_refresh_verify/defaults.py`(NATIVE_WRITE_STOP_WAIT_SECONDS)
|
||||
- Modify: `src/cbb_refresh_verify/native_repair.py:127`(增加 stop=None 并向现有 run_native_repair 传播;默认 auto_repair 不变)
|
||||
- Test: `tests/test_failure_lifecycle.py`
|
||||
- Test: `tests/test_abnormal_shutdown.py`
|
||||
- Test: `tests/test_verify_worker_stability.py`
|
||||
- Test: `tests/test_incident_safety.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 1–3 的事实解析、停止判据与后台观察。
|
||||
- `_stop_worker(process, *, timeout=5)` 保持 bool 返回兼容,但不再对未知/活跃写调用自动 kill;返回 False 表示尚未确认 worker 退出,调用方转受控观察。
|
||||
- `VerifyResult.write_outcome: dict | None = None`、`session_record_path: Path | None = None` 追加在现有默认字段之后。
|
||||
- `attempt_recovery(request, diagnosis, evidence_root, *, progress=None, stop=None)` 只补取消传播,不使其默认启用。
|
||||
- 保存等待转后台的默认界限为 120 秒,放在 `defaults.py` 的 `NATIVE_WRITE_STOP_WAIT_SECONDS`;普通合作式停止等待保持 5 秒。
|
||||
|
||||
- [x] **Step 1: 替换冲突的旧期望并增加跨组件失败测试。** `test_stop_cancels_then_stops_automation_client_after_deadline` 不能再锁定保存中会 kill 的行为。用本测试创建的 helper 进程触发 `_stop_worker`,使 `kill` 和 `stop_automation_clients` 在活跃 Save 时被调用即失败:
|
||||
|
||||
```python
|
||||
class SavingWorker:
|
||||
def request_stop(self): self.requested = True
|
||||
def wait(self, timeout): raise TimeoutError("native Save pending")
|
||||
def poll(self): return None
|
||||
def kill(self): raise AssertionError("pending Save was killed")
|
||||
def stop_automation_clients(self): raise AssertionError("save helper was killed")
|
||||
|
||||
def test_cancel_preserves_pending_save():
|
||||
worker = SavingWorker()
|
||||
assert _stop_worker(worker, timeout=0) is False
|
||||
assert worker.requested
|
||||
```
|
||||
|
||||
这个 fake 只用于停止分派边界;另用实际 sleep/helper 与真实 VBS harness 验证生命周期,不只断言 mock 被调用。
|
||||
- [x] **Step 2: 覆盖五个触发入口。** 用户停止、活动超时、对话框错误、finally 收尾、父进程退出分别触发;verify 生产配置 `stop_clients=True` 必须在测试中出现,不只测默认参数 False。
|
||||
- [x] **Step 3: 接入同一阶段判据。** 原生调用可能进行中时只写取消意图;短等待后不关闭观察句柄,120 秒后交 Task 3 观察。只有已证明未进入写入的辅助进程允许终止。`DesktopWorker.kill` 及 watchdog 不能绕开此判据;保存 helper 的注册/启动门与 supervisor 失联竞争必须被覆盖。
|
||||
- [x] **Step 4: 清理前采样并保留中断事实。** 更新 session-release/outcome/result/recovery-required 的生成逻辑。后续发现进程退出可以更新 resource_state,但不能把未知保存重写成成功;正常关闭失败保留 COMMITTED。`safe_to_continue=True` 不删除 write_outcome 中的失败。
|
||||
- [x] **Step 5: 跑 `tests/test_operation_lifecycle.py tests/test_session_record.py tests/test_failure_lifecycle.py tests/test_abnormal_shutdown.py tests/test_verify_worker_stability.py tests/test_incident_safety.py`,通过后执行交付单元 A 的完整回归并提交。** `git commit -m "fix: honor native write boundaries on every stop path"`。
|
||||
|
||||
### Task 5:管理 worker 的监督器失联与事务边界取消
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/cbb_refresh_verify/native_management.py:132`、`:209`、`:694`、`:1131`
|
||||
- Modify: `src/cbb_refresh_verify/management.py`(run_management / run_management_batch)
|
||||
- Modify: `src/cbb_refresh_verify/management_transaction.py`(沿用原 nonce/lease 身份,不放宽验证)
|
||||
- Create: `tests/test_management_supervision.py`
|
||||
- Test: `tests/test_management_native_transaction.py`
|
||||
- Test: `tests/test_management_retry_blockers.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 3 的会话记录,Task 4 的阶段停止规则。
|
||||
- 管理 job 新增 `cancel_signal`、`session_record_path`、`start_gate` 与 supervisor 创建身份;原 desktop/supervisor_pid/timeout_seconds 保持兼容。
|
||||
- 新增私有 `_require_management_continuation(job, root)`:每次新原生调用前校验当前取消/监督器身份;被取消时抛已有管理错误并明确 native_started,而不是启动下一动作。
|
||||
- 现有 `_require_add_supervisor(job, root)` 调用共享判据并保留 add deadline 检查,不移除已有安全检查。
|
||||
|
||||
- [x] **Step 1: 写无监督器和双阶段 update 测试。** 在 catalog 前使 supervisor 退出,确保不创建 LM;remove 调用内部模拟父进程退出但保留 native owner,返回后确保 add 不调用。断言部分完成与资源释放分别记录:
|
||||
|
||||
```python
|
||||
assert result.status == "RECOVERY_REQUIRED" # remove 已发生,add 未发出
|
||||
assert adapter.calls == ["remove"]
|
||||
assert result.safe_to_continue is True # 本例原生 owner 已独立证明释放
|
||||
assert not any(call[0] == "add" for call in adapter.calls if isinstance(call, tuple))
|
||||
```
|
||||
|
||||
- [x] **Step 2: 对 catalog/add/remove 三条 worker 路由分别触发取消和父进程退出。** 正在 native wait/COM 调用时 helper/worker 存活,返回后不进入下一写动作;同目标不得自动重试。
|
||||
- [x] **Step 3: 启动前持久登记并使用 gate,worker 在身份检查后 armed watchdog。** watchdog 只写自己的失联文件和取消信号,不异步退出正在做原生调用的工作进程。调用返回后执行正常自有会话收尾;未知弹窗记录并交已有提示入口。
|
||||
- [x] **Step 4: 将仅依赖 `_pending_workers/_retained_workers` 的判据补为内存+可核对记录。** 内存列表继续用于同一进程的快速收尾,但不是唯一恢复入口;读不到 result.json 不能永久推断 owner 活着。
|
||||
- [x] **Step 5: 跑管理三个测试文件与 `tests/test_native_management.py tests/test_native_export_guard.py`,通过后提交。** `git commit -m "fix: supervise management workers across cancellation and parent loss"`。
|
||||
|
||||
### Task 6:重启核对和相关库范围的可操作入口
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/cbb_refresh_verify/session_record.py`
|
||||
- Modify: `src/cbb_refresh_verify/residual_sessions.py`
|
||||
- Modify: `src/cbb_refresh_verify/ui/residual_release_dialog.py`
|
||||
- Modify: `src/cbb_refresh_verify/ui/main_window.py`
|
||||
- Test: `tests/test_session_record.py`
|
||||
- Test: `tests/test_review_release_followup.py`
|
||||
- Test: `tests/test_ui_lease_lifecycle.py`
|
||||
- Test: `tests/test_background_queue_regressions.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: A/B 单元生成的 session.json/worker-state/observation 记录,保留已存在的 release_proof / released Signal 兼容。
|
||||
- GUI 后台核对只显示状态,不自动点击原生提示、不重放新增/更新/移除、不仅按 Cbb 桌面前缀结束进程。
|
||||
- NativeQueue 使用已有 ready 回调查询已缓存的相关库可执行性;ready 自身不做 WMI、文件读取或 SMB 路径解析。
|
||||
|
||||
- [x] **Step 1: 写“重启时 active、exited、PID reused、记录损坏”四个场景。** 检查行为结果而不是只检查某函数调用次数:active 可看原生阶段,exited 需独立证明,reused 没有 native 消息,损坏记录不禁用全部 UI。
|
||||
- [x] **Step 2: 写 A 库等待、B 库可执行的队列测试。** 暂停保存的 A 保留关联租约,不占队列 active;B 可完成,A 同库新写操作不会进入。用户取消批次不会在恢复后自动重放。
|
||||
- [x] **Step 3: 接入启动时的后台发现与已有“查看原生提示/处理保存/请求原生取消/重新检查”。** 未知窗口只展示真实原因;记录 helper 正在 Save/Close 时不向普通强制结束路径放行。不为“能释放”而新增任意杀进程按钮。
|
||||
- [x] **Step 4: 证明成立后只解除匹配会话的历史记录和映射。** 关闭自有 desktop 句柄,不能宣称已删除仍有原生引用的桌面。报告保存失败单独展示,不把有效释放反转成真实占用。
|
||||
- [x] **Step 5: 跑上述四个文件与 `tests/test_residual_sessions.py tests/test_residual_release_dialog.py`,再跑 A+B 完整回归后提交。** `git commit -m "fix: reconcile retained sessions without blocking independent libraries"`。
|
||||
|
||||
### Task 7:关闭 legacy 读取的隐式启动和肯定按钮回退
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/cbb_refresh_verify/library_reader.py:249`、`:340`
|
||||
- Modify: `src/cbb_refresh_verify/mentor_adapter.py:1453`、`:1532`、`:1629`
|
||||
- Modify: `src/cbb_refresh_verify/ui/main_window.py:114`
|
||||
- Create: `tests/test_readonly_status_policy.py`
|
||||
- Test: `tests/test_library_reader.py`
|
||||
- Test: `tests/test_batch_status_faults.py`
|
||||
- Modify: `tests/test_desktop_worker.py`(旧 reader 必启动私有桌面的测试改为可达新边界)
|
||||
|
||||
**Interfaces:**
|
||||
- 默认 authoritative_status_map 入口不变;桥返回失败仍使用 UNKNOWN / UNAVAILABLE,不能升级为 PENDING/READY。
|
||||
- `read_library_flag(library, name, *, timeout_seconds=90, log_path=None)` 与 `read_library_tree_image_map(library, names, *, timeout_seconds=45, log_path=None)` 保留调用签名和返回形状,但只观察已存在、匹配库身份的 LM;不自动启动新的 LM。
|
||||
- 无匹配 LM 返回原有 FLAG_UNKNOWN 或 `{name: None}`,并附可读原因,不要求每次搜索/过滤都人工开 LM。
|
||||
- `handle_known_dialogs` 留给需要的已验证写路径;状态读取不调用它,不修改其他流程的弹窗规则。
|
||||
|
||||
- [x] **Step 1: 写未知提示和无 LM 的回归。** 把 CreateDesktop/CreateProcess/PostMessage 与 affirmative handler 设为触发即失败,调用两个兼容 reader 和 `scan_open_library_status`:
|
||||
|
||||
```python
|
||||
def test_status_read_does_not_launch_or_answer_when_lm_is_absent(monkeypatch):
|
||||
import win32process
|
||||
from cbb_refresh_verify import mentor_adapter
|
||||
monkeypatch.setattr(win32process, "CreateProcess",
|
||||
lambda *a, **kw: (_ for _ in ()).throw(AssertionError("implicit LM launch")))
|
||||
# 该测试文件的 FakeDesktop.windows() 返回 [],不连接实际 LM。
|
||||
assert mentor_adapter.read_library_tree_image_map("C:/Fixture/lib.lmc", ["A"]) == {"A": None}
|
||||
```
|
||||
|
||||
再对“修复/覆盖/保存/未知许可提示”的窗口快照参数化,要求没有任何消息发送。
|
||||
- [x] **Step 2: 运行 `python -m pytest -q tests/test_readonly_status_policy.py`,确认 RED。**
|
||||
- [x] **Step 3: 去掉读取路径的自动创建和通用肯定应答。** 抽取最小既有 LM 树观察函数,使用 exact library identity,只读树项,不关闭用户打开的窗口;窗口不可读就返回未知。若发现其他调用方仍依赖隐式启动,迁到明确的原生工具打开入口或保留未知,不隐藏恢复原行为。
|
||||
- [x] **Step 4: 跑 reader/bridge/UI 状态回归,并用混合 READY/PENDING/UNAVAILABLE 清单检查数量和筛选。** 默认桥成功时不改变结果;legacy 无 LM 不弹每项确认、不启动 Mentor、不伪造损坏。
|
||||
- [x] **Step 5: 提交。** `git commit -m "fix: keep legacy status reads observational"`。
|
||||
|
||||
### Task 8:GUI/CLI 停止传播和结果展示联调
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/cbb_refresh_verify/verify_runner.py:1251`(run_batch 默认 verifier 转发 stop)
|
||||
- Modify: `src/cbb_refresh_verify/ui/main_window.py:1504`
|
||||
- Modify: `src/cbb_refresh_verify/ui/icdb_check_task.py`
|
||||
- Modify: `src/cbb_refresh_verify/ui/management_dialog.py`
|
||||
- Modify: `src/cbb_refresh_verify/application.py`(CLI 信号进入本批次 stop)
|
||||
- Test: `tests/test_operation_queue.py`
|
||||
- Test: `tests/test_ui_batch_safety.py`
|
||||
- Test: `tests/test_background_queue_regressions.py`
|
||||
- Test: `tests/test_application.py`
|
||||
|
||||
**Interfaces:**
|
||||
- `run_batch(..., stop=event)` 的默认调用必须实际传 `run_verify(..., stop=event)`;外部注入 verifier 的原一参数签名保持不变。
|
||||
- UI 接受 write_outcome 和 session_record_path,但不直接读取/resolve 这些路径;通过现有 ServiceWorker 接收事实。
|
||||
- 文案分别为“已请求停止,等待当前保存返回”“保存已返回,关闭待确认”“已转后台观察,可查看状态”“当前状态无法确认”,只在对应事实成立时显示。
|
||||
|
||||
- [x] **Step 1: 写 CLI 默认 verifier 的 stop 传播测试与 GUI 延迟保存测试。** GUI 点击停止后 200ms 定时器仍可触发、搜索仍可编辑;新原生动作没有发出,进度不假称已保存或已释放。
|
||||
- [x] **Step 2: 写 action 抛异常、队列取消和按库 ready 的回归。** 保留已存在的 Event 轮询取消语义;不用无通知无限 wait;一项异常释放队列票据,后续可执行独立项不被遗留票据挡住。
|
||||
- [x] **Step 3: 接入停止来源与事实投影。** `auto_repair=False` 保持默认;兼容修复/复验的 stop 转发使用 Task 4 新签名。Save/Close 尚未确认时不启用本目标自动重试,也不禁用所有只读操作。
|
||||
- [x] **Step 4: 跑队列、后台、界面和 CLI 测试,检查退出/重启后未完成状态仍可见。** GUI 线程中将 Path.resolve、WMI、文件读取替换为失败哨兵,确认事实展示不触发它们。
|
||||
- [x] **Step 5: 提交。** `git commit -m "fix: propagate stop intent and display independent lifecycle facts"`。
|
||||
|
||||
### Task 9:完整回归、冻结包和隔离验收
|
||||
|
||||
**Files:**
|
||||
- Modify: `README.md`
|
||||
- Modify: `SOP.md`
|
||||
- Modify: `docs/ICDB-MANUAL-REPAIR-AND-UPDATE.md`
|
||||
- Create: `docs/releases/2026-11-06-runtime-lifecycle-validation.json`
|
||||
- Create: `docs/releases/2026-11-06-runtime-lifecycle-candidate.md`
|
||||
- Modify: `pyproject.toml`、`src/cbb_refresh_verify/__init__.py`(只在实际生成新候选包时递增为 0.2.4b2)
|
||||
- Test: `tests/test_packaging.py`、`tests/test_packaging_status_bridge.py`
|
||||
|
||||
**Interfaces:**
|
||||
- 验证记录必须关联最终 source tree SHA、测试 XML 哈希、实际版本、候选包 SHA-256、平台/Mentor 版本;缺少真实包或环境的项使用 not_run/unverified,不能写 passed。
|
||||
- 旧 `0.2.4b1` / `5eb4b2d` 的 1,631 完整回归和 63 项专项为历史基线,不是本轮验收结果。
|
||||
|
||||
- [x] **Step 1: 在独立测试互斥/临时恢复目录下串行跑最终完整套件。** `python -m pytest -q` 必须来自新工作树 src,子进程 PYTHONPATH 同步。不要同时在同一 runner 跑另一个使用真实产品互斥或固定恢复根的全量任务。
|
||||
- [x] **Step 2: 跑 `python -m compileall -q src tests` 和 `git diff --check`。** 保持源文件原行尾;记录预期 pywinauto COM 提示,新的警告另查。
|
||||
- [x] **Step 3: 生成候选包前更新为 0.2.4b2,按现有 spec 打包并运行 frozen 入口冒烟。** 验证 verify-worker、management-worker、owner-probe、dialog-agent 的模块/脚本可加载;运行“冻结程序 + fake 保存/管理 native 边界”的父进程退出与停止测试。构建环境缺外部依赖时记录具体缺项,不宣称已产生候选包。
|
||||
- [ ] **Step 4: 通过应用实际按钮运行隔离副本。** 单独记录 Save 前停止、Save 中停止、Close 延迟、管理父进程退出、legacy 未打开 LM、未知原生提示、独立库继续。缺实机场景保留未验收;不为验收在生产库保存中杀进程。
|
||||
- [x] **Step 5: 更新文档与审查描述。** 写清默认停止规则、后台观察范围、只读未知状态、真实 COM 无法取消的限制、程序回退与数据恢复的区别。测试用例数量不得替代场景证据。
|
||||
- [x] **Step 6: 提交候选记录,推送本轮差分草稿 PR。** `git commit -m "docs: record runtime lifecycle validation and candidate limits"`;按 A/B/C 提供审查顺序,不自动发布或关闭 ICDB 工单。若 main 已变化,重新整合并验证实际候选树。
|
||||
|
||||
## 验收映射与自查
|
||||
|
||||
| 审查问题 | 计划任务 | 必须看到的证据 |
|
||||
| --- | --- | --- |
|
||||
| P1-1 Save/Close 中自动强杀及误记安全 | 1、2、3、4、8 | 实际 helper 存活、无 terminate、保存/关闭/释放独立结果、跨入口停止一致 |
|
||||
| P1-2 管理失联后无监督操作 | 3、5、6 | 启动门、精确持久身份、失联取消、调用返回后无后续写入、重启可核对 |
|
||||
| P1-3 legacy 读取隐式启动/肯定应答 | 7、8 | 读取路径无 CreateProcess/点击/用户窗口关闭,未知状态可见 |
|
||||
| 直接相关停止传播和保存状态记录 | 1、2、4、8 | CLI/GUI 同一 stop,兼容修复链不吞 stop;COMMITTED 与关闭失败并存 |
|
||||
| 防止修复又导致整批/全工具卡死 | 3、6、8 | 有界等待后转观察;B 库执行,A 库活跃写入不并发;UI 始终可响应 |
|
||||
| 源码、冻结包和现场验收口径 | 9 | 三层分别记录,缺哪层明确保留,不能互相代替 |
|
||||
|
||||
本轮排除项见设计第 13 节。源文件行号以基线供定位,实施时先用 rg 重新定位所有调用方,不直接按旧行号打补丁。
|
||||
|
||||
实施记录:用户已授权执行。实施在当前会话逐项完成;独立只读审查按 requesting-code-review 技能执行,没有并行修改源码。保存启动门依赖会话协议,故先提交协议 primitive(97a3de2);mentor_adapter 的停止与只读修改共用文件,在 8d3eab1 合并提交 A/C 基础接线。管理接线为 6278091,界面及按库交接为 cb11624,独立审查修正为 d9a79b6、051498b。三单元联通后统一验证、生成候选,未提前交付不完整的 A 单元。真实环境未验收项见候选记录。
|
||||
@@ -4,22 +4,22 @@ Scope: user selected only the 2026-11-09 comments #309/#310/#313. Earlier deep-r
|
||||
|
||||
## 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.
|
||||
- [x] Reproduce BlockA releasing historical BlockB checkpoints and retained owners without naming BlockB in proof.
|
||||
- [x] 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.
|
||||
- [x] 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.
|
||||
- [x] Forward-merge backend into UI, then UI into residual branch; no history rewriting.
|
||||
- [x] Test one unreadable process/thread not affecting another, without fabricated modal windows; cover preview and action-time rechecks.
|
||||
- [x] Enumerate only target-process threads/windows, store incomplete-read metadata per PID. Keep unknown/active writers protected rather than adding a blind force override.
|
||||
- [x] Persist window identities and at most a 4 KiB output excerpt, preserve full preview in memory, stop duplicating activity output.
|
||||
- [x] Carry exact preview block scope into native Cancel and recheck identity/scope before clicking.
|
||||
- [x] 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.
|
||||
- [x] Merge residual fixes into PR #13, preserving ca39fb3 and icon.
|
||||
- [x] Address #11's line-ending note once at the tip: application.py to LF; pin it and main_window.py with targeted .gitattributes exceptions. Preserve all other file endings and the global * -text rule; EditorConfig is unnecessary.
|
||||
- [x] Independent review, integrated full suite, compile/diff checks, validation records and fast-forward pushes to existing PR branches.
|
||||
- [x] Update PR descriptions with precise results and no new package/native acceptance. Leave #3 as historical umbrella, without merging or closing it.
|
||||
@@ -0,0 +1,32 @@
|
||||
# PR #13 comment 319: residual lifecycle fixes
|
||||
|
||||
**Goal:** Fix the P2 and three P3 findings against head `96e179b` without interrupting an in-flight native writer.
|
||||
|
||||
**Scope:** https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/pulls/13#issuecomment-319
|
||||
|
||||
**Constraints:** Python 3.12/PySide6/pywin32, no new dependencies; existing isolated worktree and icon retained; no automatic ICDB Repair, native process termination, merge, release or issue closure. Real Mentor and shared-network acceptance remains outstanding.
|
||||
|
||||
## 1. Release proof and queue state
|
||||
|
||||
- [x] Reproduce an ended UNCONFIRMED observer leaving its library unavailable after explicit successful release.
|
||||
- [x] Snapshot retained entries before proof; acknowledge only those entries, for the matching library, while proof handles are still held. Failed proof and newer handoffs remain blocked. Test independent libraries and queue resumption.
|
||||
- [x] Retain final observer states for the existing residual panel, including unreadable journals; expose fresh recheck through that panel.
|
||||
|
||||
## 2. Passive discovery
|
||||
|
||||
- [x] Test that discovery of an exited session never calls release proof or modifies library checkpoints.
|
||||
- [x] Separate process observation from explicit reconciliation; startup observation stays read-only, reports ACTIVE/UNCONFIRMED and cannot claim RELEASED without proof.
|
||||
- [x] Refresh journal/status information from the running residual dialog, keeping all I/O off the Qt thread.
|
||||
|
||||
## 3. Supervisor loss
|
||||
|
||||
- [x] Use harmless real subprocesses to test PRECALL/POSTCALL exit, NATIVE_CALL/CLOSING retention, missing/unreadable journals and failed cancellation/journal writes.
|
||||
- [x] Synchronize phase transitions and helper registration with watchdog shutdown. Only matching durable and in-memory non-pending state allows worker-only exit; preserve active helpers and unknown states. Prevent subsequent calls after supervisor loss.
|
||||
- [x] Recheck after retained calls return; do not kill a native child or interpret worker exit as release proof.
|
||||
|
||||
## 4. Dead code and validation
|
||||
|
||||
- [x] Delete unused `_terminate_pid`; replace obsolete test hooks with assertions at actual process termination boundaries.
|
||||
- [x] Run focused regressions, full Python suite, compileall and diff checks. Record results and field-validation limits, then commit scoped changes. Do not rebuild or publish a candidate without documenting its source and validation.
|
||||
|
||||
Execution: implement inline in the existing isolated worktree; red/green tests per task. The user has authorized these fixes, so no further plan confirmation is needed.
|
||||
@@ -0,0 +1,201 @@
|
||||
# CBB 原生操作生命周期与只读边界设计草案
|
||||
|
||||
状态:用户已批准并授权实施。运行时实现与验证见同日计划和候选记录;不代表现场 ICDB 恢复验收。
|
||||
|
||||
范围已由用户确认:三条 P1,加上直接相关的停止与状态记录问题。
|
||||
|
||||
代码基线:`5eb4b2d7ed09947f19310ba80ba3b9a2a09b6f7d`。审查来源:[PR #12 评论 297](https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/pulls/12#issuecomment-297)。评论分析的是旧 `dc536da`;以下结论重新对照当前基线,不把旧评论当作最新提交的复审。
|
||||
|
||||
## 1. 要解决的实际问题
|
||||
|
||||
1. 用户停止、超时、失败清理和监督器失联可经不同路径结束保存 helper。杀掉调用 `doc.Save()` 的 cscript 后,退出查询又可能将它描述为已安全释放。
|
||||
2. 管理工作进程缺少统一的监督器失联处理和可跨重启核对的会话记录。新增路径已有 `_require_add_supervisor`,但 catalog、remove、COM 等待和收尾覆盖不一致。
|
||||
3. legacy 状态读取会启动私有桌面的 LM,并调用偏向肯定按钮的通用弹窗处理器。默认权威桥路径没有这项图标读取回退,不能把风险泛化成所有读取都会执行它。
|
||||
|
||||
本轮修复停止与监督行为,不能据此宣布现场 ICDB 失联已修好,或推断已经验证了保存中断的数据后果。
|
||||
|
||||
## 2. 方案比较与选择
|
||||
|
||||
| 方案 | 代价与限制 | 选择 |
|
||||
| --- | --- | --- |
|
||||
| 按异常逐处增加判断 | 改动初期较少,但用户停止、finally、kill、watchdog 容易再分叉;不能解决重启后的身份核对 | 不采用 |
|
||||
| 小型事实模型、按原生阶段停止、复用现有队列和租约 | 集中约束危险动作,同时保留现有串行操作、后台检查和确认入口;可分三个交付单元审查 | 推荐 |
|
||||
| 重写调度与自动化框架 | 改动大,可能重新引入阻塞,且难以定位回归 | 不采用 |
|
||||
|
||||
本轮只增加保存事实解析和受限会话记录两个小模块,不引入通用流程引擎、任务总线或新依赖。
|
||||
|
||||
## 3. 全局约束
|
||||
|
||||
- 技术栈保持 Python 3.12、PySide6、pywin32、Mentor EE7.9.5,不增加运行时依赖。
|
||||
- 检验、ICDB 批量检查、中心库管理保持独立;ICDB 自动 Repair 继续关闭。
|
||||
- READY 条目继续排除维护;状态读取失败不伪造 READY,也不直接判定 ICDB 损坏。
|
||||
- 自动停止、超时、失败清理、监督器失联都不得强杀可能正在原生写入的进程或 COM 保存 helper。
|
||||
- UI、搜索、筛选、日志查看和只读浏览保持可用;一个未释放写入不得占着全局执行票据等待无限长时间。
|
||||
- 同库仍在进行的写入不可并发启动;已释放的单项失败不得阻止独立项,其他独立库可排队获得执行机会。
|
||||
- 历史 JSON 只触发身份及实际资源复核,不直接构成真实占用;报告错误不得伪造占用或永久禁用入口。
|
||||
- 不自动选择历史版本、重新导入、恢复备份、删除原生锁/地址文件或修改 LMC 伪造状态。
|
||||
- 不新增全库自动备份或全库内容哈希;此前确认的人工备份策略不变。
|
||||
- 确认结束客户端与正常停止分开;本轮不增加“放弃正在进行的保存”按钮,不自动放宽服务器保护。
|
||||
- 原生动作、证据读取、路径解析、进程查询和重启核对都放在非 GUI 线程;GUI 只更新视图和提交用户意图。
|
||||
- 保留 VerifyRequest / VerifyResult 的现有参数及 safe_to_continue 兼容性,只追加有默认值的事实字段。
|
||||
- 保持原有文件行尾,不进行与功能无关的整文件规范化。
|
||||
- 开发验证只使用临时数据、模拟原生边界或隔离副本;不在生产库制造保存中断。
|
||||
|
||||
## 4. 保存、关闭和释放分开记录
|
||||
|
||||
新增 `operation_lifecycle.py`,提供纯函数,不导入 Qt、COM 或管理模块。
|
||||
|
||||
`classify_save_state(markers, *, helper_exited, native_released, forced=False)` 返回:
|
||||
|
||||
| 字段 | 值 | 能证明什么 |
|
||||
| --- | --- | --- |
|
||||
| save_state | NOT_STARTED / COMMITTED / REJECTED / UNKNOWN | COMMITTED 只来自本次 helper 的 SAVE_OK;缺标记不能推断“没有写入” |
|
||||
| close_state | CLOSED / FAILED / UNKNOWN | 只由本次 CLOSE_OK / CLOSE_FAILED 明确记录;退出码不替代关闭证据 |
|
||||
| helper_state | EXITED / RUNNING / UNKNOWN | 来自精确进程句柄或身份核对;PID 消失不证明保存完整 |
|
||||
| resource_state | RELEASED / RETAINED / UNKNOWN | 来自独立资源证明;与保存成功分开 |
|
||||
| interrupted | bool | 记录异常结束,不用进程消失掩盖中断 |
|
||||
| detail | str | 说明证据缺失、矛盾或中断的具体原因;正常结果为空字符串 |
|
||||
|
||||
SAVE_OK 表示原生 Save 返回成功,不表示工程内容、中心库权威状态或历史版本已验收。关闭失败时仍保留已取得的保存事实。证据读取失败保留 UNKNOWN,不自动将 save_state 改为 REJECTED。
|
||||
|
||||
运行中的事实只能由当前操作 nonce、helper 身份和新日志更新;不拼接上轮 save.log。发生矛盾时采用 UNKNOWN 并保留原始标记。
|
||||
|
||||
新增兼容字段 `VerifyResult.write_outcome: dict | None = None`、`VerifyResult.session_record_path: Path | None = None`;现有 release_proof 含义不变。
|
||||
|
||||
safe_to_continue 继续表达本任务是否已释放后续原生执行所需资源,不能表达保存已通过。若保存结果未知但资源已独立证明释放,结果保留失败/待核对,允许其他独立项;同一目标不自动重放。若当前仍有原生写入,只保留相关库的写入限制,不全局锁住应用。
|
||||
|
||||
## 5. 原生调用阶段与停止语义
|
||||
|
||||
原生调用使用以下最小阶段:PRECALL、NATIVE_CALL、POSTCALL、CLOSING、RELEASE_CHECK、FINISHED、UNCONFIRMED。保存 helper 启动但本轮阶段缺失时视为可能进入 NATIVE_CALL,不能据此终止。
|
||||
|
||||
| 当前事实 | 用户停止/超时后的行为 | 后续项 |
|
||||
| --- | --- | --- |
|
||||
| 原生调用尚未发出且身份已确认 | 取消启动,不再进入新的原生动作;正常释放已创建的辅助资源 | 用户取消的批次不再启动后续项 |
|
||||
| Save/Close/管理 COM 写调用可能仍在进行 | 写停止意图,继续观察调用返回;不杀 helper、worker、PCB 或服务器 | 同库写入等待;UI 和独立库继续可用 |
|
||||
| Save 已返回,文档未关闭 | 记录 COMMITTED 或 REJECTED;仅对身份一致、已确认可正常关闭的文档执行现有正常收尾 | 无新 Save,不自动放弃未保存修改 |
|
||||
| 原生调用已返回,资源已释放,但单项失败 | 保存失败及证据,保持同目标待核对,不自动重放 | 非用户取消批次可继续独立项 |
|
||||
| 无法确认调用是否返回或身份变化 | 留存原始证据,转后台观察/人工处理;不猜测已退出或强制结束 | 只限制无法确认的相关库写入 |
|
||||
|
||||
5 秒用于普通合作式停止的短等待。进入原生写入后的前台任务最多再等待 120 秒;该时长只是转后台观察的界限,不是终止进程的时限。后台观察使用独立工作线程/任务,不占 GUI 线程,不占 NativeQueue 的全局 action 票据。
|
||||
|
||||
必须在后台观察交接完成、关联库租约及会话记录保存后,才能释放原执行票据。若交接存储失败,保留内存监督并提示记录错误;不得因此调用 kill,也不得声称释放完成。
|
||||
|
||||
同库后台写入的独占由现有 LibraryLock / retained lease 约束,其他库仍通过既有串行通道运行。不能解除另一个活跃写入者的文件锁;合作锁也不能宣称约束了别的工程师直接打开 Mentor。
|
||||
|
||||
观察循环优先使用已打开进程句柄的零等待查询,不每秒重跑整库扫描或完整 WMI。等待时不得持有 `_guard` 或全局原生互斥;只有候选会话退出后才尝试独立释放证明。证明通道正忙则延后观察,不将其当作新的库故障,不挤占其他库的执行机会。
|
||||
|
||||
用户取消批次后不自动恢复该批次。后台释放确认可以解除匹配会话状态,但后续写入仍来自已经排队的独立请求或用户新的操作,不能重放历史写入。
|
||||
|
||||
## 6. 保存 helper 与所有退出路径一致
|
||||
|
||||
- `_stop_worker`、`DesktopWorker.kill`、`stop_automation_clients`、`close`、verify watchdog 和失败 finally 使用同一阶段判据。不能只修用户停止按钮。
|
||||
- 终止许可必须是已证明没有原生写调用的精确辅助进程;缺阶段、缺身份、helper 日志不可读都不是终止许可。
|
||||
- 已启动保存时,worker 不再仅因取消文件出现就放弃监督。先等当前 COM 返回,再决定正常关闭或保留原生提示。
|
||||
- VBS 在首次 Save 前检查取消。Save 返回后写 SAVE_OK / SAVE_REJECTED,再进行只读后置核对及有条件正常收尾;不让取消检查丢掉已经返回的保存事实。
|
||||
- VBS 对 Save/IsSaved/后置同步/Close 分别记录阶段和明确失败原因。接触这些调用的错误处理必须是局部检查,不用一个覆盖整份脚本的 On Error Resume Next 掩盖失败。
|
||||
- Close(True) 若仍可能写入,同样属于受保护原生调用;不得因 Save 已成功就强杀正在 Close 的 helper。
|
||||
- 父进程意外退出与用户停止采用相同的“停止新动作、观察现有调用”原则。现有 `stop_clients=True` 不能绕过保存保护。
|
||||
- 本轮不提供自动强制放弃保存。已有人工释放入口若遇到本工具明确登记的活跃 Save/Close,要显示实际阶段,不能把它当普通僵死客户端。
|
||||
|
||||
## 7. 可跨重启核对的会话记录
|
||||
|
||||
新增 `session_record.py`,只处理本工具受控的库外任务记录。它不执行 UI 操作,不从记录读取命令再运行,不依据文件存在就判占用。
|
||||
|
||||
每个会话记录:protocol/version、operation_id、operation、library、block、原生阶段、supervisor/worker/helper/native 的 PID/创建时间/完整映像、当前用户 SID/Windows 会话、desktop、取消文件、证据位置、原生调用是否可能仍在进行、保存/关闭/释放事实、记录时间和观察结果。
|
||||
|
||||
有可能新建原生进程时,先记录启动意图;CreateProcess 后记录精确身份。监督器打开工作进程的句柄后,工作进程才能获准进入原生动作;避免 GUI 在首条记录之前消失的空窗。
|
||||
|
||||
每个操作目录的 `session.json` 由启动方记录不可变身份;`worker-state.json` 只由 worker 写,`supervisor-lost.json` 只由 watchdog 写,后台观察写自己的 `observation-<observer_id>.json`。不能让多个进程覆盖同一状态文件。保存 helper 增加启动门:Python 写入 helper 精确身份后才放行进入 COM;取消、启动方消失或 30 秒内没有放行时,在 COM 调用前退出。旧测试直接运行 VBS 的无门参数模式只作兼容测试,生产启动必须使用门。
|
||||
|
||||
不按桌面名前缀批量删除桌面,不按旧 PID 杀进程。重启时:
|
||||
|
||||
1. 后台读取受控目录内受认可协议的记录,限制大小并拒绝目录链接和越界证据路径。
|
||||
2. 精确核对当前进程创建时间、映像和用户/Windows 会话;PID 复用记为 IDENTITY_CHANGED,不对替代进程做动作。
|
||||
3. 身份一致且仍活跃的会话显示原生阶段、输出和已有保存/取消选项;不自动继续写操作。
|
||||
4. 进程确已退出后仍调用现有资源释放证明;确认后归档会话记录并刷新相关视图。
|
||||
5. 未知记录只显示无法确认的原因和重新检查入口,不因为一份损坏 JSON 永久禁止所有操作。
|
||||
|
||||
CloseDesktop 只关闭本工具持有的句柄;原生进程或窗口仍引用桌面时,不宣称桌面已删除。不得把“清理桌面”作为结束正在写库进程的借口。
|
||||
|
||||
## 8. 管理 worker 的监督与取消
|
||||
|
||||
复用 `_require_add_supervisor` 的阶段检查思路,为 catalog/add/remove 都设置 supervisor identity、统一取消文件和阶段记录,而不是在管理入口外加一个无限等待。
|
||||
|
||||
- PRECALL:监督器失联或取消后,不再启动 LM、导入器、移除命令或下一阶段。
|
||||
- NATIVE_CALL:watchdog 只记录失联和停止意图;COM 或外部 CleanWGLib 调用仍在进行时不强制退出其调用进程。
|
||||
- POSTCALL:不得因为上一调用返回成功就继续 update 的下一次 add 或其他后续写入。关闭已确认空闲的自有原生会话,未知弹窗保留并暴露。
|
||||
- update 的 remove 成功而 add 未提交时返回“部分完成/需恢复”,保留该目标检查点,不把它报成纯取消,也不重新导入。
|
||||
- 正常完成和超时记录都能在重启后独立核对;不再仅依赖 `_retained_workers` 内存列表和 worker 自己写出的单个 safe_to_continue。
|
||||
|
||||
watchdog 不能解决不可取消 COM 调用的所有平台限制。验收要求是不再有无记录、无观察、可继续执行新写入的孤儿自动化;不承诺任意卡死的原生进程都能自动安全退出。
|
||||
|
||||
## 9. 状态读取的默认边界
|
||||
|
||||
推荐默认:普通读取不为 legacy 图标探测自动启动 LM,也不自动应答原生弹窗。
|
||||
|
||||
优先使用当前权威状态桥;桥不可用或无可观察的既有 LM 时,条目返回现有 UNKNOWN / UNAVAILABLE 及具体原因。无法查询不能等同于已知 PENDING,更不能等同于 ICDB 损坏。
|
||||
|
||||
`scan_open_library_status` 可以只观察用户已经打开、库身份匹配的 LM 树,不点任何按钮,不替用户关闭该 LM。发现模态提示时返回无法确认并保留可查看的提示信息。
|
||||
|
||||
`read_library_flag` / `read_library_tree_image_map` 的兼容 API 也必须服从上述边界,不能让隐藏直接调用继续启动生产库 LM 并走通用肯定按钮策略。需要自动创建 LM 的旧诊断能力不属于本轮交付;明确的用户“打开原生工具”入口保持原用途。
|
||||
|
||||
不能为了禁止状态读取自动点击,粗暴更改所有验证流程的已验证弹窗白名单。按调用目的分开,读取路径绝不调用肯定优先/fallback 操作器。
|
||||
|
||||
## 10. 批次与停止信号
|
||||
|
||||
GUI、CLI run_batch、ICDB 后台检查将 stop 传入同一请求链。兼容 auto_repair 分支补齐 stop 传播,但默认仍为关闭,不能把兼容性测试当作重新启用修复的授权。
|
||||
|
||||
队列取消、当前调用待返回、当前项失败和资源未释放分别记录。不能通过给全局 stop Event 置位,把一个库的观察状态扩散为所有独立库都停止。
|
||||
|
||||
本轮不把 Condition 改成无超时等待,除非所有取消/ready 变化都已有可靠通知;避免修复停止时引入永久等待。
|
||||
|
||||
## 11. 测试与验收
|
||||
|
||||
### 必须通过的跨组件场景
|
||||
|
||||
| 场景 | 必须观察到的结果 |
|
||||
| --- | --- |
|
||||
| Save 前取消 | Save 未调用;无新原生写入 |
|
||||
| Save 调用中取消、超时、未知弹窗或父进程退出 | helper 存活、没有强杀调用;停止意图与当前阶段已记录 |
|
||||
| Save 返回成功、Close 卡住 | 保存为 COMMITTED,关闭未确认;不得报无写入或全部完成 |
|
||||
| helper 突然退出且没有返回标记 | 保存 UNKNOWN,原生释放另行核对;不能因进程消失报安全保存 |
|
||||
| 前台等待超过 120 秒 | 转后台观察;UI 和独立库任务可运行,同库写入不能并发 |
|
||||
| 管理 GUI 在 catalog/add/remove/update 两阶段之间退出 | 无新动作越过停止边界;已发生动作、待核对范围和精确会话身份可恢复显示 |
|
||||
| 重启后 PID 复用、记录损坏或报告保存失败 | 不杀替代进程,不重放操作,不制造全局永久锁 |
|
||||
| 权威桥不可用、LM 没打开 | 状态无法确认;没有 CreateProcess、恢复/覆盖/肯定点击 |
|
||||
| 既有 LM 出现未知/修复/覆盖/保存提示 | 只观察并返回 UNKNOWN,不点击、不关闭用户会话 |
|
||||
|
||||
使用真实 cscript + 替换外部 COM 创建的 VBS harness 验证保存顺序;使用临时 sleep/helper 进程验证父进程退出、超时和进程身份;不在生产 Mentor 中途保存时做破坏试验。
|
||||
|
||||
全量 Python 测试必须串行运行,测试互斥使用独立命名空间,恢复临时根与源库分离;编译检查、diff 检查和 frozen helper 入口冒烟完成后才描述候选程序。冻结包先在 fake 原生边界跑同一保存/停止场景。
|
||||
|
||||
真实 Mentor 仅在一致隔离副本做延迟保存、当前原生取消、正常收尾、重新打开与权威状态核对;Win10、网络共享库、跨机器并发分别记录,缺环境时保留未验收项。
|
||||
|
||||
## 12. 分阶段交付和停止条件
|
||||
|
||||
交付单元 A:保存事实、helper/worker 停止规则和有界等待交接。
|
||||
|
||||
交付单元 B:管理 worker 的失联、取消、持久记录和重启核对。
|
||||
|
||||
交付单元 C:legacy 只读边界、GUI/CLI 停止接入、冻结包与隔离环境验收。
|
||||
|
||||
每个单元有独立回归和提交;三单元完成前不以局部通过宣称生命周期修复完成。原有 #10–#12 的旧评论不视为本轮新实现的批准。
|
||||
|
||||
实现从当前集成基线另开临时分支 `codex/runtime-lifecycle-safety`,不得覆盖原运行工作区,不 force-push 历史分支。执行时重新读取远端 PR/main 状态,按实际基线选择差分,避免重复合入已合并改动。先交付一个仅包含本轮运行时差分的草稿 PR,并在描述中按 A/B/C 给出审查顺序。
|
||||
|
||||
出现以下任一情况停止扩展并回到设计核对:没有办法在保留 COM 调用的同时交接观察、需要自动终止真实服务器、需要删除原生锁或地址才能让测试通过、需要引入新全局门禁才能规避身份不明。
|
||||
|
||||
## 13. 本轮明确排除
|
||||
|
||||
一般化跨机器写入互斥、全库/非目标工程内容证明、PRJ 重写与 before 字节补齐、UIA 无界线程整改、桥部署预检、CLI 全库范围确认、CI/打包外部路径/README 整理均单独排期。
|
||||
|
||||
其中与本轮直接相关的未知进程身份核对、停止传播及 Save/Close 事实拆分已纳入;不把排除项写成已修复。
|
||||
|
||||
## 14. 草案自查
|
||||
|
||||
- 三条 P1 均有明确生产调用点、拟修改边界和跨组件验收场景。
|
||||
- 没有把取消等同于强制结束,也没有把退出等同于保存成功。
|
||||
- 没有通过新增历史记录硬门禁解决问题;活动写入仍保持真实资源约束。
|
||||
- 没有依赖“调用 watchdog(stop_clients=False) 就万事解决”的错误假设。
|
||||
- 只读回退范围与权威桥路径区分;未知状态不伪造 READY/PENDING。
|
||||
- 用户已通过“按照当前的优化吧”授权实施;真实环境验收仍单独记录,不以测试计数代替。
|
||||
+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.4b2"
|
||||
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.4b2"
|
||||
@@ -1,151 +1,170 @@
|
||||
from __future__ import annotations
|
||||
import argparse, os, sys
|
||||
from pathlib import Path
|
||||
from typing import Sequence
|
||||
from .runtime_logging import configure
|
||||
|
||||
|
||||
def configure_qt_application(app):
|
||||
"""Apply a predictable light palette across machines and Qt themes."""
|
||||
from PySide6.QtGui import QColor, QPalette
|
||||
|
||||
app.setStyle('Fusion')
|
||||
palette = app.palette()
|
||||
colors = {
|
||||
QPalette.ColorRole.Window: '#f5f6f8',
|
||||
QPalette.ColorRole.WindowText: '#202124',
|
||||
QPalette.ColorRole.Base: '#ffffff',
|
||||
QPalette.ColorRole.AlternateBase: '#eef1f5',
|
||||
QPalette.ColorRole.Text: '#202124',
|
||||
QPalette.ColorRole.Button: '#eef1f5',
|
||||
QPalette.ColorRole.ButtonText: '#202124',
|
||||
QPalette.ColorRole.Highlight: '#2f6fed',
|
||||
QPalette.ColorRole.HighlightedText: '#ffffff',
|
||||
QPalette.ColorRole.ToolTipBase: '#ffffff',
|
||||
QPalette.ColorRole.ToolTipText: '#202124',
|
||||
QPalette.ColorRole.PlaceholderText: '#6b7280',
|
||||
}
|
||||
for role, color in colors.items():
|
||||
palette.setColor(role, QColor(color))
|
||||
for role in (QPalette.ColorRole.WindowText, QPalette.ColorRole.Text, QPalette.ColorRole.ButtonText):
|
||||
palette.setColor(QPalette.ColorGroup.Disabled, role, QColor('#858b94'))
|
||||
app.setPalette(palette)
|
||||
app.setStyleSheet(
|
||||
'QWidget { color: #202124; }'
|
||||
'QTableWidget, QLineEdit, QTextEdit, QSpinBox { '
|
||||
'background: #ffffff; color: #202124; selection-color: #202124; }'
|
||||
'QHeaderView::section { background: #e9edf2; color: #202124; }'
|
||||
'QPushButton, QToolButton { color: #202124; }'
|
||||
'QPushButton:disabled, QToolButton:disabled { color: #858b94; background: #e3e6eb; }'
|
||||
)
|
||||
return app
|
||||
|
||||
def resolve_data_root(cli_value: Path | None) -> Path:
|
||||
if cli_value is not None: return cli_value.expanduser().resolve()
|
||||
if getattr(sys, "frozen", False): return Path(sys.executable).resolve().parent / "data"
|
||||
local = os.environ.get("LOCALAPPDATA")
|
||||
return (Path(local) / "CbbRefreshVerify" if local else Path.home() / "AppData" / "Local" / "CbbRefreshVerify").resolve()
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(prog="CbbRefreshVerify")
|
||||
parser.add_argument('--verify-worker', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--repair-worker', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--owner-probe', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--native-backup-worker', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--management-worker', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--dialog-agent', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--batch-lmc', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--block', action='append', default=[], help=argparse.SUPPRESS)
|
||||
parser.add_argument('--libspec', default='', help=argparse.SUPPRESS)
|
||||
parser.add_argument('--dms-login-config', default='', help=argparse.SUPPRESS)
|
||||
parser.add_argument('--mentor-bin', default='', help=argparse.SUPPRESS)
|
||||
parser.add_argument("--smoke-test", action="store_true", help=argparse.SUPPRESS); parser.add_argument("--data-root", type=Path, help=argparse.SUPPRESS)
|
||||
args = parser.parse_args(list(argv) if argv is not None else None)
|
||||
if args.owner_probe:
|
||||
from .owner_probe import owner_probe_main
|
||||
return owner_probe_main(args.owner_probe)
|
||||
if args.native_backup_worker:
|
||||
from .native_backup import native_backup_worker_main
|
||||
return native_backup_worker_main(args.native_backup_worker)
|
||||
if args.management_worker:
|
||||
from .native_management import management_worker_main
|
||||
return management_worker_main(args.management_worker)
|
||||
if args.repair_worker:
|
||||
from .native_repair_ui import repair_worker_main
|
||||
return repair_worker_main(args.repair_worker)
|
||||
if args.collect_failure_logs:
|
||||
from .verify_diagnostics import failure_logs_main
|
||||
return failure_logs_main(args.collect_failure_logs)
|
||||
if args.dialog_agent:
|
||||
from .dialog_agent import dialog_agent_main
|
||||
return dialog_agent_main(args.dialog_agent)
|
||||
if args.verify_worker:
|
||||
from .mentor_adapter import worker_main
|
||||
import contextlib
|
||||
with args.verify_worker.with_name('worker.log').open('a', encoding='utf-8') as log:
|
||||
with contextlib.redirect_stdout(log), contextlib.redirect_stderr(log):
|
||||
return worker_main(args.verify_worker)
|
||||
context = configure(resolve_data_root(args.data_root)); logger = context.logger; logger.info("application_start")
|
||||
try:
|
||||
if args.batch_lmc:
|
||||
from .verify_runner import (VerifyRequest, native_lm_verify_enabled,
|
||||
run_batch, write_batch_report, failure_report_path)
|
||||
from .library_reader import read_library_fast
|
||||
from .batch_status import authoritative_status_map
|
||||
from .network_path import LibraryPathLease, select_library_file
|
||||
with LibraryPathLease.acquire(args.batch_lmc) as lease:
|
||||
mentor_path = select_library_file(lease.mentor_path)
|
||||
logger.info(
|
||||
'library_path_lease display=%s mentor=%s drive=%s remote=%s created=%s',
|
||||
lease.display_path, mentor_path, lease.drive or '-',
|
||||
lease.remote_root or '-', lease.created)
|
||||
names = list(args.block)
|
||||
if not names:
|
||||
library = read_library_fast(
|
||||
mentor_path,
|
||||
status_reader=lambda path, names: authoritative_status_map(
|
||||
names, path, context.root/'status-scan.jsonl'),
|
||||
)
|
||||
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')
|
||||
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,
|
||||
mapped_drive=lease.drive,
|
||||
mapped_remote_root=lease.remote_root,
|
||||
native_lm_verify=native_lm_verify_enabled())
|
||||
for name in names]
|
||||
try:
|
||||
results = run_batch(requests)
|
||||
except Exception:
|
||||
lease.retain_for_recovery()
|
||||
raise
|
||||
if any(not result.safe_to_continue for result in results):
|
||||
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))
|
||||
code = 0 if all(result.status == 'PASS' for result in results) else 2
|
||||
logger.info('application_clean_shutdown exit_code=%s', code)
|
||||
return code
|
||||
from .ui.main_window import MainWindow, application_icon_path
|
||||
if args.smoke_test:
|
||||
os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
|
||||
from PySide6.QtWidgets import QApplication
|
||||
app = QApplication.instance() or QApplication([sys.executable])
|
||||
configure_qt_application(app)
|
||||
window = MainWindow(logging_context=context); window.show()
|
||||
icon_path = application_icon_path()
|
||||
if icon_path.is_file():
|
||||
from PySide6.QtGui import QIcon
|
||||
app.setWindowIcon(QIcon(str(icon_path)))
|
||||
if args.smoke_test:
|
||||
from PySide6.QtCore import QTimer
|
||||
logger.info('gui_smoke_window_created title=%s', window.windowTitle())
|
||||
QTimer.singleShot(250, app.quit)
|
||||
code = int(app.exec()); logger.info("application_clean_shutdown exit_code=%s", code); return code
|
||||
except Exception: logger.exception("application_startup_failure"); return 1
|
||||
finally:
|
||||
for handler in logger.handlers: handler.flush()
|
||||
from __future__ import annotations
|
||||
import argparse, os, sys
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Sequence
|
||||
from .runtime_logging import configure
|
||||
|
||||
|
||||
@contextmanager
|
||||
def batch_stop_signals(stop):
|
||||
import signal
|
||||
previous = {}
|
||||
try:
|
||||
for name in ('SIGINT', 'SIGTERM', 'SIGBREAK'):
|
||||
signum = getattr(signal, name, None)
|
||||
if signum is not None:
|
||||
previous[signum] = signal.signal(signum, lambda *_: stop.set())
|
||||
yield
|
||||
finally:
|
||||
for signum, handler in previous.items():
|
||||
signal.signal(signum, handler)
|
||||
|
||||
|
||||
def configure_qt_application(app):
|
||||
"""Apply a predictable light palette across machines and Qt themes."""
|
||||
from PySide6.QtGui import QColor, QPalette
|
||||
|
||||
app.setStyle('Fusion')
|
||||
palette = app.palette()
|
||||
colors = {
|
||||
QPalette.ColorRole.Window: '#f5f6f8',
|
||||
QPalette.ColorRole.WindowText: '#202124',
|
||||
QPalette.ColorRole.Base: '#ffffff',
|
||||
QPalette.ColorRole.AlternateBase: '#eef1f5',
|
||||
QPalette.ColorRole.Text: '#202124',
|
||||
QPalette.ColorRole.Button: '#eef1f5',
|
||||
QPalette.ColorRole.ButtonText: '#202124',
|
||||
QPalette.ColorRole.Highlight: '#2f6fed',
|
||||
QPalette.ColorRole.HighlightedText: '#ffffff',
|
||||
QPalette.ColorRole.ToolTipBase: '#ffffff',
|
||||
QPalette.ColorRole.ToolTipText: '#202124',
|
||||
QPalette.ColorRole.PlaceholderText: '#6b7280',
|
||||
}
|
||||
for role, color in colors.items():
|
||||
palette.setColor(role, QColor(color))
|
||||
for role in (QPalette.ColorRole.WindowText, QPalette.ColorRole.Text, QPalette.ColorRole.ButtonText):
|
||||
palette.setColor(QPalette.ColorGroup.Disabled, role, QColor('#858b94'))
|
||||
app.setPalette(palette)
|
||||
app.setStyleSheet(
|
||||
'QWidget { color: #202124; }'
|
||||
'QTableWidget, QLineEdit, QTextEdit, QSpinBox { '
|
||||
'background: #ffffff; color: #202124; selection-color: #202124; }'
|
||||
'QHeaderView::section { background: #e9edf2; color: #202124; }'
|
||||
'QPushButton, QToolButton { color: #202124; }'
|
||||
'QPushButton:disabled, QToolButton:disabled { color: #858b94; background: #e3e6eb; }'
|
||||
)
|
||||
return app
|
||||
|
||||
def resolve_data_root(cli_value: Path | None) -> Path:
|
||||
if cli_value is not None: return cli_value.expanduser().resolve()
|
||||
if getattr(sys, "frozen", False): return Path(sys.executable).resolve().parent / "data"
|
||||
local = os.environ.get("LOCALAPPDATA")
|
||||
return (Path(local) / "CbbRefreshVerify" if local else Path.home() / "AppData" / "Local" / "CbbRefreshVerify").resolve()
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(prog="CbbRefreshVerify")
|
||||
parser.add_argument('--verify-worker', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--repair-worker', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--owner-probe', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--native-backup-worker', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--management-worker', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--dialog-agent', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--batch-lmc', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--block', action='append', default=[], help=argparse.SUPPRESS)
|
||||
parser.add_argument('--libspec', default='', help=argparse.SUPPRESS)
|
||||
parser.add_argument('--dms-login-config', default='', help=argparse.SUPPRESS)
|
||||
parser.add_argument('--mentor-bin', default='', help=argparse.SUPPRESS)
|
||||
parser.add_argument("--smoke-test", action="store_true", help=argparse.SUPPRESS); parser.add_argument("--data-root", type=Path, help=argparse.SUPPRESS)
|
||||
args = parser.parse_args(list(argv) if argv is not None else None)
|
||||
if args.owner_probe:
|
||||
from .owner_probe import owner_probe_main
|
||||
return owner_probe_main(args.owner_probe)
|
||||
if args.native_backup_worker:
|
||||
from .native_backup import native_backup_worker_main
|
||||
return native_backup_worker_main(args.native_backup_worker)
|
||||
if args.management_worker:
|
||||
from .native_management import management_worker_main
|
||||
return management_worker_main(args.management_worker)
|
||||
if args.repair_worker:
|
||||
from .native_repair_ui import repair_worker_main
|
||||
return repair_worker_main(args.repair_worker)
|
||||
if args.collect_failure_logs:
|
||||
from .verify_diagnostics import failure_logs_main
|
||||
return failure_logs_main(args.collect_failure_logs)
|
||||
if args.dialog_agent:
|
||||
from .dialog_agent import dialog_agent_main
|
||||
return dialog_agent_main(args.dialog_agent)
|
||||
if args.verify_worker:
|
||||
from .mentor_adapter import worker_main
|
||||
import contextlib
|
||||
with args.verify_worker.with_name('worker.log').open('a', encoding='utf-8') as log:
|
||||
with contextlib.redirect_stdout(log), contextlib.redirect_stderr(log):
|
||||
return worker_main(args.verify_worker)
|
||||
context = configure(resolve_data_root(args.data_root)); logger = context.logger; logger.info("application_start")
|
||||
try:
|
||||
if args.batch_lmc:
|
||||
from .verify_runner import (VerifyRequest, native_lm_verify_enabled,
|
||||
run_batch, write_batch_report, failure_report_path)
|
||||
from .library_reader import read_library_fast
|
||||
from .batch_status import authoritative_status_map
|
||||
from .network_path import LibraryPathLease, select_library_file
|
||||
with LibraryPathLease.acquire(args.batch_lmc) as lease:
|
||||
mentor_path = select_library_file(lease.mentor_path)
|
||||
logger.info(
|
||||
'library_path_lease display=%s mentor=%s drive=%s remote=%s created=%s',
|
||||
lease.display_path, mentor_path, lease.drive or '-',
|
||||
lease.remote_root or '-', lease.created)
|
||||
names = list(args.block)
|
||||
if not names:
|
||||
library = read_library_fast(
|
||||
mentor_path,
|
||||
status_reader=lambda path, names: authoritative_status_map(
|
||||
names, path, context.root/'status-scan.jsonl'),
|
||||
)
|
||||
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')
|
||||
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,
|
||||
mapped_drive=lease.drive,
|
||||
mapped_remote_root=lease.remote_root,
|
||||
native_lm_verify=native_lm_verify_enabled())
|
||||
for name in names]
|
||||
try:
|
||||
from threading import Event
|
||||
stop = Event()
|
||||
with batch_stop_signals(stop):
|
||||
results = run_batch(requests, stop=stop)
|
||||
except Exception:
|
||||
lease.retain_for_recovery()
|
||||
raise
|
||||
if any(not result.safe_to_continue for result in results):
|
||||
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))
|
||||
code = 0 if all(result.status == 'PASS' for result in results) else 2
|
||||
logger.info('application_clean_shutdown exit_code=%s', code)
|
||||
return code
|
||||
from .ui.main_window import MainWindow, application_icon_path
|
||||
if args.smoke_test:
|
||||
os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
|
||||
from PySide6.QtWidgets import QApplication
|
||||
app = QApplication.instance() or QApplication([sys.executable])
|
||||
configure_qt_application(app)
|
||||
window = MainWindow(logging_context=context); window.show()
|
||||
icon_path = application_icon_path()
|
||||
if icon_path.is_file():
|
||||
from PySide6.QtGui import QIcon
|
||||
app.setWindowIcon(QIcon(str(icon_path)))
|
||||
if args.smoke_test:
|
||||
from PySide6.QtCore import QTimer
|
||||
logger.info('gui_smoke_window_created title=%s', window.windowTitle())
|
||||
QTimer.singleShot(250, app.quit)
|
||||
code = int(app.exec()); logger.info("application_clean_shutdown exit_code=%s", code); return code
|
||||
except Exception: logger.exception("application_startup_failure"); return 1
|
||||
finally:
|
||||
for handler in logger.handlers: handler.flush()
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 264 KiB After Width: | Height: | Size: 120 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 4.8 KiB After Width: | Height: | Size: 1.1 MiB |
@@ -1,7 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">
|
||||
<rect x="3" y="3" width="58" height="58" rx="10" fill="#0f766e"/>
|
||||
<rect x="11" y="12" width="42" height="32" rx="4" fill="#f8fafc"/>
|
||||
<rect x="15" y="16" width="34" height="24" rx="2" fill="#dbeafe"/>
|
||||
<path d="M20 29l6 6 14-14" fill="none" stroke="#16a34a" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<rect x="25" y="47" width="14" height="4" rx="2" fill="#f8fafc"/>
|
||||
</svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024"><image width="1024" height="1024" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABAAAAAQACAYAAAB/HSuDAAEAAElEQVR4nOz9C7Ru2XUWBu69//+cc+8tVektS5ZlyQ8JWyW/UnJjjBNKHUNGG+wEEhWDR9NtIECajODQTTokZKgc8mgegxEDPQCnwQPShI4Eo8MjhoQ0VTS2wR1VALtKMio/JFmyLJVslVRV93HO/+/dY805v29+a/3n3Htu1X2cc++atuqe85/97732WnOtNb9vPtY4dOnSpUuXLndAlmUZz3JHj+O43O02dLn7enmW9eBWzaHj3vFm732W+6nL3ZPT6FHXnS5d7q6s7/Lzu3Tp0qVLl7si3QjtchxYKZ/dL7px1km5LudLuj516XI+pC/8Xbp06dLlvjYI7xew1+V0Onmn9OFmiYazNJf6nLkzch7JqNNGAJzHd+vS5V6RM7OZdOnSpUuXe1fOEniBdOOzy3mSWxn+r/dqf7/Rd29FG7rc+wKAr0Afetb1qEuXuyvTXX5+ly5dunTpclekGKNnkZjocvsE463/6v/Oat/fyrYBkCkIOw6Q4bP22i5dTiOqMzq/boZw6tKly+2RPgG7dOnSpcttlfNk7HWgc+9K6/XGZ2d9zO/U/Gn7pPXc9rDtLjcrqjfH6Vjv0S5d7o70CIAuXbp06XLb5JVUFr+TBmI3Ru9NUU+/erTv5LifFQLsOE8+PgNI6+C/y62Q1tt/ko713u7S5e5In3xdunTp0uW2y2mMvpPyRV+OHOe5PO5Z7fVdzr+0IPa4f2/3mJ/07Jd7r+v9/Xrz6la1ocvp5bjIid5/Xbp0OUvSIwC6dOnSpcttl9OAf73uVhrOxwE+9Up1A/3ek+N07U6D/5N+v5Vy3Du1c+m4yIcut186+O/SpctZlR4B0KVLly5d7ohcz0t5EnC6Vc8+Cfx1I/3elXslh/1mj1U7j+/YpUuXLl3unPQIgC5dunTpcibkuPzkV3Kvkzz++P2VPqPL+ZD7ARh3T3+XLl26dDmt9AiALl26dOlyR+R6efg3AmanyXG+xc3tcg/InQzHv11ymtSZLl26dOnS5bTSCYAuXbp06XJXCwC+EvA/nGE5r+3ucnbkbtYy6NKlS5cu96b0FIAuXbp0OUeCAnnDOZFb4XE9b4X6jot00H/P0/h1OXvSwX+XLl26dHkl0o2QLl26dDmHHvOzHsp8syD3NO9y3LF9Z7EfTlu07XY/55U846R0jbPW17dCTjvPTgLetwqQv9zz0e/FMenSpUuXLrdPegRAly5dupwxOU1I/Hkw+k/bxutdd1zEw+04KvBWyWnB252KAng5z7nfPMxthEn7s+racX1yKyJUXi7479KlS5cuXW5WOgHQpUuXLudMzgtQuBVtBLhSUHo9MHZe5OW2HWD0NH2La9p/b1bOcz+fVrRvtL9u9Pl5mIddunTp0qWLSicAunTp0uWcyVn0fL8cudmc+Pas8+EMye1uzyut/dCC1/Z/+reTQtzvNdH3Pu18Oo4QuBVyFnW6S5cuXbrcm9IJgC5dunTpcqblPHlb24J/dyLX/2bkRpETCkTPQ3+/EjlLJNq93tddunTp0uXsSCcAunTp0uUcSRsSfxbltB7V9h1OCrdW0HorgfWdiGY4aZzuVq2AkyIJXulzzrI+Xk9uluy41Xp3VmtZdOnSpUuXe1fO5YbdpUuXLve6tKCgDX0/y4DhRlXVT/r8uFx//Kz3PcvvfjPHAt7s926V3IhAOu8nUJxWblU6yWnm5UnPeiXPv5fGokuXLl263DnpEQBdunTpcgalBf/6+VkLK2/leiDoep+flF99UjG28yp3u/0v19t9rwHNW/0+p02tOGlud+nSpUuXLndCOgHQpUuXLmdUWuB/MxXgbwf4OW249Gk99TfbhrMa/n+SXM+Lfudbk88+6Sg7/Kvealx/lo9efKVy0hGApzkisPyrfXKjyIrTeO1vJkLkXhuLLl26dOly+6UTAF26dOlyRuW4FIC7efzdzQLwlgg47nz1m3n+eQM8Z7Gtp61JoCRAS0QN95gcl3ZynJx0OsL1CISTnvVKr3k513bp0qVLly5FOgHQpUuXLmdcFPSfBYP/pEJ3JwH+4wr6nRbMtwUAz8L734zcjoJ7L0du1IetN1uvP6u55reqH48rrNl+divqb7T6/3Lb2v5+3uZEly5dunS5u9I3jS5dunS5D6UN8z7ttacFke3vxwGsNnT6RkXSzioQPUmu906n/f5wB+W8FVu8Ve28W/p1q8f3rI9Xly5dunQ5G9IJgC5dunS5D+U48H2ja28WsJzGg3oc+DovAPR21wC4UwTAee3nmyGxzrLcjnE+rj/Oez916dKlS5dbI+tbdJ8uXbp06XKOgdNpC/u9nOfo908bJXC9AmunycXucm/LrTrC716V00TonPbzs/4+Xe78WBy3bvfx6NLl/EjfOLt06dLlPpTTgoBXIjcyDK8HOK4H6s+bsflywUuPADi5X+6lSJEid5vIOOt92IFmly5dutw66UUAu3Tp0uU+kutVdb+Zwnynfd71iAU91eCkEw+Oa//1CIW7DaRupeeyLcZ3PwK/46QtUHi323MvyFmbN/dae+8V0TW2j0GXLudXOgHQpUuXLvexnFTR/2a+cxo5Ccyf9tr2b8cZom2F9bNACBwHUk/bJr3uduWJ3+3+eSVyntt+FuU89Wcnfu6+9DHo0uX8SicAunTp0qXLdT3VN3PO+c3IKzlOrf3+WfZK3Yrc6tthbJ/FvroZ6QCk92eXLl26dLl56QRAly5dunS5Lshqw+5PG5Z+Ozzx7Vnqpz2n/TyC3TtRXOs8guizTPacVzlvenAWonvuR+lpN1263BvSF88uXbp0ucfletX+Tzqq7zg5TcV+/f24Z5+mgv9J3znuucfVM2ifc7eLBr7S599sxfvrjc31vvNy29e286Tfu5zcb2elb87DePWCgF26dOnyyuTMbDpdunTp0uX2yGmO+zvuWMCbqVSv378RQL/Zdl/v3xu9y3kGCyeRG7cS+Lf3f6Xtvdeq898vJMB5G6uuY126dOny8qWnAHTp0qXLPS4neeg1nPNmAXILTk+KLLjZkNHTAKGbAfTnFfxDjqtzcKO/a3rEnXrvG0WFdDnbct7GqYeid+nSpcvLl04AdOnSpct9IterRv9KvfX6neMq8Z82muA0wPFG97te2sB5kvYdT1Pb4KQIjNt9nOCN2tXl+nK3Caq7/fwuXbp06XLnpBMAXbp06XIfFTFrPfMKlm8GBJwGVOMZpwXgref6euH+JwHb43LQz2sEQHsM4I3Cnk9K4zhtH7wcfTwuBaT9vZMBNzfWXV6eDvY+7NKlS5fTSd9wunTp0uVlyMsBla8kf/tWAdhXmqd9WlD9csD3cREAtwJInkfwX+S0NQ+Ok5OIEPzttLUgjmvTy3ub2z8OJ5ERp/0Ofr8b+nIWwOt5nSdFzivJ16VLly53Q3oEQJcuXbocI+pxPe5vChiud61+50Z/V2/tcRXVbwVI0Hu+nDzt04Krm40quFEBwpcLfu80KNBxutug7no1H270nZv9292W4+pN6Nw8ru3Hfed+Bf/nWdpImbvbmntXet926XLvSF8ou3Tp0uUWGjcnAeRbHQ79coHKcVEFN/LWX+99Xl7rd+9zu/rnTnkGX65H/Xr3uxmC5ka5/yfd/04b9TdbEPKkaJjj2n+ayIYbffZy23reAdUriQq623Kr516X4/u392OXLveO9AiALl26dLkJuReMoOPC7PXfk+R2pCScRk7jub7ed299i073rFdSeO9WtPss6uorieRQPXg56SWnbcsr0beX25azImdRZ16JaETVWe73syy3ez506dLlzksnALp06dLlFspx6QH6t9Pc4zTh9a/UmNV0g5v5Tvn3dhrSLWhuUyJO0zc38163K/LjVkVH4F6nJWdu5fNV7haJAWnTKm5U1+A0z75boOZuRF7c6oiTV/qs23l/fU77rLPW7126dOlyN6QTAF26dOlyE3Ijr2MLSl5OGOpp6wXcSi/1rf7O9eQ4ENeCj+Py6E/y4h2X+33aNt4qEHijNIqXIzd7n5sBljcLQl8OcDpprE57v5P05DR9fTP3fznfvZ1yM+N+K6NM7rSX/HY/q3uuu3Tp0uV46QRAly5dutyknNdCaWdBWi/5aT2Pbfh3e8+7net7uzzvxz3jJLndgP5WyWnH6rhoEPz7Stp/o7E6T+HOZ6Xg5N2ODDnpb+epX7p06dLlTkknALp06dLlNokC0+uBnrMMOG6FEX2cV/9m7tumAVzPc3u3iYCzILcq1eRWfUflpJSYG+XonwR0X25kwo1IhDsBHlsP9Um1Oe4lIvN2rCddunTp0uXmpBMAXbp06XIb5Ljc5LMacnw7wmgV5N8q0Hia/P/hHpfrjUfr2b4R2HolYf2vhDxo58RJaR4nET83Igtu5j3uphz37ve6Dt+oRsdpCJ6zWEOhS5cuXc6T9AW0S5cuXW5xMbj2s5MKld2Ke98P/XqSZ/RmcsLvB2n7+np9cScB1HHF+o4bQ73+Rve8ne2/GzrU9kOr13e6PWjD7bz/STpxu4sS3s9rRJcuXboU6REAXbp06XKbDcNXasje78WsjoskOA78D/e5qIf9TlV0P42c5OU+CfxfL3LhLLzPnSZJjksV0P/d6nbov7dbjpvDfU536dKly+2VTgB06dLlvpZb5Z3HPW72b9f7/DwD/1uVQ33acPfz3Fd3MgXlZsbkdvXnadpwt+pl3O1CktcD4KdZK25Fus2dBP/tv7c7mucsEWNdunTpcrekEwBdunS5r+VWFN46reF93HWt9/NeArGvFJyfNiS6G/PH93n7WdunN5I7VYLine truncated
|
||||
|
Before Width: | Height: | Size: 489 B After Width: | Height: | Size: 1.5 MiB |
@@ -3,3 +3,4 @@
|
||||
DEFAULT_TIMEOUT_SECONDS = 600
|
||||
DIALOG_AGENT_STARTUP_TIMEOUT_SECONDS = 30
|
||||
WORKER_START_GATE_TIMEOUT_SECONDS = DIALOG_AGENT_STARTUP_TIMEOUT_SECONDS + 15
|
||||
NATIVE_WRITE_STOP_WAIT_SECONDS = 120
|
||||
@@ -1,6 +1,8 @@
|
||||
"""Launch automation on a private Windows desktop, never the input desktop."""
|
||||
import subprocess
|
||||
import os
|
||||
import logging
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
import threading
|
||||
import win32con
|
||||
@@ -12,46 +14,110 @@ import win32service
|
||||
|
||||
_automation_clients = []
|
||||
_automation_clients_lock = threading.Lock()
|
||||
_supervisor_lost = threading.Event()
|
||||
_native_phases = {}
|
||||
|
||||
|
||||
def launch_save_helper(command, **kwargs):
|
||||
def _phase_pending(phase):
|
||||
if phase not in ('PRECALL', 'POSTCALL', 'RELEASE_CHECK', 'FINISHED', 'NATIVE_CALL', 'CLOSING'):
|
||||
return None
|
||||
from .operation_lifecycle import stop_disposition
|
||||
return stop_disposition(call_started=phase != 'PRECALL',
|
||||
call_returned=phase in ('POSTCALL', 'RELEASE_CHECK', 'FINISHED'),
|
||||
identity_confirmed=True) == 'WAIT_FOR_RETURN'
|
||||
|
||||
|
||||
@contextmanager
|
||||
def worker_phase(operation_id, phase):
|
||||
with _automation_clients_lock:
|
||||
if _supervisor_lost.is_set() and phase in ('NATIVE_CALL', 'CLOSING'):
|
||||
raise RuntimeError('WORKER_CANCELLED: 监督器已退出,未提交新的原生调用')
|
||||
_native_phases[operation_id] = phase
|
||||
yield
|
||||
|
||||
|
||||
def _record_write_pending(record_path, operation_id=None):
|
||||
if record_path is None:
|
||||
return None
|
||||
from .session_record import read_session_record
|
||||
path = Path(record_path).with_name('worker-state.json')
|
||||
try:
|
||||
state = read_session_record(path, evidence_root=path.parent)
|
||||
if operation_id is not None and state['operation_id'] != operation_id:
|
||||
return None
|
||||
return _phase_pending(state.get('phase'))
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def launch_save_helper(command, *, start_gate=None, identity_path=None, operation_id=None, **kwargs):
|
||||
"""Register the save client atomically with respect to supervisor loss."""
|
||||
with _automation_clients_lock:
|
||||
if _supervisor_lost.is_set():
|
||||
raise RuntimeError('VERIFY_CANCELLED: 监督器已退出,未启动新的保存客户端')
|
||||
helper = subprocess.Popen(command, **kwargs)
|
||||
_automation_clients.append(helper)
|
||||
if start_gate is not None:
|
||||
from .session_record import process_identity, read_session_record, write_session_record
|
||||
if identity_path is None or not operation_id:
|
||||
raise ValueError('保存启动门缺少会话记录')
|
||||
state = {'operation_id': operation_id, 'processes': []}
|
||||
identity_path = Path(identity_path)
|
||||
if identity_path.exists():
|
||||
state = read_session_record(identity_path, evidence_root=identity_path.parent)
|
||||
if state['operation_id'] != operation_id:
|
||||
raise ValueError('保存记录不属于当前操作')
|
||||
if helper.poll() is None:
|
||||
state['processes'].append({'role': 'helper', **process_identity(helper.pid)})
|
||||
state['phase'] = 'NATIVE_CALL'
|
||||
write_session_record(identity_path, state)
|
||||
Path(start_gate).touch()
|
||||
return helper
|
||||
|
||||
|
||||
def start_supervisor_watchdog(supervisor_pid, *, cancel_path=None, stop_clients=False):
|
||||
"""A crashed supervisor must not leave unsupervised automation writing.
|
||||
def start_supervisor_watchdog(supervisor_pid, *, cancel_path=None, stop_clients=False,
|
||||
session_record_path=None, operation_id=None, supervisor_identity=None):
|
||||
"""Record stop intent; a watchdog cannot interrupt an in-flight COM call.
|
||||
|
||||
Stop only this Python worker and its registered automation clients. Native
|
||||
database owners remain alive, including a COM call already in progress.
|
||||
stop_clients is retained for old callers, never permission to kill Save.
|
||||
"""
|
||||
import win32api
|
||||
parent = win32api.OpenProcess(win32con.SYNCHRONIZE, False, int(supervisor_pid))
|
||||
if supervisor_identity is not None:
|
||||
from .session_record import process_identity, IDENTITY_KEYS
|
||||
actual = process_identity(int(supervisor_pid))
|
||||
if any(actual[k] != supervisor_identity.get(k) for k in IDENTITY_KEYS):
|
||||
parent.Close()
|
||||
raise RuntimeError('监督器进程身份已变化,未启动原生操作')
|
||||
|
||||
def watch():
|
||||
try:
|
||||
win32event.WaitForSingleObject(parent, win32event.INFINITE)
|
||||
if cancel_path is not None:
|
||||
# Let native calls finish before the worker closes its exact
|
||||
# document. Killing a pending automation client can abandon it.
|
||||
Path(cancel_path).touch()
|
||||
if not stop_clients:
|
||||
return
|
||||
threading.Event().wait(5)
|
||||
with _automation_clients_lock:
|
||||
for helper in _automation_clients:
|
||||
try:
|
||||
if helper.poll() is None:
|
||||
helper.terminate()
|
||||
except OSError:
|
||||
pass
|
||||
_supervisor_lost.set()
|
||||
if cancel_path is not None:
|
||||
try:
|
||||
Path(cancel_path).touch()
|
||||
except OSError:
|
||||
logging.getLogger(__name__).warning('Unable to record orphan cancellation', exc_info=True)
|
||||
if session_record_path is not None:
|
||||
from .session_record import write_session_record
|
||||
try:
|
||||
write_session_record(Path(session_record_path).with_name('supervisor-lost.json'),
|
||||
{'operation_id': operation_id, 'phase': 'SUPERVISOR_LOST'})
|
||||
except (OSError, ValueError):
|
||||
logging.getLogger(__name__).warning('Unable to record supervisor loss', exc_info=True)
|
||||
while True:
|
||||
with _automation_clients_lock:
|
||||
pending = _record_write_pending(session_record_path, operation_id)
|
||||
# The same gate blocks new calls/helpers after loss. A stale
|
||||
# POSTCALL on disk cannot override an active in-memory call.
|
||||
if (pending is False and _phase_pending(_native_phases.get(operation_id)) is False
|
||||
and all(helper.poll() is not None for helper in _automation_clients)):
|
||||
os._exit(75) # This Python worker only; native children remain untouched.
|
||||
threading.Event().wait(.2)
|
||||
finally:
|
||||
parent.Close()
|
||||
if cancel_path is None or stop_clients:
|
||||
os._exit(75)
|
||||
|
||||
thread = threading.Thread(target=watch, name='supervisor-watchdog', daemon=True)
|
||||
thread.start()
|
||||
@@ -80,6 +146,8 @@ class DesktopWorker:
|
||||
self.companions = []
|
||||
self.companion_pids = []
|
||||
self.job_bound = False
|
||||
self.native_worker = any(flag in command for flag in (
|
||||
'--verify-worker', '--management-worker', '--repair-worker', '--native-backup-worker'))
|
||||
# Track the session, but never use kill-on-close: PCB descendants can
|
||||
# still own a database transaction when the Python supervisor exits.
|
||||
try:
|
||||
@@ -180,24 +248,25 @@ class DesktopWorker:
|
||||
return {'safe_to_continue': False, 'remaining_pids': [], 'error': str(error)}
|
||||
|
||||
def stop_automation_clients(self):
|
||||
from .mentor_adapter import _terminate_pid
|
||||
for pid in self._save_clients():
|
||||
_terminate_pid(pid)
|
||||
# An absent return marker is not permission to interrupt Save/Close.
|
||||
return self._save_clients()
|
||||
|
||||
@property
|
||||
def returncode(self):
|
||||
return self.poll()
|
||||
|
||||
def kill(self):
|
||||
"""Stop automation clients only; preserve native PCB/iCDB sessions."""
|
||||
"""Native workers use cooperative stop, including compatibility callers."""
|
||||
if getattr(self, 'native_worker', False) or hasattr(self, 'cancel_path'):
|
||||
if hasattr(self, 'cancel_path'):
|
||||
self.cancel_path.touch()
|
||||
return False
|
||||
try:
|
||||
win32process.TerminateProcess(self.handle, 1)
|
||||
except Exception:
|
||||
pass
|
||||
# The worker is now stopped and cannot spawn another save helper.
|
||||
try:
|
||||
self.wait(timeout=5)
|
||||
self.stop_automation_clients()
|
||||
except Exception:
|
||||
pass
|
||||
for companion in self.companions:
|
||||
@@ -209,6 +278,13 @@ class DesktopWorker:
|
||||
def bind_cancellation(self, path):
|
||||
self.cancel_path = Path(path)
|
||||
|
||||
def bind_session(self, job):
|
||||
from .session_record import register_worker_session
|
||||
register_worker_session(self, job)
|
||||
|
||||
def native_write_pending(self):
|
||||
return _record_write_pending(getattr(self, 'session_record_path', None))
|
||||
|
||||
def request_stop(self):
|
||||
if not hasattr(self, 'cancel_path'):
|
||||
# Compatibility for diagnostic workers without the Verify protocol.
|
||||
@@ -228,6 +304,8 @@ class DesktopWorker:
|
||||
try:
|
||||
if self.poll() is None:
|
||||
self.request_stop()
|
||||
if getattr(self, 'native_worker', False) or hasattr(self, 'cancel_path'):
|
||||
return False # The observer keeps this exact process/desktop handle.
|
||||
except Exception:
|
||||
pass
|
||||
for companion in self.companions:
|
||||
|
||||
@@ -109,6 +109,7 @@ def refresh_integration(pi, *, emit=lambda **event: None, settle_seconds=5, time
|
||||
emit(stage='integration_action_unavailable', action=method,
|
||||
initial_status=state[name], reason='mentor_not_allowed')
|
||||
raise IntegrationError(f'{name}: required but not allowed')
|
||||
check_error() # The permission getter itself can block past cancellation.
|
||||
emit(stage='integration_action', action=method, initial_status=state[name],
|
||||
reason='required_verification' if name not in executed else 'resynchronize')
|
||||
started = clock()
|
||||
|
||||
@@ -528,6 +528,8 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
|
||||
"""
|
||||
import win32con, win32event, win32file
|
||||
library = Path(library).resolve(strict=True)
|
||||
from .session_record import retained_session_snapshot, acknowledge_library_release
|
||||
retained = retained_session_snapshot(library)
|
||||
evidence = Path(evidence_dir).resolve()
|
||||
if evidence.is_relative_to(library.parent) or library.parent.is_relative_to(evidence):
|
||||
raise ValueError('释放检查证据必须位于目标库之外。')
|
||||
@@ -597,6 +599,7 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
|
||||
if owner:
|
||||
owner['handle'].Close()
|
||||
del _owners[lease.key]
|
||||
acknowledge_library_release(record, retained, block_name=scoped)
|
||||
return record
|
||||
finally:
|
||||
if external is not None:
|
||||
|
||||
@@ -284,9 +284,8 @@ def scan_open_library_status(library: Path, names, *, tree_image_reader=None,
|
||||
image_status_map=image_status_map)
|
||||
status = reconcile_statuses(tree_statuses, fallback, names)
|
||||
uncalibrated = [name for name in names if status.get(name, 'UNKNOWN') == 'UNKNOWN']
|
||||
# The UI must never use UNKNOWN as a skip signal. Queue it as Pending
|
||||
# so it receives the real Verify flow instead of being silently omitted.
|
||||
effective = {name: ('PENDING' if value == 'UNKNOWN' else value)
|
||||
# Missing observations remain unknown; eligibility is decided by the caller.
|
||||
effective = {name: (value if tree_images.get(name) is not None else 'UNKNOWN')
|
||||
for name, value in status.items()}
|
||||
logger.info(
|
||||
'library_status_sources names=%s image_histogram=%s current_image_map=%s cached_image_map=%s image_status_map=%s cache_actions=%s filesystem=%s calibrated_tree=%s final=%s uncalibrated_sample=%s conflicts=%s ready_anchor_ids=%s unseen_tree_ids=%s',
|
||||
@@ -328,46 +327,14 @@ def scan_open_library_status(library: Path, names, *, tree_image_reader=None,
|
||||
return effective
|
||||
|
||||
try:
|
||||
from pywinauto import Desktop
|
||||
from pywinauto.controls.common_controls import TreeViewWrapper
|
||||
from cbb_refresh_verify.mentor_adapter import _tree_image, same_path
|
||||
target = None
|
||||
for window in Desktop(backend='win32').windows():
|
||||
title = window.window_text()
|
||||
if title.startswith('Library Manager:') and same_path(title.split(':', 1)[1].strip(), library):
|
||||
target = window
|
||||
break
|
||||
if target is None:
|
||||
if tree_image_reader is None:
|
||||
from cbb_refresh_verify.mentor_adapter import read_library_tree_image_map
|
||||
tree_image_reader = read_library_tree_image_map
|
||||
return finish(tree_image_reader(library, names))
|
||||
trees = [w for w in target.descendants() if 'TreeView' in w.class_name()]
|
||||
if len(trees) != 1:
|
||||
return finish({})
|
||||
tree = TreeViewWrapper(trees[0].handle)
|
||||
root_name = Path(library).name
|
||||
images = {}
|
||||
missing = []
|
||||
for name in names:
|
||||
try:
|
||||
item = tree.get_item(['Central Libraries', root_name, 'Reusable Blocks', 'Logical-Physical', name], exact=True)
|
||||
from cbb_refresh_verify.mentor_adapter import _tree_image_details
|
||||
details = _tree_image_details(item, tree)
|
||||
images[name] = details['image_id']
|
||||
logger.info('library_tree_image_item name=%s image_id=%s selected_image_id=%s state_image_id=%s image_color=%s selected_image_color=%s state_image_color=%s',
|
||||
name, details['image_id'], details['selected_image_id'],
|
||||
details['state_image_id'], details['image_color'],
|
||||
details['selected_image_color'], details['state_image_color'])
|
||||
except Exception:
|
||||
images[name] = None
|
||||
missing.append(name)
|
||||
logger.info('library_tree_image_probe requested=%s read=%s missing=%s',
|
||||
len(names), len(names) - len(missing), missing[:20])
|
||||
return finish(images)
|
||||
if tree_image_reader is None:
|
||||
from .mentor_adapter import read_library_tree_image_map
|
||||
tree_image_reader = read_library_tree_image_map
|
||||
return finish(tree_image_reader(library, names))
|
||||
except Exception as error:
|
||||
logger.warning('library_status_probe_failed path=%s error=%s', library, error)
|
||||
return finish({})
|
||||
return {name: 'UNKNOWN' for name in names}
|
||||
|
||||
|
||||
|
||||
def read_library(path: Path, *, dispatch=None):
|
||||
|
||||
@@ -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):
|
||||
def run_management(request, *, adapter=None, verifier=None, idle_check=None, progress=None, stop=None):
|
||||
from .verify_runner import VerifyRequest, run_verify
|
||||
from .backup_recovery import _idle_check
|
||||
import win32con, win32event
|
||||
@@ -191,6 +191,8 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
change_report = None
|
||||
def invoke(callback, *args):
|
||||
nonlocal owner_safe
|
||||
if stop is not None and stop.is_set():
|
||||
raise InterruptedError('MANAGEMENT_CANCELLED: 已停止后续原生操作')
|
||||
owner_safe = False
|
||||
try:
|
||||
result = callback(*args)
|
||||
@@ -244,6 +246,10 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
from .com_runtime import initialize_com, uninitialize_com
|
||||
initialized = initialize_com()
|
||||
try:
|
||||
if stop is not None and stop.is_set():
|
||||
return finish('CANCELLED', '已取消,未启动原生管理操作')
|
||||
if hasattr(adapter, 'bind_stop'):
|
||||
adapter.bind_stop(stop)
|
||||
if request.operation not in ('add', 'update', 'remove'):
|
||||
raise ValueError('不支持的管理操作。')
|
||||
validate_name(request.name); validate_name(request.partition)
|
||||
@@ -349,6 +355,8 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
if build_exclusive_library_manifest(library_root, scope=scope, progress=progress) != original:
|
||||
raise OSError('内容基线记录后中心库发生变化,停止写入。')
|
||||
if request.operation in ('remove', 'update'):
|
||||
if stop is not None and stop.is_set():
|
||||
return finish('CANCELLED', '已取消,未开始移除', owner_safe)
|
||||
checkpoint('native_remove')
|
||||
mutated = True; owner_safe = False
|
||||
native = invoke(adapter.remove, request, root/'remove')
|
||||
@@ -365,6 +373,9 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
checkpoint('removed')
|
||||
if request.operation == 'remove':
|
||||
return finish('REMOVED', '已由原生操作移除,重新读取目录确认不存在;应用未创建备份。')
|
||||
if stop is not None and stop.is_set():
|
||||
return finish('RECOVERY_REQUIRED' if mutated else 'CANCELLED',
|
||||
'已停止后续导入;已发生的原生变更需要核对', owner_safe)
|
||||
checkpoint('native_add')
|
||||
mutated = True; owner_safe = False
|
||||
native = invoke(adapter.add, staged, root/'add')
|
||||
@@ -391,7 +402,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
checkpoint('verify')
|
||||
owner_safe = False
|
||||
verified = verifier(VerifyRequest(library, request.name, root/'verify',
|
||||
mapped_drive=request.mapped_drive, mapped_remote_root=request.mapped_remote_root), progress=progress)
|
||||
mapped_drive=request.mapped_drive, mapped_remote_root=request.mapped_remote_root), progress=progress, stop=stop)
|
||||
owner_safe = verified.safe_to_continue
|
||||
checkpoint('verified', verification=asdict(verified))
|
||||
good = verified.status == 'PASS' and verified.library_flag == 'GREEN' and owner_safe
|
||||
@@ -417,14 +428,24 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
|
||||
def run_management_batch(requests, *, stop=None, progress=None, **kwargs):
|
||||
results = []
|
||||
retained_libraries = set()
|
||||
for request in requests:
|
||||
if stop is not None and stop.is_set():
|
||||
break
|
||||
result = run_management(request, progress=progress, **kwargs)
|
||||
key = str(request.library).casefold()
|
||||
if key in retained_libraries:
|
||||
result = ManagementResult(request.operation, request.library, request.name, request.partition,
|
||||
request.source, request.auto_verify, 'complete', 'SKIPPED', True,
|
||||
'同库原生会话尚未释放,未启动新的写入')
|
||||
results.append(result)
|
||||
if progress:
|
||||
progress({'stage': result.status, 'block': result.name, 'detail': result.detail})
|
||||
continue
|
||||
result = run_management(request, progress=progress, stop=stop, **kwargs)
|
||||
results.append(result)
|
||||
if progress:
|
||||
progress({'stage': result.status, 'block': result.name, 'detail': result.detail,
|
||||
'evidence_path': str(result.evidence_path or '')})
|
||||
if not result.safe_to_continue:
|
||||
break
|
||||
retained_libraries.add(key)
|
||||
return results
|
||||
@@ -821,15 +821,16 @@ def execute_job(job, emit):
|
||||
script = Path(__file__).with_name('save_verified_block.vbs')
|
||||
cscript = Path(os.environ.get('WINDIR', r'C:\Windows'))/'SysWOW64'/'cscript.exe'
|
||||
from .desktop_worker import launch_save_helper
|
||||
helper_gate = root/'start-save.signal'
|
||||
with (root/'save.log').open('w', encoding='utf-8') as log:
|
||||
helper = launch_save_helper([str(cscript), '//nologo', str(script), job['project'],
|
||||
Path(job['pcb']).name, str(job.get('cancel_signal') or '')],
|
||||
Path(job['pcb']).name, str(job.get('cancel_signal') or ''), str(helper_gate)],
|
||||
start_gate=helper_gate, identity_path=root/'worker-state.json',
|
||||
operation_id=job.get('operation_id', root.name),
|
||||
stdout=log, stderr=log, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
||||
emit(stage='save_helper', helper_pid=helper.pid)
|
||||
last_markers = ()
|
||||
while helper.poll() is None:
|
||||
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
|
||||
raise RuntimeError('VERIFY_CANCELLED: 已停止等待保存客户端')
|
||||
try:
|
||||
current = tuple(line.strip() for line in (root/'save.log').read_text(encoding='utf-8', errors='replace').splitlines() if line.strip())
|
||||
except OSError:
|
||||
@@ -837,14 +838,18 @@ def execute_job(job, emit):
|
||||
if current != last_markers:
|
||||
last_markers = current
|
||||
from .runtime_timing import parse_save_progress
|
||||
emit(stage='save_progress', **parse_save_progress('\n'.join(current)))
|
||||
emit(stage='save_progress', helper_exited=False, **parse_save_progress('\n'.join(current)))
|
||||
time.sleep(.2)
|
||||
code = helper.returncode
|
||||
save_log = (root/'save.log').read_bytes().decode('utf-8', errors='replace')
|
||||
from .runtime_timing import parse_save_progress
|
||||
emit(stage='save_progress', **parse_save_progress(save_log))
|
||||
emit(stage='save_progress', helper_exited=True, **parse_save_progress(save_log))
|
||||
markers = set(save_log.splitlines())
|
||||
if (code not in (None, 0)) or not save_log_has_core_markers(save_log):
|
||||
from .operation_lifecycle import classify_save_state
|
||||
write_facts = classify_save_state(save_log.splitlines(), helper_exited=True, native_released=None)
|
||||
if ((code not in (None, 0)) or not save_log_has_core_markers(save_log)
|
||||
or write_facts['save_state'] != 'COMMITTED' or write_facts['close_state'] != 'CLOSED'
|
||||
or write_facts['interrupted']):
|
||||
raise RuntimeError(f'保存/关闭未完成 ({code}): {save_log}')
|
||||
if 'QUIT_OK' not in markers:
|
||||
emit(stage='save_quit_recovered', detail='Save/Close 已确认,忽略卡住的 app.Quit。')
|
||||
@@ -887,6 +892,9 @@ def execute_job(job, emit):
|
||||
pass
|
||||
if helper is not None and helper.poll() is None:
|
||||
emit(stage='save_helper_retained', helper_pid=helper.pid)
|
||||
elif helper is not None:
|
||||
# A failed/truncated Save result never authorizes discard-close.
|
||||
emit(stage='save_result_retained', detail='保存或关闭结果不完整,保留原生会话供核对')
|
||||
elif diagnostic_close_attempted:
|
||||
# The process-bound checker already sent its sole WM_CLOSE.
|
||||
# Preserve an unknown prompt; never fall back to global COM Close.
|
||||
@@ -920,19 +928,6 @@ def execute_job(job, emit):
|
||||
lm_session.close()
|
||||
|
||||
|
||||
def _terminate_pid(pid, *, timeout=20):
|
||||
"""Terminate a validated automation helper PID, never its native children."""
|
||||
try:
|
||||
subprocess.run(
|
||||
[str(Path(os.environ.get('WINDIR', r'C:\Windows'))/'System32'/'taskkill.exe'), '/PID', str(int(pid)), '/F'],
|
||||
capture_output=True,
|
||||
timeout=timeout,
|
||||
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def cleanup_verify_processes(lm_pid, worker_pid, worker_parent_pid=None, *,
|
||||
expected_pcb=None, baseline_pids=(), emit=None):
|
||||
"""Observe native process release without interrupting database writes.
|
||||
@@ -994,6 +989,22 @@ def worker_main(request_path):
|
||||
root = Path(job['root'])
|
||||
|
||||
def emit(**event):
|
||||
from .session_record import update_worker_state
|
||||
phase = {'save_start': 'NATIVE_CALL', 'integration_action': 'NATIVE_CALL',
|
||||
'integration_action_complete': 'POSTCALL', 'saved_and_closed': 'RELEASE_CHECK',
|
||||
'complete': 'FINISHED', 'failed': 'UNCONFIRMED'}.get(event.get('stage'))
|
||||
identities = [(role, event.get(key)) for role, key in
|
||||
(('native', 'pcb_pid'), ('native', 'lm_pid'), ('helper', 'helper_pid'))
|
||||
if event.get(key)]
|
||||
facts = None
|
||||
if event.get('stage') == 'save_progress':
|
||||
from .operation_lifecycle import classify_save_state
|
||||
facts = classify_save_state(event.get('markers', ()),
|
||||
helper_exited=event.get('helper_exited'), native_released=None)
|
||||
phase = ('POSTCALL' if event.get('helper_exited') is True else
|
||||
'CLOSING' if 'CLOSE_START' in event.get('markers', ()) else 'NATIVE_CALL')
|
||||
if phase or identities:
|
||||
update_worker_state(job, phase or 'UNCONFIRMED', identities=identities, write_outcome=facts)
|
||||
event.update(time=time.strftime('%Y-%m-%d %H:%M:%S'), block=job['block_name'],
|
||||
monotonic_seconds=time.monotonic())
|
||||
with (root/'events.jsonl').open('a', encoding='utf-8') as stream:
|
||||
@@ -1001,8 +1012,12 @@ def worker_main(request_path):
|
||||
|
||||
try:
|
||||
if job.get('supervisor_pid'):
|
||||
from .session_record import update_worker_state
|
||||
update_worker_state(job, 'PRECALL')
|
||||
from .desktop_worker import start_supervisor_watchdog
|
||||
start_supervisor_watchdog(job['supervisor_pid'], cancel_path=job.get('cancel_signal'), stop_clients=True)
|
||||
start_supervisor_watchdog(job['supervisor_pid'], cancel_path=job.get('cancel_signal'), stop_clients=True,
|
||||
supervisor_identity=job.get('supervisor_identity'),
|
||||
session_record_path=job.get('session_record_path'), operation_id=job.get('operation_id'))
|
||||
start_gate = Path(job.get('start_gate', '')) if job.get('start_gate') else None
|
||||
if start_gate is not None:
|
||||
from .defaults import WORKER_START_GATE_TIMEOUT_SECONDS
|
||||
@@ -1450,173 +1465,58 @@ def close_library_reader(pid, desktop, *, timeout_seconds=5):
|
||||
return False
|
||||
|
||||
|
||||
def read_library_flag(library, name, *, timeout_seconds=90, log_path=None):
|
||||
"""Return (flag, detail) for one CBB by reading its tree icon.
|
||||
|
||||
Read-only: Library Manager is started on a private desktop, the tree is
|
||||
walked with messages, the icon index is read, and the process is killed.
|
||||
The cursor is never moved and no menu is opened.
|
||||
"""
|
||||
import win32con
|
||||
import win32process
|
||||
import win32service
|
||||
def _existing_library_tree_images(library, names, *, timeout_seconds):
|
||||
"""Observe a matching, enabled LM; never launch, select, answer or close it."""
|
||||
from pywinauto import Desktop
|
||||
from pywinauto.controls.common_controls import TreeViewWrapper
|
||||
|
||||
executable = library_manager_path()
|
||||
if not executable.is_file():
|
||||
return FLAG_UNKNOWN, f'找不到 Library Manager: {executable}'
|
||||
|
||||
deadline = time.monotonic() + timeout_seconds
|
||||
desktop_name = 'CbbFlagRead_' + os.urandom(5).hex()
|
||||
desktop = None
|
||||
|
||||
handle = None
|
||||
pid = None
|
||||
handled = set()
|
||||
log = log_path or Path(library).parent/'LogFiles'/'cbb_flag_read_dialogs.jsonl'
|
||||
library = Path(library)
|
||||
result = {name: None for name in names}
|
||||
try:
|
||||
desktop = win32service.CreateDesktop(desktop_name, 0, win32con.GENERIC_ALL, None)
|
||||
startup = win32process.STARTUPINFO()
|
||||
startup.lpDesktop = 'winsta0\\' + desktop_name
|
||||
handle, thread, pid, _ = win32process.CreateProcess(
|
||||
str(executable), subprocess.list2cmdline([str(executable), str(library)]),
|
||||
None, None, False, win32con.CREATE_NO_WINDOW, None, None, startup)
|
||||
thread.Close()
|
||||
target = None
|
||||
while time.monotonic() < deadline:
|
||||
target = _private_library_window(desktop, library)
|
||||
if target is not None:
|
||||
break
|
||||
handle_known_dialogs(pid, handled, log, desktop=desktop)
|
||||
time.sleep(.3)
|
||||
if target is None:
|
||||
return FLAG_UNKNOWN, 'Library Manager 窗口未就绪(状态未读取)'
|
||||
|
||||
trees = [w for w in target.descendants() if 'TreeView' in w.class_name()]
|
||||
matches = [window for window in Desktop(backend='win32').windows()
|
||||
if window.window_text().startswith('Library Manager:')
|
||||
and same_path(window.window_text().split(':', 1)[1].strip(), library)]
|
||||
if len(matches) != 1:
|
||||
return result, '未找到唯一匹配库的已打开 Library Manager,状态无法确认'
|
||||
target = matches[0]
|
||||
if not target.is_enabled():
|
||||
return result, 'Library Manager 有原生提示或正在操作,状态无法确认'
|
||||
trees = [window for window in target.descendants() if 'TreeView' in window.class_name()]
|
||||
if len(trees) != 1:
|
||||
return FLAG_UNKNOWN, '导航树不唯一(状态未读取)'
|
||||
return result, '导航树不唯一,状态无法确认'
|
||||
tree = TreeViewWrapper(trees[0].handle)
|
||||
item = tree.get_item(['Central Libraries', Path(library).name, 'Reusable Blocks', 'Logical-Physical', name], exact=True)
|
||||
item.ensure_visible()
|
||||
index = _tree_image(item, tree)
|
||||
from .library_reader import filesystem_evidence_map, infer_tree_statuses, reconcile_statuses
|
||||
evidence = filesystem_evidence_map(library, (name,))
|
||||
filesystem = {name: evidence[name]['status']}
|
||||
calibrated = infer_tree_statuses({name: index}, filesystem, (name,))
|
||||
status = reconcile_statuses(calibrated, filesystem, (name,))[name]
|
||||
flag = FLAG_GREEN if status == 'READY' else FLAG_NOT_GREEN if status == 'PENDING' else FLAG_UNKNOWN
|
||||
detail = f'图标索引 {index};持久化证据={evidence.get(name, {})};校准状态={status}'
|
||||
if flag == FLAG_UNKNOWN:
|
||||
detail += ';未取得足够的持久化证据与图标 ID 对应关系,未强行判定'
|
||||
return flag, detail
|
||||
except Exception as error:
|
||||
return FLAG_UNKNOWN, f'状态读取失败: {error}'
|
||||
finally:
|
||||
released = pid is None or close_library_reader(pid, desktop)
|
||||
if handle is not None:
|
||||
deadline = time.monotonic() + timeout_seconds
|
||||
for name in names:
|
||||
if time.monotonic() >= deadline or not target.is_enabled():
|
||||
break
|
||||
try:
|
||||
handle.Close()
|
||||
item = tree.get_item(['Central Libraries', library.name, 'Reusable Blocks',
|
||||
'Logical-Physical', name], exact=True)
|
||||
result[name] = _tree_image(item, tree)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
if desktop is not None:
|
||||
desktop.CloseDesktop()
|
||||
except Exception:
|
||||
pass
|
||||
return result, '已观察匹配库的导航树图标;图标本身不是权威状态码'
|
||||
except Exception as error:
|
||||
return result, f'状态读取失败: {error}'
|
||||
|
||||
if not released:
|
||||
raise RuntimeError(f'LIBRARY_RELEASE_UNCONFIRMED: pid={pid}; desktop={desktop_name}')
|
||||
|
||||
def read_library_flag(library, name, *, timeout_seconds=90, log_path=None):
|
||||
library = Path(library)
|
||||
images, detail = _existing_library_tree_images(library, (name,), timeout_seconds=timeout_seconds)
|
||||
if images[name] is None:
|
||||
return FLAG_UNKNOWN, detail
|
||||
from .library_reader import filesystem_evidence_map, infer_tree_statuses, reconcile_statuses
|
||||
evidence = filesystem_evidence_map(library, (name,))
|
||||
filesystem = {name: evidence[name]['status']}
|
||||
calibrated = infer_tree_statuses(images, filesystem, (name,))
|
||||
status = reconcile_statuses(calibrated, filesystem, (name,))[name]
|
||||
flag = FLAG_GREEN if status == 'READY' else FLAG_NOT_GREEN if status == 'PENDING' else FLAG_UNKNOWN
|
||||
return flag, f'{detail};图标索引 {images[name]};校准状态={status}'
|
||||
|
||||
|
||||
def read_library_tree_image_map(library, names, *, timeout_seconds=45, log_path=None):
|
||||
"""Read all CBB tree icon resource IDs in one private LM session.
|
||||
|
||||
This is deliberately read-only. It avoids the previous one-process-per-
|
||||
CBB implementation, while keeping the LM window off the user's desktop.
|
||||
The returned integer is only an observation. It is logged with each CBB
|
||||
and calibrated against independent persisted Cert evidence because Mentor
|
||||
resource IDs vary by installation. Context-menu labels are not used.
|
||||
"""
|
||||
import win32con
|
||||
import win32process
|
||||
import win32service
|
||||
from pywinauto import Desktop
|
||||
from pywinauto.controls.common_controls import TreeViewWrapper
|
||||
|
||||
names = tuple(names)
|
||||
result = {name: None for name in names}
|
||||
executable = library_manager_path()
|
||||
if not executable.is_file():
|
||||
return result
|
||||
desktop_name = 'CbbStatusRead_' + os.urandom(5).hex()
|
||||
desktop = None
|
||||
handle = None
|
||||
pid = None
|
||||
handled = set()
|
||||
log = log_path or Path(library).parent/'LogFiles'/'cbb_status_read_dialogs.jsonl'
|
||||
try:
|
||||
desktop = win32service.CreateDesktop(desktop_name, 0, win32con.GENERIC_ALL, None)
|
||||
startup = win32process.STARTUPINFO()
|
||||
startup.lpDesktop = 'winsta0\\' + desktop_name
|
||||
handle, thread, pid, _ = win32process.CreateProcess(
|
||||
str(executable), subprocess.list2cmdline([str(executable), str(library)]),
|
||||
None, None, False, win32con.CREATE_NO_WINDOW, None, None, startup)
|
||||
handle.Close(); handle = None
|
||||
thread.Close()
|
||||
deadline = time.monotonic() + timeout_seconds
|
||||
target = None
|
||||
while time.monotonic() < deadline:
|
||||
target = _private_library_window(desktop, library)
|
||||
if target is not None:
|
||||
break
|
||||
handle_known_dialogs(pid, handled, log, desktop=desktop)
|
||||
time.sleep(.25)
|
||||
if target is None:
|
||||
return result
|
||||
trees = [w for w in target.descendants() if 'TreeView' in w.class_name()]
|
||||
if len(trees) != 1:
|
||||
return result
|
||||
tree = TreeViewWrapper(trees[0].handle)
|
||||
root_name = Path(library).name
|
||||
details = {}
|
||||
for name in names:
|
||||
if time.monotonic() >= deadline:
|
||||
logger.warning('library_tree_image_probe_timeout path=%s processed=%s total=%s',
|
||||
library, len(details), len(names))
|
||||
break
|
||||
try:
|
||||
item = tree.get_item(['Central Libraries', root_name, 'Reusable Blocks', 'Logical-Physical', name], exact=True)
|
||||
details[name] = _tree_image_details(item, tree)
|
||||
result[name] = details[name]['image_id']
|
||||
except Exception:
|
||||
result[name] = None
|
||||
logger.info('library_tree_images path=%s names=%s histogram=%s', library, len(names),
|
||||
dict(Counter(str(value) for value in result.values() if value is not None)))
|
||||
for name in names:
|
||||
if name in details:
|
||||
logger.info('library_tree_image_item name=%s image_id=%s selected_image_id=%s state_image_id=%s image_color=%s selected_image_color=%s state_image_color=%s',
|
||||
name, details[name]['image_id'], details[name]['selected_image_id'],
|
||||
details[name]['state_image_id'], details[name]['image_color'],
|
||||
details[name]['selected_image_color'], details[name]['state_image_color'])
|
||||
else:
|
||||
logger.warning('library_tree_image_item_missing name=%s reason=tree_path_lookup_failed', name)
|
||||
return result
|
||||
finally:
|
||||
released = pid is None or close_library_reader(pid, desktop)
|
||||
if handle is not None:
|
||||
try:
|
||||
handle.Close()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
if desktop is not None:
|
||||
desktop.CloseDesktop()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not released:
|
||||
raise RuntimeError(f'LIBRARY_RELEASE_UNCONFIRMED: pid={pid}; desktop={desktop_name}')
|
||||
library = Path(library)
|
||||
images, _ = _existing_library_tree_images(library, tuple(names), timeout_seconds=timeout_seconds)
|
||||
return images
|
||||
|
||||
|
||||
def read_library_status_map(library, names, *, timeout_seconds=45, log_path=None,
|
||||
|
||||
@@ -69,9 +69,14 @@ class NativeManagementAdapter:
|
||||
self.mapped_drive = ''
|
||||
self.mapped_remote_root = ''
|
||||
self._pending_workers = {}
|
||||
self.stop = None
|
||||
self.session_progress = None
|
||||
|
||||
def bind_stop(self, stop):
|
||||
self.stop = stop
|
||||
|
||||
def release_confirmed(self, library):
|
||||
"""Reap only this adapter's timed-out worker after its own release result."""
|
||||
"""Worker exit/result files do not replace independent resource proof."""
|
||||
key = str(Path(library).resolve()).casefold()
|
||||
pending = self._pending_workers.get(key)
|
||||
if pending is None:
|
||||
@@ -80,10 +85,17 @@ class NativeManagementAdapter:
|
||||
if worker.poll() is None:
|
||||
return False
|
||||
try:
|
||||
result = json.loads((evidence/'result.json').read_text(encoding='utf-8'))
|
||||
if result.get('safe_to_continue') is not True:
|
||||
return False
|
||||
except (OSError, ValueError, TypeError, AttributeError):
|
||||
if (evidence/'session.json').is_file():
|
||||
from .session_record import reconcile_session_record
|
||||
proof = reconcile_session_record(evidence/'session.json', evidence_root=evidence)
|
||||
if proof['status'] != 'RELEASED':
|
||||
return False
|
||||
else:
|
||||
from .library_lock import release_retained_library
|
||||
proof = release_retained_library(library, evidence/'release-proof')
|
||||
if proof.get('status') != 'RELEASE_CONFIRMED':
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
worker.close()
|
||||
if worker in _retained_workers:
|
||||
@@ -208,6 +220,12 @@ class NativeManagementAdapter:
|
||||
|
||||
def _launch_worker_observed(self, job, evidence, state):
|
||||
from .desktop_worker import DesktopWorker
|
||||
from .session_record import process_identity
|
||||
job = {**job, 'cancel_signal': str(evidence/'cancel-management.signal'),
|
||||
'start_gate': str(evidence/'start-management.signal'),
|
||||
'session_record_path': str(evidence/'session.json'), 'operation_id': uuid4().hex,
|
||||
'supervisor_pid': os.getpid(), 'supervisor_identity': process_identity(os.getpid()),
|
||||
'block': job.get('name')}
|
||||
request_path = evidence/'request.json'
|
||||
desktop, timeout = job['desktop'], job['timeout_seconds']
|
||||
deadline = time.monotonic() + timeout
|
||||
@@ -221,13 +239,27 @@ class NativeManagementAdapter:
|
||||
worker = (self.worker_factory or DesktopWorker)(command + ['--management-worker', str(request_path)], desktop)
|
||||
state['worker'] = worker
|
||||
worker.cbb_library = str(Path(job['library']).resolve())
|
||||
if hasattr(worker, 'bind_cancellation'):
|
||||
worker.bind_cancellation(job['cancel_signal'])
|
||||
if hasattr(worker, 'bind_session'):
|
||||
worker.bind_session(job)
|
||||
Path(job['start_gate']).touch()
|
||||
while worker.poll() is None and time.monotonic() < deadline:
|
||||
if self.stop is not None and self.stop.is_set():
|
||||
Path(job['cancel_signal']).touch()
|
||||
break
|
||||
time.sleep(.1)
|
||||
if worker.poll() is None:
|
||||
# DesktopWorker.close() requests a kill without a cancellation file.
|
||||
# Keep this exact worker alive until its native call returns normally.
|
||||
_retained_workers.append(worker)
|
||||
self._pending_workers[str(Path(job['library']).resolve()).casefold()] = (worker, evidence)
|
||||
Path(job['cancel_signal']).touch()
|
||||
if getattr(worker, 'session_record_path', None):
|
||||
from .session_record import handoff_session
|
||||
handoff_session(worker.session_record_path, evidence_root=evidence, process=worker,
|
||||
progress=(lambda value: self.session_progress({'stage': 'session_observation', **value}))
|
||||
if self.session_progress is not None else None)
|
||||
if add_job:
|
||||
(evidence/'cancel-native-add.signal').touch()
|
||||
return {'success': False, 'safe_to_continue': False,
|
||||
@@ -685,13 +717,43 @@ def _set_probe_field(hwnd, control_id, expected, root):
|
||||
def _probe_add_dialog(app, job, desktop, owned_pids, root, *, library=None):
|
||||
try:
|
||||
return _probe_add_dialog_impl(app, job, desktop, owned_pids, root, library=library)
|
||||
except Exception as error:
|
||||
if job.get('_native_add_pending') and str(error).startswith('NATIVE_ADD_FAILED:'):
|
||||
try:
|
||||
failure = json.loads((Path(root)/'native-add-output.json').read_text('utf-8')).get('failure', {})
|
||||
if failure.get('acknowledged') is True:
|
||||
job['_native_add_pending'] = False
|
||||
from .session_record import update_worker_state
|
||||
update_worker_state(job, 'POSTCALL')
|
||||
except (OSError, ValueError, AttributeError):
|
||||
pass
|
||||
raise
|
||||
finally:
|
||||
import gc
|
||||
gc.collect() # Release UIA wrappers before closing native child dialogs.
|
||||
_close_probe_dialogs(desktop, owned_pids)
|
||||
if not job.get('_native_add_pending'):
|
||||
_close_probe_dialogs(desktop, owned_pids)
|
||||
|
||||
|
||||
def _require_management_continuation(job, root):
|
||||
"""Check before a new native call; never abort a call already on the stack."""
|
||||
from .library_lock import _supervisor_alive
|
||||
cancelled = job.get('cancel_signal') and Path(job['cancel_signal']).exists()
|
||||
supervisor = job.get('supervisor_pid')
|
||||
if cancelled or supervisor is None or not _supervisor_alive(supervisor):
|
||||
raise RuntimeError('MANAGEMENT_CANCELLED: 操作已停止或监督器已退出,未提交新的原生调用')
|
||||
if job.get('supervisor_identity'):
|
||||
from .session_record import process_identity, IDENTITY_KEYS
|
||||
actual = process_identity(supervisor)
|
||||
if any(actual[k] != job['supervisor_identity'].get(k) for k in IDENTITY_KEYS):
|
||||
raise RuntimeError('MANAGEMENT_CANCELLED: 监督器身份已变化,未提交新的原生调用')
|
||||
|
||||
|
||||
def _require_add_supervisor(job, root):
|
||||
try:
|
||||
_require_management_continuation(job, root)
|
||||
except RuntimeError as error:
|
||||
raise RuntimeError(f'NATIVE_ADD_CANCELLED: {error}') from error
|
||||
from .library_lock import _supervisor_alive
|
||||
deadline = job.get('native_add_deadline')
|
||||
if ((Path(root)/'cancel-native-add.signal').exists()
|
||||
@@ -773,6 +835,9 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
|
||||
_write_json(root/'native-add-log-baseline.json', log_baseline)
|
||||
observed_failures = {}
|
||||
_require_add_supervisor(job, root)
|
||||
from .session_record import update_worker_state
|
||||
update_worker_state(job, 'NATIVE_CALL', required=True)
|
||||
job['_native_add_pending'] = True
|
||||
win32gui.PostMessage(ok, win32con.BM_CLICK, 0, 0)
|
||||
success = None
|
||||
while time.monotonic() < deadline:
|
||||
@@ -803,6 +868,8 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
|
||||
break
|
||||
if not success:
|
||||
raise TimeoutError('未取得原生新增成功消息;保留副本与私有桌面证据。')
|
||||
job['_native_add_pending'] = False
|
||||
update_worker_state(job, 'POSTCALL')
|
||||
|
||||
|
||||
def run_isolated_probe(source, root, name, *, mentor_home=None, replacement_source=None):
|
||||
@@ -1038,10 +1105,15 @@ def _catalog_com(job, root):
|
||||
result = {'success': False, 'safe_to_continue': False}
|
||||
watcher = None
|
||||
try:
|
||||
_require_management_continuation(job, root)
|
||||
from .session_record import update_worker_state
|
||||
update_worker_state(job, 'NATIVE_CALL')
|
||||
app = win32com.client.DispatchEx('LibraryManager.Application')
|
||||
app.Visible = True
|
||||
processes = _process_details('LibraryManager.exe')
|
||||
owned_pids.update(int(p[0]) for p in processes)
|
||||
from .session_record import update_worker_state
|
||||
update_worker_state(job, 'POSTCALL', identities=[('native', pid) for pid in owned_pids])
|
||||
if len(owned_pids) != 1:
|
||||
raise RuntimeError('无法唯一确认本次 Library Manager 进程。')
|
||||
expected_binary = Path(job['mentor_home'])/'lm/win32/bin/LibraryManager.exe'
|
||||
@@ -1051,12 +1123,17 @@ def _catalog_com(job, root):
|
||||
watcher.start()
|
||||
if job['operation'] in ('probe_create_add', 'probe_create'):
|
||||
target = prepare_probe_library(job, root)
|
||||
_require_management_continuation(job, root)
|
||||
update_worker_state(job, 'NATIVE_CALL')
|
||||
library = app.CreateLibrary(str(target), 1)
|
||||
_write_json(root.parent/'probe-owner.json', {'library': str(target), 'token': job['probe_token']})
|
||||
else:
|
||||
if job['operation'] == 'probe_readd':
|
||||
validate_probe_readd(job, root)
|
||||
_require_management_continuation(job, root)
|
||||
update_worker_state(job, 'NATIVE_CALL')
|
||||
library = app.OpenLibrary(str(absolute_preserving_drive(job['library'])))
|
||||
update_worker_state(job, 'POSTCALL')
|
||||
if refused:
|
||||
raise RuntimeError('目录读取需要升级中心库或选择流程;已拒绝,目标未获准自动升级。')
|
||||
if library is None or Path(str(library.FullName)).resolve() != Path(job['library']).resolve():
|
||||
@@ -1065,8 +1142,11 @@ def _catalog_com(job, root):
|
||||
if int(library.FlowType) != 1:
|
||||
raise RuntimeError('Native Add requires the DxDesigner Logical-Physical library flow.')
|
||||
_probe_add_dialog(app, job, desktop, owned_pids, root, library=library)
|
||||
update_worker_state(job, 'CLOSING')
|
||||
library.Close()
|
||||
library = None
|
||||
_require_management_continuation(job, root)
|
||||
update_worker_state(job, 'NATIVE_CALL')
|
||||
library = app.OpenLibrary(str(absolute_preserving_drive(job['library'])))
|
||||
if (library is None or Path(str(library.FullName)).resolve() != Path(job['library']).resolve()
|
||||
or int(library.FlowType) != 1):
|
||||
@@ -1107,14 +1187,18 @@ def _catalog_com(job, root):
|
||||
result['detail'] = str(error)
|
||||
result['exception'] = _exception_details(error)
|
||||
finally:
|
||||
if library is not None:
|
||||
try: library.Close()
|
||||
if library is not None and not job.get('_native_add_pending'):
|
||||
try:
|
||||
update_worker_state(job, 'CLOSING')
|
||||
library.Close()
|
||||
except Exception as error:
|
||||
result['close_detail'] = str(error)
|
||||
result['close_exception'] = _exception_details(error)
|
||||
library = None
|
||||
if app is not None:
|
||||
try: app.Quit()
|
||||
if app is not None and not job.get('_native_add_pending'):
|
||||
try:
|
||||
update_worker_state(job, 'CLOSING')
|
||||
app.Quit()
|
||||
except Exception as error:
|
||||
result['quit_detail'] = str(error)
|
||||
result['quit_exception'] = _exception_details(error)
|
||||
@@ -1138,6 +1222,22 @@ def management_worker_main(request_path):
|
||||
_, desktop = _current_desktop()
|
||||
if desktop != job['desktop'] or not desktop.startswith('CbbManagement_'):
|
||||
raise RuntimeError('原生管理操作仅允许在本次私有桌面执行。')
|
||||
_require_management_continuation(job, root)
|
||||
if job.get('cancel_signal'):
|
||||
from .session_record import update_worker_state
|
||||
update_worker_state(job, 'PRECALL')
|
||||
from .desktop_worker import start_supervisor_watchdog
|
||||
start_supervisor_watchdog(job['supervisor_pid'], cancel_path=job['cancel_signal'],
|
||||
supervisor_identity=job.get('supervisor_identity'),
|
||||
session_record_path=job.get('session_record_path'), operation_id=job.get('operation_id'))
|
||||
if job.get('start_gate'):
|
||||
deadline = time.monotonic() + 30
|
||||
while not Path(job['start_gate']).is_file():
|
||||
_require_management_continuation(job, root)
|
||||
if time.monotonic() >= deadline:
|
||||
raise RuntimeError('MANAGEMENT_CANCELLED: 启动门未放行,未启动原生操作')
|
||||
time.sleep(.05)
|
||||
_require_management_continuation(job, root)
|
||||
if job.get('mapped_drive') and job.get('mapped_remote_root'):
|
||||
from .network_path import ensure_mapped_drive_visible
|
||||
ensure_mapped_drive_visible(job['mapped_drive'], job['mapped_remote_root'])
|
||||
@@ -1165,6 +1265,9 @@ def management_worker_main(request_path):
|
||||
command = [str(adapter.home/'lm/win32/bin/CleanWGLib.exe'), str(job['library']), 'F4', str(input_path)]
|
||||
_write_json(root/'command.json', command)
|
||||
with (root/'native-output.txt').open('wb') as output:
|
||||
_require_management_continuation(job, root)
|
||||
from .session_record import update_worker_state
|
||||
update_worker_state(job, 'NATIVE_CALL')
|
||||
result['safe_to_continue'] = False
|
||||
try:
|
||||
process = subprocess.Popen(command, stdout=output, stderr=subprocess.STDOUT,
|
||||
@@ -1172,17 +1275,27 @@ def management_worker_main(request_path):
|
||||
except (FileNotFoundError, PermissionError):
|
||||
result['safe_to_continue'] = True
|
||||
raise
|
||||
_write_json(root/'native-process.json', {'pid': process.pid, 'command': command})
|
||||
update_worker_state(job, 'NATIVE_CALL', identities=[('native', process.pid)])
|
||||
try:
|
||||
_write_json(root/'native-process.json', {'pid': process.pid, 'command': command})
|
||||
except OSError:
|
||||
pass # Keep supervising the native owner even when evidence storage fails.
|
||||
# Never terminate this native database owner on timeout.
|
||||
try:
|
||||
code = process.wait(timeout=float(job['timeout_seconds']))
|
||||
except subprocess.TimeoutExpired:
|
||||
result.update(detail=f'TIMEOUT: CleanWGLib PID {process.pid} 尚未释放')
|
||||
else:
|
||||
result.update(safe_to_continue=True, exit_code=code)
|
||||
text = (root/'native-output.txt').read_bytes().decode('mbcs', errors='replace')
|
||||
result.update(success=removal_output_ok(code, text, job['name'], job['partition']),
|
||||
detail=text)
|
||||
while True:
|
||||
try:
|
||||
code = process.wait(timeout=1)
|
||||
break
|
||||
except subprocess.TimeoutExpired:
|
||||
continue
|
||||
result['wait_exceeded'] = True
|
||||
result.update(safe_to_continue=True, exit_code=code)
|
||||
text = (root/'native-output.txt').read_bytes().decode('mbcs', errors='replace')
|
||||
result.update(success=removal_output_ok(code, text, job['name'], job['partition']),
|
||||
detail=text)
|
||||
else:
|
||||
raise ValueError('未验证的原生管理操作')
|
||||
except Exception as error:
|
||||
@@ -1191,5 +1304,7 @@ def management_worker_main(request_path):
|
||||
result['detail'] = str(error)
|
||||
result['exception'] = _exception_details(error)
|
||||
finally:
|
||||
from .session_record import update_worker_state
|
||||
update_worker_state(job, 'FINISHED' if result.get('safe_to_continue') is True else 'UNCONFIRMED')
|
||||
_write_json(root/'result.json', result)
|
||||
return 0 if result['success'] and result['safe_to_continue'] else 2
|
||||
@@ -124,7 +124,7 @@ def backup_project(target, destination):
|
||||
handle.Close()
|
||||
|
||||
|
||||
def attempt_recovery(request, diagnosis, evidence_root, *, progress=None):
|
||||
def attempt_recovery(request, diagnosis, evidence_root, *, progress=None, stop=None):
|
||||
root = Path(evidence_root)/'native-repair'
|
||||
root.mkdir(exist_ok=True)
|
||||
marker = root/'attempt.json'
|
||||
@@ -152,7 +152,7 @@ def attempt_recovery(request, diagnosis, evidence_root, *, progress=None):
|
||||
raise ValueError('REPAIR_DATABASE_IN_USE: 目标的保存/关闭助手尚未退出')
|
||||
callback = (lambda event: progress({'block': request.block_name, **event})) if progress else None
|
||||
record = run_native_repair(target, root, mentor_bin=request.mentor_bin,
|
||||
timeout_seconds=max(60, request.timeout_seconds), progress=callback)
|
||||
timeout_seconds=max(60, request.timeout_seconds), progress=callback, stop=stop)
|
||||
native_status = record.get('status')
|
||||
record['release'] = repair_release_state(request, target, record)
|
||||
if native_status == 'REPAIRED' and record['release']['safe_to_continue'] is not True:
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Facts from one helper invocation; process exit is not a Save result."""
|
||||
from collections.abc import Sequence
|
||||
|
||||
|
||||
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}
|
||||
save_results = names & {'SAVE_OK', 'SAVE_REJECTED', 'SAVE_RESULT_UNKNOWN',
|
||||
'CANCELLED_BEFORE_SAVE'}
|
||||
conflicting_save = (len(save_results) > 1 or
|
||||
('CANCELLED_BEFORE_SAVE' in names and 'SAVE_START' in names))
|
||||
conflicting_close = {'CLOSE_OK', 'CLOSE_FAILED'} <= names
|
||||
save_state = 'UNKNOWN'
|
||||
if not conflicting_save:
|
||||
for marker, state in (('SAVE_OK', 'COMMITTED'), ('SAVE_REJECTED', 'REJECTED'),
|
||||
('CANCELLED_BEFORE_SAVE', 'NOT_STARTED')):
|
||||
if marker in names:
|
||||
save_state = state
|
||||
close_state = 'UNKNOWN'
|
||||
if not conflicting_close:
|
||||
if 'CLOSE_OK' in names:
|
||||
close_state = 'CLOSED'
|
||||
elif 'CLOSE_FAILED' in names:
|
||||
close_state = 'FAILED'
|
||||
resource_state = ('RELEASED' if native_released is True and helper_exited is True else
|
||||
'RETAINED' if native_released is False or helper_exited is False else
|
||||
'UNKNOWN')
|
||||
reasons = []
|
||||
if conflicting_save or conflicting_close:
|
||||
reasons.append('本轮返回标记矛盾')
|
||||
if save_state == 'UNKNOWN':
|
||||
reasons.append('保存返回结果无法确认')
|
||||
if close_state == 'FAILED':
|
||||
reasons.append('原生关闭失败')
|
||||
if 'POST_SAVE_FAILED' in names:
|
||||
reasons.append('保存后核对失败')
|
||||
if forced:
|
||||
reasons.append('会话被中断,退出不代表保存完成')
|
||||
interrupted = (forced or conflicting_save or conflicting_close or
|
||||
'SAVE_RESULT_UNKNOWN' in names or
|
||||
(helper_exited is True and 'SAVE_START' in names and save_state == 'UNKNOWN'))
|
||||
return dict(save_state=save_state, close_state=close_state,
|
||||
helper_state='EXITED' if helper_exited is True else
|
||||
'RUNNING' if helper_exited is False else 'UNKNOWN',
|
||||
resource_state=resource_state, interrupted=interrupted,
|
||||
detail=';'.join(reasons))
|
||||
|
||||
|
||||
def stop_disposition(*, call_started: bool | None, call_returned: bool | None,
|
||||
identity_confirmed: bool) -> str:
|
||||
if not identity_confirmed or call_started is None:
|
||||
return 'OBSERVE_UNCONFIRMED'
|
||||
if call_started is False:
|
||||
return 'CANCEL_BEFORE_CALL' if call_returned is False else 'OBSERVE_UNCONFIRMED'
|
||||
return 'CLEANUP_RETURNED' if call_returned is True else 'WAIT_FOR_RETURN'
|
||||
@@ -21,6 +21,8 @@ _FORCE_CLIENT_NAMES = {'expeditionpcb.exe', 'librarymanager.exe', 'viewdraw.exe'
|
||||
|
||||
def force_block_reason(row):
|
||||
"""A library path proves scope, never exclusive ownership of a server."""
|
||||
if row.get('runtime_phase') in ('NATIVE_CALL', 'CLOSING', 'UNCONFIRMED'):
|
||||
return '本工具的保存或原生调用尚未确认返回,请等待或查看原生提示'
|
||||
if row.get('scope_confirmed') is not True:
|
||||
return '进程归属未确认,不允许强制结束'
|
||||
name = str(row.get('name', '')).casefold()
|
||||
@@ -355,9 +357,14 @@ def inspect_residual_sessions(library, *, block_names=()):
|
||||
if scope is not False:
|
||||
candidates.append({**row, 'scope_confirmed': scope is True})
|
||||
windows = _process_windows({r['pid'] for r in candidates})
|
||||
from .session_record import active_write_records
|
||||
runtime_writes = active_write_records(library)
|
||||
sessions = []
|
||||
for row in candidates:
|
||||
item = dict(row)
|
||||
item['library'] = str(library)
|
||||
if runtime_writes and row['scope_confirmed']:
|
||||
item['runtime_phase'] = runtime_writes[0]['phase']
|
||||
item['block_names'] = list(blocks)
|
||||
error = _window_error(windows, row['pid'])
|
||||
item.update(windows_incomplete=bool(error), window_read_error=error)
|
||||
@@ -450,6 +457,10 @@ 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 row.get('library'):
|
||||
from .session_record import active_write_records
|
||||
if active_write_records(row['library']):
|
||||
return {'release_status': 'WAITING', 'detail': '保存或原生调用尚未确认返回,未强制结束'}
|
||||
if reason := force_block_reason(row):
|
||||
return {'release_status': 'WAITING', 'detail': reason}
|
||||
with _process_handle(row['pid'], terminate=True) as handle:
|
||||
@@ -625,6 +636,10 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca
|
||||
or Path(proof.get('library', '')).resolve() != library):
|
||||
raise ValueError('释放证明与当前库不一致')
|
||||
result['status'] = 'RELEASE_CONFIRMED'
|
||||
from .session_record import record_session_release
|
||||
errors = record_session_release(proof, plan.get('runtime_sessions', []))
|
||||
if errors:
|
||||
result['evidence_error'] = ';'.join(errors)
|
||||
except BaseException as error:
|
||||
result.update(status='PARTIAL', detail=f'{type(error).__name__}: {error}')
|
||||
if not isinstance(error, Exception):
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
Option Explicit
|
||||
Dim app, doc, pi, licensing, token, expected, attempt, stable, measuredStart, operationOK, remaining
|
||||
Dim nativeError, nativeDescription
|
||||
WaitForStartGate
|
||||
CheckCancellation
|
||||
expected = WScript.Arguments(0)
|
||||
Set app = GetObject(, "MGCPCB.Application")
|
||||
Set doc = app.ActiveDocument
|
||||
@@ -17,40 +20,89 @@ token = licensing.GetToken(doc.Validate(0))
|
||||
doc.Validate token
|
||||
LogElapsed "validate", measuredStart
|
||||
WScript.Echo "LICENSE_OK"
|
||||
CheckCancellation
|
||||
WScript.Echo "SAVE_START"
|
||||
CheckCancellation
|
||||
measuredStart = Timer
|
||||
On Error Resume Next
|
||||
operationOK = doc.Save()
|
||||
nativeError = Err.Number
|
||||
nativeDescription = Err.Description
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
LogElapsed "save", measuredStart
|
||||
If Not operationOK Then WScript.Quit 4
|
||||
If nativeError <> 0 Then
|
||||
WScript.Echo "SAVE_RESULT_UNKNOWN|" & CStr(nativeError) & "|" & nativeDescription
|
||||
WScript.Quit 11
|
||||
End If
|
||||
If Not operationOK Then
|
||||
WScript.Echo "SAVE_REJECTED"
|
||||
WScript.Quit 4
|
||||
End If
|
||||
WScript.Echo "SAVE_OK"
|
||||
CheckCancellation
|
||||
measuredStart = Timer
|
||||
On Error Resume Next
|
||||
operationOK = doc.IsSaved()
|
||||
nativeError = Err.Number
|
||||
nativeDescription = Err.Description
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
LogElapsed "is_saved", measuredStart
|
||||
If Not operationOK Then WScript.Quit 5
|
||||
If nativeError <> 0 Or Not operationOK Then
|
||||
WScript.Echo "POST_SAVE_FAILED|" & CStr(nativeError) & "|" & nativeDescription
|
||||
WScript.Quit 5
|
||||
End If
|
||||
WScript.Echo "IS_SAVED"
|
||||
stable = False
|
||||
WScript.Echo "POST_SAVE_CHECK"
|
||||
measuredStart = Timer
|
||||
For attempt = 1 To 50
|
||||
On Error Resume Next
|
||||
Set pi = doc.ProjectIntegration
|
||||
If pi.ForwardAnnotationStatus = 2 And pi.SynchCESStatus = 2 And pi.LoadCESStatus = 2 And pi.BackAnnotationStatus = 2 Then
|
||||
stable = (pi.ForwardAnnotationStatus = 2 And pi.SynchCESStatus = 2 And pi.LoadCESStatus = 2 And pi.BackAnnotationStatus = 2)
|
||||
nativeError = Err.Number
|
||||
nativeDescription = Err.Description
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
If nativeError <> 0 Then
|
||||
WScript.Echo "POST_SAVE_FAILED|" & CStr(nativeError) & "|" & nativeDescription
|
||||
WScript.Quit 7
|
||||
End If
|
||||
If stable Then
|
||||
stable = True
|
||||
Exit For
|
||||
End If
|
||||
WScript.Sleep 200
|
||||
Next
|
||||
LogElapsed "post_save_check", measuredStart
|
||||
If Not stable Then WScript.Quit 7
|
||||
If Not stable Then
|
||||
WScript.Echo "POST_SAVE_FAILED|integration_not_synchronized"
|
||||
WScript.Quit 7
|
||||
End If
|
||||
WScript.Echo "POST_SAVE_SYNCHRONIZED"
|
||||
If Not doc.IsSaved() Then WScript.Quit 8
|
||||
On Error Resume Next
|
||||
operationOK = doc.IsSaved() And LCase(pi.ProjectFile) = LCase(expected)
|
||||
If WScript.Arguments.Count > 1 Then operationOK = operationOK And LCase(doc.Name) = LCase(WScript.Arguments(1))
|
||||
nativeError = Err.Number
|
||||
nativeDescription = Err.Description
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
If nativeError <> 0 Or Not operationOK Then
|
||||
WScript.Echo "POST_SAVE_FAILED|" & CStr(nativeError) & "|identity_or_saved_state_unconfirmed|" & nativeDescription
|
||||
WScript.Quit 8
|
||||
End If
|
||||
WScript.Echo "CLOSE_START"
|
||||
CheckCancellation
|
||||
measuredStart = Timer
|
||||
On Error Resume Next
|
||||
operationOK = doc.Close(True)
|
||||
nativeError = Err.Number
|
||||
nativeDescription = Err.Description
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
LogElapsed "close", measuredStart
|
||||
If Not operationOK Then WScript.Quit 6
|
||||
If nativeError <> 0 Or Not operationOK Then
|
||||
WScript.Echo "CLOSE_FAILED|" & CStr(nativeError) & "|" & nativeDescription
|
||||
WScript.Quit 6
|
||||
End If
|
||||
WScript.Echo "CLOSE_OK"
|
||||
Set pi = Nothing
|
||||
Set doc = Nothing
|
||||
@@ -75,11 +127,30 @@ Sub CheckCancellation()
|
||||
If Len(cancelPath) = 0 Then Exit Sub
|
||||
Set fso = CreateObject("Scripting.FileSystemObject")
|
||||
If fso.FileExists(cancelPath) Then
|
||||
WScript.Echo "CANCELLED_BEFORE_SAVE"
|
||||
WScript.Echo "VERIFY_CANCELLED"
|
||||
WScript.Quit 9
|
||||
End If
|
||||
End Sub
|
||||
|
||||
Sub WaitForStartGate()
|
||||
Dim fso, started, elapsed
|
||||
If WScript.Arguments.Count < 4 Then Exit Sub
|
||||
Set fso = CreateObject("Scripting.FileSystemObject")
|
||||
started = Timer
|
||||
Do
|
||||
CheckCancellation
|
||||
If fso.FileExists(WScript.Arguments(3)) Then Exit Sub
|
||||
elapsed = Timer - started
|
||||
If elapsed < 0 Then elapsed = elapsed + 86400
|
||||
If elapsed >= 30 Then
|
||||
WScript.Echo "CANCELLED_BEFORE_SAVE|start_gate_timeout"
|
||||
WScript.Quit 9
|
||||
End If
|
||||
WScript.Sleep 50
|
||||
Loop
|
||||
End Sub
|
||||
|
||||
Sub LogElapsed(phaseName, started)
|
||||
Dim elapsed
|
||||
elapsed = Timer - started
|
||||
|
||||
@@ -0,0 +1,441 @@
|
||||
"""Bounded, observation-only journal for native calls that outlive a task."""
|
||||
from contextlib import ExitStack
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import threading
|
||||
from uuid import uuid4
|
||||
|
||||
PROTOCOL = 'cbb-runtime-session'
|
||||
MAX_BYTES = 64 * 1024
|
||||
IDENTITY_KEYS = ('pid', 'created_handle', 'image', 'owner_sid', 'session_id')
|
||||
_observers = {}
|
||||
_observer_guard = threading.Lock()
|
||||
_retained_libraries = {}
|
||||
_retained_results = {}
|
||||
|
||||
|
||||
def _library_key(library):
|
||||
return os.path.normcase(os.path.normpath(str(library)))
|
||||
|
||||
|
||||
def library_available(library):
|
||||
"""Cached queue predicate: no file, process or network queries."""
|
||||
key = _library_key(library)
|
||||
with _observer_guard:
|
||||
return not any(key in aliases for aliases in _retained_libraries.values())
|
||||
|
||||
|
||||
def retained_session_snapshot(library):
|
||||
key = _library_key(library)
|
||||
with _observer_guard:
|
||||
return {path: (aliases, _retained_results.get(path, {}).get('block'))
|
||||
for path, aliases in _retained_libraries.items() if key in aliases}
|
||||
|
||||
|
||||
def acknowledge_library_release(proof, snapshot, *, block_name=None):
|
||||
"""Called under fresh proof handles; never clear a newer handoff."""
|
||||
if proof.get('status') != 'RELEASE_CONFIRMED':
|
||||
return
|
||||
key = _library_key(proof['library'])
|
||||
with _observer_guard:
|
||||
records = [dict(_retained_results.get(path, {}), path=path)
|
||||
for path, (aliases, block) in snapshot.items()
|
||||
if key in aliases and _retained_libraries.get(path) is aliases
|
||||
and (block_name is None or block == block_name)]
|
||||
record_session_release(proof, records)
|
||||
with _observer_guard:
|
||||
for path, (aliases, block) in snapshot.items():
|
||||
if (key in aliases and _retained_libraries.get(path) is aliases
|
||||
and (block_name is None or block == block_name)):
|
||||
_retained_libraries.pop(path, None)
|
||||
_retained_results.pop(path, None)
|
||||
|
||||
|
||||
def record_session_release(proof, records):
|
||||
"""Persist a past proof only for the pre-proof operation, never replay it."""
|
||||
errors = []
|
||||
if proof.get('status') != 'RELEASE_CONFIRMED':
|
||||
return errors
|
||||
library = Path(proof['library']).resolve()
|
||||
for record in records:
|
||||
try:
|
||||
path = Path(record['path'])
|
||||
session = read_session_record(path, evidence_root=path.parent)
|
||||
if (session['operation_id'] != record.get('operation_id')
|
||||
or Path(session['library']).resolve() != library):
|
||||
continue
|
||||
write_session_record(path.with_name('observation-release-'+uuid4().hex+'.json'), {
|
||||
'operation_id': session['operation_id'], 'library': str(library),
|
||||
'status': 'RELEASED', 'release_proof': proof})
|
||||
except (OSError, ValueError, KeyError) as error:
|
||||
errors.append(str(error))
|
||||
logging.getLogger(__name__).warning('Unable to record session release', exc_info=True)
|
||||
return errors
|
||||
|
||||
|
||||
def retained_session_states(library):
|
||||
key = _library_key(library)
|
||||
with _observer_guard:
|
||||
return [dict(_retained_results[path], path=path) for path, aliases in _retained_libraries.items()
|
||||
if key in aliases and path in _retained_results]
|
||||
|
||||
|
||||
def register_worker_session(worker, job):
|
||||
"""The launcher must persist identity before opening the worker's gate."""
|
||||
path = Path(job['session_record_path'])
|
||||
write_session_record(path, {k: job.get(k) for k in (
|
||||
'operation_id', 'operation', 'library', 'block', 'desktop', 'cancel_signal')}
|
||||
| {'processes': [{'role': 'worker', **process_identity(worker.pid)}]})
|
||||
worker.session_record_path = path
|
||||
worker.cbb_library = job['library']
|
||||
|
||||
|
||||
def update_worker_state(job, phase, *, identities=(), write_outcome=None, required=False):
|
||||
if not job.get('session_record_path'):
|
||||
if required:
|
||||
raise ValueError('原生写入缺少会话记录位置,未提交新的调用')
|
||||
return False
|
||||
from .desktop_worker import worker_phase
|
||||
with worker_phase(job['operation_id'], phase):
|
||||
path = Path(job['session_record_path']).with_name('worker-state.json')
|
||||
try:
|
||||
state = ({'operation_id': job['operation_id'], 'processes': []} if not path.exists()
|
||||
else read_session_record(path, evidence_root=path.parent))
|
||||
if state['operation_id'] != job['operation_id']:
|
||||
raise ValueError('工作状态操作身份不一致')
|
||||
for role, pid in identities:
|
||||
if pid and not any(p['pid'] == pid for p in state['processes']):
|
||||
state['processes'].append({'role': role, **process_identity(pid)})
|
||||
state['phase'] = phase
|
||||
if write_outcome is not None:
|
||||
state['write_outcome'] = write_outcome
|
||||
write_session_record(path, state)
|
||||
return True
|
||||
except Exception:
|
||||
if required:
|
||||
raise
|
||||
# An unavailable journal cannot interrupt an already executing COM call.
|
||||
logging.getLogger(__name__).warning('Worker session journal unavailable', exc_info=True)
|
||||
return False
|
||||
|
||||
|
||||
def process_identity(pid):
|
||||
from .residual_sessions import _process_handle, _handle_identity, _force_ownership
|
||||
with _process_handle(pid) as handle:
|
||||
identity = _handle_identity(handle)
|
||||
identity.update(_force_ownership(handle, pid))
|
||||
return {'pid': int(pid), **{k: identity[k] for k in IDENTITY_KEYS if k != 'pid'}}
|
||||
|
||||
|
||||
def write_session_record(path, record):
|
||||
path = Path(path)
|
||||
value = {'protocol': PROTOCOL, 'version': 1, **record,
|
||||
'recorded_at': datetime.now(timezone.utc).isoformat()}
|
||||
data = json.dumps(value, ensure_ascii=False, default=str, indent=2).encode('utf-8')
|
||||
if len(data) > MAX_BYTES:
|
||||
raise ValueError('会话记录超过大小限制')
|
||||
pending = path.with_name(path.name + '.' + uuid4().hex + '.pending')
|
||||
try:
|
||||
with pending.open('xb') as stream:
|
||||
stream.write(data)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(pending, path)
|
||||
finally:
|
||||
pending.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def read_session_record(path, *, evidence_root):
|
||||
path, root = Path(path).absolute(), Path(evidence_root).absolute()
|
||||
if not path.is_relative_to(root) or path == root:
|
||||
raise ValueError('会话记录位于受控证据目录之外')
|
||||
# Check every component before resolve, which would hide a junction.
|
||||
for item in (path, *path.parents):
|
||||
attrs = item.lstat()
|
||||
if getattr(attrs, 'st_file_attributes', 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT:
|
||||
raise ValueError('会话记录路径包含重解析点')
|
||||
with path.open('rb') as stream:
|
||||
data = stream.read(MAX_BYTES + 1)
|
||||
if len(data) > MAX_BYTES:
|
||||
raise ValueError('会话记录超过大小限制')
|
||||
value = json.loads(data)
|
||||
if (not isinstance(value, dict) or value.get('protocol') != PROTOCOL or
|
||||
type(value.get('version')) is not int or value['version'] != 1 or
|
||||
not isinstance(value.get('operation_id'), str) or not value['operation_id']):
|
||||
raise ValueError('会话记录协议无效')
|
||||
return value
|
||||
|
||||
|
||||
def _session(path, root):
|
||||
value = read_session_record(path, evidence_root=root)
|
||||
if (not isinstance(value.get('library'), str) or not Path(value['library']).is_absolute()
|
||||
or Path(value['library']).suffix.casefold() != '.lmc'):
|
||||
raise ValueError('会话库身份无效')
|
||||
state_path = Path(path).with_name('worker-state.json')
|
||||
state = {}
|
||||
if state_path.exists():
|
||||
state = read_session_record(state_path, evidence_root=root)
|
||||
if state['operation_id'] != value['operation_id']:
|
||||
raise ValueError('工作进程状态不属于本次操作')
|
||||
processes = value.get('processes', []) + state.get('processes', [])
|
||||
if not processes:
|
||||
raise ValueError('会话缺少精确进程身份')
|
||||
for process in processes:
|
||||
if (not isinstance(process, dict) or any(k not in process for k in IDENTITY_KEYS)
|
||||
or type(process['pid']) is not int or process['pid'] <= 0):
|
||||
raise ValueError('会话进程身份不完整')
|
||||
return value, state, processes
|
||||
|
||||
|
||||
def _result(status, detail='', *, session=None, state=None, proof=None):
|
||||
return {'status': status, 'detail': detail, 'library': (session or {}).get('library'),
|
||||
'block': (session or {}).get('block'),
|
||||
'operation_id': (session or {}).get('operation_id'),
|
||||
'phase': (state or {}).get('phase', 'UNCONFIRMED'), 'release_proof': proof}
|
||||
|
||||
|
||||
def _reconcile(path, root, handles, stack, *, release=True):
|
||||
import pywintypes, win32api, win32con, win32event
|
||||
from .residual_sessions import _handle_identity, _force_ownership
|
||||
session, state, processes = _session(path, root)
|
||||
active = False
|
||||
for identity in processes:
|
||||
if identity.get('role') == 'supervisor':
|
||||
continue
|
||||
key = tuple(identity[k] for k in IDENTITY_KEYS)
|
||||
changed_key = ('identity_changed', *key)
|
||||
if changed_key in handles:
|
||||
return _result('IDENTITY_CHANGED', '记录中的进程身份已变化,仅供观察', session=session, state=state)
|
||||
if key not in handles:
|
||||
try:
|
||||
handle = win32api.OpenProcess(win32con.SYNCHRONIZE | 0x1000, False, identity['pid'])
|
||||
except pywintypes.error as error:
|
||||
if error.winerror != 87: # Access denied is not an exit observation.
|
||||
raise
|
||||
handles[key] = None
|
||||
else:
|
||||
stack.callback(handle.Close)
|
||||
if win32event.WaitForSingleObject(handle, 0) == win32con.WAIT_OBJECT_0:
|
||||
handles[key] = handle
|
||||
continue
|
||||
actual = {'pid': identity['pid'], **_handle_identity(handle),
|
||||
**_force_ownership(handle, identity['pid'])}
|
||||
if any(actual[k] != identity[k] for k in IDENTITY_KEYS):
|
||||
handles[key] = handle
|
||||
handles[changed_key] = True
|
||||
return _result('IDENTITY_CHANGED', '记录中的进程身份已变化,仅供观察',
|
||||
session=session, state=state)
|
||||
handles[key] = handle
|
||||
handle = handles[key]
|
||||
if handle is not None and win32event.WaitForSingleObject(handle, 0) != win32con.WAIT_OBJECT_0:
|
||||
active = True
|
||||
if active:
|
||||
return _result('ACTIVE', '原生调用尚未确认返回', session=session, state=state)
|
||||
if not release:
|
||||
return _result('UNCONFIRMED', '记录中的进程已退出,需确认库占用已释放', session=session, state=state)
|
||||
from .library_lock import release_retained_library
|
||||
try:
|
||||
proof = release_retained_library(session['library'], Path(path).parent/'release-proof',
|
||||
block_name=session.get('block'))
|
||||
except Exception as error:
|
||||
return _result('UNCONFIRMED', str(error), session=session, state=state)
|
||||
if proof.get('status') != 'RELEASE_CONFIRMED':
|
||||
return _result('UNCONFIRMED', '缺少独立资源释放证明', session=session, state=state)
|
||||
from .network_path import release_retained_path_leases
|
||||
release_retained_path_leases(proof)
|
||||
return _result('RELEASED', session=session, state=state, proof=proof)
|
||||
|
||||
|
||||
def reconcile_session_record(path, *, evidence_root):
|
||||
with ExitStack() as stack:
|
||||
try:
|
||||
return _reconcile(Path(path), Path(evidence_root), {}, stack)
|
||||
except Exception as error:
|
||||
return _result('UNCONFIRMED', str(error))
|
||||
|
||||
|
||||
def inspect_session_record(path, *, evidence_root):
|
||||
"""Observe process identities without touching the production library."""
|
||||
with ExitStack() as stack:
|
||||
try:
|
||||
return _reconcile(Path(path), Path(evidence_root), {}, stack, release=False)
|
||||
except Exception as error:
|
||||
return _result('UNCONFIRMED', str(error))
|
||||
|
||||
|
||||
def observe_retained_session(path, *, evidence_root, stop=None, progress=None, process=None,
|
||||
observe_only=False):
|
||||
stop = stop if stop is not None else threading.Event()
|
||||
observation = Path(path).with_name('observation-' + uuid4().hex + '.json')
|
||||
with ExitStack() as stack:
|
||||
handles = {}
|
||||
while True:
|
||||
try:
|
||||
result = _reconcile(Path(path), Path(evidence_root), handles, stack, release=not observe_only)
|
||||
except Exception as error:
|
||||
result = _result('UNCONFIRMED', str(error))
|
||||
if (not observe_only and process is not None and process.poll() is not None
|
||||
and getattr(process, 'cbb_library', None)):
|
||||
try:
|
||||
from .library_lock import release_retained_library
|
||||
proof = release_retained_library(process.cbb_library, Path(path).parent/'release-proof')
|
||||
if proof.get('status') == 'RELEASE_CONFIRMED':
|
||||
result = _result('RELEASED', '会话记录不可读;由原进程句柄及独立资源证明确认释放',
|
||||
session={'library': str(process.cbb_library)}, proof=proof)
|
||||
except Exception:
|
||||
pass
|
||||
if result['status'] == 'IDENTITY_CHANGED' and not observe_only:
|
||||
try:
|
||||
from .library_lock import release_retained_library
|
||||
proof = release_retained_library(result['library'], Path(path).parent/'release-proof')
|
||||
if proof.get('status') == 'RELEASE_CONFIRMED':
|
||||
result = {**result, 'status': 'RELEASED', 'identity_changed': True, 'release_proof': proof}
|
||||
except Exception as error:
|
||||
result['detail'] += f';资源释放待确认:{error}'
|
||||
try:
|
||||
write_session_record(observation, {**result, 'operation_id': result['operation_id'] or 'unknown'})
|
||||
except (OSError, ValueError):
|
||||
logging.getLogger(__name__).warning('Observation journal unavailable', exc_info=True)
|
||||
if progress is not None:
|
||||
try:
|
||||
progress(result)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).warning('Observation callback failed', exc_info=True)
|
||||
if (result['status'] == 'RELEASED' or stop.is_set()
|
||||
or observe_only and result['status'] != 'ACTIVE'):
|
||||
return result
|
||||
if not handles and process is not None and process.poll() is None:
|
||||
stop.wait(1)
|
||||
continue # The exact owned handle survives a failed journal.
|
||||
if not handles and process is None:
|
||||
return result
|
||||
stop.wait(5 if result['status'] in ('UNCONFIRMED', 'IDENTITY_CHANGED') else 1)
|
||||
|
||||
|
||||
def handoff_session(path, *, evidence_root, process=None, progress=None, stop=None, observe_only=False):
|
||||
"""Retain exact handles in memory until the observer independently releases."""
|
||||
key = str(Path(path).absolute()).casefold()
|
||||
try:
|
||||
session = read_session_record(path, evidence_root=evidence_root)
|
||||
library = session['library']
|
||||
except (OSError, ValueError, KeyError):
|
||||
session = {}
|
||||
library = getattr(process, 'cbb_library', None)
|
||||
aliases = {_library_key(library), _library_key(Path(library).resolve())} if library else set()
|
||||
with _observer_guard:
|
||||
if key in _observers:
|
||||
return
|
||||
_retained_libraries[key] = aliases
|
||||
_retained_results[key] = {'status': 'UNCONFIRMED', 'phase': 'UNCONFIRMED',
|
||||
'library': str(library) if library else None, 'block': session.get('block'),
|
||||
'detail': '正在核对残留会话', 'operation_id': session.get('operation_id')}
|
||||
def notify(value):
|
||||
with _observer_guard:
|
||||
if _retained_libraries.get(key) is aliases:
|
||||
previous = _retained_results[key]
|
||||
_retained_results[key] = {**previous, **value,
|
||||
'library': value.get('library') or previous['library'],
|
||||
'operation_id': value.get('operation_id') or previous['operation_id'],
|
||||
'block': value.get('block') or previous['block']}
|
||||
if progress is not None:
|
||||
progress(value)
|
||||
def observe():
|
||||
result = None
|
||||
try:
|
||||
result = observe_retained_session(path, evidence_root=evidence_root, progress=notify,
|
||||
stop=stop, process=process, observe_only=observe_only)
|
||||
if process is not None and process.poll() is not None:
|
||||
process.close()
|
||||
return result
|
||||
finally:
|
||||
with _observer_guard:
|
||||
_observers.pop(key, None)
|
||||
if result and result['status'] == 'RELEASED':
|
||||
_retained_libraries.pop(key, None)
|
||||
_retained_results.pop(key, None)
|
||||
thread = threading.Thread(target=observe, name='retained-native-session', daemon=True)
|
||||
_observers[key] = (thread, process)
|
||||
thread.start()
|
||||
|
||||
|
||||
def discover_sessions(evidence_root, *, library=None):
|
||||
"""Only our bounded journals are inputs; never execute a stored command."""
|
||||
root = Path(evidence_root)
|
||||
found = []
|
||||
if not root.is_dir():
|
||||
return found
|
||||
visited = 0
|
||||
for folder, directories, files in os.walk(root, followlinks=False):
|
||||
directories[:] = [d for d in directories if not (
|
||||
getattr((Path(folder)/d).lstat(), 'st_file_attributes', 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT)]
|
||||
visited += 1
|
||||
if visited > 10000:
|
||||
break
|
||||
if 'session.json' not in files:
|
||||
continue
|
||||
path = Path(folder)/'session.json'
|
||||
try:
|
||||
value = read_session_record(path, evidence_root=root)
|
||||
completed = False
|
||||
for name in files:
|
||||
if not (name.startswith('observation-') and name.endswith('.json')):
|
||||
continue
|
||||
observation = read_session_record(Path(folder)/name, evidence_root=root)
|
||||
if observation['operation_id'] == value['operation_id'] and (
|
||||
observation.get('status') == 'RELEASED' and observation.get('release_proof')
|
||||
or observation.get('status') == 'FINISHED'
|
||||
and observation.get('native_release_confirmed') is True
|
||||
and observation.get('worker_exited') is True):
|
||||
completed = True
|
||||
break
|
||||
if completed:
|
||||
continue
|
||||
if library is not None and _library_key(value.get('library', '')) != _library_key(library):
|
||||
continue
|
||||
observed = inspect_session_record(path, evidence_root=root)
|
||||
value = {**value, **observed, 'library': value.get('library'),
|
||||
'block': value.get('block'), 'operation_id': value['operation_id'], 'path': str(path)}
|
||||
except (OSError, ValueError):
|
||||
continue
|
||||
found.append(value)
|
||||
return found
|
||||
|
||||
|
||||
def active_write_records(library):
|
||||
"""Called by the background residual inspector, never by a queue predicate."""
|
||||
with _observer_guard:
|
||||
paths = [Path(key) for key, aliases in _retained_libraries.items()
|
||||
if _library_key(library) in aliases]
|
||||
result = []
|
||||
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:
|
||||
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'):
|
||||
continue
|
||||
try:
|
||||
with _process_handle(identity['pid']) as handle:
|
||||
if win32event.WaitForSingleObject(handle, 0) == win32con.WAIT_OBJECT_0:
|
||||
continue
|
||||
actual = {**_handle_identity(handle), **_force_ownership(handle, identity['pid'])}
|
||||
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'})
|
||||
break
|
||||
except Exception as error:
|
||||
if getattr(error, 'winerror', None) != 87:
|
||||
result.append({**session, 'phase': 'UNCONFIRMED'})
|
||||
break
|
||||
except (OSError, ValueError):
|
||||
result.append({'phase': 'UNCONFIRMED'})
|
||||
return result
|
||||
@@ -27,6 +27,7 @@ class IcdbCheckTask(QObject):
|
||||
self.running = False
|
||||
self.report = None
|
||||
self.report_error = ''
|
||||
self.retained_libraries = set()
|
||||
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1)
|
||||
|
||||
def start(self):
|
||||
@@ -53,14 +54,18 @@ class IcdbCheckTask(QObject):
|
||||
|
||||
def _next(self):
|
||||
if self.running or not self.active: return
|
||||
if self.stop.is_set() or self.results and not self.results[-1].safe_to_continue:
|
||||
if self.stop.is_set():
|
||||
self.results.extend(VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB')
|
||||
for _ in self.requests[len(self.results):])
|
||||
while len(self.results) < len(self.requests) and str(
|
||||
self.requests[len(self.results)].lmc_file).casefold() in self.retained_libraries:
|
||||
self.results.append(VerifyResult('SKIPPED', stderr='同库原生会话尚未释放,未启动新的检查'))
|
||||
if len(self.results) == len(self.requests):
|
||||
self._report(); return
|
||||
if self.paused: return
|
||||
request = self.requests[len(self.results)]
|
||||
def check():
|
||||
from ..session_record import library_available
|
||||
try:
|
||||
def execute():
|
||||
if request.block_name in self.ready_names:
|
||||
@@ -69,7 +74,8 @@ class IcdbCheckTask(QObject):
|
||||
return VerifyResult('SKIPPED', stderr='目标已有后续管理操作,请重新检查。')
|
||||
self.event.emit({'stage': 'icdb_check_start', 'block': request.block_name})
|
||||
return self.verifier(request)
|
||||
return self.queue.run(execute, stop=self.stop, ready=lambda: not self.paused,
|
||||
return self.queue.run(execute, stop=self.stop,
|
||||
ready=lambda: not self.paused and library_available(request.lmc_file),
|
||||
waiting=lambda: self.event.emit({'stage': 'waiting_native_slot', 'block': request.block_name,
|
||||
'detail': '已排队,等待当前原生操作结束'}))
|
||||
except QueueCancelled as error:
|
||||
@@ -84,7 +90,10 @@ class IcdbCheckTask(QObject):
|
||||
self.pool.start(self.worker)
|
||||
|
||||
def _record(self, result):
|
||||
name = self.requests[len(self.results)].block_name
|
||||
request = self.requests[len(self.results)]
|
||||
name = request.block_name
|
||||
if not result.safe_to_continue:
|
||||
self.retained_libraries.add(str(request.lmc_file).casefold())
|
||||
self.results.append(result)
|
||||
if result.status in ('CANCELLED', 'QUEUE_STOP'): self.stop.set()
|
||||
self.item_done.emit(name, result)
|
||||
|
||||
@@ -127,6 +127,8 @@ class MainWindow(QWidget):
|
||||
p, names, mapping_store=self.data_root/'image-status-map.json'),
|
||||
)
|
||||
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1)
|
||||
self.lifecycle_pool = QThreadPool(self); self.lifecycle_pool.setMaxThreadCount(1)
|
||||
self._lifecycle_workers = set()
|
||||
self._lease_pending = 0
|
||||
self._lease_workers = set()
|
||||
self._mapping_busy = 0
|
||||
@@ -146,6 +148,8 @@ class MainWindow(QWidget):
|
||||
self._global_icdb_run = False
|
||||
self._icdb_completed = 0
|
||||
self.signals = ProgressSignals(self); self.signals.event.connect(self._progress)
|
||||
if hasattr(self.management_adapter, 'session_progress'):
|
||||
self.management_adapter.session_progress = self.signals.event.emit
|
||||
self.signals.version_choice.connect(self._show_version_choice)
|
||||
self.version_dialog = None
|
||||
self.lmc_edit = QLineEdit()
|
||||
@@ -369,6 +373,9 @@ class MainWindow(QWidget):
|
||||
self._lease_workers.discard(worker)
|
||||
self._lease_pending -= 1
|
||||
if hold_busy: self._mapping_busy -= 1
|
||||
from shiboken6 import isValid
|
||||
if not isValid(self) or not isValid(self.cbb_table):
|
||||
return
|
||||
if not self._mapping_busy:
|
||||
callbacks, self._mapping_finish_waiters = self._mapping_finish_waiters, []
|
||||
auto_idle, self._mapping_auto_idle = self._mapping_auto_idle, False
|
||||
@@ -385,6 +392,9 @@ class MainWindow(QWidget):
|
||||
return True
|
||||
|
||||
def _update(self):
|
||||
from shiboken6 import isValid
|
||||
if not isValid(self) or not isValid(self.cbb_table):
|
||||
return
|
||||
# The refresh flow needs only the library and a CBB; LibSpec/DMS config
|
||||
# are optional and only enable the extra contents check.
|
||||
ready = not self.busy and self.loaded_path == self.lmc_edit.text() and self.cbb_table.rowCount() > 0
|
||||
@@ -438,12 +448,38 @@ class MainWindow(QWidget):
|
||||
|
||||
def _show_unfinished_management(self):
|
||||
from cbb_refresh_verify.management import unfinished_operations
|
||||
unfinished = unfinished_operations(self.data_root/'management')
|
||||
from cbb_refresh_verify.session_record import discover_sessions, handoff_session
|
||||
root = self.data_root
|
||||
notify = self.signals.event.emit
|
||||
def inspect():
|
||||
unfinished = unfinished_operations(root/'management')
|
||||
sessions = discover_sessions(root)
|
||||
for session in sessions:
|
||||
if session['status'] == 'ACTIVE':
|
||||
handoff_session(session['path'], evidence_root=root,
|
||||
observe_only=True,
|
||||
progress=lambda value: notify({'stage': 'session_observation', **value}))
|
||||
return unfinished, sessions
|
||||
worker = ServiceWorker(inspect)
|
||||
self._lifecycle_workers.add(worker)
|
||||
worker.signals.succeeded.connect(self._unfinished_sessions_ready)
|
||||
worker.signals.failed.connect(self._display_error)
|
||||
worker.signals.finished.connect(lambda: self._lifecycle_workers.discard(worker))
|
||||
self.lifecycle_pool.start(worker)
|
||||
|
||||
def _unfinished_sessions_ready(self, payload):
|
||||
unfinished, sessions = payload
|
||||
self.unfinished_label.setText(f'发现 {len(unfinished)} 项未完成或需恢复的管理任务;只显示记录,不自动重放。'
|
||||
if unfinished else '')
|
||||
for item in unfinished:
|
||||
self.output.append(f'未完成:{item.get("name", "")} {item.get("status", "")} '
|
||||
f'{item.get("stage", "")}\n{item["evidence_path"]}')
|
||||
for session in sessions:
|
||||
if session['status'] != 'RELEASED':
|
||||
phase = {'NATIVE_CALL': '原生操作进行中', 'CLOSING': '正在关闭', 'POSTCALL': '原生调用已返回',
|
||||
'PRECALL': '尚未开始', 'UNCONFIRMED': '当前状态无法确认'}.get(session.get('phase'), '待核对')
|
||||
self.output.append(f'未完成会话:{session.get("block") or ""} · '
|
||||
f'{phase} · {session.get("detail", "")}\n{session["path"]}')
|
||||
|
||||
def check_library_release(self):
|
||||
if self.busy or not self.lmc_edit.text().strip():
|
||||
@@ -740,7 +776,10 @@ class MainWindow(QWidget):
|
||||
self.pool.start(self.worker)
|
||||
|
||||
def _queued_action(self, action):
|
||||
from cbb_refresh_verify.session_record import library_available
|
||||
library = getattr(self, 'mentor_lmc_path', None) or self.lmc_edit.text()
|
||||
return lambda: self.native_queue.run(action, stop=self.stop,
|
||||
ready=lambda: library_available(library),
|
||||
waiting=lambda: self.signals.event.emit({'stage': 'waiting_native_slot',
|
||||
'detail': '已排队,等待当前原生操作结束'}))
|
||||
|
||||
@@ -1355,6 +1394,15 @@ class MainWindow(QWidget):
|
||||
return True
|
||||
|
||||
def _progress(self, event):
|
||||
from shiboken6 import isValid
|
||||
if not isValid(self) or not isValid(self.cbb_table):
|
||||
return
|
||||
if event.get('stage') in ('session_handoff', 'save_stop_requested'):
|
||||
self.status_label.setText(event.get('detail', '当前状态无法确认'))
|
||||
if (event.get('stage') == 'session_observation' and event.get('status') == 'RELEASED'
|
||||
and event.get('release_proof')):
|
||||
self._complete_library_release(event['library'], event['release_proof'])
|
||||
self.native_queue.wake()
|
||||
line = f"{event.get('block', '')} | {event.get('stage', '')}"
|
||||
for key in ('detail', 'error', 'action', 'statuses', 'evidence'):
|
||||
if event.get(key): line += f' | {event[key]}'
|
||||
|
||||
@@ -171,9 +171,11 @@ class ManagementDialog(QDialog):
|
||||
progress=self.signals.progress.emit)
|
||||
if self.native_queue is None: return action()
|
||||
from ..operation_queue import QueueCancelled
|
||||
from ..session_record import library_available
|
||||
try:
|
||||
return self.native_queue.run(action, stop=self.stop, waiting=lambda: self.signals.progress.emit(
|
||||
{'stage': 'waiting_native_slot', 'detail': '已排队,等待当前检查结束'}))
|
||||
{'stage': 'waiting_native_slot', 'detail': '已排队,等待当前检查结束'}),
|
||||
ready=lambda: library_available(self.template.library))
|
||||
except QueueCancelled as error:
|
||||
from ..management import ManagementResult
|
||||
return [ManagementResult(r.operation, r.library, r.name, r.partition, r.source, r.auto_verify,
|
||||
|
||||
@@ -30,6 +30,9 @@ class ResidualReleaseDialog(QDialog):
|
||||
self.message = QLabel('正在检查当前库关联的会话…')
|
||||
self.message.setWordWrap(True)
|
||||
layout.addWidget(self.message)
|
||||
self.runtime_label = QLabel()
|
||||
self.runtime_label.setWordWrap(True)
|
||||
layout.addWidget(self.runtime_label)
|
||||
self.table = QTableWidget(0, 6)
|
||||
self.table.setHorizontalHeaderLabels(['工程', '程序', 'PID', '状态', '窗口位置', '程序路径'])
|
||||
self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
|
||||
@@ -155,6 +158,7 @@ class ResidualReleaseDialog(QDialog):
|
||||
or any(r.get('release_status') != 'RELEASED' for r in result['sessions'])):
|
||||
return False
|
||||
self.plan = None
|
||||
self.runtime_label.clear()
|
||||
self.released.emit(proof)
|
||||
return True
|
||||
|
||||
@@ -191,10 +195,19 @@ class ResidualReleaseDialog(QDialog):
|
||||
elif not plan['sessions']:
|
||||
text += '确认后将复查库占用状态。'
|
||||
self.message.setText(text)
|
||||
states = {'ACTIVE': '进行中', 'UNCONFIRMED': '待核对', 'IDENTITY_CHANGED': '待核对'}
|
||||
self.runtime_label.setText('\n'.join(
|
||||
f'{states.get(row["status"], "待核对")} · {row.get("block") or "当前库"} · '
|
||||
f'{row.get("detail") or "操作状态需重新核对"}' for row in plan.get('runtime_sessions', [])))
|
||||
def inspect():
|
||||
from cbb_refresh_verify.network_path import select_library_file
|
||||
from cbb_refresh_verify.session_record import discover_sessions, retained_session_states
|
||||
library = self.library if self.library.suffix.casefold() == '.lmc' else select_library_file(self.library)
|
||||
return inspect_residual_sessions(library)
|
||||
plan = inspect_residual_sessions(library)
|
||||
states = {row['path']: row for row in retained_session_states(library)}
|
||||
states.update({str(Path(row['path']).absolute()).casefold(): row for row in
|
||||
discover_sessions(self.evidence_dir.parent, library=library)})
|
||||
return {**plan, 'runtime_sessions': list(states.values())}
|
||||
self._start(inspect, ready)
|
||||
|
||||
def force_release(self):
|
||||
|
||||
@@ -103,6 +103,8 @@ class VerifyResult:
|
||||
incomplete_timing_phases: tuple[str, ...] = ()
|
||||
recovery_attempts: tuple[dict, ...] = ()
|
||||
release_proof: dict | None = None
|
||||
write_outcome: dict | None = None
|
||||
session_record_path: Path | None = None
|
||||
|
||||
|
||||
def resolve_importer(mentor_bin: str | None = None) -> Path:
|
||||
@@ -229,25 +231,26 @@ def _run_process(command, timeout_seconds, cwd, *, evidence_root=None):
|
||||
|
||||
|
||||
def _stop_worker(process, *, timeout=5):
|
||||
"""Stop automation clients; native database owners are preserved."""
|
||||
"""Request stop without interrupting a possibly unreturned native call."""
|
||||
try:
|
||||
if hasattr(process, 'request_stop'):
|
||||
process.request_stop()
|
||||
else:
|
||||
process.kill()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
if getattr(process, '_stop_wait_complete', False):
|
||||
return process.poll() is not None
|
||||
process.wait(timeout=timeout)
|
||||
except Exception:
|
||||
try:
|
||||
process.kill() # Automation clients only; never the native tree.
|
||||
process.wait(timeout=5)
|
||||
except Exception:
|
||||
pass
|
||||
pending = getattr(process, 'native_write_pending', lambda: False)()
|
||||
if pending is not False and not getattr(process, '_stop_wait_complete', False):
|
||||
from .defaults import NATIVE_WRITE_STOP_WAIT_SECONDS
|
||||
try:
|
||||
process.wait(timeout=max(0, NATIVE_WRITE_STOP_WAIT_SECONDS - timeout))
|
||||
except Exception:
|
||||
pass
|
||||
process._stop_wait_complete = True
|
||||
try:
|
||||
if hasattr(process, 'stop_automation_clients'):
|
||||
process.stop_automation_clients()
|
||||
return process.poll() is not None
|
||||
except Exception:
|
||||
return False
|
||||
@@ -596,7 +599,7 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
|
||||
snapshot = original.evidence_path.with_name('pre-repair-result.json')
|
||||
snapshot.write_text(json.dumps(asdict(original), ensure_ascii=False, default=str, indent=2),
|
||||
encoding='utf-8')
|
||||
recovery = attempt_recovery(request, diagnosis, result.evidence_path.parent, progress=progress)
|
||||
recovery = attempt_recovery(request, diagnosis, result.evidence_path.parent, progress=progress, stop=stop)
|
||||
recovery = {**recovery, 'original_error': original.stderr,
|
||||
'original_evidence': str(original.evidence_path),
|
||||
'original_result_snapshot': str(snapshot),
|
||||
@@ -621,7 +624,7 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
|
||||
result = _run_verify_serialized(
|
||||
replace(request, auto_repair=False, maintenance=False), progress=progress, flag_reader=flag_reader,
|
||||
process_runner=process_runner, port_check=port_check,
|
||||
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt)
|
||||
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt, stop=stop)
|
||||
recovery['validation_evidence'] = str(result.evidence_path or '')
|
||||
recovery['validation_passed'] = (result.status == 'PASS'
|
||||
and result.library_flag == 'GREEN' and result.safe_to_continue)
|
||||
@@ -700,6 +703,14 @@ def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_
|
||||
result = _run_verify(request, timing=timing, progress=progress, flag_reader=flag_reader,
|
||||
process_runner=process_runner, port_check=port_check,
|
||||
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt, stop=stop)
|
||||
if result.evidence_path:
|
||||
try:
|
||||
facts = json.loads(result.evidence_path.with_name('write-outcome.json').read_text('utf-8'))
|
||||
session = result.evidence_path.with_name('session.json')
|
||||
result = replace(result, write_outcome=facts,
|
||||
session_record_path=session if session.is_file() else None)
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
if not request.auto_repair and result.evidence_path:
|
||||
try:
|
||||
release = json.loads(result.evidence_path.with_name('session-release.json').read_text('utf-8'))
|
||||
@@ -874,6 +885,10 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
'desktop': 'CbbVerify_' + uuid4().hex[:12],
|
||||
'cancel_signal': str(root/'cancel-worker.signal'),
|
||||
'start_gate': str(root/'start-worker.signal')}
|
||||
job.update(operation_id=root.name, operation='verify', library=str(request.lmc_file),
|
||||
block=request.block_name, session_record_path=str(root/'session.json'))
|
||||
from .session_record import process_identity
|
||||
job['supervisor_identity'] = process_identity(os.getpid())
|
||||
consent = None
|
||||
job_path = root/'request.json'
|
||||
try:
|
||||
@@ -919,6 +934,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
process = DesktopWorker(worker_command(job_path), job['desktop'])
|
||||
if hasattr(process, 'bind_cancellation'):
|
||||
process.bind_cancellation(job['cancel_signal'])
|
||||
if hasattr(process, 'bind_session'):
|
||||
process.bind_session(job)
|
||||
deadline = ActivityDeadline(request.timeout_seconds)
|
||||
last_activity_key = None
|
||||
phase = DialogPhase.PCB_STARTING
|
||||
@@ -950,6 +967,12 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
Path(job['start_gate']).touch()
|
||||
while process.poll() is None:
|
||||
if stop is not None and stop.is_set():
|
||||
save_markers = timing._save_markers
|
||||
detail = ('保存已返回,关闭待确认' if 'SAVE_OK' in save_markers and 'CLOSE_OK' not in save_markers else
|
||||
'已请求停止,等待当前保存返回' if phase == DialogPhase.SAVE else
|
||||
'已请求停止,等待当前原生操作返回')
|
||||
_notify_progress(progress, {'stage': 'save_stop_requested', 'block': request.block_name,
|
||||
'detail': detail})
|
||||
_stop_worker(process)
|
||||
return finish(VerifyResult('CANCELLED', stderr='已取消当前校验。',
|
||||
safe_to_continue=False, error_stage=phase.value))
|
||||
@@ -1143,7 +1166,15 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
automation_release = process.automation_release_state()
|
||||
else:
|
||||
automation_release = {'safe_to_continue': worker_exited, 'remaining_pids': []}
|
||||
process.close()
|
||||
if worker_exited:
|
||||
process.close()
|
||||
elif getattr(process, 'session_record_path', None):
|
||||
from .session_record import handoff_session
|
||||
handoff_session(process.session_record_path, evidence_root=root,
|
||||
process=process, progress=lambda state: _notify_progress(progress,
|
||||
{'stage': 'session_observation', 'block': request.block_name, **state}))
|
||||
_notify_progress(progress, {'stage': 'session_handoff', 'block': request.block_name,
|
||||
'detail': '已转后台观察,可查看状态'})
|
||||
except Exception as error:
|
||||
close_errors.append(str(error))
|
||||
if 'process' in locals():
|
||||
@@ -1189,11 +1220,23 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
release_result['remaining_pids'] = sorted(set(release_result.get('remaining_pids', []))
|
||||
| set(automation_release.get('remaining_pids', [])))
|
||||
try:
|
||||
from .operation_lifecycle import classify_save_state
|
||||
save_lines = ((root/'save.log').read_text('utf-8', errors='replace').splitlines()
|
||||
if (root/'save.log').is_file() else [])
|
||||
_write_optional_evidence(root/'write-outcome.json', classify_save_state(save_lines,
|
||||
helper_exited=(False if automation_release.get('remaining_pids') else
|
||||
True if worker_exited and automation_release.get('safe_to_continue') else None),
|
||||
native_released=release_result.get('safe_to_continue') is True))
|
||||
(root/'session-release.json').write_text(json.dumps({
|
||||
**(release_result or {}), 'block': request.block_name,
|
||||
'library': str(request.lmc_file), 'worker_exited': worker_exited,
|
||||
'worker_pid': getattr(process, 'pid', None)},
|
||||
ensure_ascii=False, default=str, indent=2), encoding='utf-8')
|
||||
if worker_exited and release_result.get('safe_to_continue') is True and (root/'session.json').is_file():
|
||||
from .session_record import write_session_record
|
||||
write_session_record(root/'observation-supervisor.json', {
|
||||
'operation_id': job['operation_id'], 'status': 'FINISHED',
|
||||
'native_release_confirmed': True, 'worker_exited': True})
|
||||
except OSError:
|
||||
pass
|
||||
if not release_result or not release_result.get('safe_to_continue'):
|
||||
@@ -1253,12 +1296,16 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
|
||||
if max_workers != 1:
|
||||
raise ValueError('Only serial Verify is supported for the shared Library Manager session')
|
||||
if verifier is None:
|
||||
verifier = lambda request: run_verify(request, flag_reader=read_library_flag_if_available) # noqa: E731
|
||||
verifier = lambda request: run_verify(request, flag_reader=read_library_flag_if_available, stop=stop) # noqa: E731
|
||||
results = []
|
||||
queue_stop = False
|
||||
retained_libraries = set()
|
||||
for request in requests:
|
||||
library_key = str(getattr(request, 'lmc_file', '__injected_verifier_scope__')).casefold()
|
||||
if queue_stop or (stop is not None and stop.is_set()):
|
||||
result = VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB')
|
||||
elif library_key in retained_libraries:
|
||||
result = VerifyResult('SKIPPED', stderr='同库原生会话尚未释放,未启动新的写入')
|
||||
else:
|
||||
try:
|
||||
result = verifier(request)
|
||||
@@ -1267,7 +1314,9 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
|
||||
result = VerifyResult('FAIL', stderr=str(error), safe_to_continue=False)
|
||||
results.append(result)
|
||||
# Never start another writer after an unconfirmed native shutdown.
|
||||
queue_stop = queue_stop or result.status in {'QUEUE_STOP', 'CANCELLED'} or not result.safe_to_continue
|
||||
if not result.safe_to_continue:
|
||||
retained_libraries.add(library_key)
|
||||
queue_stop = queue_stop or result.status in {'QUEUE_STOP', 'CANCELLED'}
|
||||
if queue_stop and stop is not None:
|
||||
stop.set()
|
||||
if progress: _notify_progress(progress, request.block_name, result)
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import ast
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
workspace = Path(sys.argv[1]).resolve()
|
||||
bundle_root = Path(sys.argv[2]).resolve()
|
||||
sys.path.insert(0, str(workspace/'src'))
|
||||
fixture = bundle_root/'fixture-dist/runtime_lifecycle_frozen_fixture/runtime_lifecycle_frozen_fixture.exe'
|
||||
native_source = bundle_root/'dist/CbbRefreshVerify-Background/_internal/cbb_refresh_verify/save_verified_block.vbs'
|
||||
root = bundle_root/('frozen-boundaries-' + uuid4().hex[:8])
|
||||
root.mkdir()
|
||||
test_ast = ast.parse((workspace/'tests/test_save_helper_runtime.py').read_text('utf-8'))
|
||||
classes = next(node.value for node in ast.walk(test_ast) if isinstance(node, ast.Constant)
|
||||
and isinstance(node.value, str) and 'Class FakePi' in node.value and 'SAVE_BODY' in node.value)
|
||||
save_body = '''Dim fso, flag
|
||||
Set fso = CreateObject("Scripting.FileSystemObject")
|
||||
Set flag = fso.CreateTextFile(WScript.Arguments(4), True)
|
||||
flag.Close
|
||||
WScript.Sleep 2000
|
||||
Set flag = fso.CreateTextFile(WScript.Arguments(5), True)
|
||||
flag.Close
|
||||
Save = True'''
|
||||
classes = classes.replace('SAVE_BODY', save_body).replace('CLOSE_BODY', 'Close = True').replace('IS_SAVED_VALUE', 'True')
|
||||
source = native_source.read_text('utf-8').replace('Option Explicit', 'Option Explicit\nDim closedDoc\n' + classes)
|
||||
source = source.replace('GetObject(, "MGCPCB.Application")', 'New FakeApp')
|
||||
source = source.replace('CreateObject("MGCPCBAutomationLicensing.Application")', 'New FakeLic')
|
||||
script = root/'native-boundary.vbs'
|
||||
script.write_text(source, 'ascii')
|
||||
|
||||
from cbb_refresh_verify.desktop_worker import DesktopWorker
|
||||
from cbb_refresh_verify.session_record import process_identity, read_session_record
|
||||
from cbb_refresh_verify.operation_lifecycle import classify_save_state
|
||||
from cbb_refresh_verify.verify_runner import _stop_worker
|
||||
results = []
|
||||
for mode in ('save', 'management'):
|
||||
for stop_kind in ('cancel', 'supervisor-loss'):
|
||||
evidence = root/(mode+'-'+stop_kind)
|
||||
evidence.mkdir()
|
||||
supervisor = subprocess.Popen([sys.executable, '-c', 'import time;time.sleep(30)'],
|
||||
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
job = dict(root=str(evidence), operation_id=uuid4().hex, operation='catalog' if mode=='management' else 'verify',
|
||||
library=str(evidence/'lib.lmc'), block='Fixture', block_name='Fixture',
|
||||
desktop=('CbbManagement_' if mode=='management' else 'CbbVerify_')+uuid4().hex[:10],
|
||||
supervisor_pid=supervisor.pid, supervisor_identity=process_identity(supervisor.pid),
|
||||
cancel_signal=str(evidence/'cancel.signal'), start_gate=str(evidence/'start.signal'),
|
||||
session_record_path=str(evidence/'session.json'), script=str(script),
|
||||
cscript=str(Path(os.environ['WINDIR'])/'SysWOW64/cscript.exe'))
|
||||
request = evidence/'request.json'
|
||||
request.write_text(json.dumps(job), 'utf-8')
|
||||
worker = DesktopWorker([str(fixture), '--'+mode+'-worker', str(request)], job['desktop'])
|
||||
worker.bind_cancellation(job['cancel_signal'])
|
||||
worker.bind_session(job)
|
||||
try:
|
||||
Path(job['start_gate']).touch()
|
||||
deadline = time.monotonic()+30
|
||||
while not (evidence/'call-started').exists() and time.monotonic()<deadline:
|
||||
assert worker.poll() is None, 'fixture exited before native boundary'
|
||||
time.sleep(.02)
|
||||
assert (evidence/'call-started').exists()
|
||||
if stop_kind == 'supervisor-loss':
|
||||
supervisor.terminate()
|
||||
supervisor.wait(5)
|
||||
deadline = time.monotonic()+1
|
||||
while not Path(job['cancel_signal']).exists() and time.monotonic()<deadline:
|
||||
time.sleep(.01)
|
||||
assert Path(job['cancel_signal']).exists()
|
||||
assert worker.poll() is None
|
||||
else:
|
||||
worker.request_stop()
|
||||
time.sleep(.1)
|
||||
assert worker.poll() is None
|
||||
if mode == 'save':
|
||||
state = read_session_record(evidence/'worker-state.json', evidence_root=evidence)
|
||||
assert any(p.get('role') == 'helper' for p in state['processes'])
|
||||
assert worker.wait(20) == (0 if mode=='save' else 2)
|
||||
assert (evidence/'call-returned').exists()
|
||||
assert not (evidence/'unexpected-follow-on-call').exists()
|
||||
if mode == 'save':
|
||||
facts = classify_save_state((evidence/'save.log').read_text('utf-8').splitlines(),
|
||||
helper_exited=True, native_released=None)
|
||||
assert facts['save_state'] == 'COMMITTED' and facts['close_state'] == 'CLOSED'
|
||||
results.append({'mode': mode, 'stop_kind': stop_kind, 'status': 'passed'})
|
||||
finally:
|
||||
if supervisor.poll() is None:
|
||||
supervisor.terminate()
|
||||
supervisor.wait(5)
|
||||
worker.close()
|
||||
(root/'result.json').write_text(json.dumps({'scope':'separate frozen fixture; fake native COM/management boundary',
|
||||
'product_native_database_recovery_validated':False,'results':results},ensure_ascii=False,indent=2),'utf-8')
|
||||
print(json.dumps({'evidence':str(root/'result.json'),'results':results}),flush=True)
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Test artifact only: frozen native boundaries, never shipped with the product."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
mode, request = sys.argv[1:3]
|
||||
job = json.loads(Path(request).read_text('utf-8'))
|
||||
root = Path(job['root'])
|
||||
if mode == '--save-worker':
|
||||
from cbb_refresh_verify import mentor_adapter
|
||||
from cbb_refresh_verify.desktop_worker import launch_save_helper
|
||||
def native_boundary(job, emit):
|
||||
with (root/'save.log').open('w', encoding='utf-8') as output:
|
||||
gate = root/'save-gate'
|
||||
helper = launch_save_helper([job['cscript'], '//nologo', job['script'],
|
||||
'expected.prj', 'CBB.pcb', job['cancel_signal'], str(gate),
|
||||
str(root/'call-started'), str(root/'call-returned')],
|
||||
start_gate=gate, identity_path=root/'worker-state.json', operation_id=job['operation_id'],
|
||||
stdout=output, stderr=output, creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
while helper.poll() is None:
|
||||
time.sleep(.02)
|
||||
if helper.returncode:
|
||||
raise RuntimeError(f'helper failed {helper.returncode}')
|
||||
return {'status': 'PASS', 'safe_to_continue': True, 'stdout': 'fake native Save/Close returned'}
|
||||
mentor_adapter.execute_job = native_boundary
|
||||
raise SystemExit(mentor_adapter.worker_main(request))
|
||||
if mode == '--management-worker':
|
||||
from cbb_refresh_verify import native_management
|
||||
def native_boundary(job, evidence):
|
||||
(root/'call-started').touch()
|
||||
time.sleep(2)
|
||||
(root/'call-returned').touch()
|
||||
try:
|
||||
native_management._require_management_continuation(job, root)
|
||||
except RuntimeError as error:
|
||||
return {'success': False, 'safe_to_continue': True, 'detail': str(error)}
|
||||
(root/'unexpected-follow-on-call').touch()
|
||||
return {'success': True, 'safe_to_continue': True}
|
||||
native_management._catalog_native = native_boundary
|
||||
raise SystemExit(native_management.management_worker_main(request))
|
||||
raise SystemExit(3)
|
||||
@@ -0,0 +1,82 @@
|
||||
import ast
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
from uuid import uuid4
|
||||
|
||||
workspace = Path(sys.argv[1]).resolve()
|
||||
bundle_root = Path(sys.argv[2]).resolve()
|
||||
sys.path.insert(0, str(workspace/'src'))
|
||||
exe = bundle_root/'dist/CbbRefreshVerify-Background/CbbRefreshVerify.exe'
|
||||
root = bundle_root/('smoke-' + uuid4().hex[:8])
|
||||
root.mkdir()
|
||||
results = {}
|
||||
env = dict(os.environ, QT_QPA_PLATFORM='offscreen')
|
||||
|
||||
def run(mode, job, expected):
|
||||
folder = root/mode
|
||||
folder.mkdir()
|
||||
request = folder/'request.json'
|
||||
request.write_text(json.dumps(job(folder)), 'utf-8')
|
||||
result = subprocess.run([str(exe), '--'+mode, str(request)], env=env, timeout=60,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
assert result.returncode == expected, (mode, result.returncode)
|
||||
results[mode] = {'exit_code': result.returncode, 'status': 'passed', 'evidence': str(folder)}
|
||||
return folder
|
||||
|
||||
gui = root/'gui'
|
||||
result = subprocess.run([str(exe), '--smoke-test', '--data-root', str(gui)], env=env,
|
||||
timeout=60, creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
assert result.returncode == 0
|
||||
assert 'gui_smoke_window_created' in (gui/'logs/application.log').read_text('utf-8')
|
||||
results['gui'] = {'status': 'passed', 'exit_code': 0}
|
||||
|
||||
def cancelled(folder):
|
||||
cancel = folder/'cancel.signal'
|
||||
cancel.touch()
|
||||
return {'root': str(folder), 'block_name': 'Fixture', 'cancel_signal': str(cancel)}
|
||||
folder = run('verify-worker', cancelled, 1)
|
||||
outcome = json.loads((folder/'outcome.json').read_text('utf-8'))
|
||||
assert 'VERIFY_CANCELLED' in outcome['stderr'] and not (folder/'save.log').exists()
|
||||
folder = run('management-worker', lambda p: {'desktop': 'NotThisDesktop', 'operation': 'catalog'}, 2)
|
||||
assert json.loads((folder/'result.json').read_text('utf-8'))['safe_to_continue'] is True
|
||||
folder = run('owner-probe', lambda p: {'names': ['CodexLifecycleNonexistent.exe']}, 0)
|
||||
assert json.loads((folder/'result.json').read_text('utf-8'))['owners'] == []
|
||||
|
||||
from cbb_refresh_verify.desktop_worker import DesktopWorker
|
||||
from cbb_refresh_verify.dialog_agent import DialogAgentClient
|
||||
from cbb_refresh_verify.dialog_models import DialogPhase
|
||||
name = 'CbbLifecycleSmoke_' + uuid4().hex[:8]
|
||||
client = DialogAgentClient.prepare(root/'dialog-agent', desktop_name=name, timeout_seconds=15)
|
||||
worker = DesktopWorker([str(exe), '--dialog-agent', str(client.paths.config)], name)
|
||||
try:
|
||||
client._accept(30)
|
||||
assert client.observe(DialogPhase.PCB_STARTING, pids=[]) == ()
|
||||
client.close()
|
||||
assert worker.wait(20) == 0
|
||||
results['dialog-agent'] = {'status': 'passed', 'exit_code': 0, 'scope': 'empty PID set, observe only'}
|
||||
finally:
|
||||
client.close()
|
||||
worker.close()
|
||||
|
||||
from PyInstaller.archive.readers import ZlibArchiveReader
|
||||
pyz = bundle_root/'build/CbbRefreshVerify/PYZ-00.pyz'
|
||||
code = ZlibArchiveReader(str(pyz)).extract('cbb_refresh_verify')
|
||||
assert '0.2.4b2' in code.co_consts
|
||||
toc = ast.literal_eval((bundle_root/'build/CbbRefreshVerify/Analysis-00.toc').read_text('utf-8'))
|
||||
stack, rows = [toc], []
|
||||
while stack:
|
||||
value = stack.pop()
|
||||
if isinstance(value, (list, tuple)):
|
||||
if (len(value) >= 2 and isinstance(value[0], str) and value[0].startswith('cbb_refresh_verify')
|
||||
and isinstance(value[1], str) and value[1].endswith('.py')):
|
||||
rows.append(value)
|
||||
else:
|
||||
stack.extend(value)
|
||||
assert rows and all(Path(row[1]).is_relative_to(workspace/'src') for row in rows)
|
||||
results['module_origins'] = {'status': 'passed', 'module_count': len(rows), 'source_root': str(workspace/'src')}
|
||||
results['version'] = '0.2.4b2'
|
||||
(root/'result.json').write_text(json.dumps(results, ensure_ascii=False, indent=2), 'utf-8')
|
||||
print(json.dumps({'evidence': str(root/'result.json'), **results}, ensure_ascii=False), flush=True)
|
||||
@@ -72,7 +72,7 @@ def test_crashed_worker_cannot_pass_even_with_pass_file(tmp_path, monkeypatch, o
|
||||
assert result.safe_to_continue is True # Proven release permits another item; crash stays FAIL.
|
||||
|
||||
|
||||
def test_supervisor_crash_stops_registered_save_helper_but_not_native(tmp_path):
|
||||
def test_supervisor_crash_preserves_registered_save_caller_and_native(tmp_path):
|
||||
import subprocess, sys, time
|
||||
import win32api, win32con, win32process, win32event
|
||||
supervisor = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)'])
|
||||
@@ -98,8 +98,9 @@ def test_supervisor_crash_stops_registered_save_helper_but_not_native(tmp_path):
|
||||
win32con.PROCESS_TERMINATE | win32con.SYNCHRONIZE, False, pid))
|
||||
supervisor.terminate()
|
||||
supervisor.wait(5)
|
||||
assert worker.wait(8) == 75
|
||||
assert win32event.WaitForSingleObject(handles[1], 3000) == win32con.WAIT_OBJECT_0
|
||||
time.sleep(.5)
|
||||
assert worker.poll() is None
|
||||
assert win32event.WaitForSingleObject(handles[1], 0) == win32con.WAIT_TIMEOUT
|
||||
assert win32process.GetExitCodeProcess(handles[0]) == 259
|
||||
finally:
|
||||
for process in (supervisor, worker):
|
||||
|
||||
@@ -1,6 +1,22 @@
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def test_cli_signal_requests_cooperative_batch_stop(tmp_path, monkeypatch):
|
||||
import signal
|
||||
from cbb_refresh_verify import application, verify_runner
|
||||
library = tmp_path/'center.lmc'
|
||||
library.touch()
|
||||
old = signal.getsignal(signal.SIGINT)
|
||||
def run(requests, *, stop):
|
||||
signal.getsignal(signal.SIGINT)(signal.SIGINT, None)
|
||||
assert stop.is_set()
|
||||
return [verify_runner.VerifyResult('CANCELLED')]
|
||||
monkeypatch.setattr(verify_runner, 'run_batch', run)
|
||||
assert application.main(['--batch-lmc', str(library), '--block', 'A',
|
||||
'--data-root', str(tmp_path/'data')]) == 2
|
||||
assert signal.getsignal(signal.SIGINT) is old
|
||||
|
||||
|
||||
def test_smoke_arguments_exit_zero_and_write_lifecycle_log(tmp_path: Path):
|
||||
import subprocess, sys
|
||||
result = subprocess.run([sys.executable, '-m', 'cbb_refresh_verify', '--smoke-test', '--data-root', str(tmp_path)], timeout=30)
|
||||
|
||||
@@ -66,8 +66,8 @@ def test_stop_worker_escalates_only_after_cooperative_deadline():
|
||||
if not self.stopped: raise TimeoutError()
|
||||
def kill(self): calls.append('client_stop'); self.stopped = True
|
||||
def poll(self): return 1 if self.stopped else None
|
||||
assert runner._stop_worker(Worker(), timeout=.1) is True
|
||||
assert calls == ['cancel', 'wait', 'client_stop', 'wait']
|
||||
assert runner._stop_worker(Worker(), timeout=.1) is False
|
||||
assert calls == ['cancel', 'wait']
|
||||
|
||||
|
||||
def test_cancel_reaches_current_supervised_worker(tmp_path, monkeypatch):
|
||||
@@ -223,7 +223,7 @@ def test_save_and_failure_close_clients_are_both_tracked(script, monkeypatch):
|
||||
assert proof['safe_to_continue'] is False and proof['remaining_pids'] == [22]
|
||||
|
||||
|
||||
def test_watchdog_with_cancel_signal_stops_clients_after_supervisor_exit(tmp_path):
|
||||
def test_watchdog_with_cancel_signal_retains_callers_after_supervisor_exit(tmp_path):
|
||||
import subprocess, sys, time
|
||||
import win32api, win32con, win32process
|
||||
supervisor = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)'])
|
||||
@@ -246,9 +246,12 @@ def test_watchdog_with_cancel_signal_stops_clients_after_supervisor_exit(tmp_pat
|
||||
for pid in json.loads(ready.read_text()):
|
||||
handles.append(win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_TERMINATE, False, pid))
|
||||
supervisor.terminate(); supervisor.wait(5)
|
||||
assert worker.wait(10) == 75 and cancel.is_file()
|
||||
deadline = time.monotonic()+3
|
||||
while not cancel.is_file() and time.monotonic()<deadline:
|
||||
time.sleep(.02)
|
||||
assert worker.poll() is None and cancel.is_file()
|
||||
assert win32process.GetExitCodeProcess(handles[0]) == 259
|
||||
assert win32process.GetExitCodeProcess(handles[1]) != 259
|
||||
assert win32process.GetExitCodeProcess(handles[1]) == 259
|
||||
finally:
|
||||
for p in (supervisor, worker):
|
||||
if p.poll() is None: p.terminate()
|
||||
|
||||
@@ -111,10 +111,12 @@ def test_reader_does_not_create_desktop_before_preparation_finishes(monkeypatch,
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reader', ['read_library_flag', 'read_library_tree_image_map'])
|
||||
def test_reader_closes_desktop_when_process_launch_fails(monkeypatch, tmp_path, reader):
|
||||
def test_reader_never_creates_a_desktop_or_process(monkeypatch, tmp_path, reader):
|
||||
import win32service
|
||||
import win32process
|
||||
import cbb_refresh_verify.mentor_adapter as module
|
||||
from pywinauto import Desktop
|
||||
monkeypatch.setattr(Desktop, 'windows', lambda *_: [])
|
||||
|
||||
closed = []
|
||||
|
||||
@@ -133,11 +135,10 @@ def test_reader_closes_desktop_when_process_launch_fails(monkeypatch, tmp_path,
|
||||
if reader == 'read_library_flag':
|
||||
flag, detail = module.read_library_flag(tmp_path / 'library.lmc', 'Block')
|
||||
assert flag == module.FLAG_UNKNOWN
|
||||
assert 'launch failed' in detail
|
||||
assert 'Library Manager' in detail
|
||||
else:
|
||||
with pytest.raises(RuntimeError, match='launch failed'):
|
||||
module.read_library_tree_image_map(tmp_path / 'library.lmc', ['Block'])
|
||||
assert closed == ['desktop']
|
||||
assert module.read_library_tree_image_map(tmp_path / 'library.lmc', ['Block']) == {'Block': None}
|
||||
assert closed == []
|
||||
|
||||
|
||||
def test_constructor_releases_private_desktop_when_process_launch_fails(monkeypatch):
|
||||
|
||||
@@ -133,7 +133,8 @@ def test_supervisor_loss_stops_automation_but_preserves_native_like_process(tmp_
|
||||
False, int(ready.read_text()))
|
||||
supervisor.terminate()
|
||||
supervisor.wait(5)
|
||||
assert worker.wait(8) == 75
|
||||
time.sleep(.5)
|
||||
assert worker.poll() is None
|
||||
assert win32process.GetExitCodeProcess(native_handle) == 259
|
||||
finally:
|
||||
if supervisor.poll() is None: supervisor.terminate()
|
||||
@@ -167,7 +168,7 @@ def test_cli_unsafe_batch_preserves_created_drive(tmp_path, monkeypatch):
|
||||
lease = LibraryPathLease.acquire(r'\\server\share\lib.lmc', backend=backend)
|
||||
monkeypatch.setattr(LibraryPathLease, 'acquire', lambda path: lease)
|
||||
monkeypatch.setattr('cbb_refresh_verify.network_path.select_library_file', lambda path: tmp_path/'lib.lmc')
|
||||
monkeypatch.setattr('cbb_refresh_verify.verify_runner.run_batch', lambda requests: [VerifyResult('FAIL', safe_to_continue=False)])
|
||||
monkeypatch.setattr('cbb_refresh_verify.verify_runner.run_batch', lambda requests, **kw: [VerifyResult('FAIL', safe_to_continue=False)])
|
||||
code = application.main(['--batch-lmc', r'\\server\share\lib.lmc', '--block', 'CBB', '--data-root', str(tmp_path/'run')])
|
||||
assert code == 2
|
||||
assert not backend.cancelled
|
||||
|
||||
@@ -120,7 +120,7 @@ End Class
|
||||
assert ('NATIVE_QUIT' in outcome.stdout) is (identity and close_ok and not other_document)
|
||||
|
||||
|
||||
def test_cancel_after_native_save_returns_stops_later_native_operations(tmp_path):
|
||||
def test_cancel_after_native_save_returns_keeps_save_fact_and_normal_close(tmp_path):
|
||||
source = Path('src/cbb_refresh_verify/save_verified_block.vbs').read_text('utf-8')
|
||||
classes = r'''
|
||||
Class FakePi
|
||||
@@ -182,9 +182,10 @@ End Class
|
||||
'//nologo', str(harness), 'expected.prj', 'CBB.pcb', str(tmp_path/'cancel.signal')],
|
||||
capture_output=True, text=True, timeout=10)
|
||||
assert 'NATIVE_SAVE_RETURNED' in outcome.stdout
|
||||
assert outcome.returncode == 9, outcome.stderr
|
||||
assert 'VERIFY_CANCELLED' in outcome.stdout
|
||||
assert 'CLOSE_OK' not in outcome.stdout
|
||||
assert 'SAVE_OK' in outcome.stdout
|
||||
assert 'CLOSE_OK' in outcome.stdout
|
||||
assert 'SAVE_REJECTED' not in outcome.stdout
|
||||
assert outcome.returncode == 10, outcome.stderr # FakeApp retains another document.
|
||||
|
||||
|
||||
def test_worker_attempts_normal_close_after_idle_integration_failure(tmp_path, monkeypatch):
|
||||
@@ -200,14 +201,16 @@ def test_worker_attempts_normal_close_after_idle_integration_failure(tmp_path, m
|
||||
assert not any(event['stage'] == 'save_start' for event in events)
|
||||
|
||||
|
||||
def test_stop_cancels_then_stops_automation_client_after_deadline(tmp_path):
|
||||
def test_stop_cancels_without_killing_pending_native_call(tmp_path):
|
||||
calls = []
|
||||
class BusyWorker:
|
||||
def request_stop(self): calls.append('cancel')
|
||||
def wait(self, timeout): raise TimeoutError('native Save still running')
|
||||
def kill(self): calls.append('kill')
|
||||
runner._stop_worker(BusyWorker(), timeout=0)
|
||||
assert calls == ['cancel', 'kill']
|
||||
def stop_automation_clients(self): calls.append('stop-helper')
|
||||
def poll(self): return None
|
||||
assert runner._stop_worker(BusyWorker(), timeout=0) is False
|
||||
assert calls == ['cancel']
|
||||
|
||||
|
||||
def test_status_server_close_allows_eof_cleanup_before_termination(tmp_path):
|
||||
@@ -255,13 +258,14 @@ def test_shared_address_is_diagnostic_after_successful_native_execution(tmp_path
|
||||
assert any(event['stage'] == 'icdb_address_remaining' for event in events)
|
||||
|
||||
|
||||
def test_cooperative_supervisor_loss_keeps_pending_save_helper_alive(tmp_path):
|
||||
@pytest.mark.parametrize('stop_clients', [False, True])
|
||||
def test_cooperative_supervisor_loss_keeps_pending_save_helper_alive(tmp_path, stop_clients):
|
||||
import win32api, win32con, win32process
|
||||
supervisor = subprocess.Popen([sys.executable, '-c', 'import time;time.sleep(30)'])
|
||||
script, ready, cancel = tmp_path/'worker.py', tmp_path/'ready.json', tmp_path/'cancel.signal'
|
||||
script.write_text('import subprocess,sys,time,json\nfrom pathlib import Path\n'
|
||||
'from cbb_refresh_verify.desktop_worker import start_supervisor_watchdog,launch_save_helper\n'
|
||||
f'start_supervisor_watchdog({supervisor.pid},cancel_path={str(cancel)!r})\n'
|
||||
f'start_supervisor_watchdog({supervisor.pid},cancel_path={str(cancel)!r},stop_clients={stop_clients!r})\n'
|
||||
'helper=launch_save_helper([sys.executable,"-c","import time;time.sleep(30)"])\n'
|
||||
f'Path({str(ready)!r}).write_text(json.dumps(helper.pid))\n'
|
||||
'time.sleep(30)\n', encoding='utf-8')
|
||||
@@ -280,6 +284,7 @@ def test_cooperative_supervisor_loss_keeps_pending_save_helper_alive(tmp_path):
|
||||
while not cancel.exists() and time.monotonic()<deadline:
|
||||
time.sleep(.05)
|
||||
assert cancel.exists()
|
||||
time.sleep(5.2 if stop_clients else .1)
|
||||
assert worker.poll() is None
|
||||
assert win32process.GetExitCodeProcess(handle) == 259
|
||||
finally:
|
||||
|
||||
@@ -57,7 +57,9 @@ def test_unsafe_result_stops_batch_even_when_reported_pass():
|
||||
|
||||
def test_cleanup_does_not_force_terminate_native_database_owner(monkeypatch):
|
||||
killed = []
|
||||
monkeypatch.setattr(adapter, '_terminate_pid', lambda pid, **k: killed.append(pid))
|
||||
import win32api
|
||||
monkeypatch.setattr(adapter.subprocess, 'run', lambda *args, **kwargs: killed.append(args))
|
||||
monkeypatch.setattr(win32api, 'TerminateProcess', lambda *args: killed.append(args))
|
||||
monkeypatch.setattr(adapter, '_process_details', lambda name:
|
||||
[(22, 'ExpeditionPCB.exe', 'pcb', 11)] if name == 'ExpeditionPCB.exe' else [])
|
||||
events = []
|
||||
|
||||
@@ -32,6 +32,21 @@ class FakeProjectIntegration:
|
||||
return True
|
||||
|
||||
|
||||
def test_cancel_during_allowed_getter_prevents_new_integration_call():
|
||||
from threading import Event
|
||||
stop = Event()
|
||||
class Integration(FakeProjectIntegration):
|
||||
@property
|
||||
def IsForwardAnnotationAllowed(self):
|
||||
stop.set()
|
||||
return True
|
||||
integration = Integration()
|
||||
with pytest.raises(IntegrationError, match='VERIFY_CANCELLED'):
|
||||
refresh_integration(integration, settle_seconds=0,
|
||||
error_reader=lambda: 'VERIFY_CANCELLED' if stop.is_set() else '')
|
||||
assert integration.forward_calls == 0
|
||||
|
||||
|
||||
def test_database_restoration_dialog_requires_manual_recovery():
|
||||
action = choose_dialog_action(
|
||||
'Database Restoration',
|
||||
@@ -81,8 +96,8 @@ def test_cleanup_verify_processes_confirms_absent_worker_parent_and_lm(monkeypat
|
||||
from cbb_refresh_verify import mentor_adapter
|
||||
|
||||
terminated = []
|
||||
monkeypatch.setattr(mentor_adapter, '_terminate_pid',
|
||||
lambda pid, **_kwargs: terminated.append(int(pid)))
|
||||
monkeypatch.setattr(mentor_adapter.subprocess, 'run',
|
||||
lambda *args, **kwargs: terminated.append(args))
|
||||
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _name: ())
|
||||
result = cleanup_verify_processes(101, 202, 303, emit=lambda **event: None)
|
||||
assert terminated == []
|
||||
@@ -105,8 +120,8 @@ def test_cleanup_verify_processes_discovers_unbound_target_pcb_processes(monkeyp
|
||||
(999, r'C:\Mentor\wg\ExpeditionPCB.exe', command, 0),
|
||||
],
|
||||
)
|
||||
monkeypatch.setattr(mentor_adapter, '_terminate_pid',
|
||||
lambda pid, **_kwargs: terminated.append(int(pid)))
|
||||
monkeypatch.setattr(mentor_adapter.subprocess, 'run',
|
||||
lambda *args, **kwargs: terminated.append(args))
|
||||
|
||||
result = mentor_adapter.cleanup_verify_processes(
|
||||
101,
|
||||
|
||||
@@ -323,7 +323,7 @@ def test_status_scan_logs_each_cbb_image_id(caplog, tmp_path):
|
||||
assert 'name=B image_id=28' in caplog.text
|
||||
|
||||
|
||||
def test_status_scan_keeps_only_missing_cert_or_project_items_pending(tmp_path):
|
||||
def test_status_scan_without_native_observation_does_not_guess_status(tmp_path):
|
||||
lmc = tmp_path / 'center.lmc'
|
||||
lmc.touch()
|
||||
root = lmc.parent / 'ReusableBlocksLP'
|
||||
@@ -348,7 +348,7 @@ def test_status_scan_keeps_only_missing_cert_or_project_items_pending(tmp_path):
|
||||
('READY_CBB', 'IP101GR', 'MISSING_CBB'),
|
||||
tree_image_reader=lambda _library, _names: {},
|
||||
)
|
||||
assert result == {'READY_CBB': 'READY', 'IP101GR': 'PENDING', 'MISSING_CBB': 'PENDING'}
|
||||
assert result == {'READY_CBB': 'UNKNOWN', 'IP101GR': 'UNKNOWN', 'MISSING_CBB': 'UNKNOWN'}
|
||||
|
||||
|
||||
def test_filesystem_evidence_exposes_multiple_persistent_dimensions(tmp_path):
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
from dataclasses import replace
|
||||
import json
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
from test_verify_runner import fixture, request
|
||||
|
||||
|
||||
def test_default_batch_verifier_receives_current_stop(monkeypatch, tmp_path):
|
||||
stop = threading.Event()
|
||||
received = []
|
||||
def verify(req, **kw):
|
||||
received.append(kw.get('stop'))
|
||||
return runner.VerifyResult('FAIL')
|
||||
monkeypatch.setattr(runner, 'run_verify', verify)
|
||||
runner.run_batch([request(tmp_path)], stop=stop)
|
||||
assert received == [stop]
|
||||
|
||||
|
||||
def test_stopped_helper_save_fact_survives_supervisor_finally(tmp_path, monkeypatch):
|
||||
fixture(tmp_path)
|
||||
stop = threading.Event()
|
||||
class SavingWorker:
|
||||
desktop = None
|
||||
pid = None
|
||||
returncode = None
|
||||
def __init__(self, command, *_a, **_kw):
|
||||
self.root = __import__('pathlib').Path(command[-1]).parent
|
||||
(self.root/'save.log').write_text('SAVE_START\nSAVE_OK\nCLOSE_START\n')
|
||||
stop.set()
|
||||
def poll(self): return None
|
||||
def request_stop(self): pass
|
||||
def wait(self, timeout): raise TimeoutError('Close pending')
|
||||
def kill(self): pytest.fail('Stop/finally interrupted native Close')
|
||||
def stop_automation_clients(self): pytest.fail('Save caller was killed')
|
||||
def close(self): pass
|
||||
def automation_release_state(self):
|
||||
return {'safe_to_continue': False, 'remaining_pids': [42]}
|
||||
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', SavingWorker)
|
||||
monkeypatch.setattr(runner, '_cleanup_session_processes',
|
||||
lambda *a, **kw: {'safe_to_continue': False, 'remaining_pids': []})
|
||||
result = runner.run_verify(request(tmp_path), stop=stop, port_check=lambda: (True, ''))
|
||||
assert result.status == 'CANCELLED'
|
||||
assert result.safe_to_continue is False
|
||||
assert result.write_outcome['save_state'] == 'COMMITTED'
|
||||
assert result.write_outcome['close_state'] == 'UNKNOWN'
|
||||
assert result.write_outcome['helper_state'] == 'RUNNING'
|
||||
|
||||
|
||||
def test_unreleased_library_does_not_cancel_an_independent_library(tmp_path):
|
||||
first = request(tmp_path)
|
||||
second = replace(first, lmc_file=tmp_path/'other.lmc')
|
||||
calls = []
|
||||
def verify(req):
|
||||
calls.append(req.lmc_file)
|
||||
return runner.VerifyResult('TIMEOUT', safe_to_continue=req == second)
|
||||
stop = threading.Event()
|
||||
results = runner.run_batch([first, second, first], stop=stop, verifier=verify)
|
||||
assert calls == [first.lmc_file, second.lmc_file]
|
||||
assert [r.status for r in results] == ['TIMEOUT', 'TIMEOUT', 'SKIPPED']
|
||||
assert not stop.is_set()
|
||||
|
||||
|
||||
def test_contradictory_helper_result_cannot_be_promoted_by_core_success_markers(tmp_path, monkeypatch):
|
||||
from types import SimpleNamespace
|
||||
from test_verify_worker_stability import exercise_worker
|
||||
from cbb_refresh_verify import mentor_adapter
|
||||
job, events, execute = exercise_worker(tmp_path, monkeypatch)
|
||||
def helper(command, **kw):
|
||||
kw['stdout'].write('LICENSE_OK\nSAVE_OK\nSAVE_REJECTED\nIS_SAVED\nPOST_SAVE_SYNCHRONIZED\nCLOSE_OK\nQUIT_OK\n')
|
||||
kw['stdout'].flush()
|
||||
return SimpleNamespace(pid=3, poll=lambda: 0, returncode=0)
|
||||
monkeypatch.setattr(mentor_adapter.subprocess, 'Popen', helper)
|
||||
with pytest.raises(RuntimeError, match='保存/关闭未完成'):
|
||||
execute()
|
||||
assert not any(event['stage'] == 'complete' for event in events)
|
||||
@@ -241,7 +241,8 @@ def test_timeout_stops_batch_and_persists_ambiguous_native_stage(setup):
|
||||
adapter.remove = timeout
|
||||
results = run_management_batch([request, replace(request, name='Other')], adapter=adapter,
|
||||
idle_check=lambda *_: None)
|
||||
assert len(results) == 1 and not results[0].safe_to_continue
|
||||
assert len(results) == 2 and not results[0].safe_to_continue
|
||||
assert results[1].status == 'SKIPPED'
|
||||
assert results[0].status == 'RECOVERY_REQUIRED'
|
||||
|
||||
|
||||
|
||||
@@ -99,7 +99,8 @@ def test_probe_preloads_uia_before_com_proxy_creation_but_catalog_stays_read_onl
|
||||
monkeypatch.setattr(native, '_probe_add_dialog', editor)
|
||||
monkeypatch.setattr(native, '_wait_native_exit', lambda pids: True)
|
||||
result = native._catalog_native({'operation': operation, 'desktop': 'CbbManagement_test',
|
||||
'library': str(library_path), 'mentor_home': str(tmp_path), 'probe_token': 'fixture'}, root)
|
||||
'library': str(library_path), 'mentor_home': str(tmp_path), 'probe_token': 'fixture',
|
||||
'supervisor_pid': __import__('os').getpid()}, root)
|
||||
assert events[:2] == (['dispatch', 'library-close'] if operation == 'catalog' else ['uia-loaded', 'dispatch'])
|
||||
if operation == 'catalog':
|
||||
assert result['success'] and 'uia-loaded' not in events
|
||||
|
||||
@@ -156,7 +156,8 @@ def test_removal_cli_keeps_mapped_drive_spelling(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify.management import Capability
|
||||
job = {'operation': 'remove', 'library': 'S:\\library\\mentor.lmc', 'name': 'Block',
|
||||
'partition': 'Logical-Physical', 'desktop': 'CbbManagement_fixture',
|
||||
'mentor_home': str(tmp_path), 'timeout_seconds': 10}
|
||||
'mentor_home': str(tmp_path), 'timeout_seconds': 10,
|
||||
'supervisor_pid': __import__('os').getpid()}
|
||||
request = tmp_path/'request.json'; request.write_text(json.dumps(job), encoding='utf-8')
|
||||
monkeypatch.setattr(native, '_current_desktop', lambda: (None, job['desktop']))
|
||||
monkeypatch.setattr(native.NativeManagementAdapter, 'capabilities', lambda self: {'remove': Capability(True, 'fake transport')})
|
||||
|
||||
@@ -179,9 +179,15 @@ def test_batch_cache_binds_exact_library_identity(tmp_path):
|
||||
assert fingerprint_library(first).sha256 != fingerprint_library(second).sha256
|
||||
|
||||
|
||||
def test_timed_out_management_worker_releases_only_after_its_result(tmp_path, monkeypatch):
|
||||
def test_timed_out_management_worker_requires_independent_release_proof(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
state = {'exit': None}
|
||||
proven = {'released': False}
|
||||
def release(*a, **kw):
|
||||
if not proven['released']:
|
||||
raise OSError('native resources still owned')
|
||||
return {'status': 'RELEASE_CONFIRMED', 'library': str(library)}
|
||||
monkeypatch.setattr('cbb_refresh_verify.library_lock.release_retained_library', release)
|
||||
worker = SimpleNamespace(poll=lambda: state['exit'], close=lambda: None)
|
||||
adapter = native.NativeManagementAdapter(mentor_home=tmp_path, worker_factory=lambda *_: worker)
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
@@ -195,6 +201,8 @@ def test_timed_out_management_worker_releases_only_after_its_result(tmp_path, mo
|
||||
assert adapter.release_confirmed(library) is False
|
||||
(evidence/'result.json').write_text(json.dumps({'success': False, 'safe_to_continue': True}))
|
||||
assert adapter.release_confirmed(tmp_path/'other.lmc') is False
|
||||
assert adapter.release_confirmed(library) is False
|
||||
proven['released'] = True
|
||||
assert adapter.release_confirmed(library) is True
|
||||
assert worker not in native._retained_workers
|
||||
finally:
|
||||
@@ -483,19 +491,21 @@ def test_native_add_passive_postcheck_failure_preserves_release(transaction, mon
|
||||
|
||||
|
||||
@pytest.mark.parametrize('case,safe', [('exit_output_error', True), ('popen_missing', True),
|
||||
('popen_denied', True), ('popen_unknown', False), ('timeout', False)])
|
||||
('popen_denied', True), ('popen_unknown', False), ('timeout', True)])
|
||||
def test_remove_worker_preserves_exit_and_known_creation_rejection(tmp_path, monkeypatch, case, safe):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
job = tmp_path/'request.json'
|
||||
job.write_text(json.dumps({'operation': 'remove', 'desktop': 'CbbManagement_test',
|
||||
'mentor_home': str(tmp_path), 'library': str(tmp_path/'lib.lmc'), 'name': 'Block',
|
||||
'partition': 'Logical-Physical', 'timeout_seconds': 1}), encoding='utf-8')
|
||||
'partition': 'Logical-Physical', 'timeout_seconds': 1,
|
||||
'supervisor_pid': __import__('os').getpid()}), encoding='utf-8')
|
||||
monkeypatch.setattr(native, '_current_desktop', lambda: (None, 'CbbManagement_test'))
|
||||
monkeypatch.setattr(native.NativeManagementAdapter, 'capabilities', lambda _: {
|
||||
'remove': SimpleNamespace(supported=True)})
|
||||
observed = {'waited': False}
|
||||
def wait(timeout):
|
||||
if case == 'timeout':
|
||||
if case == 'timeout' and not observed.get('timed_out'):
|
||||
observed['timed_out'] = True
|
||||
raise native.subprocess.TimeoutExpired('fake CleanWGLib', timeout)
|
||||
observed['waited'] = True
|
||||
return 0
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
from dataclasses import replace
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
|
||||
import pytest
|
||||
|
||||
from cbb_refresh_verify import native_management as native
|
||||
from cbb_refresh_verify.session_record import process_identity
|
||||
from test_management import setup, execute
|
||||
|
||||
|
||||
@pytest.mark.parametrize('operation', ['catalog', 'add', 'remove'])
|
||||
@pytest.mark.parametrize('reason', ['cancelled', 'parent_gone', 'identity_changed'])
|
||||
def test_management_worker_checks_stop_before_any_native_route(tmp_path, monkeypatch, operation, reason):
|
||||
cancel = tmp_path/'cancel.signal'
|
||||
identity = process_identity(os.getpid())
|
||||
if reason == 'cancelled':
|
||||
cancel.touch()
|
||||
if reason == 'identity_changed':
|
||||
identity['created_handle'] = 'old'
|
||||
job = dict(operation=operation, library=str(tmp_path/'lib.lmc'), desktop='CbbManagement_Test',
|
||||
supervisor_pid=-1 if reason == 'parent_gone' else os.getpid(),
|
||||
supervisor_identity=identity, cancel_signal=str(cancel), operation_id='test-management')
|
||||
request = tmp_path/'request.json'
|
||||
request.write_text(json.dumps(job))
|
||||
monkeypatch.setattr(native, '_current_desktop', lambda: (None, job['desktop']))
|
||||
monkeypatch.setattr(native, '_catalog_native', lambda *a: pytest.fail('unsupervised native route'))
|
||||
monkeypatch.setattr(native.subprocess, 'Popen', lambda *a, **kw: pytest.fail('unsupervised remove'))
|
||||
assert native.management_worker_main(request) == 2
|
||||
result = json.loads((tmp_path/'result.json').read_text())
|
||||
assert not result['success']
|
||||
assert result['safe_to_continue'] is True
|
||||
assert 'CANCELLED' in result['detail'] or '监督器' in result['detail']
|
||||
|
||||
|
||||
def test_cancel_after_remove_stops_update_before_catalog_and_add(setup):
|
||||
req, adapter, source = setup
|
||||
stop = Event()
|
||||
remove = adapter.remove
|
||||
def stop_after_remove(*args):
|
||||
result = remove(*args)
|
||||
stop.set()
|
||||
return result
|
||||
adapter.remove = stop_after_remove
|
||||
result = execute(replace(req, operation='update', source=source), adapter, stop=stop)
|
||||
assert adapter.calls == ['remove']
|
||||
assert result.status == 'RECOVERY_REQUIRED'
|
||||
assert result.safe_to_continue is True
|
||||
checkpoint = json.loads(result.evidence_path.read_text('utf-8'))
|
||||
assert any(item['stage'] == 'native_remove' for item in checkpoint['history'])
|
||||
|
||||
|
||||
def test_cancel_before_catalog_does_not_launch_native(setup):
|
||||
req, adapter, _ = setup
|
||||
stop = Event()
|
||||
stop.set()
|
||||
adapter.catalog = lambda *a: pytest.fail('catalog after cancellation')
|
||||
result = execute(req, adapter, stop=stop)
|
||||
assert result.status == 'CANCELLED'
|
||||
assert result.safe_to_continue is True
|
||||
|
||||
|
||||
def test_real_management_worker_parent_loss_waits_for_native_boundary(tmp_path):
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from cbb_refresh_verify.session_record import write_session_record
|
||||
supervisor = subprocess.Popen([sys.executable, '-c', 'import time;time.sleep(30)'])
|
||||
request, script = tmp_path/'request.json', tmp_path/'worker.py'
|
||||
gate, cancel, started, continued = [tmp_path/name for name in ('gate', 'cancel', 'started', 'continued')]
|
||||
job = dict(operation='catalog', library=str(tmp_path/'lib.lmc'), desktop='CbbManagement_test',
|
||||
supervisor_pid=supervisor.pid, supervisor_identity=process_identity(supervisor.pid),
|
||||
cancel_signal=str(cancel), start_gate=str(gate), operation_id='real-management',
|
||||
session_record_path=str(tmp_path/'session.json'))
|
||||
request.write_text(json.dumps(job))
|
||||
script.write_text('import time,sys\nfrom pathlib import Path\n'
|
||||
'from cbb_refresh_verify import native_management as n\n'
|
||||
'n._current_desktop=lambda:(None,"CbbManagement_test")\n'
|
||||
'def native_call(job,root):\n'
|
||||
' from cbb_refresh_verify.session_record import update_worker_state\n'
|
||||
' update_worker_state(job,"NATIVE_CALL")\n'
|
||||
f' Path({str(started)!r}).touch()\n'
|
||||
' time.sleep(1.5)\n'
|
||||
' try: n._require_management_continuation(job,root)\n'
|
||||
' except RuntimeError as e: return dict(success=False,safe_to_continue=True,detail=str(e))\n'
|
||||
f' Path({str(continued)!r}).touch()\n'
|
||||
' return dict(success=True,safe_to_continue=True)\n'
|
||||
'n._catalog_native=native_call\n'
|
||||
f'sys.exit(n.management_worker_main({str(request)!r}))\n')
|
||||
worker = subprocess.Popen([sys.executable, str(script)])
|
||||
try:
|
||||
write_session_record(tmp_path/'session.json', dict(operation_id='real-management',
|
||||
library=job['library'], processes=[{'role': 'worker', **process_identity(worker.pid)}]))
|
||||
gate.touch()
|
||||
deadline = time.monotonic()+8
|
||||
while not started.exists() and time.monotonic()<deadline:
|
||||
time.sleep(.02)
|
||||
assert started.exists()
|
||||
supervisor.terminate(); supervisor.wait(5)
|
||||
deadline = time.monotonic()+1
|
||||
while not cancel.exists() and time.monotonic()<deadline:
|
||||
time.sleep(.02)
|
||||
assert cancel.exists() and worker.poll() is None
|
||||
assert worker.wait(5) == 2
|
||||
assert not continued.exists()
|
||||
assert (tmp_path/'supervisor-lost.json').is_file()
|
||||
assert json.loads((tmp_path/'result.json').read_text())['safe_to_continue'] is True
|
||||
finally:
|
||||
for process in (worker, supervisor):
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
process.wait(5)
|
||||
|
||||
|
||||
def test_remove_timeout_keeps_worker_observing_until_native_returns(tmp_path, monkeypatch):
|
||||
from types import SimpleNamespace
|
||||
from threading import Thread
|
||||
entered, release, done = Event(), Event(), Event()
|
||||
job = tmp_path/'request.json'
|
||||
job.write_text(json.dumps(dict(operation='remove', library=str(tmp_path/'lib.lmc'),
|
||||
desktop='CbbManagement_test', mentor_home=str(tmp_path), name='A',
|
||||
partition='Logical-Physical', timeout_seconds=0, supervisor_pid=os.getpid())))
|
||||
monkeypatch.setattr(native, '_current_desktop', lambda: (None, 'CbbManagement_test'))
|
||||
monkeypatch.setattr(native.NativeManagementAdapter, 'capabilities',
|
||||
lambda _: {'remove': SimpleNamespace(supported=True)})
|
||||
def wait(timeout):
|
||||
entered.set()
|
||||
if not release.wait(.05):
|
||||
raise native.subprocess.TimeoutExpired('fake native remove', timeout)
|
||||
return 0
|
||||
monkeypatch.setattr(native.subprocess, 'Popen', lambda *a, **kw: SimpleNamespace(pid=123456, wait=wait))
|
||||
def run():
|
||||
try:
|
||||
native.management_worker_main(job)
|
||||
finally:
|
||||
done.set()
|
||||
thread = Thread(target=run)
|
||||
thread.start()
|
||||
try:
|
||||
assert entered.wait(3)
|
||||
assert not done.wait(.2), 'native timeout abandoned the still-running owner'
|
||||
finally:
|
||||
release.set()
|
||||
thread.join(3)
|
||||
assert done.is_set()
|
||||
assert json.loads((tmp_path/'result.json').read_text())['safe_to_continue'] is True
|
||||
@@ -76,7 +76,8 @@ def test_restart_shows_unfinished_without_starting_worker(qtbot, tmp_path):
|
||||
adapter = SimpleNamespace(capabilities=lambda: {n: Capability(False, 'disabled') for n in ('add', 'update', 'remove')})
|
||||
window = MainWindow(data_root=tmp_path, management_adapter=adapter)
|
||||
qtbot.addWidget(window)
|
||||
assert '未完成' in window.unfinished_label.text() and not window.busy
|
||||
qtbot.waitUntil(lambda: '未完成' in window.unfinished_label.text())
|
||||
assert not window.busy
|
||||
assert 'Block' in window.output.toPlainText()
|
||||
|
||||
|
||||
|
||||
@@ -52,7 +52,9 @@ def test_add_timeout_publishes_cancellation_without_killing_native_owner(tmp_pat
|
||||
assert len(native._retained_workers)==1
|
||||
|
||||
|
||||
def test_cancellation_during_log_evidence_prevents_native_submit(tmp_path, monkeypatch):
|
||||
@pytest.mark.parametrize('cancel', [True, False])
|
||||
@pytest.mark.parametrize('journal_error', [False, True])
|
||||
def test_cancellation_and_phase_at_native_add_submit(tmp_path, monkeypatch, cancel, journal_error):
|
||||
import os,sys
|
||||
from types import SimpleNamespace
|
||||
import win32gui,win32process
|
||||
@@ -78,19 +80,59 @@ def test_cancellation_during_log_evidence_prevents_native_submit(tmp_path, monke
|
||||
def post(h,*args):
|
||||
state['posted'].append(h)
|
||||
if h==110:state['new']=True
|
||||
if h==210:
|
||||
from cbb_refresh_verify.session_record import read_session_record
|
||||
assert read_session_record(root/'worker-state.json', evidence_root=root)['phase'] == 'NATIVE_CALL'
|
||||
monkeypatch.setattr(win32gui,'PostMessage',post)
|
||||
original=native._write_json
|
||||
def write(path,data):
|
||||
original(path,data)
|
||||
if path.name=='native-add-log-baseline.json':(root/'cancel-native-add.signal').touch()
|
||||
if path.name=='native-add-log-baseline.json' and cancel:(root/'cancel-native-add.signal').touch()
|
||||
monkeypatch.setattr(native,'_write_json',write)
|
||||
monkeypatch.setattr(failures,'observe_add_failure',lambda *a:(_ for _ in ()).throw(RuntimeError('unsafe OK posted')))
|
||||
desktop=SimpleNamespace(EnumDesktopWindows=lambda:[100,200] if state['new'] else [100])
|
||||
job={'operation':'probe_create_add','source':str(source),'library':str(library),
|
||||
'name':'Block','timeout_seconds':5,'supervisor_pid':os.getpid()}
|
||||
with pytest.raises(RuntimeError,match='NATIVE_ADD_CANCELLED'):
|
||||
'name':'Block','timeout_seconds':5,'supervisor_pid':os.getpid(),
|
||||
'operation_id':'test-add-phase','session_record_path':str(root/'session.json')}
|
||||
from cbb_refresh_verify.session_record import write_session_record
|
||||
write_session_record(root/'worker-state.json', {'operation_id': 'test-add-phase', 'phase':'POSTCALL', 'processes':[]})
|
||||
if journal_error:
|
||||
def fail(*a, **kw): raise OSError('phase journal unavailable')
|
||||
monkeypatch.setattr('cbb_refresh_verify.session_record.write_session_record', fail)
|
||||
expected = OSError if journal_error and not cancel else RuntimeError
|
||||
message = 'NATIVE_ADD_CANCELLED' if cancel else 'phase journal unavailable' if journal_error else 'unsafe OK posted'
|
||||
with pytest.raises(expected, match=message):
|
||||
native._probe_add_dialog_impl(SimpleNamespace(OnReusableBlocksEditor=lambda:None),job,desktop,{99},root)
|
||||
assert state['posted']==[110]
|
||||
assert state['posted']==([110] if cancel or journal_error else [110,210])
|
||||
|
||||
|
||||
def test_unknown_pending_add_does_not_send_cleanup_dialog_actions(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import native_management as native
|
||||
def pending(app, job, *a, **kw):
|
||||
job['_native_add_pending'] = True
|
||||
raise TimeoutError('native Add pending')
|
||||
monkeypatch.setattr(native, '_probe_add_dialog_impl', pending)
|
||||
monkeypatch.setattr(native, '_close_probe_dialogs', lambda *a: pytest.fail('closing a pending Add'))
|
||||
with pytest.raises(TimeoutError):
|
||||
native._probe_add_dialog(None, {}, None, set(), tmp_path)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('acknowledged', [False, True])
|
||||
def test_add_failure_only_allows_cleanup_after_confirmed_native_ack(tmp_path, monkeypatch, acknowledged):
|
||||
import json
|
||||
from cbb_refresh_verify import native_management as native
|
||||
job = {}
|
||||
def failed(app, job, *a, **kw):
|
||||
job['_native_add_pending'] = True
|
||||
(tmp_path/'native-add-output.json').write_text(json.dumps({'failure': {'acknowledged': acknowledged}}))
|
||||
raise RuntimeError('NATIVE_ADD_FAILED: simulated complete error')
|
||||
closed = []
|
||||
monkeypatch.setattr(native, '_probe_add_dialog_impl', failed)
|
||||
monkeypatch.setattr(native, '_close_probe_dialogs', lambda *a: closed.append(True))
|
||||
with pytest.raises(RuntimeError, match='NATIVE_ADD_FAILED'):
|
||||
native._probe_add_dialog(None, job, None, set(), tmp_path)
|
||||
assert bool(closed) is acknowledged
|
||||
assert job['_native_add_pending'] is not acknowledged
|
||||
|
||||
|
||||
def test_copy_failure_log_must_be_new_and_match_current_block(tmp_path):
|
||||
|
||||
@@ -384,7 +384,8 @@ def test_native_catalog_only_uses_com_records_and_checks_exact_process(tmp_path,
|
||||
monkeypatch.setattr(mentor, '_process_details', lambda _: [(123, str(tmp_path/'lm/win32/bin/LibraryManager.exe'), '', 0)] if state['running'] else [])
|
||||
monkeypatch.setattr(native, '_wait_native_exit', lambda _: not state['running'])
|
||||
result = native._catalog_native({'operation': 'catalog', 'library': str(library_path),
|
||||
'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path)}, tmp_path)
|
||||
'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path),
|
||||
'supervisor_pid': __import__('os').getpid()}, tmp_path)
|
||||
assert result['success'] and result['safe_to_continue']
|
||||
assert [(entry['name'], entry['partition']) for entry in result['entries']] == records
|
||||
assert result['flow'] == flow
|
||||
@@ -428,6 +429,37 @@ def test_com_failure_without_owner_identity_cannot_claim_release(tmp_path, monke
|
||||
assert native._catalog_native({}, tmp_path)['safe_to_continue'] is False
|
||||
|
||||
|
||||
def test_pending_async_add_does_not_close_or_quit_library(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
import cbb_refresh_verify.mentor_adapter as mentor
|
||||
import win32com.client
|
||||
library_path = tmp_path/'lib.lmc'
|
||||
running = []
|
||||
class Library:
|
||||
FullName = str(library_path)
|
||||
FlowType = 1
|
||||
def Close(self): pytest.fail('Close during pending Add')
|
||||
class App:
|
||||
def OpenLibrary(self, path): return Library()
|
||||
def Quit(self): pytest.fail('Quit during pending Add')
|
||||
def dispatch(*a): running.append(True); return App()
|
||||
monkeypatch.setattr(win32com.client, 'DispatchEx', dispatch)
|
||||
monkeypatch.setattr(native, 'validate_owned_fixture_add', lambda *a: None)
|
||||
monkeypatch.setattr(native, '_current_desktop', lambda: (SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test'))
|
||||
monkeypatch.setattr(mentor, '_process_details', lambda _: [
|
||||
(123, str(tmp_path/'lm/win32/bin/LibraryManager.exe'), '', 0)] if running else [])
|
||||
def pending(app, job, *a, **kw):
|
||||
job['_native_add_pending'] = True
|
||||
raise TimeoutError('native result unknown')
|
||||
monkeypatch.setattr(native, '_probe_add_dialog', pending)
|
||||
result = native._catalog_com({'operation': 'add', 'library': str(library_path),
|
||||
'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path),
|
||||
'supervisor_pid': __import__('os').getpid()}, tmp_path)
|
||||
assert result['success'] is False
|
||||
assert result['native_pids'] == [123]
|
||||
assert 'native result unknown' in result['detail']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('registered', [True, False])
|
||||
def test_shared_add_reopens_exact_catalog_and_reports_identity_mismatch(tmp_path, monkeypatch, registered):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
@@ -461,7 +493,8 @@ def test_shared_add_reopens_exact_catalog_and_reports_identity_mismatch(tmp_path
|
||||
monkeypatch.setattr(native, 'validate_owned_fixture_add', lambda *a: None)
|
||||
result = native._catalog_com({'operation': 'add', 'library': str(library_path),
|
||||
'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path),
|
||||
'name': 'Block', 'partition': 'Logical-Physical', 'source_identity': {'expected': 'bytes'}}, tmp_path)
|
||||
'name': 'Block', 'partition': 'Logical-Physical', 'source_identity': {'expected': 'bytes'},
|
||||
'supervisor_pid': __import__('os').getpid()}, tmp_path)
|
||||
assert events == ['open', 'add', 'close', 'open', 'catalog', 'close']
|
||||
assert result['success'] is registered
|
||||
assert result['identity_matches'] is False
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import pytest
|
||||
|
||||
from cbb_refresh_verify.operation_lifecycle import classify_save_state, stop_disposition
|
||||
|
||||
|
||||
def facts(markers, *, exited=True, released=True, forced=False):
|
||||
return classify_save_state(markers, helper_exited=exited,
|
||||
native_released=released, forced=forced)
|
||||
|
||||
|
||||
def test_saved_but_not_closed_retains_independent_facts():
|
||||
result = facts(['SAVE_START', 'SAVE_OK', 'CLOSE_START'], exited=False, released=False)
|
||||
assert result['save_state'] == 'COMMITTED'
|
||||
assert result['close_state'] == 'UNKNOWN'
|
||||
assert result['helper_state'] == 'RUNNING'
|
||||
assert result['resource_state'] == 'RETAINED'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('markers,expected', [
|
||||
([], 'UNKNOWN'),
|
||||
(['SAVE_START'], 'UNKNOWN'),
|
||||
(['CANCELLED_BEFORE_SAVE'], 'NOT_STARTED'),
|
||||
(['SAVE_START', 'SAVE_REJECTED'], 'REJECTED'),
|
||||
(['SAVE_START', 'SAVE_RESULT_UNKNOWN|123|broken'], 'UNKNOWN'),
|
||||
(['SAVE_OK', 'POST_SAVE_FAILED'], 'COMMITTED'),
|
||||
(['SAVE_OK', 'CLOSE_FAILED|5|busy'], 'COMMITTED'),
|
||||
])
|
||||
def test_process_exit_never_substitutes_for_save_return(markers, expected):
|
||||
result = facts(markers)
|
||||
assert result['save_state'] == expected
|
||||
assert result['resource_state'] == 'RELEASED'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('markers', [
|
||||
['SAVE_OK', 'SAVE_REJECTED'], ['CANCELLED_BEFORE_SAVE', 'SAVE_START'],
|
||||
['SAVE_OK', 'SAVE_RESULT_UNKNOWN'], ['CLOSE_OK', 'CLOSE_FAILED'],
|
||||
])
|
||||
def test_contradictory_markers_are_not_success(markers):
|
||||
result = facts(markers)
|
||||
if any(m.startswith('SAVE') or m == 'CANCELLED_BEFORE_SAVE' for m in markers):
|
||||
assert result['save_state'] == 'UNKNOWN'
|
||||
else:
|
||||
assert result['close_state'] == 'UNKNOWN'
|
||||
assert result['detail']
|
||||
|
||||
|
||||
def test_successful_save_and_failed_close_survive_force_and_later_release():
|
||||
result = facts(['SAVE_START', 'SAVE_OK', 'CLOSE_FAILED'], forced=True)
|
||||
assert result['save_state'] == 'COMMITTED'
|
||||
assert result['close_state'] == 'FAILED'
|
||||
assert result['resource_state'] == 'RELEASED'
|
||||
assert result['interrupted'] is True
|
||||
|
||||
|
||||
def test_close_and_exit_without_save_return_remains_unknown():
|
||||
result = facts(['SAVE_START', 'CLOSE_OK'], forced=True)
|
||||
assert result['save_state'] == 'UNKNOWN'
|
||||
assert result['close_state'] == 'CLOSED'
|
||||
assert result['interrupted'] is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize('exited,released,expected', [
|
||||
(None, True, 'UNKNOWN'), (True, None, 'UNKNOWN'),
|
||||
(False, True, 'RETAINED'), (True, False, 'RETAINED'),
|
||||
])
|
||||
def test_resource_release_requires_both_observations(exited, released, expected):
|
||||
assert facts(['SAVE_OK'], exited=exited, released=released)['resource_state'] == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize('started,returned,identity,expected', [
|
||||
(False, False, True, 'CANCEL_BEFORE_CALL'),
|
||||
(True, False, True, 'WAIT_FOR_RETURN'),
|
||||
(True, None, True, 'WAIT_FOR_RETURN'),
|
||||
(True, True, True, 'CLEANUP_RETURNED'),
|
||||
(None, None, True, 'OBSERVE_UNCONFIRMED'),
|
||||
(False, False, False, 'OBSERVE_UNCONFIRMED'),
|
||||
(False, True, True, 'OBSERVE_UNCONFIRMED'),
|
||||
])
|
||||
def test_stop_requires_positive_call_and_identity_evidence(started, returned, identity, expected):
|
||||
assert stop_disposition(call_started=started, call_returned=returned,
|
||||
identity_confirmed=identity) == expected
|
||||
@@ -0,0 +1,41 @@
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from cbb_refresh_verify import mentor_adapter as adapter
|
||||
from cbb_refresh_verify.library_reader import scan_open_library_status
|
||||
|
||||
|
||||
@pytest.mark.parametrize('prompt', ['', 'Repair database', 'Overwrite existing library',
|
||||
'Save changes?', 'Unknown license warning'])
|
||||
def test_compat_readers_neither_launch_nor_answer_native_prompts(monkeypatch, tmp_path, prompt):
|
||||
import win32process, win32service, win32gui
|
||||
from pywinauto import Desktop
|
||||
def forbidden(*a, **kw):
|
||||
pytest.fail('status observation attempted a native action')
|
||||
monkeypatch.setattr(win32process, 'CreateProcess', forbidden)
|
||||
monkeypatch.setattr(win32service, 'CreateDesktop', forbidden)
|
||||
monkeypatch.setattr(win32gui, 'PostMessage', forbidden)
|
||||
monkeypatch.setattr(adapter, 'handle_known_dialogs', forbidden)
|
||||
monkeypatch.setattr(adapter, 'close_library_reader', forbidden)
|
||||
library = tmp_path/'lib.lmc'
|
||||
target = SimpleNamespace(window_text=lambda: f'Library Manager: {library}',
|
||||
is_enabled=lambda: not bool(prompt), descendants=lambda: [], handle=0)
|
||||
monkeypatch.setattr(Desktop, 'windows', lambda *_: [target] if prompt else [])
|
||||
assert adapter.read_library_flag(library, 'A')[0] == adapter.FLAG_UNKNOWN
|
||||
assert adapter.read_library_tree_image_map(library, ['A']) == {'A': None}
|
||||
assert scan_open_library_status(library, ['A']) == {'A': 'UNKNOWN'}
|
||||
|
||||
|
||||
def test_wrong_library_window_is_not_a_status_source(monkeypatch, tmp_path):
|
||||
from pywinauto import Desktop
|
||||
import win32process, win32service
|
||||
monkeypatch.setattr(win32process, 'CreateProcess', lambda *a, **kw: pytest.fail('implicit launch'))
|
||||
monkeypatch.setattr(win32service, 'CreateDesktop', lambda *a, **kw: pytest.fail('implicit desktop'))
|
||||
def forbidden():
|
||||
pytest.fail('read another library tree')
|
||||
window = SimpleNamespace(window_text=lambda: 'Library Manager: C:/Other/lib.lmc',
|
||||
descendants=forbidden)
|
||||
monkeypatch.setattr(Desktop, 'windows', lambda *_: [window])
|
||||
assert adapter.read_library_tree_image_map(tmp_path/'lib.lmc', ['A']) == {'A': None}
|
||||
@@ -56,7 +56,8 @@ def test_confirm_releases_full_plan_and_only_emits_actual_library_proof(qtbot, t
|
||||
qtbot.waitUntil(lambda: not dialog.busy)
|
||||
qtbot.mouseClick(dialog.confirm_button, Qt.LeftButton)
|
||||
qtbot.waitUntil(lambda: not dialog.busy)
|
||||
assert calls == [plan] and released == [proof]
|
||||
assert len(calls) == 1 and calls[0]['sessions'] == plan['sessions']
|
||||
assert calls[0]['library'] == plan['library'] and released == [proof]
|
||||
assert '已释放 2' in dialog.message.text()
|
||||
assert not dialog.confirm_button.isEnabled()
|
||||
|
||||
|
||||
@@ -4,6 +4,11 @@ from types import SimpleNamespace
|
||||
import pytest
|
||||
|
||||
|
||||
def test_registered_save_is_not_treated_as_an_idle_hung_client():
|
||||
from cbb_refresh_verify.residual_sessions import force_block_reason
|
||||
assert '保存' in force_block_reason({'runtime_phase': 'NATIVE_CALL'})
|
||||
|
||||
|
||||
OWNERSHIP = {"owner_sid": "S-1-current", "session_id": 1, "force_user_confirmed": True}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
"""Review 319 regressions; native databases are replaced by isolated files."""
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from cbb_refresh_verify import session_record as sessions
|
||||
from test_session_record import child, record
|
||||
|
||||
|
||||
def retain_unconfirmed(root, library):
|
||||
root.mkdir(parents=True)
|
||||
path = root/'session.json'
|
||||
sessions.write_session_record(path, dict(operation_id=root.name, library=str(library), processes=[]))
|
||||
done = Event()
|
||||
sessions.handoff_session(path, evidence_root=root, progress=lambda _: done.set())
|
||||
assert done.wait(3)
|
||||
with sessions._observer_guard:
|
||||
observer = sessions._observers.get(str(path.absolute()).casefold())
|
||||
if observer:
|
||||
observer[0].join(3)
|
||||
assert not observer[0].is_alive()
|
||||
assert not sessions.library_available(library)
|
||||
return path
|
||||
|
||||
|
||||
def test_explicit_proof_resumes_queue_after_unconfirmed_observer_ended(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import library_lock as locks
|
||||
from cbb_refresh_verify.operation_queue import NativeQueue
|
||||
monkeypatch.setattr(sessions, '_retained_libraries', {})
|
||||
library = tmp_path/'library/lib.lmc'
|
||||
library.parent.mkdir(); library.touch()
|
||||
other = tmp_path/'other.lmc'
|
||||
retain_unconfirmed(tmp_path/'old', library)
|
||||
retain_unconfirmed(tmp_path/'independent', other)
|
||||
@contextmanager
|
||||
def proof(*args, **kwargs):
|
||||
yield {'native_owners': [], 'addresses': [], 'exclusive_files': [str(library)]}
|
||||
monkeypatch.setattr(locks, '_prove_library_released', proof)
|
||||
result = locks.release_retained_library(library, tmp_path/'proof')
|
||||
assert result['status'] == 'RELEASE_CONFIRMED'
|
||||
assert sessions.library_available(library), 'successful explicit proof left the queue blocked'
|
||||
assert sessions.discover_sessions(tmp_path/'old') == [], 'released history reappeared as unconfirmed'
|
||||
assert not sessions.library_available(other)
|
||||
assert NativeQueue().run(lambda: 'resumed', ready=lambda: sessions.library_available(library)) == 'resumed'
|
||||
|
||||
|
||||
def test_failed_proof_and_newer_handoff_cannot_clear_queue_retention(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import library_lock as locks
|
||||
monkeypatch.setattr(sessions, '_retained_libraries', {})
|
||||
library = tmp_path/'library/lib.lmc'
|
||||
library.parent.mkdir(); library.touch()
|
||||
old = retain_unconfirmed(tmp_path/'old', library)
|
||||
def denied(*args, **kwargs):
|
||||
raise OSError('external owner remains')
|
||||
monkeypatch.setattr(locks, '_prove_library_released', denied)
|
||||
with pytest.raises(OSError, match='external owner'):
|
||||
locks.release_retained_library(library, tmp_path/'proof')
|
||||
assert not sessions.library_available(library)
|
||||
@contextmanager
|
||||
def proof(*args, **kwargs):
|
||||
retain_unconfirmed(tmp_path/'new', library)
|
||||
yield {'native_owners': [], 'addresses': [], 'exclusive_files': [str(library)]}
|
||||
monkeypatch.setattr(locks, '_prove_library_released', proof)
|
||||
locks.release_retained_library(library, tmp_path/'proof')
|
||||
assert not sessions.library_available(library)
|
||||
assert str(old.absolute()).casefold() not in sessions._retained_libraries
|
||||
|
||||
|
||||
def test_discovery_of_exited_session_never_reconciles_library(tmp_path, child, monkeypatch):
|
||||
path = record(tmp_path, [dict(role='worker', **sessions.process_identity(child.pid))])
|
||||
child.terminate(); child.wait(5)
|
||||
def forbidden(*args, **kwargs):
|
||||
pytest.fail('passive history scan attempted library release')
|
||||
monkeypatch.setattr('cbb_refresh_verify.library_lock.release_retained_library', forbidden)
|
||||
found = sessions.discover_sessions(tmp_path)
|
||||
assert len(found) == 1 and found[0]['path'] == str(path)
|
||||
assert found[0]['status'] == 'UNCONFIRMED'
|
||||
assert found[0]['release_proof'] is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('phase', ['PRECALL', 'POSTCALL'])
|
||||
@pytest.mark.parametrize('broken_evidence', [False, True])
|
||||
def test_parent_loss_exits_idle_worker_even_when_stop_evidence_fails(tmp_path, phase, broken_evidence):
|
||||
run_watchdog_case(tmp_path, phase, broken_evidence=broken_evidence, exits=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('phase', ['NATIVE_CALL', 'CLOSING', 'UNCONFIRMED'])
|
||||
def test_parent_loss_preserves_pending_or_unknown_worker(tmp_path, phase):
|
||||
run_watchdog_case(tmp_path, phase, exits=False)
|
||||
|
||||
|
||||
def test_stale_postcall_journal_cannot_override_in_memory_active_call(tmp_path):
|
||||
run_watchdog_case(tmp_path, 'NATIVE_CALL', stale=True, exits=False)
|
||||
|
||||
|
||||
def test_missing_journal_preserves_worker_until_state_can_be_confirmed(tmp_path):
|
||||
run_watchdog_case(tmp_path, 'POSTCALL', missing=True, exits=False)
|
||||
|
||||
|
||||
def run_watchdog_case(root, phase, *, exits, broken_evidence=False, stale=False, missing=False):
|
||||
supervisor = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)'])
|
||||
script, ready, returned = root/'worker.py', root/'ready', root/'returned'
|
||||
cancel = root/'missing/cancel' if broken_evidence else root/'cancel'
|
||||
script.write_text(
|
||||
'import time\nfrom pathlib import Path\n'
|
||||
'from cbb_refresh_verify import session_record as s, desktop_worker as d\n'
|
||||
f'job=dict(operation_id="watchdog-test", session_record_path={str(root/"session.json")!r})\n'
|
||||
f's.update_worker_state(job, {"POSTCALL" if stale else phase!r})\n'
|
||||
'original=s.write_session_record\n'
|
||||
'def write(path,value):\n'
|
||||
f' if {broken_evidence!r} and Path(path).name=="supervisor-lost.json": raise OSError("disk full")\n'
|
||||
f' if {stale!r} and Path(path).name=="worker-state.json": raise OSError("stale journal")\n'
|
||||
' return original(path,value)\n'
|
||||
's.write_session_record=write\n'
|
||||
+ (f's.update_worker_state(job,{phase!r})\n' if stale else '') +
|
||||
(f'Path({str(root/"worker-state.json")!r}).unlink()\n' if missing else '') +
|
||||
f'd.start_supervisor_watchdog({supervisor.pid},cancel_path={str(cancel)!r},'
|
||||
'session_record_path=job["session_record_path"],operation_id=job["operation_id"])\n'
|
||||
f'Path({str(ready)!r}).touch()\n'
|
||||
f'while not Path({str(returned)!r}).exists(): time.sleep(.02)\n'
|
||||
's.write_session_record=original\n'
|
||||
's.update_worker_state(job,"POSTCALL")\n'
|
||||
'time.sleep(30)\n', encoding='utf-8')
|
||||
log = (root/'worker.log').open('wb')
|
||||
worker = subprocess.Popen([sys.executable, str(script)], stdout=log, stderr=log)
|
||||
try:
|
||||
deadline = time.monotonic()+6
|
||||
while not ready.exists() and worker.poll() is None and time.monotonic()<deadline:
|
||||
time.sleep(.02)
|
||||
assert ready.exists()
|
||||
supervisor.terminate(); supervisor.wait(5)
|
||||
if exits:
|
||||
assert worker.wait(4) == 75, 'idle orphan must exit without another application checkpoint'
|
||||
else:
|
||||
with pytest.raises(subprocess.TimeoutExpired):
|
||||
worker.wait(.4)
|
||||
returned.touch()
|
||||
assert worker.wait(4) == 75, 'watchdog must recheck once the pending call returns'
|
||||
finally:
|
||||
for process in (worker, supervisor):
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
process.wait(5)
|
||||
log.close()
|
||||
|
||||
|
||||
def test_residual_dialog_refresh_shows_runtime_blocker_without_releasing(qtbot, tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import library_lock as locks
|
||||
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
|
||||
monkeypatch.setattr(sessions, '_retained_libraries', {})
|
||||
library = tmp_path/'library/lib.lmc'
|
||||
library.parent.mkdir(); library.touch()
|
||||
monkeypatch.setattr(locks, 'inspect_residual_sessions', lambda *_: {'library': str(library), 'sessions': []})
|
||||
monkeypatch.setattr(locks, 'release_retained_library', lambda *a, **kw: pytest.fail('preview mutated library'))
|
||||
dialog = ResidualReleaseDialog(library, tmp_path/'release-checks')
|
||||
qtbot.addWidget(dialog)
|
||||
qtbot.waitUntil(lambda: not dialog.busy)
|
||||
retain_unconfirmed(tmp_path/'late-session', library)
|
||||
dialog.refresh_button.click()
|
||||
qtbot.waitUntil(lambda: not dialog.busy)
|
||||
assert dialog.plan['runtime_sessions'][0]['status'] == 'UNCONFIRMED'
|
||||
assert '待核对' in dialog.runtime_label.text()
|
||||
assert not sessions.library_available(library)
|
||||
|
||||
|
||||
def test_passive_handoff_reports_final_unconfirmed_state_without_proof(tmp_path, child, monkeypatch):
|
||||
from threading import Event
|
||||
path = record(tmp_path, [dict(role='worker', **sessions.process_identity(child.pid))])
|
||||
monkeypatch.setattr(sessions, '_retained_libraries', {})
|
||||
monkeypatch.setattr('cbb_refresh_verify.library_lock.release_retained_library',
|
||||
lambda *a, **kw: pytest.fail('startup observer released the library'))
|
||||
terminal = Event()
|
||||
sessions.handoff_session(path, evidence_root=tmp_path, observe_only=True,
|
||||
progress=lambda value: terminal.set() if value['status'] == 'UNCONFIRMED' else None)
|
||||
child.terminate(); child.wait(5)
|
||||
assert terminal.wait(3)
|
||||
states = sessions.retained_session_states(tmp_path/'lib.lmc')
|
||||
assert len(states) == 1 and states[0]['status'] == 'UNCONFIRMED'
|
||||
assert states[0]['detail']
|
||||
assert not sessions.library_available(tmp_path/'lib.lmc')
|
||||
|
||||
|
||||
def test_explicit_release_marks_discovered_history_without_an_in_memory_observer(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import library_lock as locks, residual_sessions as residual
|
||||
library = tmp_path/'library/lib.lmc'
|
||||
library.parent.mkdir(); library.touch()
|
||||
root = tmp_path/'history'; root.mkdir()
|
||||
path = root/'session.json'
|
||||
sessions.write_session_record(path, dict(operation_id='old-session', library=str(library), processes=[]))
|
||||
found = sessions.discover_sessions(root)
|
||||
assert len(found) == 1
|
||||
monkeypatch.setattr(residual, 'query_process_snapshot', lambda: [])
|
||||
@contextmanager
|
||||
def proof(*args, **kwargs):
|
||||
yield {'native_owners': [], 'addresses': [], 'exclusive_files': [str(library)]}
|
||||
monkeypatch.setattr(locks, '_prove_library_released', proof)
|
||||
outcome = residual.release_residual_sessions(dict(library=str(library), sessions=[], runtime_sessions=found),
|
||||
tmp_path/'release')
|
||||
assert outcome['status'] == 'RELEASE_CONFIRMED'
|
||||
assert sessions.discover_sessions(root) == []
|
||||
@@ -113,7 +113,7 @@ def _without_authorized_checkpoint_cleanup(text):
|
||||
tree = ast.parse(text)
|
||||
parents = {child: parent for parent in ast.walk(tree) for child in ast.iter_child_nodes(parent)}
|
||||
allowed = {('LibraryLock', '_exit_owned'): 'marker', ('LibraryLock', '__enter__'): 'marker',
|
||||
('release_retained_library',): 'checkpoint'}
|
||||
('release_retained_library',): 'checkpoint', ('write_session_record',): 'pending'}
|
||||
used, spans = set(), []
|
||||
for call in ast.walk(tree):
|
||||
if not (isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute)
|
||||
@@ -127,7 +127,7 @@ def _without_authorized_checkpoint_cleanup(text):
|
||||
scope = tuple(scope)
|
||||
if scope in used or allowed.get(scope) != call.func.value.id:
|
||||
continue
|
||||
expected = ([('missing_ok', True)] if scope == ('LibraryLock', '_exit_owned') else [])
|
||||
expected = ([('missing_ok', True)] if scope in (('LibraryLock', '_exit_owned'), ('write_session_record',)) else [])
|
||||
keywords = [(k.arg, k.value.value if isinstance(k.value, ast.Constant) else None) for k in call.keywords]
|
||||
if keywords == expected and call.lineno == call.end_lineno:
|
||||
spans.append((call.lineno - 1, call.col_offset, call.end_col_offset))
|
||||
@@ -143,7 +143,7 @@ def _without_authorized_checkpoint_cleanup(text):
|
||||
def test_verification_never_deletes_or_moves_library_files():
|
||||
for path in production_sources():
|
||||
text = path.read_text(encoding='utf-8')
|
||||
if path == SOURCE_ROOT/'library_lock.py':
|
||||
if path.name in ('library_lock.py', 'session_record.py'):
|
||||
# Approved runtime JSON lifecycle only. Actual sidecar/engineering
|
||||
# protection is also exercised against real files below.
|
||||
text = _without_authorized_checkpoint_cleanup(text)
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from cbb_refresh_verify.desktop_worker import launch_save_helper
|
||||
|
||||
|
||||
def test_helper_gate_only_opens_after_exact_identity_is_durable(tmp_path):
|
||||
gate, journal, called = tmp_path/'gate', tmp_path/'worker-state.json', tmp_path/'called.json'
|
||||
script = tmp_path/'helper.py'
|
||||
script.write_text('import json,time\nfrom pathlib import Path\n'
|
||||
f'gate=Path({str(gate)!r})\n'
|
||||
'while not gate.exists(): time.sleep(.02)\n'
|
||||
f'Path({str(called)!r}).write_text(Path({str(journal)!r}).read_text())\n')
|
||||
helper = None
|
||||
try:
|
||||
helper = launch_save_helper([sys.executable, str(script)], start_gate=gate,
|
||||
identity_path=journal, operation_id='test-gate')
|
||||
helper.wait(5)
|
||||
record = json.loads(called.read_text())
|
||||
assert record['operation_id'] == 'test-gate'
|
||||
identity = record['processes'][0]
|
||||
assert identity['pid'] == helper.pid
|
||||
assert identity['created_handle'] and identity['owner_sid']
|
||||
assert identity['image'].casefold() == sys.executable.casefold()
|
||||
finally:
|
||||
if helper is not None and helper.poll() is None:
|
||||
helper.terminate()
|
||||
helper.wait(5)
|
||||
|
||||
|
||||
def test_identity_storage_failure_does_not_allow_native_call(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import desktop_worker
|
||||
gate = tmp_path/'gate'
|
||||
script = tmp_path/'helper.py'
|
||||
script.write_text('import time;time.sleep(.5)')
|
||||
created = []
|
||||
real_popen = subprocess.Popen
|
||||
def popen(*a, **kw):
|
||||
process = real_popen(*a, **kw)
|
||||
created.append(process)
|
||||
return process
|
||||
monkeypatch.setattr(desktop_worker.subprocess, 'Popen', popen)
|
||||
def fail(*a, **kw):
|
||||
raise OSError('journal unavailable')
|
||||
monkeypatch.setattr('cbb_refresh_verify.session_record.write_session_record', fail)
|
||||
with pytest.raises(OSError, match='journal unavailable'):
|
||||
launch_save_helper([sys.executable, str(script)], start_gate=gate,
|
||||
identity_path=tmp_path/'worker-state.json', operation_id='test')
|
||||
assert not gate.exists()
|
||||
for process in created:
|
||||
process.wait(5)
|
||||
@@ -85,3 +85,119 @@ End Class
|
||||
assert completed.returncode == 4, completed.stderr
|
||||
assert 'SAVE_OK' not in parsed['markers']
|
||||
assert 'CLOSE_OK' not in parsed['markers']
|
||||
|
||||
|
||||
def run_helper(tmp_path, *, save_body='Save = True', close_body='Close = True',
|
||||
is_saved='True', gated=False, cancelled=False):
|
||||
source = Path('src/cbb_refresh_verify/save_verified_block.vbs').read_text('utf-8')
|
||||
classes = '''
|
||||
Class FakePi
|
||||
Public ProjectFile, ForwardAnnotationStatus, SynchCESStatus, LoadCESStatus, BackAnnotationStatus
|
||||
Private Sub Class_Initialize
|
||||
ProjectFile = WScript.Arguments(0)
|
||||
ForwardAnnotationStatus = 2
|
||||
SynchCESStatus = 2
|
||||
LoadCESStatus = 2
|
||||
BackAnnotationStatus = 2
|
||||
End Sub
|
||||
End Class
|
||||
Class FakeDoc
|
||||
Public Name
|
||||
Private Sub Class_Initialize
|
||||
Name = "CBB.pcb"
|
||||
End Sub
|
||||
Public Property Get ProjectIntegration
|
||||
Set ProjectIntegration = New FakePi
|
||||
End Property
|
||||
Public Function Validate(token)
|
||||
Validate = 17
|
||||
End Function
|
||||
Public Function Save()
|
||||
WScript.Echo "TEST_SAVE_CALLED"
|
||||
SAVE_BODY
|
||||
End Function
|
||||
Public Function IsSaved()
|
||||
IsSaved = IS_SAVED_VALUE
|
||||
End Function
|
||||
Public Function Close(saveChanges)
|
||||
CLOSE_BODY
|
||||
closedDoc = True
|
||||
End Function
|
||||
End Class
|
||||
Class FakeApp
|
||||
Public Property Get ActiveDocument
|
||||
If closedDoc Then
|
||||
Set ActiveDocument = Nothing
|
||||
Else
|
||||
Set ActiveDocument = New FakeDoc
|
||||
End If
|
||||
End Property
|
||||
Public Sub Quit()
|
||||
WScript.Echo "TEST_QUIT"
|
||||
End Sub
|
||||
End Class
|
||||
Class FakeLic
|
||||
Public Function GetToken(value)
|
||||
GetToken = value
|
||||
End Function
|
||||
End Class
|
||||
'''.replace('SAVE_BODY', save_body).replace('CLOSE_BODY', close_body).replace('IS_SAVED_VALUE', is_saved)
|
||||
source = source.replace('Option Explicit', 'Option Explicit\nDim closedDoc\n' + classes)
|
||||
source = source.replace('GetObject(, "MGCPCB.Application")', 'New FakeApp')
|
||||
source = source.replace('CreateObject("MGCPCBAutomationLicensing.Application")', 'New FakeLic')
|
||||
harness = tmp_path/'facts.vbs'
|
||||
harness.write_text(source, encoding='ascii')
|
||||
cancel = tmp_path/'cancel.signal'
|
||||
if cancelled:
|
||||
cancel.touch()
|
||||
args = [str(Path(os.environ['WINDIR'])/'SysWOW64/cscript.exe'), '//nologo',
|
||||
str(harness), 'expected.prj', 'CBB.pcb', str(cancel)]
|
||||
if gated:
|
||||
args.append(str(tmp_path/'start.signal'))
|
||||
return subprocess.run(args, capture_output=True, text=True, timeout=35)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('body,marker', [('Close = False', 'CLOSE_FAILED'),
|
||||
('Err.Raise 5, "FakeDoc", "close failed"', 'CLOSE_FAILED')])
|
||||
def test_close_failure_keeps_successful_save_fact(tmp_path, body, marker):
|
||||
result = run_helper(tmp_path, close_body=body)
|
||||
assert 'SAVE_OK' in result.stdout
|
||||
assert marker in result.stdout
|
||||
assert 'CLOSE_OK' not in result.stdout
|
||||
assert result.returncode != 0
|
||||
|
||||
|
||||
def test_save_exception_has_unknown_result_marker(tmp_path):
|
||||
result = run_helper(tmp_path, save_body='Err.Raise 5, "FakeDoc", "save failed"')
|
||||
assert 'SAVE_RESULT_UNKNOWN|5|' in result.stdout
|
||||
assert 'CLOSE_START' not in result.stdout
|
||||
assert result.returncode != 0
|
||||
|
||||
|
||||
def test_saved_document_postcheck_failure_does_not_discard_save_fact(tmp_path):
|
||||
result = run_helper(tmp_path, is_saved='False')
|
||||
assert 'SAVE_OK' in result.stdout
|
||||
assert 'POST_SAVE_FAILED' in result.stdout
|
||||
assert 'CLOSE_START' not in result.stdout
|
||||
|
||||
|
||||
def test_cancellation_in_save_allows_identity_checked_saved_close(tmp_path):
|
||||
result = run_helper(tmp_path, save_body='''
|
||||
Dim fso, flag
|
||||
Set fso = CreateObject("Scripting.FileSystemObject")
|
||||
Set flag = fso.CreateTextFile(WScript.Arguments(2), True)
|
||||
flag.Close
|
||||
Save = True
|
||||
''')
|
||||
assert 'SAVE_OK' in result.stdout
|
||||
assert 'CLOSE_OK' in result.stdout
|
||||
assert 'QUIT_OK' in result.stdout
|
||||
assert result.returncode == 0, result.stderr
|
||||
|
||||
|
||||
def test_unopened_gate_cancellation_exits_before_com(tmp_path):
|
||||
result = run_helper(tmp_path, gated=True, cancelled=True)
|
||||
assert 'CANCELLED_BEFORE_SAVE' in result.stdout
|
||||
assert 'TEST_SAVE_CALLED' not in result.stdout
|
||||
assert 'VALIDATE_START' not in result.stdout
|
||||
assert result.returncode == 9
|
||||
@@ -0,0 +1,186 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from cbb_refresh_verify import session_record as sessions
|
||||
|
||||
|
||||
def record(tmp_path, processes):
|
||||
path = tmp_path/'session.json'
|
||||
sessions.write_session_record(path, dict(operation_id='test-session', operation='verify',
|
||||
library=str(tmp_path/'lib.lmc'), block='A', processes=processes))
|
||||
return path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def child():
|
||||
process = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)'])
|
||||
try:
|
||||
yield process
|
||||
finally:
|
||||
process.terminate()
|
||||
process.wait(5)
|
||||
|
||||
|
||||
def test_round_trip_and_exact_live_process(tmp_path, child):
|
||||
identity = sessions.process_identity(child.pid)
|
||||
path = record(tmp_path, [dict(role='worker', **identity)])
|
||||
value = sessions.read_session_record(path, evidence_root=tmp_path)
|
||||
assert value['protocol'] == 'cbb-runtime-session'
|
||||
assert value['version'] == 1
|
||||
result = sessions.reconcile_session_record(path, evidence_root=tmp_path)
|
||||
assert result['status'] == 'ACTIVE'
|
||||
assert result['release_proof'] is None
|
||||
assert child.poll() is None
|
||||
|
||||
|
||||
@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):
|
||||
identity = sessions.process_identity(child.pid)
|
||||
identity[key] = value
|
||||
path = record(tmp_path, [dict(role='worker', **identity)])
|
||||
result = sessions.reconcile_session_record(path, evidence_root=tmp_path)
|
||||
assert result['status'] == 'IDENTITY_CHANGED'
|
||||
assert result['release_proof'] is None
|
||||
assert child.poll() is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('kind', ['outside', 'large', 'invalid', 'unknown_protocol'])
|
||||
def test_untrusted_record_is_unconfirmed_not_an_occupancy_fact(tmp_path, kind):
|
||||
owned = tmp_path/'owned'
|
||||
owned.mkdir()
|
||||
path = (tmp_path if kind == 'outside' else owned)/'session.json'
|
||||
path.write_text('x'*65537 if kind == 'large' else '{' if kind == 'invalid' else '{}')
|
||||
result = sessions.reconcile_session_record(path, evidence_root=owned)
|
||||
assert result['status'] == 'UNCONFIRMED'
|
||||
assert result['release_proof'] is None
|
||||
|
||||
|
||||
def test_exited_process_alone_is_not_release_proof(tmp_path, child, monkeypatch):
|
||||
path = record(tmp_path, [dict(role='worker', **sessions.process_identity(child.pid))])
|
||||
child.terminate()
|
||||
child.wait(5)
|
||||
def busy(*a, **kw):
|
||||
raise OSError('database still occupied')
|
||||
monkeypatch.setattr('cbb_refresh_verify.library_lock.release_retained_library', busy)
|
||||
result = sessions.reconcile_session_record(path, evidence_root=tmp_path)
|
||||
assert result['status'] == 'UNCONFIRMED'
|
||||
assert result['release_proof'] is None
|
||||
assert 'occupied' in result['detail']
|
||||
|
||||
|
||||
def test_release_uses_independent_proof_and_does_not_replay(tmp_path, child, monkeypatch):
|
||||
path = record(tmp_path, [dict(role='worker', **sessions.process_identity(child.pid))])
|
||||
child.terminate()
|
||||
child.wait(5)
|
||||
proof = {'status': 'RELEASE_CONFIRMED', 'library': str(tmp_path/'lib.lmc')}
|
||||
monkeypatch.setattr('cbb_refresh_verify.library_lock.release_retained_library', lambda *a, **kw: proof)
|
||||
result = sessions.reconcile_session_record(path, evidence_root=tmp_path)
|
||||
assert result['status'] == 'RELEASED'
|
||||
assert result['release_proof'] == proof
|
||||
|
||||
|
||||
def test_observation_can_stop_without_claiming_native_release(tmp_path, child):
|
||||
import threading
|
||||
path = record(tmp_path, [dict(role='worker', **sessions.process_identity(child.pid))])
|
||||
stop = threading.Event()
|
||||
stop.set()
|
||||
result = sessions.observe_retained_session(path, evidence_root=tmp_path, stop=stop)
|
||||
assert result['status'] == 'ACTIVE'
|
||||
assert result['release_proof'] is None
|
||||
assert child.poll() is None
|
||||
|
||||
|
||||
def test_worker_state_cannot_replace_another_operation(tmp_path, child):
|
||||
path = record(tmp_path, [dict(role='worker', **sessions.process_identity(child.pid))])
|
||||
sessions.write_session_record(tmp_path/'worker-state.json', {
|
||||
'operation_id': 'different', 'processes': [], 'phase': 'FINISHED'})
|
||||
result = sessions.reconcile_session_record(path, evidence_root=tmp_path)
|
||||
assert result['status'] == 'UNCONFIRMED'
|
||||
assert child.poll() is None
|
||||
|
||||
|
||||
def test_retained_session_yields_global_queue_but_keeps_same_library_waiting(tmp_path, child):
|
||||
import threading
|
||||
from cbb_refresh_verify.operation_queue import NativeQueue
|
||||
from cbb_refresh_verify.session_record import handoff_session, library_available
|
||||
library = tmp_path/'lib.lmc'
|
||||
path = record(tmp_path, [dict(role='worker', **sessions.process_identity(child.pid))])
|
||||
queue = NativeQueue()
|
||||
observation_stop = threading.Event()
|
||||
queue.run(lambda: handoff_session(path, evidence_root=tmp_path, stop=observation_stop))
|
||||
assert library_available(library) is False
|
||||
assert library_available(tmp_path/'other.lmc') is True
|
||||
assert queue.run(lambda: 'other-completed', ready=lambda: library_available(tmp_path/'other.lmc')) == 'other-completed'
|
||||
stop = threading.Event()
|
||||
stop.set()
|
||||
from cbb_refresh_verify.operation_queue import QueueCancelled
|
||||
with pytest.raises(QueueCancelled):
|
||||
queue.run(lambda: pytest.fail('overlapping writer'), stop=stop,
|
||||
ready=lambda: library_available(library))
|
||||
observation_stop.set()
|
||||
|
||||
|
||||
def test_bad_journal_does_not_drop_in_memory_supervision(tmp_path, child):
|
||||
import threading
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
path = tmp_path/'session.json'
|
||||
path.write_text('{')
|
||||
stop = threading.Event()
|
||||
process = SimpleNamespace(poll=child.poll, close=lambda: None, cbb_library=tmp_path/'lib.lmc')
|
||||
sessions.handoff_session(path, evidence_root=tmp_path, process=process, stop=stop)
|
||||
key = str(path.absolute()).casefold()
|
||||
try:
|
||||
time.sleep(.1)
|
||||
with sessions._observer_guard:
|
||||
assert key in sessions._observers, 'active owned handle lost its observer because JSON was unreadable'
|
||||
assert child.poll() is None
|
||||
finally:
|
||||
stop.set()
|
||||
|
||||
|
||||
def test_reused_pid_keeps_observing_resources_and_unblocks_only_after_proof(tmp_path, child, monkeypatch):
|
||||
import threading
|
||||
identity = sessions.process_identity(child.pid)
|
||||
identity['created_handle'] = 'previous-owner'
|
||||
path = record(tmp_path, [dict(role='worker', **identity)])
|
||||
released = threading.Event()
|
||||
stop = threading.Event()
|
||||
proof = {'status': 'RELEASE_CONFIRMED', 'library': str(tmp_path/'lib.lmc')}
|
||||
monkeypatch.setattr('cbb_refresh_verify.library_lock.release_retained_library', lambda *a, **kw: proof)
|
||||
def progress(result):
|
||||
if result['status'] == 'RELEASED':
|
||||
released.set()
|
||||
sessions.handoff_session(path, evidence_root=tmp_path, stop=stop, progress=progress)
|
||||
try:
|
||||
assert released.wait(3), 'PID reuse ended observation before independent release'
|
||||
assert child.poll() is None
|
||||
# The callback precedes final observer cleanup by a few instructions.
|
||||
import time
|
||||
deadline = time.monotonic()+1
|
||||
while not sessions.library_available(tmp_path/'lib.lmc') and time.monotonic()<deadline:
|
||||
time.sleep(.01)
|
||||
assert sessions.library_available(tmp_path/'lib.lmc')
|
||||
finally:
|
||||
stop.set()
|
||||
|
||||
|
||||
def test_retained_live_worker_with_stale_postcall_phase_is_still_protected(tmp_path, child):
|
||||
import threading
|
||||
path = record(tmp_path, [dict(role='worker', **sessions.process_identity(child.pid))])
|
||||
sessions.write_session_record(tmp_path/'worker-state.json', dict(operation_id='test-session',
|
||||
processes=[], phase='POSTCALL'))
|
||||
stop = threading.Event()
|
||||
sessions.handoff_session(path, evidence_root=tmp_path, stop=stop)
|
||||
try:
|
||||
writes = sessions.active_write_records(tmp_path/'lib.lmc')
|
||||
assert writes and writes[0]['phase'] == 'UNCONFIRMED'
|
||||
assert child.poll() is None
|
||||
finally:
|
||||
stop.set()
|
||||
@@ -8,6 +8,25 @@ from PySide6.QtCore import QTimer
|
||||
from test_ui_filters import load_window
|
||||
|
||||
|
||||
def test_late_lease_callback_does_not_refresh_destroyed_view(qtbot, tmp_path, monkeypatch):
|
||||
import shiboken6
|
||||
window = load_window(qtbot, tmp_path, monkeypatch)
|
||||
entered, release = Event(), Event()
|
||||
def action():
|
||||
entered.set()
|
||||
assert release.wait(3)
|
||||
try:
|
||||
window._lease_action(action)
|
||||
qtbot.waitUntil(entered.is_set)
|
||||
window.cbb_table.deleteLater()
|
||||
qtbot.waitUntil(lambda: not shiboken6.isValid(window.cbb_table))
|
||||
release.set()
|
||||
qtbot.waitUntil(lambda: window._lease_pending == 0)
|
||||
finally:
|
||||
release.set()
|
||||
window.pool.waitForDone(3000)
|
||||
|
||||
|
||||
def slow_lease(main_thread):
|
||||
entered, release, closed = Event(), Event(), Event()
|
||||
calls = []
|
||||
|
||||
@@ -499,8 +499,7 @@ def test_parallelism_rejected_for_shared_library(tmp_path):
|
||||
run_batch([], max_workers=2)
|
||||
|
||||
|
||||
def test_timeout_stops_automation_and_allows_retry_when_no_native_owner_remains(tmp_path, monkeypatch):
|
||||
"""A timed-out item must not leave a Mentor process holding the library."""
|
||||
def test_timeout_without_release_evidence_preserves_native_caller(tmp_path, monkeypatch):
|
||||
fixture(tmp_path)
|
||||
killed = []
|
||||
|
||||
@@ -520,11 +519,11 @@ def test_timeout_stops_automation_and_allows_retry_when_no_native_owner_remains(
|
||||
port_check=PORTS_OK)
|
||||
|
||||
assert result.status == 'TIMEOUT'
|
||||
assert killed == [True]
|
||||
assert result.safe_to_continue
|
||||
assert killed == []
|
||||
assert result.safe_to_continue is False
|
||||
|
||||
|
||||
def test_fatal_dialog_terminates_current_worker_and_cannot_become_pass(tmp_path, monkeypatch):
|
||||
def test_fatal_dialog_preserves_current_worker_and_cannot_become_pass(tmp_path, monkeypatch):
|
||||
fixture(tmp_path)
|
||||
killed = []
|
||||
|
||||
@@ -557,7 +556,7 @@ def test_fatal_dialog_terminates_current_worker_and_cannot_become_pass(tmp_path,
|
||||
|
||||
assert result.status == 'FAIL'
|
||||
assert result.stderr.startswith('SAVE_REUSABLE_BLOCK_FAILED')
|
||||
assert killed == [True]
|
||||
assert killed == []
|
||||
|
||||
|
||||
def test_worker_events_advance_dialog_phase():
|
||||
@@ -631,7 +630,7 @@ def test_unknown_dialog_writes_snapshot_before_current_item_fails(tmp_path, monk
|
||||
assert '"error_code": "UNKNOWN_DIALOG"' in dialog_records
|
||||
assert 'Unknown recovery prompt' in dialog_records
|
||||
assert (evidence/'process_tree.json').is_file()
|
||||
assert killed == [True]
|
||||
assert killed == []
|
||||
|
||||
|
||||
def test_library_flag_is_reported_verbatim_and_never_fabricated(tmp_path, monkeypatch):
|
||||
|
||||
Reference in new issue
Block a user