Compare commits
49
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
14cacb1d1c | ||
|
|
fa1f662e1d | ||
|
|
b4737b5102 | ||
|
|
8869093eb0 | ||
|
|
c1e259603a | ||
|
|
5e9509e573 | ||
|
|
906cfc06be | ||
|
|
32dcd80d1e | ||
|
|
8818fa9841 | ||
|
|
701e5cd3b4 | ||
|
|
7eafae417d | ||
|
|
a3f69de201 | ||
|
|
7cc65f78da | ||
|
|
845ae58690 | ||
|
|
d5d1a3deea | ||
|
|
a64636ba0d | ||
|
|
4402486baa | ||
|
|
de81bbf293 | ||
|
|
e0bb2438e8 | ||
|
|
fd50805380 | ||
|
|
eaff46e50e | ||
|
|
8bfa4eed34 | ||
|
|
f964ff347c | ||
|
|
2149e71b67 | ||
|
|
7c27f9604e | ||
|
|
87e10740f7 | ||
|
|
d40fa3a750 | ||
|
|
36ff964230 | ||
|
|
07206ce0d1 | ||
|
|
5b7e7bea2f | ||
|
|
eabf61c73b | ||
|
|
dbc685b9a5 | ||
|
|
cd7a5e0ca1 | ||
|
|
601dd7b6b2 | ||
|
|
8374cabe5c | ||
|
|
ddff6bd857 | ||
|
|
0440b2efbf | ||
|
|
b070837acb | ||
|
|
a1b38c242f | ||
|
|
efb8cae478 | ||
|
|
e4875b4eca | ||
|
|
ec9f8a3e40 | ||
|
|
fa5590468d | ||
|
|
fee4a67ff1 | ||
|
|
1572e2d8ca | ||
|
|
cbc5723849 | ||
|
|
b2ddd76a04 | ||
|
|
39af2112e3 | ||
|
|
229df4b0ef |
No files matched your search
@@ -2,7 +2,9 @@
|
|||||||
|
|
||||||
当前临时分支的备份策略(2026-11-03):应用不再自动备份中心库或 CBB 工程。新增、替换、移除、校验、ICDB 维护和恢复在执行前提示手动备份;请自行保留可用副本。导入暂存、恢复用隔离验证库和轻量操作证据仍会生成,Mentor 原生 Repair 自身的备份行为保持不变。详见[自动备份检查与调整](docs/releases/2026-11-03-manual-backup.md)。此条优先于下方历史版本的备份说明。
|
当前临时分支的备份策略(2026-11-03):应用不再自动备份中心库或 CBB 工程。新增、替换、移除、校验、ICDB 维护和恢复在执行前提示手动备份;请自行保留可用副本。导入暂存、恢复用隔离验证库和轻量操作证据仍会生成,Mentor 原生 Repair 自身的备份行为保持不变。详见[自动备份检查与调整](docs/releases/2026-11-03-manual-backup.md)。此条优先于下方历史版本的备份说明。
|
||||||
|
|
||||||
当前开发版本:**[0.2.4b2 生命周期候选](docs/releases/2026-11-06-runtime-lifecycle-candidate.md)(开发候选,待现场验收)**。ICDB 批量检查在后台逐项运行,普通校验、管理和恢复可排队;READY 工程在实际执行前再次排除。检查不自动 Repair、Restore 或选择历史版本,也不代表中心库 READY。
|
当前测试版本:**[0.2.4b3](docs/releases/v0.2.4-beta.3.md)(待现场验收)**。ICDB 批量检查在后台逐项运行,普通校验、管理和恢复可排队;READY 工程在实际执行前再次排除。检查不自动 Repair、Restore 或选择历史版本,也不代表中心库 READY。
|
||||||
|
|
||||||
|
管理写入因无法完成占用确认而未执行,或恢复安装前选择跳过,结果为 `SKIPPED`;取消为 `CANCELLED`,与实际操作失败区分。文件身份核对失败保留“需要恢复”,后续独立 CBB 依据各自会话释放和写前检查决定是否继续,不自动重放失败目标。
|
||||||
|
|
||||||
停止、超时或应用失联只停止后续原生动作,不结束正在 Save/Close 的调用进程。普通停止等待 5 秒,可能正在写入时最多等待 120 秒后交给后台观察;这不是强制结束时限。保存结果、关闭结果和资源释放分别记录。相关库等待释放,独立库可以排队继续;界面、筛选和日志保持可用。重启只核对未完成会话,不重放管理写操作。legacy 状态读取只观察已打开且匹配库的 LM,不启动 LM 或回答弹窗;无法读取保持 UNKNOWN。
|
停止、超时或应用失联只停止后续原生动作,不结束正在 Save/Close 的调用进程。普通停止等待 5 秒,可能正在写入时最多等待 120 秒后交给后台观察;这不是强制结束时限。保存结果、关闭结果和资源释放分别记录。相关库等待释放,独立库可以排队继续;界面、筛选和日志保持可用。重启只核对未完成会话,不重放管理写操作。legacy 状态读取只观察已打开且匹配库的 LM,不启动 LM 或回答弹窗;无法读取保持 UNKNOWN。
|
||||||
|
|
||||||
@@ -10,7 +12,9 @@
|
|||||||
|
|
||||||
自动流程不强杀原生会话;释放入口默认正常关闭。另有单独确认的“强制结束客户端”操作,仅限属于当前 Windows 用户和会话、归属及进程身份已确认的 PCB、Library Manager、DxDesigner/viewdraw、iCDB Project Backup 客户端。**ICDB 数据库服务器、后台导入器和归属未知的进程不允许强制结束**,即使命令指向当前库也不例外。客户端中其他已打开工程可能一并退出、未保存更改可能丢失;必须先记录确认名单,结束后重新证明库已释放,不能宣称数据库已修复。详见 [操作规程](SOP.md) 与 [版本说明](docs/releases/v0.2.4-beta.1.md)。下方日期记录为历史行为,以本说明为准。
|
自动流程不强杀原生会话;释放入口默认正常关闭。另有单独确认的“强制结束客户端”操作,仅限属于当前 Windows 用户和会话、归属及进程身份已确认的 PCB、Library Manager、DxDesigner/viewdraw、iCDB Project Backup 客户端。**ICDB 数据库服务器、后台导入器和归属未知的进程不允许强制结束**,即使命令指向当前库也不例外。客户端中其他已打开工程可能一并退出、未保存更改可能丢失;必须先记录确认名单,结束后重新证明库已释放,不能宣称数据库已修复。详见 [操作规程](SOP.md) 与 [版本说明](docs/releases/v0.2.4-beta.1.md)。下方日期记录为历史行为,以本说明为准。
|
||||||
|
|
||||||
本目录是独立的 CBB 中心库上传后校验工具,不属于 Part Replacement,也不负责 CBB 工程复制或中心库上传。
|
本目录是独立的 CBB 检验、ICDB 维护和中心库管理工具,不属于 Part Replacement;管理入口接收已整理好的完整 PRJ/PCB 工程。
|
||||||
|
|
||||||
|
导入不运行 ASCII、CSV 或 EDIF 导出。新增/替换确认原生注册、目录复读、工程关联、顶层块及 Layout;顶层块允许保持来源名,或由原生导入改为本次 CBB 注册名,映射会单独记录。其余工程文件差异保留清单供核对,不以原生改写 PRJ 或运行历史判定导入失败。原生重写 ICDB 后不比较其原始字节,也不宣称已证明原理图语义等价。上传后自动校验可独立勾选,只有完整原生 Verify 和权威 READY 才显示校验通过。无效来源或已释放的单项失败逐项报告,不影响后续独立条目。
|
||||||
|
|
||||||
针对 `The last server session ... lost the connection to the database`,修复分支增加
|
针对 `The last server session ... lost the connection to the database`,修复分支增加
|
||||||
`ICDB_REPAIR_REQUIRED` 专项识别、共享符号库路径诊断及停止批次处理。现场原生修复步骤及实现边界见
|
`ICDB_REPAIR_REQUIRED` 专项识别、共享符号库路径诊断及停止批次处理。现场原生修复步骤及实现边界见
|
||||||
@@ -21,7 +25,7 @@
|
|||||||
|
|
||||||
Windows 11 / Mentor EE7.9.5 隔离库已完成原生更新、备份恢复、校验到 READY 和释放验证,记录见 [2026-11-12 验证](docs/releases/2026-11-12-scoped-release-validation.md)。历史候选包仅证明对应提交,后续代码合并不等同于现场验收或正式发布。
|
Windows 11 / Mentor EE7.9.5 隔离库已完成原生更新、备份恢复、校验到 READY 和释放验证,记录见 [2026-11-12 验证](docs/releases/2026-11-12-scoped-release-validation.md)。历史候选包仅证明对应提交,后续代码合并不等同于现场验收或正式发布。
|
||||||
|
|
||||||
- A/B 输入的原生 EDIF 导出曾返回 `0xC0000005`,根因尚未定位,相关输入继续按失败处理。
|
- A/B 输入的独立 EDIF 导出曾返回 `0xC0000005`,根因尚未定位;该导出已从普通导入流程移出,不能据此判定导入失败或 ICDB 损坏。
|
||||||
- Windows 10、跨机器共享库和现场服务器会话失联的一致故障副本尚未验收。跨机器释放依赖 SMB 共享模式语义,目前没有跨机器实测证明。
|
- Windows 10、跨机器共享库和现场服务器会话失联的一致故障副本尚未验收。跨机器释放依赖 SMB 共享模式语义,目前没有跨机器实测证明。
|
||||||
- 自动 ICDB Repair 保持关闭。共享库原生服务器若无法删除自身地址文件,或早停后仍有原生弹窗,需要继续核对;不以进程列表为空或端口不可达代替释放证明。
|
- 自动 ICDB Repair 保持关闭。共享库原生服务器若无法删除自身地址文件,或早停后仍有原生弹窗,需要继续核对;不以进程列表为空或端口不可达代替释放证明。
|
||||||
- 验收文档中的本机路径、原始日志、截图、测试 XML 和冻结包不随 Git 分发;仓库保留说明及摘要,原始材料须在验收机器查看或另行归档。
|
- 验收文档中的本机路径、原始日志、截图、测试 XML 和冻结包不随 Git 分发;仓库保留说明及摘要,原始材料须在验收机器查看或另行归档。
|
||||||
|
|||||||
@@ -15,6 +15,12 @@ python -m pytest -q
|
|||||||
python -m compileall -q src tests
|
python -m compileall -q src tests
|
||||||
```
|
```
|
||||||
|
|
||||||
|
For an isolated checkout, set `$env:PYTHONPATH = (Resolve-Path ./src).Path` so
|
||||||
|
test subprocesses import that checkout rather than another editable installation.
|
||||||
|
The repository's `.gitattributes` preserves CRLF (`* -text`); use
|
||||||
|
`git -c core.whitespace=cr-at-eol diff --check` to check whitespace in a clean
|
||||||
|
clone without reporting the preserved CR bytes as trailing whitespace.
|
||||||
|
|
||||||
The source import was verified with 336 pytest cases. Tests use fake local files
|
The source import was verified with 336 pytest cases. Tests use fake local files
|
||||||
and replace the production Mentor COM/process boundary where required; they do
|
and replace the production Mentor COM/process boundary where required; they do
|
||||||
not establish field success against a live network library.
|
not establish field success against a live network library.
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# CBB 检查、校验、管理与残留释放操作规程
|
# CBB 检查、校验、管理与残留释放操作规程
|
||||||
|
|
||||||
适用开发版本:0.2.4b2。未完成现场验收,不自动发布或关闭工单。以下为当前规程,下方旧上传校验检查表保留为历史参考。
|
适用测试版本:0.2.4b3。测试版发布不代表现场验收,不自动关闭工单。以下为当前规程,下方旧上传校验检查表保留为历史参考。
|
||||||
|
|
||||||
## 当前操作与队列
|
## 当前操作与队列
|
||||||
|
|
||||||
@@ -16,8 +16,12 @@
|
|||||||
|
|
||||||
新增拒绝同名冲突;更新先原生移除再导入,失败可能需要人工备份恢复;移除后重新读取目录确认。版本回退由操作员在原生界面选择,核对工程内容后单独校验。
|
新增拒绝同名冲突;更新先原生移除再导入,失败可能需要人工备份恢复;移除后重新读取目录确认。版本回退由操作员在原生界面选择,核对工程内容后单独校验。
|
||||||
|
|
||||||
|
新增和替换不调用 ASCII/CSV/EDIF 导出器;原生成功回执、重新读库、目标工程关联、顶层块及 Layout 确认后记录上传完成,不等同于 READY 或原理图语义等价。顶层块允许来源名或本次 CBB 注册名,保留原生命名变换记录;其他名称仍拒绝。其余文件差异单独保留清单并提示核对,不因 PRJ 规范化或历史记录差异阻止后续条目。可在批次开始前取消“上传后自动校验”。来源旧库路径可在暂存副本中改为所选目标库,来源原件不改;无效来源按行报告,已释放的失败不阻止后续条目。
|
||||||
|
|
||||||
## 历史记录、操作结果与报告
|
## 历史记录、操作结果与报告
|
||||||
|
|
||||||
|
管理写入无法取得占用确认、或恢复安装前选择跳过时,记录 `SKIPPED`(已跳过 / 未执行);取消记录 `CANCELLED`。这两者不等于实际上传或恢复失败。文件核对失败仍记录“需要恢复”并禁止自动重放该目标;后续独立 CBB 在会话释放及自身写前检查通过后可继续。
|
||||||
|
|
||||||
校验和管理遇到历史释放记录时,先复核实际进程、地址、独占文件及导出副本。确认释放后归档记录再继续,不以历史 JSON 本身判定真实占用;同目标未完成写入仍需核对,不自动重放。释放证明在管理首次原生调用前写入检查点,并在结果中保留。
|
校验和管理遇到历史释放记录时,先复核实际进程、地址、独占文件及导出副本。确认释放后归档记录再继续,不以历史 JSON 本身判定真实占用;同目标未完成写入仍需核对,不自动重放。释放证明在管理首次原生调用前写入检查点,并在结果中保留。
|
||||||
|
|
||||||
管理操作生成目标工程、库配置和共享依赖的写前/写后主要文件清单及新增、删除、修改差分;不增加自动全库备份,也不声称检查了其他 CBB 内容。报告不可用与原生操作失败分别记录;本任务已释放时可继续独立项。
|
管理操作生成目标工程、库配置和共享依赖的写前/写后主要文件清单及新增、删除、修改差分;不增加自动全库备份,也不声称检查了其他 CBB 内容。报告不可用与原生操作失败分别记录;本任务已释放时可继续独立项。
|
||||||
@@ -40,7 +44,7 @@
|
|||||||
|
|
||||||
## 已知限制与证据位置
|
## 已知限制与证据位置
|
||||||
|
|
||||||
A/B 输入的原生 EDIF 导出曾返回 `0xC0000005`,尚未定位,不能将该输入记成导入通过。Windows 10、跨机器共享库和现场失联故障副本仍待验收;跨机释放依赖 SMB 共享模式语义,目前没有跨机实测。自动 ICDB Repair 保持关闭,共享数据库地址残留或晚到弹窗按现场状态继续核对。
|
A/B 输入的独立 EDIF 导出曾返回 `0xC0000005`,尚未定位;普通导入已不依赖该导出,导入是否完成以本次原生操作与复读证据判定。Windows 10、跨机器共享库和现场失联故障副本仍待验收;跨机释放依赖 SMB 共享模式语义,目前没有跨机实测。自动 ICDB Repair 保持关闭,共享数据库地址残留或晚到弹窗按现场状态继续核对。
|
||||||
|
|
||||||
代码合并不表示现场验收完成。文档中的本机路径、日志、截图、测试 XML 和候选包未入库;仓库仅保留验证摘要,原始材料需在验收机器查看或另行归档。
|
代码合并不表示现场验收完成。文档中的本机路径、日志、截图、测试 XML 和候选包未入库;仓库仅保留验证摘要,原始材料需在验收机器查看或另行归档。
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,319 @@
|
|||||||
|
{
|
||||||
|
"created": "2026-11-13T15:28:15.015734+08:00",
|
||||||
|
"base_main": "cbc57238496bc84f4228aa44929208a9516dff1b",
|
||||||
|
"branch": "codex/import-without-export-gate",
|
||||||
|
"full_suite": {
|
||||||
|
"tests": 1895,
|
||||||
|
"failures": 0,
|
||||||
|
"errors": 0,
|
||||||
|
"skipped": 0
|
||||||
|
},
|
||||||
|
"first_wrong_source_suite": {
|
||||||
|
"tests": 1893,
|
||||||
|
"failures": 15,
|
||||||
|
"errors": 0,
|
||||||
|
"skipped": 0
|
||||||
|
},
|
||||||
|
"first_wrong_source_reason": "Subprocesses used the editable original checkout; corrected by explicit PYTHONPATH to this worktree.",
|
||||||
|
"frozen": {
|
||||||
|
"module_count": 64,
|
||||||
|
"source_and_frozen_code_equal": true,
|
||||||
|
"source_sha256_checked": true,
|
||||||
|
"packaged_assets_equal": true,
|
||||||
|
"exe_icon_images_equal": true,
|
||||||
|
"executable_sha256": "98a642d8e81f42b708934bb4dc2d023c49c2acdae5851151a430f101c74c9615"
|
||||||
|
},
|
||||||
|
"native": [
|
||||||
|
{
|
||||||
|
"name": "1GPHY_RTL8211F_A",
|
||||||
|
"status": "UPLOADED_VERIFY_FAILED",
|
||||||
|
"safe_to_continue": true,
|
||||||
|
"detail": "原生注册、工程关联、顶层块和 Layout 已确认;未核验原理图语义。其他工程文件有差异,已记录供核对。\nProject Integration error: ERROR: There are no PartsDB partitions from which to extract parts | ERROR: Unable to create local PDB | ERROR: Problem Making Local Parts DataBase",
|
||||||
|
"checkpoint": "F:\\CbbI1113\\d3\\management\\management-9a5e12feb292441e8c5709270ffef18b\\checkpoint.json",
|
||||||
|
"native_add_success": true,
|
||||||
|
"registration_matches": true,
|
||||||
|
"top_level_block_mapping": {
|
||||||
|
"source": "1GPHY_RTL8211F",
|
||||||
|
"registered": "1GPHY_RTL8211F_A",
|
||||||
|
"allowed": [
|
||||||
|
"1GPHY_RTL8211F",
|
||||||
|
"1GPHY_RTL8211F_A"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"assets_match": false,
|
||||||
|
"asset_differences": {
|
||||||
|
"added": [
|
||||||
|
"PCB/1GPHY_RTL8211F_A.pcb",
|
||||||
|
"database/cdbback/2026-11-13 15.12.50-49956.zip"
|
||||||
|
],
|
||||||
|
"deleted": [
|
||||||
|
"PCB/1GPHY_RTL8211F.pcb"
|
||||||
|
],
|
||||||
|
"modified": [
|
||||||
|
"1GPHY_RTL8211F_A.prj"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"verification": [
|
||||||
|
{
|
||||||
|
"stage": "verified",
|
||||||
|
"time": "2026-11-13T07:18:34.641758+00:00",
|
||||||
|
"verification": {
|
||||||
|
"status": "FAIL",
|
||||||
|
"stderr": "Project Integration error: ERROR: There are no PartsDB partitions from which to extract parts | ERROR: Unable to create local PDB | ERROR: Problem Making Local Parts DataBase",
|
||||||
|
"stdout": "",
|
||||||
|
"evidence_path": "F:\\CbbI1113\\d3\\management\\management-9a5e12feb292441e8c5709270ffef18b\\verify\\verify-43d609b6535d\\result.json",
|
||||||
|
"safe_to_continue": true,
|
||||||
|
"library_flag": "UNKNOWN",
|
||||||
|
"library_flag_detail": "",
|
||||||
|
"report_path": null,
|
||||||
|
"content_check_exit_code": null,
|
||||||
|
"error_category": "MENTOR_PROJECT_INTEGRATION",
|
||||||
|
"error_stage": "forward_annotation",
|
||||||
|
"bridge_attempts": [],
|
||||||
|
"timings_seconds": {
|
||||||
|
"preflight": 0.031,
|
||||||
|
"worker_setup": 6.328,
|
||||||
|
"pcb_startup": 100.469,
|
||||||
|
"failure_diagnostics": 1.25,
|
||||||
|
"integration": 24.953,
|
||||||
|
"forward_annotation": 24.812,
|
||||||
|
"total": 133.406
|
||||||
|
},
|
||||||
|
"incomplete_timing_phases": [
|
||||||
|
"integration",
|
||||||
|
"forward_annotation"
|
||||||
|
],
|
||||||
|
"recovery_attempts": [],
|
||||||
|
"release_proof": null,
|
||||||
|
"write_outcome": {
|
||||||
|
"save_state": "UNKNOWN",
|
||||||
|
"close_state": "UNKNOWN",
|
||||||
|
"helper_state": "EXITED",
|
||||||
|
"resource_state": "RELEASED",
|
||||||
|
"interrupted": false,
|
||||||
|
"detail": "保存返回结果无法确认"
|
||||||
|
},
|
||||||
|
"session_record_path": "F:\\CbbI1113\\d3\\management\\management-9a5e12feb292441e8c5709270ffef18b\\verify\\verify-43d609b6535d\\session.json"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "1GPHY_RTL8211F",
|
||||||
|
"status": "UPLOADED_VERIFY_FAILED",
|
||||||
|
"safe_to_continue": true,
|
||||||
|
"detail": "原生注册、工程关联、顶层块和 Layout 已确认;未核验原理图语义。其他工程文件有差异,已记录供核对。\nProject Integration error: ERROR: There are no PartsDB partitions from which to extract parts | ERROR: Unable to create local PDB | ERROR: Problem Making Local Parts DataBase",
|
||||||
|
"checkpoint": "F:\\CbbI1113\\d3\\management\\management-6be18dcb186846e78b3220b59631249e\\checkpoint.json",
|
||||||
|
"native_add_success": true,
|
||||||
|
"registration_matches": true,
|
||||||
|
"top_level_block_mapping": {
|
||||||
|
"source": "1GPHY_RTL8211F",
|
||||||
|
"registered": "1GPHY_RTL8211F",
|
||||||
|
"allowed": [
|
||||||
|
"1GPHY_RTL8211F",
|
||||||
|
"1GPHY_RTL8211F"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"assets_match": false,
|
||||||
|
"asset_differences": {
|
||||||
|
"added": [],
|
||||||
|
"deleted": [
|
||||||
|
"database/cdbsvr/events/events - Abs 的冲突副本 1 - 2026-09-16 07-16-58.dat",
|
||||||
|
"database/cdbsvr/events/events - Abs 的冲突副本 1 - 2026-09-16 07-16-58.idx"
|
||||||
|
],
|
||||||
|
"modified": [
|
||||||
|
"1GPHY_RTL8211F.prj"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"verification": [
|
||||||
|
{
|
||||||
|
"stage": "verified",
|
||||||
|
"time": "2026-11-13T07:23:45.773452+00:00",
|
||||||
|
"verification": {
|
||||||
|
"status": "FAIL",
|
||||||
|
"stderr": "Project Integration error: ERROR: There are no PartsDB partitions from which to extract parts | ERROR: Unable to create local PDB | ERROR: Problem Making Local Parts DataBase",
|
||||||
|
"stdout": "",
|
||||||
|
"evidence_path": "F:\\CbbI1113\\d3\\management\\management-6be18dcb186846e78b3220b59631249e\\verify\\verify-53e1561b73fa\\result.json",
|
||||||
|
"safe_to_continue": true,
|
||||||
|
"library_flag": "UNKNOWN",
|
||||||
|
"library_flag_detail": "",
|
||||||
|
"report_path": null,
|
||||||
|
"content_check_exit_code": null,
|
||||||
|
"error_category": "MENTOR_PROJECT_INTEGRATION",
|
||||||
|
"error_stage": "forward_annotation",
|
||||||
|
"bridge_attempts": [],
|
||||||
|
"timings_seconds": {
|
||||||
|
"preflight": 0.047,
|
||||||
|
"worker_setup": 3.766,
|
||||||
|
"pcb_startup": 80.469,
|
||||||
|
"failure_diagnostics": 1.39,
|
||||||
|
"integration": 22.359,
|
||||||
|
"forward_annotation": 22.297,
|
||||||
|
"total": 106.844
|
||||||
|
},
|
||||||
|
"incomplete_timing_phases": [
|
||||||
|
"integration",
|
||||||
|
"forward_annotation"
|
||||||
|
],
|
||||||
|
"recovery_attempts": [],
|
||||||
|
"release_proof": null,
|
||||||
|
"write_outcome": {
|
||||||
|
"save_state": "UNKNOWN",
|
||||||
|
"close_state": "UNKNOWN",
|
||||||
|
"helper_state": "EXITED",
|
||||||
|
"resource_state": "RELEASED",
|
||||||
|
"interrupted": false,
|
||||||
|
"detail": "保存返回结果无法确认"
|
||||||
|
},
|
||||||
|
"session_record_path": "F:\\CbbI1113\\d3\\management\\management-6be18dcb186846e78b3220b59631249e\\verify\\verify-53e1561b73fa\\session.json"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"duplicate_conflict": {
|
||||||
|
"passed": true,
|
||||||
|
"records": [
|
||||||
|
{
|
||||||
|
"operation": "add",
|
||||||
|
"library": "F:\\CbbI1113\\library3\\native-add\\fixture\\mentor_lib.lmc",
|
||||||
|
"name": "1GPHY_RTL8211F",
|
||||||
|
"partition": "Logical-Physical",
|
||||||
|
"source": "F:\\CbbI1113\\A\\1GPHY_RTL8211F.prj",
|
||||||
|
"auto_verify": false,
|
||||||
|
"stage": "complete",
|
||||||
|
"status": "UPLOAD_FAILED",
|
||||||
|
"safe_to_continue": true,
|
||||||
|
"detail": "同名 CBB 已存在;新增禁止覆盖,请使用明确的同名更新。",
|
||||||
|
"evidence_path": "F:\\CbbI1113\\d4\\management\\management-f43f218e0dcb41e8bfe09d5f2f69a0a8\\checkpoint.json",
|
||||||
|
"release_proof": null,
|
||||||
|
"change_report": null,
|
||||||
|
"history": [
|
||||||
|
{
|
||||||
|
"stage": "release_check",
|
||||||
|
"time": "2026-11-13T07:25:51.703695+00:00"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"stage": "catalog_before",
|
||||||
|
"time": "2026-11-13T07:26:22.388154+00:00"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"backup_policy": "manual"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"target_and_shared_content_unchanged": true,
|
||||||
|
"catalog": {
|
||||||
|
"library": "F:\\CbbI1113\\library3\\native-add\\fixture\\mentor_lib.lmc",
|
||||||
|
"flow": 1,
|
||||||
|
"entries": [
|
||||||
|
{
|
||||||
|
"name": "1GPHY_RTL8211F",
|
||||||
|
"partition": "Logical-Physical",
|
||||||
|
"engineering_identity": {
|
||||||
|
"top_level_block": "1GPHY_RTL8211F",
|
||||||
|
"schematic_sha256": "ed969340d9e89875b30c7c0ab175e82a92f965743f798cca297ad8de24a55f94",
|
||||||
|
"layout_sha256": "61c2107047afd2ce8778028bdc5527cb1e2ca14b13190625a2c9c5397077b4f8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "1GPHY_RTL8211F_A",
|
||||||
|
"partition": "Logical-Physical",
|
||||||
|
"engineering_identity": {
|
||||||
|
"top_level_block": "1GPHY_RTL8211F_A",
|
||||||
|
"schematic_sha256": "400183e788a0980f8e08a140e1eb7f96b845c48cf486e51c90cdb33900688e41",
|
||||||
|
"layout_sha256": "3b78437a66f3d9a510b7aed6130928629b1b15fa86a8029e1786006e900fb5d5"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"safe_to_continue": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"source_hashes": {
|
||||||
|
"src/cbb_refresh_verify/application.py": "62b9b013563a216d020c8366cccb8f949b02afa72dc63c26940804441cc23057",
|
||||||
|
"src/cbb_refresh_verify/backup_recovery.py": "f07741fdeed73871eda1d4e72803bb516cc877b5b49973e3f7aa18972228baa2",
|
||||||
|
"src/cbb_refresh_verify/batch_status.py": "55a4007cf54491ca8e045a5bf86aa4353ac8437cca5a76cd79304962e3d3fa0a",
|
||||||
|
"src/cbb_refresh_verify/com_runtime.py": "f0f3802d16c791a8bf9dfef44a94917072bfbe8fb3a927d76be8ef0341c7ed35",
|
||||||
|
"src/cbb_refresh_verify/content_check.py": "8239c17b6e2452917ed573a7deb3e4c8583eaef91bf3630eff5f424d2e398aa9",
|
||||||
|
"src/cbb_refresh_verify/defaults.py": "a1c03192f4a61ad0924b24bb635705b1ee4811d35483a02864200f95edbbebe3",
|
||||||
|
"src/cbb_refresh_verify/desktop_worker.py": "27d751816552d215dd8ee9cd67941d824f7b4493120ead7c3f87e5eba5ec4a92",
|
||||||
|
"src/cbb_refresh_verify/diagnostic_open.py": "d6c49ffe5a9969d95edbbc896d47a7e100f248380a287f99ba7bb8b92dbb3072",
|
||||||
|
"src/cbb_refresh_verify/dialog_agent.py": "5acb6e5cf1350a7ca20a6fe480668435fac785835874f266881973010db6504b",
|
||||||
|
"src/cbb_refresh_verify/dialog_models.py": "f68cee01d927b48364276d3c1f79e63ce8af231878db0b907d292780cfbafb56",
|
||||||
|
"src/cbb_refresh_verify/dialog_probe.py": "d61f0c955c961980c9635940eefb9c7947c1fe90b4b6fd844720df41ddb0aa0e",
|
||||||
|
"src/cbb_refresh_verify/dialog_rules.py": "3189b476f7ff4678b59212ed7b4081164e038a7cf7662cd895f9019cb3c1edc5",
|
||||||
|
"src/cbb_refresh_verify/dialog_supervisor.py": "15c415c2d2e916f0b64ba04416164ff3b50996d70b22d3b4ac2226b5547ac247",
|
||||||
|
"src/cbb_refresh_verify/failed_session.py": "7e6f7fa5ebcf2d49f00c5efc5f5d26412704b68e9122e476ac1f672009a98c09",
|
||||||
|
"src/cbb_refresh_verify/icdb_maintenance.py": "e81d253d8b4d3e7c1000c45335a392c72b110748675c2c3324ebe524a7252e98",
|
||||||
|
"src/cbb_refresh_verify/icdb_ownership.py": "7bf2342c1efa34a2ebcbf27964a40a490220f7146fbb6ef957b8d8dd1e511f03",
|
||||||
|
"src/cbb_refresh_verify/icdb_recovery.py": "358c0e9a004f1e0b2127513286e1dffd94b0180a8b7314aa9655462f570b6360",
|
||||||
|
"src/cbb_refresh_verify/integration.py": "f188856af69ba25e265988c51db7a6d4263326440d972ca78378b733b891c1ed",
|
||||||
|
"src/cbb_refresh_verify/library_lock.py": "6836ec8ac21e788eb75326ff44cb31ad4bdfb5f381bd35cdf33e6b34c7fca89e",
|
||||||
|
"src/cbb_refresh_verify/library_manager_verify.py": "71e16a8581ad44b646be78b480f9812d596a6d162b3eec03d078bf4ea4503195",
|
||||||
|
"src/cbb_refresh_verify/library_reader.py": "d4007caa361edd467773e49f721e02671d5a9bcb30741769a57349850b12c438",
|
||||||
|
"src/cbb_refresh_verify/maintenance_entry.py": "3b93c25f69d7a961facd8004e20e155a84cc18f06d57b741a9055786ed058990",
|
||||||
|
"src/cbb_refresh_verify/management.py": "773f9405c39b3fdcea4647da84ca97e9113e03db386a45bfabd468a98ed1fb36",
|
||||||
|
"src/cbb_refresh_verify/management_transaction.py": "32c53caaead05d5db3a31d3e30721e65434e5837095dc0a7812f825603aa37a0",
|
||||||
|
"src/cbb_refresh_verify/mentor_adapter.py": "1fc8c98d5508120e03bf001a42dd3e0da7b165eb18c90f1aed83147d17db8638",
|
||||||
|
"src/cbb_refresh_verify/mentor_paths.py": "ba48c0003b3eacc88906497b2e43b299ca4536a9f7dae44bbacf6a6ec694c116",
|
||||||
|
"src/cbb_refresh_verify/models.py": "9e8209a8b006df923f1d07ccab64bbcfe5d674c4fc5f5426bfbc9b11da4ee105",
|
||||||
|
"src/cbb_refresh_verify/native_add_failures.py": "192202732423dc624c5548c75e80bb20973e5087c21d4798c9637f25b6de7e94",
|
||||||
|
"src/cbb_refresh_verify/native_backup.py": "7276fa3d9298e85550151cf0c7191d84bd08a18a72df5d854a3c38f1a88b001d",
|
||||||
|
"src/cbb_refresh_verify/native_engineering_identity.py": "e704e8f56c43629a1593d490776af328bb032208ee2f5ffd1d1be6c3114f5412",
|
||||||
|
"src/cbb_refresh_verify/native_export_guard.py": "c3eeadd557d2f89bfce855c0736c953043ebe97bc81aa74e40bd370780a54741",
|
||||||
|
"src/cbb_refresh_verify/native_management.py": "5eca3b40ef57ecd4a12a0d0c26afd1bb1afb448a0b7c5452bfe80591a3a74b77",
|
||||||
|
"src/cbb_refresh_verify/native_occupancy.py": "7d686079d12217382adace6361cd343d977b91075e3b157cf410ca92d07ffc49",
|
||||||
|
"src/cbb_refresh_verify/native_repair.py": "9f024dcb5e3a76369191033474fefd30787b6ae350c315f3cf38e92e5a1f3e98",
|
||||||
|
"src/cbb_refresh_verify/native_repair_ui.py": "3eb2af181befea94af8b3b3131edff09589f340bcba777abbe3b67fd31b80393",
|
||||||
|
"src/cbb_refresh_verify/network_path.py": "6b5b159502d42a46bf4ee26d5698fd2c6498b359088e2138eae46e9065b13c6f",
|
||||||
|
"src/cbb_refresh_verify/operation_lifecycle.py": "3838c5a501711d16f578c45ebbc6f960872b0c3ba6bbda9a597f994ef746cef6",
|
||||||
|
"src/cbb_refresh_verify/operation_queue.py": "a6932d8bc68ac436091f6d362557c66d274ec52d0f295a22f014a3396845c79f",
|
||||||
|
"src/cbb_refresh_verify/owner_probe.py": "8dcfd60246cb2979db34d02e0a2d605c334b6f7e2666f22daa2f50c0408bc903",
|
||||||
|
"src/cbb_refresh_verify/pcb_bridge.py": "2f6c2b09642100468814500569dbfc6695fc2a46b9a3b8333daa8e1530cdeef5",
|
||||||
|
"src/cbb_refresh_verify/pcb_open_consent.py": "7ad9c3a183f565b8b1f7a57b7c29ee9cbc3a79fe1ac0d778459edbdcb25b5664",
|
||||||
|
"src/cbb_refresh_verify/pcb_restore_prompt.py": "39e0b8623a838911eff61066f3e9c8ede4364dbf73efc5a8994197ec72a96488",
|
||||||
|
"src/cbb_refresh_verify/post_repair_consent.py": "3b1eaff1db58fd311a9dbc5fdcd850911b04cc5afd4e747f70a62b721b8fafa4",
|
||||||
|
"src/cbb_refresh_verify/post_verify_diagnostics.py": "2442de485bc0d6a34c4b2d9b10bc5f323ea38f9ff66674119a50f5c6043bac63",
|
||||||
|
"src/cbb_refresh_verify/reimport_recovery.py": "66b2ba8f8c2ec9ae8c386d6b1aa74a1fbb6bfb509c4df0a262f8d7a0ca48469e",
|
||||||
|
"src/cbb_refresh_verify/residual_sessions.py": "4ac500b33b209611d54eb496c6c30727ba159742d625431ceea84471a5fc3442",
|
||||||
|
"src/cbb_refresh_verify/runtime_logging.py": "44ac25430a89c5ffc9e48e88c227e88052f4c815365e8556f67918f3edaba39e",
|
||||||
|
"src/cbb_refresh_verify/runtime_timing.py": "c4ed4057b5000e0b86ccc7dd1fe2004d6e0dae29f397fec77b01ad41a81c6367",
|
||||||
|
"src/cbb_refresh_verify/scoped_manifest.py": "9318bf0f929d23c18466a25d83a4a9903822093c123aae10510061788c6d0ab7",
|
||||||
|
"src/cbb_refresh_verify/session_record.py": "2bc3cff365008864584138a4ff13538bb6b2f90d981e7d008a1300f9102c6e7e",
|
||||||
|
"src/cbb_refresh_verify/status_bridge.py": "05d627d02934a14f5de409472c291d37565a95b836f9c130111aae80612e9196",
|
||||||
|
"src/cbb_refresh_verify/verify_diagnostics.py": "041b77d7d49e4c86338ed5e5741d0d27a2c42bc358f4da54b3efe64af847e9b8",
|
||||||
|
"src/cbb_refresh_verify/verify_probe.py": "3ed743df49d195c74f5045985ab23491d103ee2c42c07b558c1e037176402ed2",
|
||||||
|
"src/cbb_refresh_verify/verify_runner.py": "3027ef7fc1ef6365ff36ae0c83389d869b92ffcd96985d10275bca4dc9483e3f",
|
||||||
|
"src/cbb_refresh_verify/__init__.py": "dd960394d88657820dba858792abf0de258e05efceb08ae2f0b39c6ad78bc469",
|
||||||
|
"src/cbb_refresh_verify/__main__.py": "dc4be034a0e43d4b659a9300137c29a6a6b7a32b7eaef02b6dff9a88c41305c0",
|
||||||
|
"src/cbb_refresh_verify/ui/backup_notice.py": "1a3fa5ac18a267907faf95f36d61b9f08bcbb939eef4d480dd06af1391a81599",
|
||||||
|
"src/cbb_refresh_verify/ui/backup_recovery_dialog.py": "65081eb8d9791f8ec1316023a80edb07a91b2658b9ed27cb4cf21addb0f26026",
|
||||||
|
"src/cbb_refresh_verify/ui/icdb_check_task.py": "ade3bf414aa29b42f4c1535c613b2cacb2735f6abc7900e6da25999390a5891d",
|
||||||
|
"src/cbb_refresh_verify/ui/main_window.py": "af65fcd8e41f35f412e8c23f525821c92b2cfb78b9d0fd4f88c515249dbd24e1",
|
||||||
|
"src/cbb_refresh_verify/ui/management_dialog.py": "4ae522e8509d9153af9d41d349f1611c80f73c0913f01f33cc5a122665cf56bf",
|
||||||
|
"src/cbb_refresh_verify/ui/pcb_open_dialog.py": "3cabdc15f1b2abaeb919a7f29f32d4b053186701fd514646d9bdd3ea32f364f6",
|
||||||
|
"src/cbb_refresh_verify/ui/pcb_restore_dialog.py": "b7228d828df235ac51502dc68760d28c4896af02c780e9806e11c32dba7f62da",
|
||||||
|
"src/cbb_refresh_verify/ui/residual_release_dialog.py": "1d2a26bfc7ee21b11d7edbc3074b4c525e8c9fb628bca45b08bd06fc672586c8",
|
||||||
|
"src/cbb_refresh_verify/ui/workers.py": "4cc9360a4820ded27a7d5ef709fc9f04b1d4804cb1e7a614f6c357ed547da888",
|
||||||
|
"src/cbb_refresh_verify/ui/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
||||||
|
},
|
||||||
|
"local_evidence_sha256": {
|
||||||
|
"F:\\CbbI1113\\full-suite.xml": "df15b248bb4eb21580800d43ce60a5ac4f4bae5a4d3c67580f45f0752472fcab",
|
||||||
|
"F:\\CbbI1113\\full-suite-final3.xml": "d0702c2a69dab5aef57c4fa7e7f9d633058b3c03dae5970665c393c979476ab6",
|
||||||
|
"F:\\CbbI1113\\accept.log": "39620df9b61514eed6b1c48edb19d6e1abbb71c1e4c7e7d31f0a7e1968442220",
|
||||||
|
"F:\\CbbI1113\\accept2.log": "b3d1509d1c6d65973ba4da666103785402aef576c1fe78936c559caaaa02a62d",
|
||||||
|
"F:\\CbbI1113\\accept2-resume.log": "6c5fb656f12c4e790ca1b3f01593283161bff7f8b253fd4e1444c53f0fb49d91",
|
||||||
|
"F:\\CbbI1113\\accept3.log": "0a69d374c5ae3652aac7e871578a45f090220cd3d04e8701390d95abd020a8d9",
|
||||||
|
"F:\\CbbI1113\\auto-verify-trial.json": "8729b9c6f4a48199f2e2515c59bae1891ce61b00a5572a9721dd25e003e196a0",
|
||||||
|
"F:\\CbbI1113\\accept4.log": "81af1d0a6146b33220dd85996ab7d4b28eee820fa6d8fb30314effea249cd568",
|
||||||
|
"F:\\CbbI1113\\duplicate-conflict-trial.json": "b7051b3e01102e51c551dde8aade9d358454a97ff91fb547702c8a4dbeb5928e",
|
||||||
|
"F:\\CbbI1113\\native-add-wait-chain.json": "f671192272d5edcd9ed3ea736b42ea7d330c86adaadc1a5cc434b6c55fb270c1"
|
||||||
|
},
|
||||||
|
"independent_review": "No actionable findings; static review only; three updates reviewed.",
|
||||||
|
"cloud_beta2_updated": false,
|
||||||
|
"schematic_semantic_equivalence_checked": false,
|
||||||
|
"known_limits": [
|
||||||
|
"Automatic ICDB Repair disabled; field lost-session recovery unverified.",
|
||||||
|
"Windows 10 and cross-machine SMB unverified.",
|
||||||
|
"Long native Add waits observed; root cause not determined; not claimed fixed."
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
# 2026-11-13:CBB 导入与附加核验解耦
|
||||||
|
|
||||||
|
分支:`codex/import-without-export-gate`;基线 main:`cbc57238496bc84f4228aa44929208a9516dff1b`。
|
||||||
|
原始工程、运行日志、截图、测试 XML 和冻结包保留在本机 `F:\CbbI1113`;仓库只保存说明和验证摘要。
|
||||||
|
|
||||||
|
## 原因与修改
|
||||||
|
|
||||||
|
此前导入会在原生 Add 之前和之后强制执行 ASCII、CSV、EDIF 内容导出;能力探测也依赖这些导出器。因此 EDIF 导出崩溃能让本来尚未执行 Add 的工程显示“上传失败”,取消上传后自动校验也不能避开它。
|
||||||
|
|
||||||
|
- 新增、同名替换和隔离管理适配器均不再调用或要求安装这些导出器。独立导出诊断代码保留,EDIF 崩溃根因没有被宣称解决。
|
||||||
|
- 保留完整来源暂存及复制核验、事务随机标识、检查点、库基线、精确进程和租约验证、原生成功回执以及重新读库。只在暂存副本中重定位库引用,来源旧库地址失效不会拒绝向明确选择的新库导入。
|
||||||
|
- 上传完成必须确认目标库、名称、分区、工程关联、顶层块和 Layout。顶层块允许保持来源名或被原生导入改成本次注册名;真实映射与实际目标身份保留在证据中,不能接受第三个名称。
|
||||||
|
- PRJ 路径规范化、默认标记、历史/其他工程文件的差异单独保存 `assets_match` 和增删改清单,并提示核对;不再以全文件相等判定上传失败。Layout 不一致、关联错误或结构缺失仍拒绝确认。
|
||||||
|
- 不比较原生重写后的 ICDB 原始字节,也不再声称证明了原理图语义等价。`identity_proof` 保存实际复读结果,没有伪造为来源内容。
|
||||||
|
- 上传后 Verify 保持独立可选;只有 PASS、权威 GREEN/READY 和释放确认才能记录 `UPLOADED_VERIFIED`。否则区分 `UPLOADED` 与 `UPLOADED_VERIFY_FAILED`。
|
||||||
|
- 来源或名称错误按行进入结果,其他有效条目继续。界面仍拒绝同批重复目标,避免对同一目标提交含糊的多次变更。单项失败先复核释放,只有未释放的相关库暂停后续写入;不绕过真实数据库占用。
|
||||||
|
|
||||||
|
## 回归与代码复核
|
||||||
|
|
||||||
|
新增用例先复现:导出器缺失导致能力禁用、导入调用附加导出、单行无效来源挡住批次、旧库地址失效、原生 PRJ 改写以及原生顶层块改名误报失败。保留陌生顶层块和 Layout 差异的拒绝用例,以及上传后 Verify 失败时安全继续下一项的用例。
|
||||||
|
|
||||||
|
最终源码全量回归 **1,895 passed**,1 条既有 pywinauto STA COM 警告;编译检查通过。冻结包的 64 个应用模块、资产和 EXE 图标与源码一致。独立只读代码复核没有发现待修正项;该复核没有执行原生操作。
|
||||||
|
|
||||||
|
第一轮全量运行有 15 项失败:子进程使用了机器 editable 安装的原始工作目录,而不是本隔离工作区。该轮不计为通过;显式设置 `PYTHONPATH` 到本工作区 `src` 后,全套通过。后续测试与原生试验均固定此路径,未更改用户 Python 安装。
|
||||||
|
|
||||||
|
## 实机中保留的失败
|
||||||
|
|
||||||
|
- 第一轮冻结包在全新隔离库实际成功新增 A/B,但 PRJ 自动规范化及历史事件冲突副本缺失被旧的全资产相等规则误报为 `RECOVERY_REQUIRED`。已增加差异证据及回归;该轮不算整体验收通过。
|
||||||
|
- 第二轮实际选择文件后移走一个测试文件、取消确认后重试并连点执行:失效行显示失败,A 随后 `UPLOADED`,B 的原生 Add 也成功。B 被后续“目标顶层块必须等于来源”检查误报为需恢复;已按本次原生命名变换修订。两项都确认释放,主程序最后正常退出 0。该轮同样不算全部通过。
|
||||||
|
- 原生 Add 曾长时间等待。窗口、进程与等待链证据保留;没有确定底层原因,不宣称已修复耗时,也不强制结束原生写入来得到成功结果。
|
||||||
|
|
||||||
|
## 最新冻结包的实际批量链路
|
||||||
|
|
||||||
|
候选程序:`F:\CbbI1113\candidate3\dist\CbbRefreshVerify-Background\CbbRefreshVerify.exe`。
|
||||||
|
SHA-256:`98a642d8e81f42b708934bb4dc2d023c49c2acdae5851151a430f101c74c9615`。
|
||||||
|
|
||||||
|
第三轮从应用真实按钮和文件选择器向全新空隔离库依次导入 B、A,开启上传后自动校验;没有替换原生适配器,没有前台鼠标接管,也没有强制结束进程或删除原生地址/锁文件。
|
||||||
|
|
||||||
|
| 步骤 | 实际结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| B 的原生 Add 与复读 | 原生明确成功,库/名称/分区及工程关联确认;Layout 一致;顶层块从 `1GPHY_RTL8211F` 变为本次注册名 `1GPHY_RTL8211F_A`,映射保留,上传确认通过。 |
|
||||||
|
| B 的上传后 Verify | `MENTOR_PROJECT_INTEGRATION / forward_annotation`,原文 `There are no PartsDB partitions from which to extract parts`。空库没有 PartsDB,不能创建本地 PDB;记录 `UPLOADED_VERIFY_FAILED`、safe=true,不记为上传失败或 READY。 |
|
||||||
|
| B 失败后的同批 A | 实际继续执行 A 的原生 Add,注册及 Layout 复读通过;没有因为 B 的 Verify 失败停掉整批。 |
|
||||||
|
| A 的上传后 Verify | 同样因空库缺 PartsDB 返回 `UPLOADED_VERIFY_FAILED`、safe=true。没有把失败伪造成 READY。 |
|
||||||
|
| 独立目录读取 | 重新启动原生 Library Manager,确认两个正确名称均存在。 |
|
||||||
|
| 来源与退出 | 两份输入主要内容清单未变;原生会话释放,应用正常退出 0;整条试验控制器退出 0。 |
|
||||||
|
| 附加导出 | 本批未生成 ASCII/CSV/EDIF 导出进程记录;对应自动化回归也禁止普通导入调用这些导出边界。 |
|
||||||
|
|
||||||
|
第三轮原始证据:`accept3.log`、`auto-verify-trial.json`、`d3/management/*/checkpoint.json`、各项 `add/identity-comparison.json` 及 `verify/*/result.json`。此试验验证真实上传和“校验失败后释放并继续”的负向场景;**不是多个新增项在依赖完整的中心库中全部达到 READY 的验收**。
|
||||||
|
|
||||||
|
第四轮从同一最新冻结包重新打开该库,实际再次新增已有的 A:取消后重新确认、执行中连点均未重复提交;原生目录确认同名后返回 `UPLOAD_FAILED`、safe=true,检查点没有 `native_add` 阶段。目标及共享主要工程内容清单前后完全一致;独立原生目录仍只有 A/B,程序正常退出 0。证据为 `accept4.log`、`duplicate-conflict-trial.json` 和 `d4/management/*/checkpoint.json`。
|
||||||
|
|
||||||
|
机器可读摘要见同目录 `2026-11-13-import-decoupling-validation.json`。最初两轮发现问题的包及失败记录没有覆盖或改为成功。
|
||||||
|
|
||||||
|
## 范围
|
||||||
|
|
||||||
|
未更新云端既有 `v0.2.4-beta.2`,未合并 main 或关闭工单。自动 ICDB Repair 保持禁用。现场失联故障、Windows 10、跨机器共享库及任意工程内容的完整语义等价仍不在已验证结论中。
|
||||||
@@ -0,0 +1,430 @@
|
|||||||
|
{
|
||||||
|
"schema_version": 1,
|
||||||
|
"created": "2026-11-13T17:31:37.910526+08:00",
|
||||||
|
"review": "https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/pulls/13#issuecomment-414",
|
||||||
|
"base_commit": "1572e2d8cab905c28f96f562851db00ef7ea8ad6",
|
||||||
|
"environment": {
|
||||||
|
"windows": [
|
||||||
|
"11",
|
||||||
|
"10.0.26200",
|
||||||
|
"SP0",
|
||||||
|
"Multiprocessor Free"
|
||||||
|
],
|
||||||
|
"python": "3.12.10",
|
||||||
|
"mentor": "EE7.9.5"
|
||||||
|
},
|
||||||
|
"commands": [
|
||||||
|
"python -X utf8 F:/CbbReview414/run_tests.py tests --junitxml=F:/CbbReview414/full-final.xml",
|
||||||
|
"python -X utf8 F:/CbbReview414/run_tests.py tests/test_review414_write_admission.py --junitxml=F:/CbbReview414/admission-extra.xml",
|
||||||
|
"python -X utf8 -m compileall -q src tests",
|
||||||
|
"git diff --check",
|
||||||
|
"python -X utf8 F:/CbbReview414/build.py",
|
||||||
|
"python -X utf8 F:/CbbReview414/verify_bundle.py",
|
||||||
|
"python -X utf8 F:/CbbReview414/create_library.py",
|
||||||
|
"python -X utf8 F:/CbbReview414/driver7.py"
|
||||||
|
],
|
||||||
|
"full_suite": {
|
||||||
|
"path": "F:\\CbbReview414\\full-final.xml",
|
||||||
|
"sha256": "075f7b76002b451a72af65d64428c0b6c65e5fa5c8776036a5fff55584a6dc54",
|
||||||
|
"tests": 1912,
|
||||||
|
"failures": 0,
|
||||||
|
"errors": 0,
|
||||||
|
"skipped": 0,
|
||||||
|
"seconds": 520.549
|
||||||
|
},
|
||||||
|
"additional_admission_suite": {
|
||||||
|
"path": "F:\\CbbReview414\\admission-extra.xml",
|
||||||
|
"sha256": "6aa78606fc7aa4af1b3e2f8865752a60a518d9d25b5f88924f2b1d88280b2ac0",
|
||||||
|
"tests": 14,
|
||||||
|
"failures": 0,
|
||||||
|
"errors": 0,
|
||||||
|
"skipped": 0,
|
||||||
|
"seconds": 5.299
|
||||||
|
},
|
||||||
|
"focused_serial_suite": {
|
||||||
|
"path": "F:\\CbbReview414\\focused-serial-final.xml",
|
||||||
|
"sha256": "8f68dc1ffd22d41f343299ff4382157c5fcb7ce68dc5198d2755a87dc1764337",
|
||||||
|
"tests": 19,
|
||||||
|
"failures": 0,
|
||||||
|
"errors": 0,
|
||||||
|
"skipped": 0,
|
||||||
|
"seconds": 5.036
|
||||||
|
},
|
||||||
|
"concurrent_test_failure": {
|
||||||
|
"result": {
|
||||||
|
"path": "F:\\CbbReview414\\focused-final.xml",
|
||||||
|
"sha256": "6246c57aee87142dae183aa48399ff2e3f8e8afbff0c4f6f3655d02b93b535fa",
|
||||||
|
"tests": 19,
|
||||||
|
"failures": 4,
|
||||||
|
"errors": 0,
|
||||||
|
"skipped": 0,
|
||||||
|
"seconds": 7.213
|
||||||
|
},
|
||||||
|
"reason": "Coordinator ran mutex-using tests during live native acceptance; four management/recovery tests were rejected by Local\\CbbRefreshVerify795. Rerun serially after native trial."
|
||||||
|
},
|
||||||
|
"count_note": "Full suite collected 1912 before two additional tests were appended. Additional 14-test run includes both new tests and 12 already in full suite; 1914 distinct tests passed.",
|
||||||
|
"compileall_passed": true,
|
||||||
|
"diff_check_passed": true,
|
||||||
|
"bundle": {
|
||||||
|
"module_count": 66,
|
||||||
|
"source_and_frozen_code_equal": true,
|
||||||
|
"source_sha256_checked": true,
|
||||||
|
"packaged_assets_equal": true,
|
||||||
|
"exe_icon_images_equal": true,
|
||||||
|
"executable_sha256": "818decc5f0778a27affe3b047da526595007608e234b89c05d3e1c375e1c4cf8"
|
||||||
|
},
|
||||||
|
"red_reproductions": [
|
||||||
|
{
|
||||||
|
"path": "F:\\CbbReview414\\open-red.xml",
|
||||||
|
"sha256": "b33502766075ece9777ceee3f6e7dde66dfb558eff08a5f860ccc0ebd63f9500"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "F:\\CbbReview414\\queue-red.xml",
|
||||||
|
"sha256": "a5bbad8641c7851a5fa3a4bdd15b17784c9c90c92ee4f8c8fc7e51b62ae25f40"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "F:\\CbbReview414\\write-red.xml",
|
||||||
|
"sha256": "4d0b0c6ebb0382955470ecb6072126b1d4f0708e6f77c49060c5be6b592220d7"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "F:\\CbbReview414\\query-batch-red.xml",
|
||||||
|
"sha256": "6299777fd6d3c87849b0b7069afb0d238d4f4f20f84d7cdea59b81f4a479694f"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "F:\\CbbReview414\\export-red.xml",
|
||||||
|
"sha256": "16724c8a015b5cb1c2d304abe6f5678716a4b4d40fd29880cb6f8a2ade451462"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "F:\\CbbReview414\\restore-consent-red.xml",
|
||||||
|
"sha256": "e9e2edad0c3481bea26c00c14253c9fa9b2e2bbcb3679583e52489ac3072f571"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "F:\\CbbReview414\\default-cancel-red.xml",
|
||||||
|
"sha256": "2e4b9b64d9a7fe8c719b08db407b78e6c866a647040761c1be36d566b86dca36"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"native_trial": {
|
||||||
|
"records": [
|
||||||
|
{
|
||||||
|
"operation": "add",
|
||||||
|
"name": "1GPHY_RTL8211F_A",
|
||||||
|
"status": "CANCELLED",
|
||||||
|
"safe_to_continue": true,
|
||||||
|
"detail": "已取消本批次,未提交后续写入。",
|
||||||
|
"evidence_path": "F:\\CbbReview414\\d7\\management\\management-00175f4d987f48da80bb7821017e7617\\checkpoint.json"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"operation": "add",
|
||||||
|
"name": "1GPHY_RTL8211F_A",
|
||||||
|
"status": "SKIPPED",
|
||||||
|
"safe_to_continue": true,
|
||||||
|
"detail": "用户跳过本项,未确认未知程序与目标库无关。",
|
||||||
|
"evidence_path": "F:\\CbbReview414\\d7\\management\\management-26da6781691c47c7a8172b5947db7191\\checkpoint.json"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"operation": "add",
|
||||||
|
"name": "1GPHY_RTL8211F",
|
||||||
|
"status": "UPLOADED",
|
||||||
|
"safe_to_continue": true,
|
||||||
|
"detail": "上传已确认;本批次未启用自动校验。\n原生注册、工程关联、顶层块和 Layout 已确认;未核验原理图语义。其他工程文件有差异,已记录供核对。",
|
||||||
|
"evidence_path": "F:\\CbbReview414\\d7\\management\\management-2a587eeb2919405d9b570df82ff75a2a\\checkpoint.json"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"choices": [
|
||||||
|
"cancel",
|
||||||
|
"skip",
|
||||||
|
"continue"
|
||||||
|
],
|
||||||
|
"catalog": {
|
||||||
|
"library": "F:\\CbbReview414\\library\\native-add\\fixture\\mentor_lib.lmc",
|
||||||
|
"flow": 1,
|
||||||
|
"safe_to_continue": true,
|
||||||
|
"names": [
|
||||||
|
"1GPHY_RTL8211F"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"sources_unchanged": true,
|
||||||
|
"parked_untouched_until_explicit_user_close": true,
|
||||||
|
"user_closed_owned_empty_client_before_continue": true,
|
||||||
|
"evidence": {
|
||||||
|
"path": "F:\\CbbReview414\\native-trial.json",
|
||||||
|
"sha256": "ecb21df8fd56755dd3bdc6374fa82b5623c523c396314a1c049c225fc82559df"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"native_action_log": {
|
||||||
|
"path": "F:\\CbbReview414\\actions7.jsonl",
|
||||||
|
"sha256": "4ee465d2750b826de428693f89fe0cd9d19f67e5ad08c0fb11451184a883faf2"
|
||||||
|
},
|
||||||
|
"superseded_drivers": {
|
||||||
|
"reason": "UIA traversal of disabled parent during modal prompt stalled the driver. Native windows were cancelled normally; no forced native termination.",
|
||||||
|
"logs": [
|
||||||
|
{
|
||||||
|
"path": "F:\\CbbReview414\\accept4.log",
|
||||||
|
"sha256": "f551539adec4e38072a58eff9e1a8c7589d926f2f120342a101f8476450b4b12"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "F:\\CbbReview414\\accept5.log",
|
||||||
|
"sha256": "d2db6fa91df459d367900832a10c15459ba1ea8fb2a3773c29593c875597a03e"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"rejected_native_trial": {
|
||||||
|
"log": {
|
||||||
|
"path": "F:\\CbbReview414\\accept6.log",
|
||||||
|
"sha256": "73cf87c9328d2e4104077f36ecfbdc383ef67d5d5e54674f640d88d8e5a9de16"
|
||||||
|
},
|
||||||
|
"statuses": [
|
||||||
|
"CANCELLED",
|
||||||
|
"SKIPPED",
|
||||||
|
"UPLOAD_FAILED"
|
||||||
|
],
|
||||||
|
"reason": "Existing native _catalog_com refuses any preexisting LibraryManager even after write consent.",
|
||||||
|
"no_force_termination": true,
|
||||||
|
"foreign_client_untouched": true
|
||||||
|
},
|
||||||
|
"interaction_method": "Private desktop Win32 keyboard messages for modal owner decisions; UIA for idle dialogs only. Skip/Continue key routing separately verified against actual Qt dialog.",
|
||||||
|
"history_provenance": [
|
||||||
|
{
|
||||||
|
"tests": 1775,
|
||||||
|
"record_commit": "fdd07224aac99bee8d1f29e8e82d6a2c49964c87",
|
||||||
|
"record": "2026-11-09-full-review-followup-validation.json",
|
||||||
|
"manifest": null,
|
||||||
|
"recorded_manifest_checked_files": 27,
|
||||||
|
"manifest_mismatches": [],
|
||||||
|
"exact_historical_tree_available": false,
|
||||||
|
"collection_exit": 0,
|
||||||
|
"collection_summary": "1775 tests collected in 12.12s"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"tests": 1851,
|
||||||
|
"record_commit": "42d0cebc54191681b53dcecb120f53236c1963bb",
|
||||||
|
"record": "2026-11-12-native-acceptance-validation.json",
|
||||||
|
"manifest": "F:/CbbAccept-20261112/candidate-release4/source-sha256.json",
|
||||||
|
"recorded_manifest_checked_files": 70,
|
||||||
|
"manifest_mismatches": [],
|
||||||
|
"exact_historical_tree_available": false,
|
||||||
|
"collection_exit": 0,
|
||||||
|
"collection_summary": "1851 tests collected in 11.38s"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"tests": 1880,
|
||||||
|
"record_commit": "466f400514acc8531a219db8e75641be35304a3f",
|
||||||
|
"record": "2026-11-12-scoped-release-validation.json",
|
||||||
|
"manifest": "F:/CbbAccept-20261112/candidate-scoped10/source-sha256.json",
|
||||||
|
"recorded_manifest_checked_files": 72,
|
||||||
|
"manifest_mismatches": [],
|
||||||
|
"exact_historical_tree_available": false,
|
||||||
|
"collection_exit": 0,
|
||||||
|
"collection_summary": "1880 tests collected in 13.05s"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"independent_review": "Both findings fixed; final static review reported no additional actionable findings.",
|
||||||
|
"tested_files_sha256": {
|
||||||
|
"src/cbb_refresh_verify/application.py": "62b9b013563a216d020c8366cccb8f949b02afa72dc63c26940804441cc23057",
|
||||||
|
"src/cbb_refresh_verify/backup_recovery.py": "08ca467304f8ce34185212a92de0ebd0b83455302fe9351d09874b180222b523",
|
||||||
|
"src/cbb_refresh_verify/batch_status.py": "55a4007cf54491ca8e045a5bf86aa4353ac8437cca5a76cd79304962e3d3fa0a",
|
||||||
|
"src/cbb_refresh_verify/close_failed_block.vbs": "e5f0d9678e07a239e96e634b90cdc761de52fc136311fae31484fa38d6fd9781",
|
||||||
|
"src/cbb_refresh_verify/com_runtime.py": "f0f3802d16c791a8bf9dfef44a94917072bfbe8fb3a927d76be8ef0341c7ed35",
|
||||||
|
"src/cbb_refresh_verify/content_check.py": "8239c17b6e2452917ed573a7deb3e4c8583eaef91bf3630eff5f424d2e398aa9",
|
||||||
|
"src/cbb_refresh_verify/defaults.py": "a1c03192f4a61ad0924b24bb635705b1ee4811d35483a02864200f95edbbebe3",
|
||||||
|
"src/cbb_refresh_verify/desktop_worker.py": "27d751816552d215dd8ee9cd67941d824f7b4493120ead7c3f87e5eba5ec4a92",
|
||||||
|
"src/cbb_refresh_verify/diagnostic_open.py": "d6c49ffe5a9969d95edbbc896d47a7e100f248380a287f99ba7bb8b92dbb3072",
|
||||||
|
"src/cbb_refresh_verify/dialog_agent.py": "5acb6e5cf1350a7ca20a6fe480668435fac785835874f266881973010db6504b",
|
||||||
|
"src/cbb_refresh_verify/dialog_models.py": "f68cee01d927b48364276d3c1f79e63ce8af231878db0b907d292780cfbafb56",
|
||||||
|
"src/cbb_refresh_verify/dialog_probe.py": "d61f0c955c961980c9635940eefb9c7947c1fe90b4b6fd844720df41ddb0aa0e",
|
||||||
|
"src/cbb_refresh_verify/dialog_rules.py": "3189b476f7ff4678b59212ed7b4081164e038a7cf7662cd895f9019cb3c1edc5",
|
||||||
|
"src/cbb_refresh_verify/dialog_supervisor.py": "15c415c2d2e916f0b64ba04416164ff3b50996d70b22d3b4ac2226b5547ac247",
|
||||||
|
"src/cbb_refresh_verify/failed_session.py": "7e6f7fa5ebcf2d49f00c5efc5f5d26412704b68e9122e476ac1f672009a98c09",
|
||||||
|
"src/cbb_refresh_verify/icdb_maintenance.py": "e81d253d8b4d3e7c1000c45335a392c72b110748675c2c3324ebe524a7252e98",
|
||||||
|
"src/cbb_refresh_verify/icdb_ownership.py": "7bf2342c1efa34a2ebcbf27964a40a490220f7146fbb6ef957b8d8dd1e511f03",
|
||||||
|
"src/cbb_refresh_verify/icdb_recovery.py": "358c0e9a004f1e0b2127513286e1dffd94b0180a8b7314aa9655462f570b6360",
|
||||||
|
"src/cbb_refresh_verify/integration.py": "f188856af69ba25e265988c51db7a6d4263326440d972ca78378b733b891c1ed",
|
||||||
|
"src/cbb_refresh_verify/library_lock.py": "6836ec8ac21e788eb75326ff44cb31ad4bdfb5f381bd35cdf33e6b34c7fca89e",
|
||||||
|
"src/cbb_refresh_verify/library_manager_verify.py": "71e16a8581ad44b646be78b480f9812d596a6d162b3eec03d078bf4ea4503195",
|
||||||
|
"src/cbb_refresh_verify/library_reader.py": "d4007caa361edd467773e49f721e02671d5a9bcb30741769a57349850b12c438",
|
||||||
|
"src/cbb_refresh_verify/maintenance_entry.py": "3b93c25f69d7a961facd8004e20e155a84cc18f06d57b741a9055786ed058990",
|
||||||
|
"src/cbb_refresh_verify/management.py": "7ead9bfffeb44201e44f73d9f039590f091e9a456982f2110dca8ec3695f8803",
|
||||||
|
"src/cbb_refresh_verify/management_transaction.py": "32c53caaead05d5db3a31d3e30721e65434e5837095dc0a7812f825603aa37a0",
|
||||||
|
"src/cbb_refresh_verify/mentor_adapter.py": "1fc8c98d5508120e03bf001a42dd3e0da7b165eb18c90f1aed83147d17db8638",
|
||||||
|
"src/cbb_refresh_verify/mentor_paths.py": "ba48c0003b3eacc88906497b2e43b299ca4536a9f7dae44bbacf6a6ec694c116",
|
||||||
|
"src/cbb_refresh_verify/models.py": "9e8209a8b006df923f1d07ccab64bbcfe5d674c4fc5f5426bfbc9b11da4ee105",
|
||||||
|
"src/cbb_refresh_verify/native_add_failures.py": "192202732423dc624c5548c75e80bb20973e5087c21d4798c9637f25b6de7e94",
|
||||||
|
"src/cbb_refresh_verify/native_backup.py": "7276fa3d9298e85550151cf0c7191d84bd08a18a72df5d854a3c38f1a88b001d",
|
||||||
|
"src/cbb_refresh_verify/native_engineering_identity.py": "e704e8f56c43629a1593d490776af328bb032208ee2f5ffd1d1be6c3114f5412",
|
||||||
|
"src/cbb_refresh_verify/native_export_guard.py": "523cdf44db8e1665634feadba963ccf26777dc8942fb2eb604d2c30bbe92cbb6",
|
||||||
|
"src/cbb_refresh_verify/native_management.py": "1e8a298aac8c63aef68b1e799d1f06e43de7abdc165be5086e7089a61e643e88",
|
||||||
|
"src/cbb_refresh_verify/native_occupancy.py": "7d686079d12217382adace6361cd343d977b91075e3b157cf410ca92d07ffc49",
|
||||||
|
"src/cbb_refresh_verify/native_repair.py": "9f024dcb5e3a76369191033474fefd30787b6ae350c315f3cf38e92e5a1f3e98",
|
||||||
|
"src/cbb_refresh_verify/native_repair_ui.py": "3eb2af181befea94af8b3b3131edff09589f340bcba777abbe3b67fd31b80393",
|
||||||
|
"src/cbb_refresh_verify/network_path.py": "6b5b159502d42a46bf4ee26d5698fd2c6498b359088e2138eae46e9065b13c6f",
|
||||||
|
"src/cbb_refresh_verify/operation_lifecycle.py": "3838c5a501711d16f578c45ebbc6f960872b0c3ba6bbda9a597f994ef746cef6",
|
||||||
|
"src/cbb_refresh_verify/operation_queue.py": "a6932d8bc68ac436091f6d362557c66d274ec52d0f295a22f014a3396845c79f",
|
||||||
|
"src/cbb_refresh_verify/owner_probe.py": "8dcfd60246cb2979db34d02e0a2d605c334b6f7e2666f22daa2f50c0408bc903",
|
||||||
|
"src/cbb_refresh_verify/pcb_bridge.py": "2f6c2b09642100468814500569dbfc6695fc2a46b9a3b8333daa8e1530cdeef5",
|
||||||
|
"src/cbb_refresh_verify/pcb_open_consent.py": "2680930acc4daa314529c435337915333c05a8594ec28bc053c930054602590f",
|
||||||
|
"src/cbb_refresh_verify/pcb_restore_prompt.py": "39e0b8623a838911eff61066f3e9c8ede4364dbf73efc5a8994197ec72a96488",
|
||||||
|
"src/cbb_refresh_verify/post_repair_consent.py": "3b1eaff1db58fd311a9dbc5fdcd850911b04cc5afd4e747f70a62b721b8fafa4",
|
||||||
|
"src/cbb_refresh_verify/post_verify_diagnostics.py": "2442de485bc0d6a34c4b2d9b10bc5f323ea38f9ff66674119a50f5c6043bac63",
|
||||||
|
"src/cbb_refresh_verify/reimport_recovery.py": "ef148549751fa47518f5f2ca8f32ba25794ec5f22e0de545476ea33f89a3f0bf",
|
||||||
|
"src/cbb_refresh_verify/residual_sessions.py": "4ac500b33b209611d54eb496c6c30727ba159742d625431ceea84471a5fc3442",
|
||||||
|
"src/cbb_refresh_verify/runtime_logging.py": "44ac25430a89c5ffc9e48e88c227e88052f4c815365e8556f67918f3edaba39e",
|
||||||
|
"src/cbb_refresh_verify/runtime_timing.py": "c4ed4057b5000e0b86ccc7dd1fe2004d6e0dae29f397fec77b01ad41a81c6367",
|
||||||
|
"src/cbb_refresh_verify/save_verified_block.vbs": "926175562ef82bb2e732231dbc18d8a88059c7e6143c9f4e502cabfd0d170bcd",
|
||||||
|
"src/cbb_refresh_verify/scoped_manifest.py": "9318bf0f929d23c18466a25d83a4a9903822093c123aae10510061788c6d0ab7",
|
||||||
|
"src/cbb_refresh_verify/session_record.py": "2bc3cff365008864584138a4ff13538bb6b2f90d981e7d008a1300f9102c6e7e",
|
||||||
|
"src/cbb_refresh_verify/status_bridge.py": "05d627d02934a14f5de409472c291d37565a95b836f9c130111aae80612e9196",
|
||||||
|
"src/cbb_refresh_verify/verify_diagnostics.py": "041b77d7d49e4c86338ed5e5741d0d27a2c42bc358f4da54b3efe64af847e9b8",
|
||||||
|
"src/cbb_refresh_verify/verify_probe.py": "3ed743df49d195c74f5045985ab23491d103ee2c42c07b558c1e037176402ed2",
|
||||||
|
"src/cbb_refresh_verify/verify_runner.py": "3027ef7fc1ef6365ff36ae0c83389d869b92ffcd96985d10275bca4dc9483e3f",
|
||||||
|
"src/cbb_refresh_verify/write_admission.py": "e38b460370596f49499fbda3033b2962dda125aa62862fd2327bf6d376d192b9",
|
||||||
|
"src/cbb_refresh_verify/__init__.py": "dd960394d88657820dba858792abf0de258e05efceb08ae2f0b39c6ad78bc469",
|
||||||
|
"src/cbb_refresh_verify/__main__.py": "dc4be034a0e43d4b659a9300137c29a6a6b7a32b7eaef02b6dff9a88c41305c0",
|
||||||
|
"src/cbb_refresh_verify/assets/cbb_refresh_verify.ico": "62d4472ebaa94f9b39aebae06459685d3322041d0e1a7ada9f368cfd816ba1d6",
|
||||||
|
"src/cbb_refresh_verify/assets/cbb_refresh_verify.png": "840f657fd7c622d9afd78625a64ed8ad04c90a895dd3c9fd37eebae543cdebe8",
|
||||||
|
"src/cbb_refresh_verify/assets/cbb_refresh_verify.svg": "cbba5b3f339cbeb5eb43012709237359442ef67c69fc5b6679a8ee4c0a1b7328",
|
||||||
|
"src/cbb_refresh_verify/assets/dialog_rules.v1.json": "3911080fc799a819662e225a7ad73e883abd8dcc9936cc30ec1b2d6d51a03c6e",
|
||||||
|
"src/cbb_refresh_verify/ui/backup_notice.py": "1a3fa5ac18a267907faf95f36d61b9f08bcbb939eef4d480dd06af1391a81599",
|
||||||
|
"src/cbb_refresh_verify/ui/backup_recovery_dialog.py": "ba30b79cd652b74b6e8f438d6bd5f0fc0229594ff4be2358f81c6dd3cb82e77a",
|
||||||
|
"src/cbb_refresh_verify/ui/icdb_check_task.py": "ade3bf414aa29b42f4c1535c613b2cacb2735f6abc7900e6da25999390a5891d",
|
||||||
|
"src/cbb_refresh_verify/ui/main_window.py": "2c919badeeee0280e49387b88b058555a9fa6ace04835c094fccd782bf0af9c0",
|
||||||
|
"src/cbb_refresh_verify/ui/management_dialog.py": "8e2024957be874905685167c7eab440ecee9320170c1553340025b10fa1754d6",
|
||||||
|
"src/cbb_refresh_verify/ui/pcb_open_dialog.py": "3cabdc15f1b2abaeb919a7f29f32d4b053186701fd514646d9bdd3ea32f364f6",
|
||||||
|
"src/cbb_refresh_verify/ui/pcb_restore_dialog.py": "b7228d828df235ac51502dc68760d28c4896af02c780e9806e11c32dba7f62da",
|
||||||
|
"src/cbb_refresh_verify/ui/residual_release_dialog.py": "1d2a26bfc7ee21b11d7edbc3074b4c525e8c9fb628bca45b08bd06fc672586c8",
|
||||||
|
"src/cbb_refresh_verify/ui/workers.py": "4cc9360a4820ded27a7d5ef709fc9f04b1d4804cb1e7a614f6c357ed547da888",
|
||||||
|
"src/cbb_refresh_verify/ui/write_owner_dialog.py": "c77f4d57e683fa397a39a573171198922f6158e19a8a96ca3627af60b5a8963f",
|
||||||
|
"src/cbb_refresh_verify/ui/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||||
|
"tests/button_simulation.py": "3278868565853001103557d5f7ada42b11b05c03feb9032deed0327b6609de2b",
|
||||||
|
"tests/CBBRefresh.Core.Tests.ps1": "e90774cde77189bc577ee374b50a8cc951740d2d3c36c786c73abbd128181a59",
|
||||||
|
"tests/ContentCheck.ExitCode.Tests.ps1": "efa0d1e8a77715932670ab8ac299984e023867d07ff57b09fc7da6d68c4d6fd9",
|
||||||
|
"tests/test_abnormal_shutdown.py": "0abdeaf51e2ffc3f771e09aefa9ec647a72b7f64757c9f3851926fbd392cbbcd",
|
||||||
|
"tests/test_all_buttons.py": "897ae449a15fe36fb6198a947575609346d5ce1a22c0a8c4d2950b9f00035d4f",
|
||||||
|
"tests/test_application.py": "bba12187fca6fee0f4f8862182bb40d939e2995016af2cdbb3fd756f6a99135d",
|
||||||
|
"tests/test_automation_license.py": "45e9c75d0d3e1a76f997f7da4cc87b5eb1b05a4ea2356408725742eac8a09ffb",
|
||||||
|
"tests/test_background_icdb.py": "df9bd9e8252e0dee4527dc6a740c0c33e76d1fb06a79b816cc15809d95716e44",
|
||||||
|
"tests/test_background_queue_regressions.py": "132866bfccc9a7ac5cb234f97aaf6a290e2e4ef949f31e2f70b0f3eafeb99046",
|
||||||
|
"tests/test_backup_recovery.py": "efd88c0c00440ac915b147c2e6dee8044ca805b03f90ab9f171cbde1db11cb9b",
|
||||||
|
"tests/test_backup_recovery_dialog.py": "b2f65864b861d95e99d5efb61ada915ae41973d2b49d08f2d536781997dd00cb",
|
||||||
|
"tests/test_batch_blockers.py": "4387293d3a5820fab630e3c5fe1b424f61ba6947773e5a61125d840433c5c62a",
|
||||||
|
"tests/test_batch_item_yield.py": "ed4be6d1e854b18d054a75c92171cd46b6b64411c2f74e9a3caf31fba3c7366b",
|
||||||
|
"tests/test_batch_status.py": "c1f9af0c7c6f3171b3726fb53346f480b13b8d9cd88111a9c12e2fae2392bbff",
|
||||||
|
"tests/test_batch_status_faults.py": "314e890c9aee439c8a75b4dfd605685240c74f6212da975fd50526bd70b4a0ff",
|
||||||
|
"tests/test_desktop_worker.py": "671d616f04a01d74508b328e3b6fc8f6c7191a91de0dcaa486aa98a3718353ff",
|
||||||
|
"tests/test_diagnostic_open.py": "b44f8f7b171602ad2691ea2e064ac9fe94f2fabb9fcc2eb6760cc1dd365b9423",
|
||||||
|
"tests/test_dialog_agent.py": "8c746e47d55637ca18d7cc998f324a0c2e0a5214dcfe8fcb6458c060619c211c",
|
||||||
|
"tests/test_dialog_models.py": "6902cf5c292458340fb48241b34875e111a0113d706cd82775934a7f72bab7b9",
|
||||||
|
"tests/test_dialog_probe.py": "55c98f6102957a27a96dcfd4f4bf3af499b5055225b77ef93b7b332dfd4ac472",
|
||||||
|
"tests/test_dialog_rules.py": "96bf36493da770679e9207e96b3088ef7f471aea22e17c254f33326ffef0d7f9",
|
||||||
|
"tests/test_dialog_startup_budget.py": "6f23c01836e4894ae82c3345a2383c4f8eb0517056c5b953c43100acd0fc3739",
|
||||||
|
"tests/test_dialog_supervisor.py": "4c1b00050127a65b0a8cf1c7a94fd673431ea3f04b76033a463804d0468ad2d9",
|
||||||
|
"tests/test_extended_safety.py": "7450816abba89aba1f4739f819f43631def82701fe07481279db2b3f3ed96cf6",
|
||||||
|
"tests/test_external_owner_release.py": "675ddbab4a97e86febac3003b9083c259295534941aa0463488a5a1206cfaf92",
|
||||||
|
"tests/test_failed_startup.py": "eca757ea46a4c0aa4fb0368ff53f26822af71612d251ecd87132686fe3c3794b",
|
||||||
|
"tests/test_failure_lifecycle.py": "dfeac56744a44e6f4c7898516749ca478f53d7c7f08b3843a05ef7f448c469a7",
|
||||||
|
"tests/test_icdb_address.py": "cbdc07e5043349c796a4ea1ce3d4989062094cd28929a9ef7d42c5ba75b77907",
|
||||||
|
"tests/test_icdb_batch_check.py": "e83982e0fd0b3744bdc62965b26970ded31aacfedea94283d9e321ef70a8232f",
|
||||||
|
"tests/test_icdb_open_check.py": "1f3750169755d0553bac3e0f8bec244038b84f9cd970e17c9f6eb67dee0e3dba",
|
||||||
|
"tests/test_icdb_recovery.py": "298ddac4b79b4400efc99ff27c58ca49fffea1f401a31071451b2fdaca59036e",
|
||||||
|
"tests/test_import_without_export_gate.py": "ae3dd0fb41c41773ce2d54aa9f9be83bbb56a0d09c59d600b10575fa8f0d2cd4",
|
||||||
|
"tests/test_incident_safety.py": "52f3ccb04db8971bf38628c2bd334d4fd79795e97de6538f6f66cb35f7123ece",
|
||||||
|
"tests/test_independent_operations.py": "4ba5798df3346bce74c3703c158f1dce1d1ba14df748606fcaf900c8568753e0",
|
||||||
|
"tests/test_integration.py": "9e9d30692607c889e1e3744a63c79c68e3af7d4c86804e0bcebe48e68765086c",
|
||||||
|
"tests/test_late_release_continuation.py": "34c62a628cbc08f4e8b9a1919c13f17772a2d26d1996fae34a35f814725b00e2",
|
||||||
|
"tests/test_library_lock.py": "3d65bd941faa441404045ce0140ea3ea5e58fb7d410b7b76bb9f03a9ea03d3af",
|
||||||
|
"tests/test_library_reader.py": "b39a1dc9d99c2463b744141e3c3489cd49ac4a637e7835559a9c3fe9cbafbb58",
|
||||||
|
"tests/test_lifecycle_supervision.py": "cfe29f1e73c6ef38d11e185e211b6e2fb60247f53a44e99dd1e2f8cf7a009faa",
|
||||||
|
"tests/test_maintenance_diagnosis.py": "0849aef555475a03b061eacf499f261fb75f2e727f35dba3cbceafac92e2a638",
|
||||||
|
"tests/test_maintenance_entry.py": "5ed3cda8e0c829fb2964e27f1bdc6fa8ee8dcde93ec63338959bf754b62d6a0b",
|
||||||
|
"tests/test_maintenance_owner_scope.py": "7cf64dc7f2b126684dcac6e619cbd87eca3d85ec2fc1f70f057154679dad6026",
|
||||||
|
"tests/test_maintenance_review.py": "ba807fd8c25c1b52cf2443d8bcf2f57539819715c0bc6c358d31d8542c2e7ce5",
|
||||||
|
"tests/test_maintenance_startup_gate.py": "4f69d33218483a658b51b2012ae8bfa83aff8a787152a38b19dadc4c0d3ffe36",
|
||||||
|
"tests/test_maintenance_ui.py": "2a640ba5e979a3fead81f0a38603b6105ffcb883dbb8484ccc42c99ee8c311db",
|
||||||
|
"tests/test_management.py": "cad0fb43eca9e7022a33a5e9ff0a408465b262fd304b146cdc85c28265f2e74f",
|
||||||
|
"tests/test_management_diagnostics.py": "671a9d7c112ededbee332db9b6fbab786fb37e9367d992f902f3ab2c9f60880b",
|
||||||
|
"tests/test_management_native_transaction.py": "7ca227aae6426c4d0d998edfd8620ec18905aaf212f0be20ceba97b1cde3a9a4",
|
||||||
|
"tests/test_management_probe_guards.py": "ae9be3dbd7c6a616478b7d4ea3498c428ff94a985089fe798463c5cab456f151",
|
||||||
|
"tests/test_management_retry_blockers.py": "124dbef291dbe331ba0c3e7de1665c910ea43e37b1563429b387f0f2233953ee",
|
||||||
|
"tests/test_management_source.py": "16e608ed9c8b0aa81cf08d49f165a33a1403c4ea7f2a5be44e8cfc8cb49850ad",
|
||||||
|
"tests/test_management_supervision.py": "2dcadd6551a94c52e5d4e74285959f10144a89c48af87e508abaea945652d1f6",
|
||||||
|
"tests/test_management_ui.py": "da3e2bc0b5c73926324a539edfa2f718ae1b585df96324a928a0c1a909e48083",
|
||||||
|
"tests/test_manual_backup_ui.py": "927e42ec4a1e0139c71a41b0cad1389ad47b0881381203c18b307cd2d137983a",
|
||||||
|
"tests/test_mentor_paths.py": "a05a91812a74b58e76f36d581216ee43969d2576b8a8e7d1cde3e301c52cf4c1",
|
||||||
|
"tests/test_native_add_failures.py": "ceedd60e030628b1af149d08d16216d5f7158a63686729bb357c148da86fb0ec",
|
||||||
|
"tests/test_native_backup.py": "43ec0c6b14b53864553feaf5d9fb498b37866f24edc486c0749160d3f803db5f",
|
||||||
|
"tests/test_native_engineering_identity.py": "a1adcf6883a9b55c2c37d9f491faf40dd4928f4d8db675419fd288dd31552c69",
|
||||||
|
"tests/test_native_export_guard.py": "f8ec4fa1058af55008e9628f79f2dc70b6e551f36815a812d10bfdf955cada51",
|
||||||
|
"tests/test_native_inspection_release_regressions.py": "8f7bb0b2b641d437872f1dd1d0c2547c2522c81e3c0351c31a7125f751d91927",
|
||||||
|
"tests/test_native_management.py": "badf33d4d00104c7e96e336777fb3e49690cc9db5ce1b071f98520aa5b6668f1",
|
||||||
|
"tests/test_native_management_fields.py": "9917ca0910e19bd809c86d0120c652145261528ace33c3b805f5663442c4a973",
|
||||||
|
"tests/test_native_occupancy.py": "56293dbe24bd3cd4f74cf8208e933faab7d737e5a5684a5d38838d063c3aef6d",
|
||||||
|
"tests/test_native_repair.py": "113185ced72d8f4f4eafca99054d97fe80a504d1c6cc91aaf86f55cea1b7e138",
|
||||||
|
"tests/test_navigation_tabs.py": "d7d5bbfc752f73c1b1d4615ffafc1266e772d96f3f3ba3d82c4b4baf678b292d",
|
||||||
|
"tests/test_network_path.py": "f52624391ae78e9b913dace2b1a9a2875a5855f86dc9e12c324ef493e6c7817b",
|
||||||
|
"tests/test_network_release_safety.py": "caef536d0a40b2eb848c1b8ab095ab374af247c03dd44acf8a70f0f500db6dac",
|
||||||
|
"tests/test_operation_lifecycle.py": "c0ce6c86b73021a8b162ae9e67a10aeec8a27a98e382fd82e1449a451a9a8c3c",
|
||||||
|
"tests/test_operation_queue.py": "8137528603f015695ed4d60a0c8fa8e7bf0a1c4659f8dc2a181291f5d500e6a1",
|
||||||
|
"tests/test_owner_probe.py": "deb757e022980f11ef48e57a2fd002ee3e90ec647a4666a0c4d4427313b6f725",
|
||||||
|
"tests/test_packaging.py": "87a6d04419775c0c5c806e0e569a48d7ef199a0bff8736b211443a1f471e7e8a",
|
||||||
|
"tests/test_packaging_status_bridge.py": "cbfaeac070a1494a1d8609fc25e9a779a63354c8914b4c6c57fdc7c31b70d472",
|
||||||
|
"tests/test_pcb_bridge.py": "527fb63147a203a2e9419da989aff600d3e461580989e39e8ede3a8cc57b901a",
|
||||||
|
"tests/test_pcb_open_consent.py": "5bf9ef6276d221b73ebe0dd14cff4fe5dc11bfec7b8be3266ae4a6b6a588d354",
|
||||||
|
"tests/test_pcb_restore_prompt.py": "a005691d0296587e520e20c4430e9e55227d767c8e910e950a9f2e93aeccb2c7",
|
||||||
|
"tests/test_pcb_version_choice.py": "0825c28333e4ed4f5a63847b6f5bb11143e922c7203d2770ce9c78fc8edec20f",
|
||||||
|
"tests/test_post_repair_consent.py": "bf417b378255386dc97ad8efdf5003b0691aa5d69da9d9256aa367dc16a2d4bb",
|
||||||
|
"tests/test_post_verify_diagnostics.py": "212857e56581998a3a3cd53635030b68a089fc4d630a8b0ee7ef3f137090dcc4",
|
||||||
|
"tests/test_private_desktop_discovery.py": "5361493313ae6864e252cdb9f2c72e71b39264a1c022beb4cf0c04c143cdd91e",
|
||||||
|
"tests/test_readonly_status_policy.py": "3ed40d7bdf2d3e6f70b38803b89a8b982336556444b45c6ba6b0a7c6df52a97f",
|
||||||
|
"tests/test_reimport_recovery.py": "875e5e2a0f6251ec5a251457848c7eac5dfd1674fcbb4745155f6d5d8bf4a4be",
|
||||||
|
"tests/test_residual_release_dialog.py": "10b23d009703d542e5ce8ecb35a4833e0135bb8852b4116e49eedc7010397a1e",
|
||||||
|
"tests/test_residual_sessions.py": "2c51ed1dc95a3afa7ebb24027963dfa9d13aba9c407e508e22ccc6e9f762dfeb",
|
||||||
|
"tests/test_review313_residual_isolation.py": "52a8024ed4e2a7fed219fe46cacdf76fa971166feedd557206716ef7f6d3c914",
|
||||||
|
"tests/test_review326_dispatch_and_receipts.py": "ce4d529246da1c4d53c3dec70ef49542165064404301dec3e32851df62492ecf",
|
||||||
|
"tests/test_review326_queue_guidance.py": "c2c97aceddd9713618afdd5f2a7be4764b56a1b62fc672282fb8c218b4969c74",
|
||||||
|
"tests/test_review345_ui_cli.py": "795e7e4f9bda8874c6a65a08863cab19f4adb3412287276ee2960588f0fd2fa8",
|
||||||
|
"tests/test_review348_release_comparison.py": "ceccdb3d6f7bc6cb65562c059f13aa2bc5d89d98c6f64b0f11d9b943ebbde165",
|
||||||
|
"tests/test_review381_queue_release.py": "e0d62424cbf70ec9573db78ede0a4c6534775399194eed4c6b28ba8d468307be",
|
||||||
|
"tests/test_review391.py": "304d46d63af87ea4a9bca83834b77cc44c5c9addf7b0f3752431304ee612568c",
|
||||||
|
"tests/test_review414_export_and_audit.py": "ec785c2656bed97de6c8467885f2ad0877b55ee872b02928744d399e8767d8a0",
|
||||||
|
"tests/test_review414_open_and_queue.py": "db065207dacaccd0bd80af52c1f1edaf36a278e7cf2dce7c9b44bc51dd0e1cec",
|
||||||
|
"tests/test_review414_write_admission.py": "604ee7429053d408943a1d74b18c6bbf2de817e9e0b76c82abe7a1faceafdf9f",
|
||||||
|
"tests/test_review_319.py": "831fd34d426abb4436b9132bfb7ed754994155a34ac60a59378dee0964b54d28",
|
||||||
|
"tests/test_review_backend_followup.py": "2f3f51a72ecd05fc33c6b5a8dddaecfd12d2b50df423c87b4c18d1e52b2609bd",
|
||||||
|
"tests/test_review_foreign_release_evidence.py": "cbf2af02418f6bd3ec720a7a7658cf97f06d1a6e12009fdff2a99f465711591e",
|
||||||
|
"tests/test_review_management_ui_followup.py": "746602a84c3ba9cb041c5dd354b39d344355b71a3666b27a47eb9aee231e171c",
|
||||||
|
"tests/test_review_release_followup.py": "ab375f67e63cf3f33fa67ce19058be442c2ec56f810d4fc58ef5484272cbda49",
|
||||||
|
"tests/test_runtime_timing.py": "7152cd8fedfe165e769dadc1238c347d9f4d3e93cd57f6ed991e14d959e720f7",
|
||||||
|
"tests/test_safety.py": "ccf5febaf0a974d5e5357398a6946d3f121e07a6247c2f0dc5b71d86b39cac52",
|
||||||
|
"tests/test_save_helper_identity.py": "178a68c4a9a8c618dad3d8393e816dd1d2a16aef8d1fb9984117fe9dc8d06add",
|
||||||
|
"tests/test_save_helper_runtime.py": "00b092ec799da4bca424e1ee63a83bee783c81dbcdc20b7526fda8b45bb4b72a",
|
||||||
|
"tests/test_scan_isolation.py": "cab02bfe55ed515f889d3fcba6e6880344f482cc3a78a072b543b7a871cf92ab",
|
||||||
|
"tests/test_scoped_manifest.py": "fe9b2047d2c43812e851dd89ff250a2e5907dda89b3f5d9ae0a4dc4c5f452eac",
|
||||||
|
"tests/test_session_record.py": "6b51b19adfb232275195da7ff1ba91a5ce5e296f9424a7a1a29fc67ecfdfb108",
|
||||||
|
"tests/test_status_bridge.py": "fe1c0632d4d5fd5a1caf221903d4cfe38eda62aaa4298e3438735e31b8459ab2",
|
||||||
|
"tests/test_status_bridge_server.py": "7d8cd72d69afae0f96ebbd9bb3be2ae3c222f01108e45ab51a09e54d4d8527cc",
|
||||||
|
"tests/test_ui.py": "306a66698296a050744869b0756ddd0eefee5019618ff90b684da136a9787854",
|
||||||
|
"tests/test_ui_batch_safety.py": "12a8d82d4aedbeee315a02a49ec0e9888547ad4abd63e181e7f392b2a39e26dc",
|
||||||
|
"tests/test_ui_filters.py": "155e8f72d18c5c76b353d4b99f3828339c80908a9910f01641ba5c32a3929c75",
|
||||||
|
"tests/test_ui_lease_lifecycle.py": "18ea8af868373fa795a4911754be55068fe75833ce35579c1212fd7f4713f149",
|
||||||
|
"tests/test_verify_diagnostics.py": "b6431194e9f4c86a42110cac0d5f712c27b063f43b4ce820327aded81602908c",
|
||||||
|
"tests/test_verify_probe.py": "aeb65b5bd2df14e8a8f3ba5501855b5946e6f8a22f0d26960c00ff1b0daea56b",
|
||||||
|
"tests/test_verify_runner.py": "e58619f55873302c39129ce50e50fb25173a96ab309d975aa4f47f0bd3459fbb",
|
||||||
|
"tests/test_verify_worker_stability.py": "eae03400c2e3c8a0bc339c8dc05d890403c6bfb4c6d70d0361bc1b882b47d618",
|
||||||
|
"tests/fixtures/icdb-repair-startup-windows-sanitized.json": "a7fe3a34d47fb36d7f98ca8c1df4bb9a50d5faa9aee5bf76db5dbc3f3d06d03d",
|
||||||
|
"tests/fixtures/issue2-lost-session-sanitized.json": "7ed4b567acabb38ff643ebd2c5b3d90b4fd9f33368f67ce3f436ba93ccf24519",
|
||||||
|
"tests/fixtures/pcb-version-choice-sanitized.json": "ce0cb6d9135970cb4fbfa31fa057271b174dc37e57d90a5d4ac9ecf3ebabddfd",
|
||||||
|
"tests/support/runtime_lifecycle_frozen_boundaries.py": "bf98533a1c06ccf4453d20b3804323779719e697141b8dc64fa679960a979cfd",
|
||||||
|
"tests/support/runtime_lifecycle_frozen_fixture.py": "b87761c06a300f0d93bce864d3d31e045f2135324b2a9a42f8682ccbff09ad22",
|
||||||
|
"tests/support/runtime_lifecycle_frozen_smoke.py": "b11e0aac71c1079625ac9832dc5c38197bc80110478c4d9e02c2a3bc58a2a2d0"
|
||||||
|
},
|
||||||
|
"automatic_icdb_repair": false,
|
||||||
|
"merged": false,
|
||||||
|
"published": false,
|
||||||
|
"limitations": [
|
||||||
|
"Real field lost-server-session recovery is not accepted.",
|
||||||
|
"Windows 10 and cross-machine SMB not tested.",
|
||||||
|
"PCB sharing-violation regression uses real Win32 handles with controlled callback; no claim of field popup repair acceptance.",
|
||||||
|
"Long native Add waits remain undiagnosed.",
|
||||||
|
"Preexisting LibraryManager still prevents native catalog activation; user must close it normally before continuing. Multi-client COM ownership is not verified.",
|
||||||
|
"Unknown-client consent is user attestation, not proof of future native ownership."
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
# PR #13 评论 414 修复与验证
|
||||||
|
|
||||||
|
审查基准为 main `cbc57238496bc84f4228aa44929208a9516dff1b`;本轮修改基于
|
||||||
|
`1572e2d`,保留正常导入与可选导出诊断解耦。审查链接:
|
||||||
|
https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/pulls/13#issuecomment-414
|
||||||
|
|
||||||
|
## 审查意见处理
|
||||||
|
|
||||||
|
| 意见 | 处理及验证 |
|
||||||
|
| --- | --- |
|
||||||
|
| P2-1 未知原生进程在写前被忽略 | 仅在中心库写入和备份替换时要求明确选择继续、跳过本项或取消批次。许可限定本批次、目标库、PID/创建时间/映像/用户/会话,先落盘后生效。实际目标进程、数据库句柄冲突和地址记录不能用此确认绕过。确认后重新查询进程及资源。 |
|
||||||
|
| P2-2 独占探测句柄跨越原生“读写打开”点击 | 退出 resource_guard、释放句柄并重核原生进程身份后才派发点击;保留实时窗口身份核对及单次回答。真实 Windows CreateFile 回归试验在原实现产生 sharing violation,修复后读写打开成功。 |
|
||||||
|
| 后台读 QWidget / 使用当前库 | 队列、批次结束刷新及备份会话读取使用请求绑定的库;后台缺少显式库参数直接拒绝,避免从控件推导。Qt 工作线程回归试验验证不再读取 lmc_edit.text。 |
|
||||||
|
| 导出预存进程豁免偏宽 | 需要最新快照的创建时间与完整映像匹配;当前绑定副本或归属未知的原生客户端不豁免。相同创建时间但映像冲突不能解释为原进程已退出。内存和磁盘释放路径均有测试。 |
|
||||||
|
| 非 checkpoint 租约不落盘 | 此描述不准确:已有 LibraryLock 会写入并 flush `.lock` 审计文本(机器/PID/时间/库),原生校验另有 session 记录。增加实测断言;审计不是占用证明,不增加新阻塞记录。 |
|
||||||
|
| 历史测试数字缺少复现信息 | 见下表及命令;区分记录提交和精确被测树,不用单个旧提交冒充混合工作树。 |
|
||||||
|
|
||||||
|
整批校验和 ICDB 检查仍独立。未知进程确认不会关闭这些进程。用户需要确认它们在本批次完成前不使用目标库;程序仍无法仅凭命令行证明另一个客户端未来不会打开此库。
|
||||||
|
|
||||||
|
独立复核另发现两个集成缺陷:确认记录创建恢复目录后,恢复再次以独占方式创建同名目录;以及调用方未传 Event 时“取消本批次”仍执行下一项。均先以回归测试复现,再修复;跳过继续、取消停止,新出现进程和记录写盘失败也有覆盖。
|
||||||
|
|
||||||
|
## 历史测试数字的来源与复现边界
|
||||||
|
|
||||||
|
| 数字 | 保存记录的提交 | 原始证据 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 1775 | `fdd07224aac99bee8d1f29e8e82d6a2c49964c87` | `2026-11-09-full-review-followup-validation.json`:四个分支 head、27 个被测文件散列、XML 路径与散列。 |
|
||||||
|
| 1851 | `42d0cebc54191681b53dcecb120f53236c1963bb` | `2026-11-12-native-acceptance-validation.json`:baseline `b86e4e3`、XML 结果、candidate-release4/source-sha256.json。 |
|
||||||
|
| 1880 | `466f400514acc8531a219db8e75641be35304a3f` | `2026-11-12-scoped-release-validation.json`:full-scoped-final10.xml、冻结包散列。 |
|
||||||
|
|
||||||
|
本轮从以上三个提交分别导出干净快照,设置各自 PYTHONPATH 后运行
|
||||||
|
`python -X utf8 -m pytest --collect-only -q tests`,实际分别收集到
|
||||||
|
1775 / 1851 / 1880 项;对应记录的 27 / 70 / 72 个文件散列均与这些提交一致。
|
||||||
|
以上提交可作为复现入口,但本轮没有重跑三份历史全套测试,收集数量不等于重新验证通过。
|
||||||
|
历史记录未覆盖的测试文件及外部环境不能靠这项散列核对证明完全相同。
|
||||||
|
|
||||||
|
当前版本可从本修复提交干净检出后运行以下命令。必须显式设置 PYTHONPATH,避免可编辑安装及测试子进程加载到另一份工作区:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$env:PYTHONPATH = (Resolve-Path ./src).Path
|
||||||
|
python -X utf8 -m pytest -q tests --junitxml=full-suite.xml
|
||||||
|
python -X utf8 -m pytest -q tests/test_review414_open_and_queue.py tests/test_review414_write_admission.py tests/test_review414_export_and_audit.py --junitxml=review414.xml
|
||||||
|
python -X utf8 -m compileall -q src tests
|
||||||
|
git diff --check
|
||||||
|
```
|
||||||
|
|
||||||
|
本轮实际命令、XML、源码散列、冻结包核对及隔离原生操作结果见相邻
|
||||||
|
`2026-11-13-review-414-validation.json`。
|
||||||
|
|
||||||
|
全量 1912 项通过后新增两个边界用例,追加的 14 项测试全部通过(其中 12 项与全量重合,合计 1914 个不同用例)。
|
||||||
|
冻结包 66 个模块与当前源码一致,图标及资源一致。隔离空库的实际按钮操作得到:
|
||||||
|
取消仅产生一个 CANCELLED;新批次第一项 SKIPPED、第二项 UPLOADED,独立读取只确认第二个工程。
|
||||||
|
两个来源目录的工程内容清单保持一致,程序与原生任务正常退出。
|
||||||
|
“继续”之前由测试用户正常关闭本任务创建的空 LibraryManager;没有强制终止外部软件。
|
||||||
|
两轮旧驱动卡在模态窗的 UIA 读取、一次保留 LibraryManager 导致原生拒绝,以及一次回归测试与原生试验并行造成互斥拒绝,均保留原记录,不计为通过。
|
||||||
|
|
||||||
|
## 验收边界
|
||||||
|
|
||||||
|
本轮不启用自动 ICDB Repair,不关闭现场工单。Windows 10、跨机器 SMB、现场服务器会话失联完整修复未验收。原生 Add 长等待的原因尚未定位;这轮不以缩短超时掩盖它。当前云端发布包保持不变。
|
||||||
|
|
||||||
|
冻结包实测额外确认一项既有边界:原生 `_catalog_com` 仍要求启动前没有其他
|
||||||
|
LibraryManager,避免将其他客户端错误登记为本次所有者。因此当未知客户端恰为
|
||||||
|
LibraryManager 时,选择继续仍可能得到“已有 Library Manager 运行”;确认不会绕过该原生入口限制。
|
||||||
|
并行 LibraryManager 的隔离接入需要单独验证 COM 返回对象与窗口/PID 的精确归属,
|
||||||
|
本轮没有直接删除检查。该失败试验及正常关闭测试会话后重试的结果分别保留。
|
||||||
@@ -0,0 +1,309 @@
|
|||||||
|
{
|
||||||
|
"schema_version": 1,
|
||||||
|
"created": "2026-11-16T10:04:07.868924+08:00",
|
||||||
|
"review": "https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/pulls/13#issuecomment-430",
|
||||||
|
"base_commit": "fee4a67",
|
||||||
|
"code_commit": "fa5590468d62d7b4605f73e09fe961416020727c",
|
||||||
|
"environment": {
|
||||||
|
"windows": [
|
||||||
|
"11",
|
||||||
|
"10.0.26200",
|
||||||
|
"SP0",
|
||||||
|
"Multiprocessor Free"
|
||||||
|
],
|
||||||
|
"python": "3.12.10",
|
||||||
|
"mentor": "EE7.9.5"
|
||||||
|
},
|
||||||
|
"full_suite": {
|
||||||
|
"local_path": "F:\\CbbReview414\\review430-full.xml",
|
||||||
|
"sha256": "dda0f591d2652fc39622a62fb3767cfd4eba5420fa099dcfa7aa87b14733dee5",
|
||||||
|
"tests": 1924,
|
||||||
|
"failures": 0,
|
||||||
|
"errors": 0,
|
||||||
|
"skipped": 0,
|
||||||
|
"seconds": 316.455
|
||||||
|
},
|
||||||
|
"focused_suite": {
|
||||||
|
"local_path": "F:\\CbbReview414\\review430-focused.xml",
|
||||||
|
"sha256": "a09dac537ddf2adc8f014cfeea58454e3c05a1f0fe3ea8abd784f81b8843832e",
|
||||||
|
"tests": 89,
|
||||||
|
"failures": 0,
|
||||||
|
"errors": 0,
|
||||||
|
"skipped": 0,
|
||||||
|
"seconds": 32.99
|
||||||
|
},
|
||||||
|
"red_reproduction": {
|
||||||
|
"local_path": "F:\\CbbReview414\\review430-red.xml",
|
||||||
|
"sha256": "a0280295b7415e28974227b8a94bc62612b45d4903c1e0257ba269e37a149d7c",
|
||||||
|
"tests": 10,
|
||||||
|
"failures": 7,
|
||||||
|
"errors": 0,
|
||||||
|
"skipped": 0,
|
||||||
|
"seconds": 7.787
|
||||||
|
},
|
||||||
|
"commands": [
|
||||||
|
"PYTHONPATH=<checkout>/src python -X utf8 -m pytest -q tests --junitxml=full-suite.xml",
|
||||||
|
"python -X utf8 -m compileall -q src tests",
|
||||||
|
"git diff --check",
|
||||||
|
"python -X utf8 <local-evidence-root>/build.py",
|
||||||
|
"python -X utf8 <local-evidence-root>/verify_bundle.py",
|
||||||
|
"python -X utf8 <local-evidence-root>/driver.py"
|
||||||
|
],
|
||||||
|
"compileall_passed": true,
|
||||||
|
"diff_check_passed": true,
|
||||||
|
"bundle": {
|
||||||
|
"module_count": 66,
|
||||||
|
"source_and_frozen_code_equal": true,
|
||||||
|
"source_sha256_checked": true,
|
||||||
|
"packaged_assets_equal": true,
|
||||||
|
"exe_icon_images_equal": true,
|
||||||
|
"executable_sha256": "ab02971c5bd8e46881433b66922e927075ab0cea7c18fb7f79243089de97ce22"
|
||||||
|
},
|
||||||
|
"smoke": {
|
||||||
|
"backup_status": "SKIPPED",
|
||||||
|
"backup_target_unchanged": true,
|
||||||
|
"management": [
|
||||||
|
{
|
||||||
|
"name": "1GPHY_RTL8211F",
|
||||||
|
"status": "SKIPPED",
|
||||||
|
"safe_to_continue": true,
|
||||||
|
"evidence_path": "F:\\CbbReview430\\data\\management\\management-c1bb58f1e8f543f68453c03c138deba0\\checkpoint.json"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "1GPHY_RTL8211F_A",
|
||||||
|
"status": "UPLOADED",
|
||||||
|
"safe_to_continue": true,
|
||||||
|
"evidence_path": "F:\\CbbReview430\\data\\management\\management-c6a380a4685a41669f5d2fc615de3756\\checkpoint.json"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"readback_names": [
|
||||||
|
"1GPHY_RTL8211F",
|
||||||
|
"1GPHY_RTL8211F_A"
|
||||||
|
],
|
||||||
|
"sources_unchanged": true,
|
||||||
|
"choices": [
|
||||||
|
"skip",
|
||||||
|
"skip",
|
||||||
|
"continue"
|
||||||
|
],
|
||||||
|
"client_normal_quit_before_continue": true,
|
||||||
|
"app_exit_code": 0
|
||||||
|
},
|
||||||
|
"smoke_evidence": {
|
||||||
|
"local_path": "F:\\CbbReview430\\smoke.json",
|
||||||
|
"sha256": "e3903cc6c2eb9e8cb4c7c3a4f83036703cd60622f0ced3211be8de8a9c52956c"
|
||||||
|
},
|
||||||
|
"actions": {
|
||||||
|
"local_path": "F:\\CbbReview430\\actions.jsonl",
|
||||||
|
"sha256": "2e442ac332fb56bf355f69254283361dab386634972fac6e1a6cc5b0649a9806"
|
||||||
|
},
|
||||||
|
"source_manifest": {
|
||||||
|
"local_path": "F:\\CbbReview430\\candidate\\source-sha256.json",
|
||||||
|
"sha256": "76cfa8ab47243c569ab9ee284b5c66df4b3f9eca7bfa0dae19a236a9c2ee1035"
|
||||||
|
},
|
||||||
|
"code_review": "Independent read-only review: no actionable findings; ready for PR after full suite.",
|
||||||
|
"warning": "Existing pywinauto Revert to STA COM threading mode warning.",
|
||||||
|
"evidence_note": "local_path values name local audit artifacts, not public download locations; redact before external sharing.",
|
||||||
|
"source_sha256": {
|
||||||
|
"src/cbb_refresh_verify/application.py": "62b9b013563a216d020c8366cccb8f949b02afa72dc63c26940804441cc23057",
|
||||||
|
"src/cbb_refresh_verify/backup_recovery.py": "1d7ef08ef53ca7a0971cdacb0908d9bb06d067b06dc2329fa58722ce9068921d",
|
||||||
|
"src/cbb_refresh_verify/batch_status.py": "55a4007cf54491ca8e045a5bf86aa4353ac8437cca5a76cd79304962e3d3fa0a",
|
||||||
|
"src/cbb_refresh_verify/close_failed_block.vbs": "e5f0d9678e07a239e96e634b90cdc761de52fc136311fae31484fa38d6fd9781",
|
||||||
|
"src/cbb_refresh_verify/com_runtime.py": "f0f3802d16c791a8bf9dfef44a94917072bfbe8fb3a927d76be8ef0341c7ed35",
|
||||||
|
"src/cbb_refresh_verify/content_check.py": "8239c17b6e2452917ed573a7deb3e4c8583eaef91bf3630eff5f424d2e398aa9",
|
||||||
|
"src/cbb_refresh_verify/defaults.py": "a1c03192f4a61ad0924b24bb635705b1ee4811d35483a02864200f95edbbebe3",
|
||||||
|
"src/cbb_refresh_verify/desktop_worker.py": "27d751816552d215dd8ee9cd67941d824f7b4493120ead7c3f87e5eba5ec4a92",
|
||||||
|
"src/cbb_refresh_verify/diagnostic_open.py": "d6c49ffe5a9969d95edbbc896d47a7e100f248380a287f99ba7bb8b92dbb3072",
|
||||||
|
"src/cbb_refresh_verify/dialog_agent.py": "5acb6e5cf1350a7ca20a6fe480668435fac785835874f266881973010db6504b",
|
||||||
|
"src/cbb_refresh_verify/dialog_models.py": "f68cee01d927b48364276d3c1f79e63ce8af231878db0b907d292780cfbafb56",
|
||||||
|
"src/cbb_refresh_verify/dialog_probe.py": "d61f0c955c961980c9635940eefb9c7947c1fe90b4b6fd844720df41ddb0aa0e",
|
||||||
|
"src/cbb_refresh_verify/dialog_rules.py": "3189b476f7ff4678b59212ed7b4081164e038a7cf7662cd895f9019cb3c1edc5",
|
||||||
|
"src/cbb_refresh_verify/dialog_supervisor.py": "15c415c2d2e916f0b64ba04416164ff3b50996d70b22d3b4ac2226b5547ac247",
|
||||||
|
"src/cbb_refresh_verify/failed_session.py": "7e6f7fa5ebcf2d49f00c5efc5f5d26412704b68e9122e476ac1f672009a98c09",
|
||||||
|
"src/cbb_refresh_verify/icdb_maintenance.py": "e81d253d8b4d3e7c1000c45335a392c72b110748675c2c3324ebe524a7252e98",
|
||||||
|
"src/cbb_refresh_verify/icdb_ownership.py": "7bf2342c1efa34a2ebcbf27964a40a490220f7146fbb6ef957b8d8dd1e511f03",
|
||||||
|
"src/cbb_refresh_verify/icdb_recovery.py": "358c0e9a004f1e0b2127513286e1dffd94b0180a8b7314aa9655462f570b6360",
|
||||||
|
"src/cbb_refresh_verify/integration.py": "f188856af69ba25e265988c51db7a6d4263326440d972ca78378b733b891c1ed",
|
||||||
|
"src/cbb_refresh_verify/library_lock.py": "6836ec8ac21e788eb75326ff44cb31ad4bdfb5f381bd35cdf33e6b34c7fca89e",
|
||||||
|
"src/cbb_refresh_verify/library_manager_verify.py": "71e16a8581ad44b646be78b480f9812d596a6d162b3eec03d078bf4ea4503195",
|
||||||
|
"src/cbb_refresh_verify/library_reader.py": "d4007caa361edd467773e49f721e02671d5a9bcb30741769a57349850b12c438",
|
||||||
|
"src/cbb_refresh_verify/maintenance_entry.py": "3b93c25f69d7a961facd8004e20e155a84cc18f06d57b741a9055786ed058990",
|
||||||
|
"src/cbb_refresh_verify/management.py": "7ead9bfffeb44201e44f73d9f039590f091e9a456982f2110dca8ec3695f8803",
|
||||||
|
"src/cbb_refresh_verify/management_transaction.py": "32c53caaead05d5db3a31d3e30721e65434e5837095dc0a7812f825603aa37a0",
|
||||||
|
"src/cbb_refresh_verify/mentor_adapter.py": "1fc8c98d5508120e03bf001a42dd3e0da7b165eb18c90f1aed83147d17db8638",
|
||||||
|
"src/cbb_refresh_verify/mentor_paths.py": "ba48c0003b3eacc88906497b2e43b299ca4536a9f7dae44bbacf6a6ec694c116",
|
||||||
|
"src/cbb_refresh_verify/models.py": "9e8209a8b006df923f1d07ccab64bbcfe5d674c4fc5f5426bfbc9b11da4ee105",
|
||||||
|
"src/cbb_refresh_verify/native_add_failures.py": "192202732423dc624c5548c75e80bb20973e5087c21d4798c9637f25b6de7e94",
|
||||||
|
"src/cbb_refresh_verify/native_backup.py": "7276fa3d9298e85550151cf0c7191d84bd08a18a72df5d854a3c38f1a88b001d",
|
||||||
|
"src/cbb_refresh_verify/native_engineering_identity.py": "8c0fc144707d68a9b85f6da50ef950f1f6e7fee248acbf34d19b707d51212be0",
|
||||||
|
"src/cbb_refresh_verify/native_export_guard.py": "523cdf44db8e1665634feadba963ccf26777dc8942fb2eb604d2c30bbe92cbb6",
|
||||||
|
"src/cbb_refresh_verify/native_management.py": "eb2ec311489eaf5deb06893a54a02469c9b2bb9baccbdd6563bae295aafcf363",
|
||||||
|
"src/cbb_refresh_verify/native_occupancy.py": "7d686079d12217382adace6361cd343d977b91075e3b157cf410ca92d07ffc49",
|
||||||
|
"src/cbb_refresh_verify/native_repair.py": "9f024dcb5e3a76369191033474fefd30787b6ae350c315f3cf38e92e5a1f3e98",
|
||||||
|
"src/cbb_refresh_verify/native_repair_ui.py": "3eb2af181befea94af8b3b3131edff09589f340bcba777abbe3b67fd31b80393",
|
||||||
|
"src/cbb_refresh_verify/network_path.py": "6b5b159502d42a46bf4ee26d5698fd2c6498b359088e2138eae46e9065b13c6f",
|
||||||
|
"src/cbb_refresh_verify/operation_lifecycle.py": "3838c5a501711d16f578c45ebbc6f960872b0c3ba6bbda9a597f994ef746cef6",
|
||||||
|
"src/cbb_refresh_verify/operation_queue.py": "a6932d8bc68ac436091f6d362557c66d274ec52d0f295a22f014a3396845c79f",
|
||||||
|
"src/cbb_refresh_verify/owner_probe.py": "8dcfd60246cb2979db34d02e0a2d605c334b6f7e2666f22daa2f50c0408bc903",
|
||||||
|
"src/cbb_refresh_verify/pcb_bridge.py": "2f6c2b09642100468814500569dbfc6695fc2a46b9a3b8333daa8e1530cdeef5",
|
||||||
|
"src/cbb_refresh_verify/pcb_open_consent.py": "59b6998afab074a98a1bf7eb0d05f2347ccb642b3b217e399ea856a5a8b1c56b",
|
||||||
|
"src/cbb_refresh_verify/pcb_restore_prompt.py": "39e0b8623a838911eff61066f3e9c8ede4364dbf73efc5a8994197ec72a96488",
|
||||||
|
"src/cbb_refresh_verify/post_repair_consent.py": "3b1eaff1db58fd311a9dbc5fdcd850911b04cc5afd4e747f70a62b721b8fafa4",
|
||||||
|
"src/cbb_refresh_verify/post_verify_diagnostics.py": "2442de485bc0d6a34c4b2d9b10bc5f323ea38f9ff66674119a50f5c6043bac63",
|
||||||
|
"src/cbb_refresh_verify/reimport_recovery.py": "ef148549751fa47518f5f2ca8f32ba25794ec5f22e0de545476ea33f89a3f0bf",
|
||||||
|
"src/cbb_refresh_verify/residual_sessions.py": "4ac500b33b209611d54eb496c6c30727ba159742d625431ceea84471a5fc3442",
|
||||||
|
"src/cbb_refresh_verify/runtime_logging.py": "44ac25430a89c5ffc9e48e88c227e88052f4c815365e8556f67918f3edaba39e",
|
||||||
|
"src/cbb_refresh_verify/runtime_timing.py": "c4ed4057b5000e0b86ccc7dd1fe2004d6e0dae29f397fec77b01ad41a81c6367",
|
||||||
|
"src/cbb_refresh_verify/save_verified_block.vbs": "926175562ef82bb2e732231dbc18d8a88059c7e6143c9f4e502cabfd0d170bcd",
|
||||||
|
"src/cbb_refresh_verify/scoped_manifest.py": "9318bf0f929d23c18466a25d83a4a9903822093c123aae10510061788c6d0ab7",
|
||||||
|
"src/cbb_refresh_verify/session_record.py": "2bc3cff365008864584138a4ff13538bb6b2f90d981e7d008a1300f9102c6e7e",
|
||||||
|
"src/cbb_refresh_verify/status_bridge.py": "05d627d02934a14f5de409472c291d37565a95b836f9c130111aae80612e9196",
|
||||||
|
"src/cbb_refresh_verify/verify_diagnostics.py": "041b77d7d49e4c86338ed5e5741d0d27a2c42bc358f4da54b3efe64af847e9b8",
|
||||||
|
"src/cbb_refresh_verify/verify_probe.py": "3ed743df49d195c74f5045985ab23491d103ee2c42c07b558c1e037176402ed2",
|
||||||
|
"src/cbb_refresh_verify/verify_runner.py": "3027ef7fc1ef6365ff36ae0c83389d869b92ffcd96985d10275bca4dc9483e3f",
|
||||||
|
"src/cbb_refresh_verify/write_admission.py": "0f8280912ec5c7af07a5f08b62a6b2cf7c95f93c745b443d0c7812d752558ce3",
|
||||||
|
"src/cbb_refresh_verify/__init__.py": "dd960394d88657820dba858792abf0de258e05efceb08ae2f0b39c6ad78bc469",
|
||||||
|
"src/cbb_refresh_verify/__main__.py": "dc4be034a0e43d4b659a9300137c29a6a6b7a32b7eaef02b6dff9a88c41305c0",
|
||||||
|
"src/cbb_refresh_verify/assets/cbb_refresh_verify.ico": "62d4472ebaa94f9b39aebae06459685d3322041d0e1a7ada9f368cfd816ba1d6",
|
||||||
|
"src/cbb_refresh_verify/assets/cbb_refresh_verify.png": "840f657fd7c622d9afd78625a64ed8ad04c90a895dd3c9fd37eebae543cdebe8",
|
||||||
|
"src/cbb_refresh_verify/assets/cbb_refresh_verify.svg": "cbba5b3f339cbeb5eb43012709237359442ef67c69fc5b6679a8ee4c0a1b7328",
|
||||||
|
"src/cbb_refresh_verify/assets/dialog_rules.v1.json": "3911080fc799a819662e225a7ad73e883abd8dcc9936cc30ec1b2d6d51a03c6e",
|
||||||
|
"src/cbb_refresh_verify/ui/backup_notice.py": "1a3fa5ac18a267907faf95f36d61b9f08bcbb939eef4d480dd06af1391a81599",
|
||||||
|
"src/cbb_refresh_verify/ui/backup_recovery_dialog.py": "be4796d664b8bc812244ced70f4cb616e433cef698813787f68d74408cd5cbbd",
|
||||||
|
"src/cbb_refresh_verify/ui/icdb_check_task.py": "ade3bf414aa29b42f4c1535c613b2cacb2735f6abc7900e6da25999390a5891d",
|
||||||
|
"src/cbb_refresh_verify/ui/main_window.py": "2c919badeeee0280e49387b88b058555a9fa6ace04835c094fccd782bf0af9c0",
|
||||||
|
"src/cbb_refresh_verify/ui/management_dialog.py": "8e2024957be874905685167c7eab440ecee9320170c1553340025b10fa1754d6",
|
||||||
|
"src/cbb_refresh_verify/ui/pcb_open_dialog.py": "3cabdc15f1b2abaeb919a7f29f32d4b053186701fd514646d9bdd3ea32f364f6",
|
||||||
|
"src/cbb_refresh_verify/ui/pcb_restore_dialog.py": "b7228d828df235ac51502dc68760d28c4896af02c780e9806e11c32dba7f62da",
|
||||||
|
"src/cbb_refresh_verify/ui/residual_release_dialog.py": "1d2a26bfc7ee21b11d7edbc3074b4c525e8c9fb628bca45b08bd06fc672586c8",
|
||||||
|
"src/cbb_refresh_verify/ui/workers.py": "4cc9360a4820ded27a7d5ef709fc9f04b1d4804cb1e7a614f6c357ed547da888",
|
||||||
|
"src/cbb_refresh_verify/ui/write_owner_dialog.py": "00c6091cc7d6109e41cdc3f9433b55c24725be444e440b894af21cbf751537c3",
|
||||||
|
"src/cbb_refresh_verify/ui/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
||||||
|
},
|
||||||
|
"tests_sha256": {
|
||||||
|
"tests/button_simulation.py": "3278868565853001103557d5f7ada42b11b05c03feb9032deed0327b6609de2b",
|
||||||
|
"tests/test_abnormal_shutdown.py": "0abdeaf51e2ffc3f771e09aefa9ec647a72b7f64757c9f3851926fbd392cbbcd",
|
||||||
|
"tests/test_all_buttons.py": "897ae449a15fe36fb6198a947575609346d5ce1a22c0a8c4d2950b9f00035d4f",
|
||||||
|
"tests/test_application.py": "bba12187fca6fee0f4f8862182bb40d939e2995016af2cdbb3fd756f6a99135d",
|
||||||
|
"tests/test_automation_license.py": "45e9c75d0d3e1a76f997f7da4cc87b5eb1b05a4ea2356408725742eac8a09ffb",
|
||||||
|
"tests/test_background_icdb.py": "df9bd9e8252e0dee4527dc6a740c0c33e76d1fb06a79b816cc15809d95716e44",
|
||||||
|
"tests/test_background_queue_regressions.py": "132866bfccc9a7ac5cb234f97aaf6a290e2e4ef949f31e2f70b0f3eafeb99046",
|
||||||
|
"tests/test_backup_recovery.py": "efd88c0c00440ac915b147c2e6dee8044ca805b03f90ab9f171cbde1db11cb9b",
|
||||||
|
"tests/test_backup_recovery_dialog.py": "b2f65864b861d95e99d5efb61ada915ae41973d2b49d08f2d536781997dd00cb",
|
||||||
|
"tests/test_batch_blockers.py": "4387293d3a5820fab630e3c5fe1b424f61ba6947773e5a61125d840433c5c62a",
|
||||||
|
"tests/test_batch_item_yield.py": "ed4be6d1e854b18d054a75c92171cd46b6b64411c2f74e9a3caf31fba3c7366b",
|
||||||
|
"tests/test_batch_status.py": "c1f9af0c7c6f3171b3726fb53346f480b13b8d9cd88111a9c12e2fae2392bbff",
|
||||||
|
"tests/test_batch_status_faults.py": "314e890c9aee439c8a75b4dfd605685240c74f6212da975fd50526bd70b4a0ff",
|
||||||
|
"tests/test_desktop_worker.py": "671d616f04a01d74508b328e3b6fc8f6c7191a91de0dcaa486aa98a3718353ff",
|
||||||
|
"tests/test_diagnostic_open.py": "b44f8f7b171602ad2691ea2e064ac9fe94f2fabb9fcc2eb6760cc1dd365b9423",
|
||||||
|
"tests/test_dialog_agent.py": "8c746e47d55637ca18d7cc998f324a0c2e0a5214dcfe8fcb6458c060619c211c",
|
||||||
|
"tests/test_dialog_models.py": "6902cf5c292458340fb48241b34875e111a0113d706cd82775934a7f72bab7b9",
|
||||||
|
"tests/test_dialog_probe.py": "55c98f6102957a27a96dcfd4f4bf3af499b5055225b77ef93b7b332dfd4ac472",
|
||||||
|
"tests/test_dialog_rules.py": "96bf36493da770679e9207e96b3088ef7f471aea22e17c254f33326ffef0d7f9",
|
||||||
|
"tests/test_dialog_startup_budget.py": "6f23c01836e4894ae82c3345a2383c4f8eb0517056c5b953c43100acd0fc3739",
|
||||||
|
"tests/test_dialog_supervisor.py": "4c1b00050127a65b0a8cf1c7a94fd673431ea3f04b76033a463804d0468ad2d9",
|
||||||
|
"tests/test_extended_safety.py": "7450816abba89aba1f4739f819f43631def82701fe07481279db2b3f3ed96cf6",
|
||||||
|
"tests/test_external_owner_release.py": "675ddbab4a97e86febac3003b9083c259295534941aa0463488a5a1206cfaf92",
|
||||||
|
"tests/test_failed_startup.py": "eca757ea46a4c0aa4fb0368ff53f26822af71612d251ecd87132686fe3c3794b",
|
||||||
|
"tests/test_failure_lifecycle.py": "dfeac56744a44e6f4c7898516749ca478f53d7c7f08b3843a05ef7f448c469a7",
|
||||||
|
"tests/test_icdb_address.py": "cbdc07e5043349c796a4ea1ce3d4989062094cd28929a9ef7d42c5ba75b77907",
|
||||||
|
"tests/test_icdb_batch_check.py": "e83982e0fd0b3744bdc62965b26970ded31aacfedea94283d9e321ef70a8232f",
|
||||||
|
"tests/test_icdb_open_check.py": "1f3750169755d0553bac3e0f8bec244038b84f9cd970e17c9f6eb67dee0e3dba",
|
||||||
|
"tests/test_icdb_recovery.py": "298ddac4b79b4400efc99ff27c58ca49fffea1f401a31071451b2fdaca59036e",
|
||||||
|
"tests/test_import_without_export_gate.py": "ae3dd0fb41c41773ce2d54aa9f9be83bbb56a0d09c59d600b10575fa8f0d2cd4",
|
||||||
|
"tests/test_incident_safety.py": "52f3ccb04db8971bf38628c2bd334d4fd79795e97de6538f6f66cb35f7123ece",
|
||||||
|
"tests/test_independent_operations.py": "4ba5798df3346bce74c3703c158f1dce1d1ba14df748606fcaf900c8568753e0",
|
||||||
|
"tests/test_integration.py": "9e9d30692607c889e1e3744a63c79c68e3af7d4c86804e0bcebe48e68765086c",
|
||||||
|
"tests/test_late_release_continuation.py": "34c62a628cbc08f4e8b9a1919c13f17772a2d26d1996fae34a35f814725b00e2",
|
||||||
|
"tests/test_library_lock.py": "3d65bd941faa441404045ce0140ea3ea5e58fb7d410b7b76bb9f03a9ea03d3af",
|
||||||
|
"tests/test_library_reader.py": "b39a1dc9d99c2463b744141e3c3489cd49ac4a637e7835559a9c3fe9cbafbb58",
|
||||||
|
"tests/test_lifecycle_supervision.py": "cfe29f1e73c6ef38d11e185e211b6e2fb60247f53a44e99dd1e2f8cf7a009faa",
|
||||||
|
"tests/test_maintenance_diagnosis.py": "0849aef555475a03b061eacf499f261fb75f2e727f35dba3cbceafac92e2a638",
|
||||||
|
"tests/test_maintenance_entry.py": "5ed3cda8e0c829fb2964e27f1bdc6fa8ee8dcde93ec63338959bf754b62d6a0b",
|
||||||
|
"tests/test_maintenance_owner_scope.py": "7cf64dc7f2b126684dcac6e619cbd87eca3d85ec2fc1f70f057154679dad6026",
|
||||||
|
"tests/test_maintenance_review.py": "ba807fd8c25c1b52cf2443d8bcf2f57539819715c0bc6c358d31d8542c2e7ce5",
|
||||||
|
"tests/test_maintenance_startup_gate.py": "4f69d33218483a658b51b2012ae8bfa83aff8a787152a38b19dadc4c0d3ffe36",
|
||||||
|
"tests/test_maintenance_ui.py": "2a640ba5e979a3fead81f0a38603b6105ffcb883dbb8484ccc42c99ee8c311db",
|
||||||
|
"tests/test_management.py": "cad0fb43eca9e7022a33a5e9ff0a408465b262fd304b146cdc85c28265f2e74f",
|
||||||
|
"tests/test_management_diagnostics.py": "671a9d7c112ededbee332db9b6fbab786fb37e9367d992f902f3ab2c9f60880b",
|
||||||
|
"tests/test_management_native_transaction.py": "7ca227aae6426c4d0d998edfd8620ec18905aaf212f0be20ceba97b1cde3a9a4",
|
||||||
|
"tests/test_management_probe_guards.py": "ae9be3dbd7c6a616478b7d4ea3498c428ff94a985089fe798463c5cab456f151",
|
||||||
|
"tests/test_management_retry_blockers.py": "124dbef291dbe331ba0c3e7de1665c910ea43e37b1563429b387f0f2233953ee",
|
||||||
|
"tests/test_management_source.py": "16e608ed9c8b0aa81cf08d49f165a33a1403c4ea7f2a5be44e8cfc8cb49850ad",
|
||||||
|
"tests/test_management_supervision.py": "2dcadd6551a94c52e5d4e74285959f10144a89c48af87e508abaea945652d1f6",
|
||||||
|
"tests/test_management_ui.py": "da3e2bc0b5c73926324a539edfa2f718ae1b585df96324a928a0c1a909e48083",
|
||||||
|
"tests/test_manual_backup_ui.py": "927e42ec4a1e0139c71a41b0cad1389ad47b0881381203c18b307cd2d137983a",
|
||||||
|
"tests/test_mentor_paths.py": "a05a91812a74b58e76f36d581216ee43969d2576b8a8e7d1cde3e301c52cf4c1",
|
||||||
|
"tests/test_native_add_failures.py": "ceedd60e030628b1af149d08d16216d5f7158a63686729bb357c148da86fb0ec",
|
||||||
|
"tests/test_native_backup.py": "43ec0c6b14b53864553feaf5d9fb498b37866f24edc486c0749160d3f803db5f",
|
||||||
|
"tests/test_native_engineering_identity.py": "a1adcf6883a9b55c2c37d9f491faf40dd4928f4d8db675419fd288dd31552c69",
|
||||||
|
"tests/test_native_export_guard.py": "f8ec4fa1058af55008e9628f79f2dc70b6e551f36815a812d10bfdf955cada51",
|
||||||
|
"tests/test_native_inspection_release_regressions.py": "8f7bb0b2b641d437872f1dd1d0c2547c2522c81e3c0351c31a7125f751d91927",
|
||||||
|
"tests/test_native_management.py": "badf33d4d00104c7e96e336777fb3e49690cc9db5ce1b071f98520aa5b6668f1",
|
||||||
|
"tests/test_native_management_fields.py": "9917ca0910e19bd809c86d0120c652145261528ace33c3b805f5663442c4a973",
|
||||||
|
"tests/test_native_occupancy.py": "56293dbe24bd3cd4f74cf8208e933faab7d737e5a5684a5d38838d063c3aef6d",
|
||||||
|
"tests/test_native_repair.py": "113185ced72d8f4f4eafca99054d97fe80a504d1c6cc91aaf86f55cea1b7e138",
|
||||||
|
"tests/test_navigation_tabs.py": "d7d5bbfc752f73c1b1d4615ffafc1266e772d96f3f3ba3d82c4b4baf678b292d",
|
||||||
|
"tests/test_network_path.py": "f52624391ae78e9b913dace2b1a9a2875a5855f86dc9e12c324ef493e6c7817b",
|
||||||
|
"tests/test_network_release_safety.py": "caef536d0a40b2eb848c1b8ab095ab374af247c03dd44acf8a70f0f500db6dac",
|
||||||
|
"tests/test_operation_lifecycle.py": "c0ce6c86b73021a8b162ae9e67a10aeec8a27a98e382fd82e1449a451a9a8c3c",
|
||||||
|
"tests/test_operation_queue.py": "8137528603f015695ed4d60a0c8fa8e7bf0a1c4659f8dc2a181291f5d500e6a1",
|
||||||
|
"tests/test_owner_probe.py": "deb757e022980f11ef48e57a2fd002ee3e90ec647a4666a0c4d4427313b6f725",
|
||||||
|
"tests/test_packaging.py": "87a6d04419775c0c5c806e0e569a48d7ef199a0bff8736b211443a1f471e7e8a",
|
||||||
|
"tests/test_packaging_status_bridge.py": "cbfaeac070a1494a1d8609fc25e9a779a63354c8914b4c6c57fdc7c31b70d472",
|
||||||
|
"tests/test_pcb_bridge.py": "527fb63147a203a2e9419da989aff600d3e461580989e39e8ede3a8cc57b901a",
|
||||||
|
"tests/test_pcb_open_consent.py": "5bf9ef6276d221b73ebe0dd14cff4fe5dc11bfec7b8be3266ae4a6b6a588d354",
|
||||||
|
"tests/test_pcb_restore_prompt.py": "a005691d0296587e520e20c4430e9e55227d767c8e910e950a9f2e93aeccb2c7",
|
||||||
|
"tests/test_pcb_version_choice.py": "0825c28333e4ed4f5a63847b6f5bb11143e922c7203d2770ce9c78fc8edec20f",
|
||||||
|
"tests/test_post_repair_consent.py": "bf417b378255386dc97ad8efdf5003b0691aa5d69da9d9256aa367dc16a2d4bb",
|
||||||
|
"tests/test_post_verify_diagnostics.py": "212857e56581998a3a3cd53635030b68a089fc4d630a8b0ee7ef3f137090dcc4",
|
||||||
|
"tests/test_private_desktop_discovery.py": "5361493313ae6864e252cdb9f2c72e71b39264a1c022beb4cf0c04c143cdd91e",
|
||||||
|
"tests/test_readonly_status_policy.py": "3ed40d7bdf2d3e6f70b38803b89a8b982336556444b45c6ba6b0a7c6df52a97f",
|
||||||
|
"tests/test_reimport_recovery.py": "875e5e2a0f6251ec5a251457848c7eac5dfd1674fcbb4745155f6d5d8bf4a4be",
|
||||||
|
"tests/test_residual_release_dialog.py": "10b23d009703d542e5ce8ecb35a4833e0135bb8852b4116e49eedc7010397a1e",
|
||||||
|
"tests/test_residual_sessions.py": "2c51ed1dc95a3afa7ebb24027963dfa9d13aba9c407e508e22ccc6e9f762dfeb",
|
||||||
|
"tests/test_review313_residual_isolation.py": "52a8024ed4e2a7fed219fe46cacdf76fa971166feedd557206716ef7f6d3c914",
|
||||||
|
"tests/test_review326_dispatch_and_receipts.py": "ce4d529246da1c4d53c3dec70ef49542165064404301dec3e32851df62492ecf",
|
||||||
|
"tests/test_review326_queue_guidance.py": "c2c97aceddd9713618afdd5f2a7be4764b56a1b62fc672282fb8c218b4969c74",
|
||||||
|
"tests/test_review345_ui_cli.py": "795e7e4f9bda8874c6a65a08863cab19f4adb3412287276ee2960588f0fd2fa8",
|
||||||
|
"tests/test_review348_release_comparison.py": "ceccdb3d6f7bc6cb65562c059f13aa2bc5d89d98c6f64b0f11d9b943ebbde165",
|
||||||
|
"tests/test_review381_queue_release.py": "e0d62424cbf70ec9573db78ede0a4c6534775399194eed4c6b28ba8d468307be",
|
||||||
|
"tests/test_review391.py": "304d46d63af87ea4a9bca83834b77cc44c5c9addf7b0f3752431304ee612568c",
|
||||||
|
"tests/test_review414_export_and_audit.py": "ec785c2656bed97de6c8467885f2ad0877b55ee872b02928744d399e8767d8a0",
|
||||||
|
"tests/test_review414_open_and_queue.py": "db065207dacaccd0bd80af52c1f1edaf36a278e7cf2dce7c9b44bc51dd0e1cec",
|
||||||
|
"tests/test_review414_write_admission.py": "b1b18fc69eeb9110baf3a7bb214938d5b8f681d7ad234991c92550210c8bf171",
|
||||||
|
"tests/test_review430.py": "7350f3883ddb9be48cc66fa7b0f612e1b45acf2298c80a7faa3da1f05d6d4c83",
|
||||||
|
"tests/test_review_319.py": "831fd34d426abb4436b9132bfb7ed754994155a34ac60a59378dee0964b54d28",
|
||||||
|
"tests/test_review_backend_followup.py": "2f3f51a72ecd05fc33c6b5a8dddaecfd12d2b50df423c87b4c18d1e52b2609bd",
|
||||||
|
"tests/test_review_foreign_release_evidence.py": "cbf2af02418f6bd3ec720a7a7658cf97f06d1a6e12009fdff2a99f465711591e",
|
||||||
|
"tests/test_review_management_ui_followup.py": "746602a84c3ba9cb041c5dd354b39d344355b71a3666b27a47eb9aee231e171c",
|
||||||
|
"tests/test_review_release_followup.py": "ab375f67e63cf3f33fa67ce19058be442c2ec56f810d4fc58ef5484272cbda49",
|
||||||
|
"tests/test_runtime_timing.py": "7152cd8fedfe165e769dadc1238c347d9f4d3e93cd57f6ed991e14d959e720f7",
|
||||||
|
"tests/test_safety.py": "ccf5febaf0a974d5e5357398a6946d3f121e07a6247c2f0dc5b71d86b39cac52",
|
||||||
|
"tests/test_save_helper_identity.py": "178a68c4a9a8c618dad3d8393e816dd1d2a16aef8d1fb9984117fe9dc8d06add",
|
||||||
|
"tests/test_save_helper_runtime.py": "00b092ec799da4bca424e1ee63a83bee783c81dbcdc20b7526fda8b45bb4b72a",
|
||||||
|
"tests/test_scan_isolation.py": "cab02bfe55ed515f889d3fcba6e6880344f482cc3a78a072b543b7a871cf92ab",
|
||||||
|
"tests/test_scoped_manifest.py": "fe9b2047d2c43812e851dd89ff250a2e5907dda89b3f5d9ae0a4dc4c5f452eac",
|
||||||
|
"tests/test_session_record.py": "6b51b19adfb232275195da7ff1ba91a5ce5e296f9424a7a1a29fc67ecfdfb108",
|
||||||
|
"tests/test_status_bridge.py": "fe1c0632d4d5fd5a1caf221903d4cfe38eda62aaa4298e3438735e31b8459ab2",
|
||||||
|
"tests/test_status_bridge_server.py": "7d8cd72d69afae0f96ebbd9bb3be2ae3c222f01108e45ab51a09e54d4d8527cc",
|
||||||
|
"tests/test_ui.py": "306a66698296a050744869b0756ddd0eefee5019618ff90b684da136a9787854",
|
||||||
|
"tests/test_ui_batch_safety.py": "12a8d82d4aedbeee315a02a49ec0e9888547ad4abd63e181e7f392b2a39e26dc",
|
||||||
|
"tests/test_ui_filters.py": "155e8f72d18c5c76b353d4b99f3828339c80908a9910f01641ba5c32a3929c75",
|
||||||
|
"tests/test_ui_lease_lifecycle.py": "18ea8af868373fa795a4911754be55068fe75833ce35579c1212fd7f4713f149",
|
||||||
|
"tests/test_verify_diagnostics.py": "b6431194e9f4c86a42110cac0d5f712c27b063f43b4ce820327aded81602908c",
|
||||||
|
"tests/test_verify_probe.py": "aeb65b5bd2df14e8a8f3ba5501855b5946e6f8a22f0d26960c00ff1b0daea56b",
|
||||||
|
"tests/test_verify_runner.py": "e58619f55873302c39129ce50e50fb25173a96ab309d975aa4f47f0bd3459fbb",
|
||||||
|
"tests/test_verify_worker_stability.py": "eae03400c2e3c8a0bc339c8dc05d890403c6bfb4c6d70d0361bc1b882b47d618"
|
||||||
|
},
|
||||||
|
"semantic_decision": "File-only identity failure remains RECOVERY_REQUIRED; native exit/resource proof governs independent continuation, and same-target replay remains prohibited.",
|
||||||
|
"merged": false,
|
||||||
|
"published": false,
|
||||||
|
"automatic_icdb_repair": false,
|
||||||
|
"limits": [
|
||||||
|
"Schematic semantic equivalence is not proven by import; UPLOADED is distinct from READY.",
|
||||||
|
"Other LibraryManager must be closed normally before native catalog activation; concurrent COM ownership remains unverified.",
|
||||||
|
"Windows 10, cross-machine SMB and field lost-server-session recovery remain unverified.",
|
||||||
|
"EDIF crash root cause remains undiagnosed; ordinary import does not invoke export."
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
# PR #13 后续评论 430
|
||||||
|
|
||||||
|
对应审查:https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/pulls/13#issuecomment-430
|
||||||
|
|
||||||
|
基准为本地 `fee4a67`。新 PR 同时包含 main `cbc5723` 后尚未推送的导入解耦和评论 414 修复。
|
||||||
|
本次为代码候选版,不更新云端 `v0.2.4-beta.2`,不启用自动 ICDB Repair。
|
||||||
|
|
||||||
|
## 三项语义处理
|
||||||
|
|
||||||
|
1. **文件身份不等于原生释放证明。** `capture_registration_identity` 只读文件,不创建原生进程。
|
||||||
|
原生注册及目录重新打开后,必须先确认其会话已退出,才进行文件核对。
|
||||||
|
文件核对异常仍返回该项 `RECOVERY_REQUIRED`,不能改报上传成功、READY,也不能自动重放该目标。
|
||||||
|
后续独立 CBB 可在自身写前检查通过后继续;不把文件读取异常伪装成“原生会话未释放”。
|
||||||
|
代码保留最后一次原生目录读取的退出证明,不再用文件采集对象的同名字段覆盖它。
|
||||||
|
原生释放未确认则拒绝文件采集,后续仍按已有释放证明流程处理。
|
||||||
|
2. **未执行与失败分开。** 无界面无法完成占用确认时返回 `SKIPPED`,保留原因码及“需通过界面确认”的说明。
|
||||||
|
备份替换在安装前跳过或取消,分别返回 `SKIPPED` / `CANCELLED`,界面显示“恢复已跳过” / “恢复已取消”。
|
||||||
|
安装后的失败仍按失败记录,不能被重新解释成未执行。真实占用、身份变化、检查失败仍拒绝操作。
|
||||||
|
3. **避免无等待时的重复探测。** 无未知原生客户端时只做一轮进程查询和资源探测。
|
||||||
|
只要进入未知客户端确认路径,返回后仍重新查询进程并探测资源;不会持有独占句柄等待用户选择。
|
||||||
|
|
||||||
|
整理了新增的确认模块及相关修改的空格、分行,并在 PCB 点击处写明已知取舍:
|
||||||
|
为避免 Mentor 自身的 sharing violation,先关闭独占探测句柄,再复核身份和点击。
|
||||||
|
两者之间仍有短暂竞态窗口,不能当作跨机器资源锁。
|
||||||
|
|
||||||
|
## 验证与复现
|
||||||
|
|
||||||
|
先复现错误再修改:新增 10 项用例中 7 项在旧代码上失败,3 项确认原有边界。
|
||||||
|
针对性 89 项、全量 1924 项通过。冻结包 66 个模块、资源及 PE 图标与源码一致。
|
||||||
|
私有桌面中实际恢复跳过后显示“恢复已跳过”,目标工程内容未变;
|
||||||
|
批量新增第一项 SKIPPED、第二项 UPLOADED,独立目录重新读取确认新增条目存在。
|
||||||
|
两个来源工程保持一致,程序退出码为 0。本轮未启用上传后自动 Verify,因此不声称 READY。
|
||||||
|
完整结果见相邻
|
||||||
|
`2026-11-16-review-430-validation.json`。
|
||||||
|
|
||||||
|
在 Windows Python 3.12、已安装项目依赖的干净工作树执行:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$env:PYTHONPATH = (Resolve-Path ./src).Path
|
||||||
|
python -X utf8 -m pytest -q tests --junitxml=full-suite.xml
|
||||||
|
python -X utf8 -m pytest -q tests/test_review430.py tests/test_review414_write_admission.py tests/test_import_without_export_gate.py tests/test_management_native_transaction.py tests/test_backup_recovery.py tests/test_backup_recovery_dialog.py
|
||||||
|
python -X utf8 -m compileall -q src tests
|
||||||
|
git diff --check
|
||||||
|
```
|
||||||
|
|
||||||
|
包含全局任务互斥的测试与实际 Mentor 试验串行执行。
|
||||||
|
验证 JSON 中列出的本机证据路径仅供本次审计,不作为其他机器可直接访问的下载路径。
|
||||||
|
未入库的 XML、进程记录、截图及冻结程序按文件散列关联;外发前需处理本机路径和工程名称。
|
||||||
|
|
||||||
|
## 产品与验收边界
|
||||||
|
|
||||||
|
正常导入确认原生注册、名称/分区、工程引用、允许的顶层块和 Layout;原生重写后的 ICDB 字节不作原理图语义等价证明。
|
||||||
|
`schematic_semantics_checked=False` 保持明确;上传成功不等于 READY,完整 Verify 为独立、可选步骤。
|
||||||
|
单项输入或可选 Verify 失败不阻止已释放的独立 CBB 继续,这与本轮用户确认的行为一致。
|
||||||
|
|
||||||
|
原生 COM 入口仍拒绝已有其他 LibraryManager 的情况,未冒险将其他客户端登记为本任务所有者;
|
||||||
|
用户可正常关闭相关会话再继续。EDIF 崩溃根因、Windows 10、跨机器 SMB 和现场服务器会话失联修复仍未验收。
|
||||||
|
本次实际按钮试验只操作隔离库及本任务创建的空会话,不关闭用户的其他程序。
|
||||||
|
|
||||||
|
## 回滚
|
||||||
|
|
||||||
|
通过 revert 新 PR 合入的提交回滚程序代码;云端旧发布包不受该 PR 自动影响。
|
||||||
|
程序回滚不会撤销用户已完成的库写入:根据逐项检查点与人工备份恢复,不自动重放管理任务。
|
||||||
@@ -0,0 +1,257 @@
|
|||||||
|
{
|
||||||
|
"schema_version": 1,
|
||||||
|
"created": "2026-11-16T14:36:55.137608+08:00",
|
||||||
|
"base_commit": "e4875b4eca1bc487514d479df15f2a4ac92df5e3",
|
||||||
|
"branch": "codex/unattended-prompt-defaults",
|
||||||
|
"full_suite": {
|
||||||
|
"path": "F:\\CbbUnattended-20261116\\full-final.xml",
|
||||||
|
"sha256": "8717cf87707b525a17eb2a3a292677360eade0d374e7d6eb42a6c2d07209d520",
|
||||||
|
"tests": 1937,
|
||||||
|
"failures": 0,
|
||||||
|
"errors": 0,
|
||||||
|
"skipped": 0
|
||||||
|
},
|
||||||
|
"red_original_no_timeout": {
|
||||||
|
"path": "F:\\CbbUnattended-20261116\\red.xml",
|
||||||
|
"sha256": "b0c46ca9c76ce41f9c9053ec94a08d416a3b18d775f3d9e3af1d469ac96b1225",
|
||||||
|
"tests": 3,
|
||||||
|
"failures": 3,
|
||||||
|
"errors": 0,
|
||||||
|
"skipped": 0
|
||||||
|
},
|
||||||
|
"button_and_prompt_integration": {
|
||||||
|
"path": "F:\\CbbUnattended-20261116\\integration-final.xml",
|
||||||
|
"sha256": "002f68c353fdf3a6e5eacfd2596df8b15f30a8a76ef3c262d2da3fc64e35a202",
|
||||||
|
"tests": 100,
|
||||||
|
"failures": 0,
|
||||||
|
"errors": 0,
|
||||||
|
"skipped": 0
|
||||||
|
},
|
||||||
|
"first_full_run": {
|
||||||
|
"path": "F:\\CbbUnattended-20261116\\full-suite.xml",
|
||||||
|
"sha256": "a6d2d5fe0d240ede5a90fff7b8f4c70635c12b82ef3423185c8ee975db17bf53",
|
||||||
|
"tests": 1935,
|
||||||
|
"failures": 6,
|
||||||
|
"errors": 2,
|
||||||
|
"skipped": 0
|
||||||
|
},
|
||||||
|
"first_full_run_explanation": "Four notification tests expected the old OK button; two recovery-summary paths recreated the Close button and invalidated countdown. Fixed redundant recreation and aligned notification clicks; failed evidence retained.",
|
||||||
|
"static_api_trial": {
|
||||||
|
"final_design": "Explicit QMessageBox object; no application event interception.",
|
||||||
|
"rejected": "Static Qt question interception caused timer ownership/slot errors in experiments; rejected and replaced before final integration."
|
||||||
|
},
|
||||||
|
"default_timeout_ms": 3000,
|
||||||
|
"defaults": {
|
||||||
|
"submitted_verify_check_management_recovery": "confirm",
|
||||||
|
"unknown_owner": "skip",
|
||||||
|
"uncertain_pcb_readwrite": "skip",
|
||||||
|
"version": "last_user_saved_if_enabled_else_cancel",
|
||||||
|
"native_cancel": "confirm",
|
||||||
|
"save_before_close": "save",
|
||||||
|
"force_terminate": "cancel",
|
||||||
|
"notification": "close"
|
||||||
|
},
|
||||||
|
"compileall_passed": true,
|
||||||
|
"diff_check_passed": true,
|
||||||
|
"independent_review": "Final read-only rereview found no remaining actionable issues.",
|
||||||
|
"files_sha256": {
|
||||||
|
"src/cbb_refresh_verify/application.py": "62b9b013563a216d020c8366cccb8f949b02afa72dc63c26940804441cc23057",
|
||||||
|
"src/cbb_refresh_verify/backup_recovery.py": "1d7ef08ef53ca7a0971cdacb0908d9bb06d067b06dc2329fa58722ce9068921d",
|
||||||
|
"src/cbb_refresh_verify/batch_status.py": "55a4007cf54491ca8e045a5bf86aa4353ac8437cca5a76cd79304962e3d3fa0a",
|
||||||
|
"src/cbb_refresh_verify/com_runtime.py": "f0f3802d16c791a8bf9dfef44a94917072bfbe8fb3a927d76be8ef0341c7ed35",
|
||||||
|
"src/cbb_refresh_verify/content_check.py": "8239c17b6e2452917ed573a7deb3e4c8583eaef91bf3630eff5f424d2e398aa9",
|
||||||
|
"src/cbb_refresh_verify/defaults.py": "a1c03192f4a61ad0924b24bb635705b1ee4811d35483a02864200f95edbbebe3",
|
||||||
|
"src/cbb_refresh_verify/desktop_worker.py": "27d751816552d215dd8ee9cd67941d824f7b4493120ead7c3f87e5eba5ec4a92",
|
||||||
|
"src/cbb_refresh_verify/diagnostic_open.py": "d6c49ffe5a9969d95edbbc896d47a7e100f248380a287f99ba7bb8b92dbb3072",
|
||||||
|
"src/cbb_refresh_verify/dialog_agent.py": "5acb6e5cf1350a7ca20a6fe480668435fac785835874f266881973010db6504b",
|
||||||
|
"src/cbb_refresh_verify/dialog_models.py": "f68cee01d927b48364276d3c1f79e63ce8af231878db0b907d292780cfbafb56",
|
||||||
|
"src/cbb_refresh_verify/dialog_probe.py": "d61f0c955c961980c9635940eefb9c7947c1fe90b4b6fd844720df41ddb0aa0e",
|
||||||
|
"src/cbb_refresh_verify/dialog_rules.py": "3189b476f7ff4678b59212ed7b4081164e038a7cf7662cd895f9019cb3c1edc5",
|
||||||
|
"src/cbb_refresh_verify/dialog_supervisor.py": "15c415c2d2e916f0b64ba04416164ff3b50996d70b22d3b4ac2226b5547ac247",
|
||||||
|
"src/cbb_refresh_verify/failed_session.py": "7e6f7fa5ebcf2d49f00c5efc5f5d26412704b68e9122e476ac1f672009a98c09",
|
||||||
|
"src/cbb_refresh_verify/icdb_maintenance.py": "e81d253d8b4d3e7c1000c45335a392c72b110748675c2c3324ebe524a7252e98",
|
||||||
|
"src/cbb_refresh_verify/icdb_ownership.py": "7bf2342c1efa34a2ebcbf27964a40a490220f7146fbb6ef957b8d8dd1e511f03",
|
||||||
|
"src/cbb_refresh_verify/icdb_recovery.py": "358c0e9a004f1e0b2127513286e1dffd94b0180a8b7314aa9655462f570b6360",
|
||||||
|
"src/cbb_refresh_verify/integration.py": "f188856af69ba25e265988c51db7a6d4263326440d972ca78378b733b891c1ed",
|
||||||
|
"src/cbb_refresh_verify/library_lock.py": "6836ec8ac21e788eb75326ff44cb31ad4bdfb5f381bd35cdf33e6b34c7fca89e",
|
||||||
|
"src/cbb_refresh_verify/library_manager_verify.py": "71e16a8581ad44b646be78b480f9812d596a6d162b3eec03d078bf4ea4503195",
|
||||||
|
"src/cbb_refresh_verify/library_reader.py": "d4007caa361edd467773e49f721e02671d5a9bcb30741769a57349850b12c438",
|
||||||
|
"src/cbb_refresh_verify/maintenance_entry.py": "3b93c25f69d7a961facd8004e20e155a84cc18f06d57b741a9055786ed058990",
|
||||||
|
"src/cbb_refresh_verify/management.py": "7ead9bfffeb44201e44f73d9f039590f091e9a456982f2110dca8ec3695f8803",
|
||||||
|
"src/cbb_refresh_verify/management_transaction.py": "32c53caaead05d5db3a31d3e30721e65434e5837095dc0a7812f825603aa37a0",
|
||||||
|
"src/cbb_refresh_verify/mentor_adapter.py": "1fc8c98d5508120e03bf001a42dd3e0da7b165eb18c90f1aed83147d17db8638",
|
||||||
|
"src/cbb_refresh_verify/mentor_paths.py": "ba48c0003b3eacc88906497b2e43b299ca4536a9f7dae44bbacf6a6ec694c116",
|
||||||
|
"src/cbb_refresh_verify/models.py": "9e8209a8b006df923f1d07ccab64bbcfe5d674c4fc5f5426bfbc9b11da4ee105",
|
||||||
|
"src/cbb_refresh_verify/native_add_failures.py": "192202732423dc624c5548c75e80bb20973e5087c21d4798c9637f25b6de7e94",
|
||||||
|
"src/cbb_refresh_verify/native_backup.py": "7276fa3d9298e85550151cf0c7191d84bd08a18a72df5d854a3c38f1a88b001d",
|
||||||
|
"src/cbb_refresh_verify/native_engineering_identity.py": "8c0fc144707d68a9b85f6da50ef950f1f6e7fee248acbf34d19b707d51212be0",
|
||||||
|
"src/cbb_refresh_verify/native_export_guard.py": "523cdf44db8e1665634feadba963ccf26777dc8942fb2eb604d2c30bbe92cbb6",
|
||||||
|
"src/cbb_refresh_verify/native_management.py": "eb2ec311489eaf5deb06893a54a02469c9b2bb9baccbdd6563bae295aafcf363",
|
||||||
|
"src/cbb_refresh_verify/native_occupancy.py": "7d686079d12217382adace6361cd343d977b91075e3b157cf410ca92d07ffc49",
|
||||||
|
"src/cbb_refresh_verify/native_repair.py": "9f024dcb5e3a76369191033474fefd30787b6ae350c315f3cf38e92e5a1f3e98",
|
||||||
|
"src/cbb_refresh_verify/native_repair_ui.py": "3eb2af181befea94af8b3b3131edff09589f340bcba777abbe3b67fd31b80393",
|
||||||
|
"src/cbb_refresh_verify/network_path.py": "6b5b159502d42a46bf4ee26d5698fd2c6498b359088e2138eae46e9065b13c6f",
|
||||||
|
"src/cbb_refresh_verify/operation_lifecycle.py": "3838c5a501711d16f578c45ebbc6f960872b0c3ba6bbda9a597f994ef746cef6",
|
||||||
|
"src/cbb_refresh_verify/operation_queue.py": "a6932d8bc68ac436091f6d362557c66d274ec52d0f295a22f014a3396845c79f",
|
||||||
|
"src/cbb_refresh_verify/owner_probe.py": "8dcfd60246cb2979db34d02e0a2d605c334b6f7e2666f22daa2f50c0408bc903",
|
||||||
|
"src/cbb_refresh_verify/pcb_bridge.py": "2f6c2b09642100468814500569dbfc6695fc2a46b9a3b8333daa8e1530cdeef5",
|
||||||
|
"src/cbb_refresh_verify/pcb_open_consent.py": "fd56dfe0b537408745127d80ea68cc59d3f333954af76bac7a7b324d66badc65",
|
||||||
|
"src/cbb_refresh_verify/pcb_restore_prompt.py": "a488ab48845173f463042c17ad1e719fe37a4bcf98a660f06453eef171b0e7bb",
|
||||||
|
"src/cbb_refresh_verify/post_repair_consent.py": "3b1eaff1db58fd311a9dbc5fdcd850911b04cc5afd4e747f70a62b721b8fafa4",
|
||||||
|
"src/cbb_refresh_verify/post_verify_diagnostics.py": "2442de485bc0d6a34c4b2d9b10bc5f323ea38f9ff66674119a50f5c6043bac63",
|
||||||
|
"src/cbb_refresh_verify/reimport_recovery.py": "ef148549751fa47518f5f2ca8f32ba25794ec5f22e0de545476ea33f89a3f0bf",
|
||||||
|
"src/cbb_refresh_verify/residual_sessions.py": "4ac500b33b209611d54eb496c6c30727ba159742d625431ceea84471a5fc3442",
|
||||||
|
"src/cbb_refresh_verify/runtime_logging.py": "44ac25430a89c5ffc9e48e88c227e88052f4c815365e8556f67918f3edaba39e",
|
||||||
|
"src/cbb_refresh_verify/runtime_timing.py": "c4ed4057b5000e0b86ccc7dd1fe2004d6e0dae29f397fec77b01ad41a81c6367",
|
||||||
|
"src/cbb_refresh_verify/scoped_manifest.py": "9318bf0f929d23c18466a25d83a4a9903822093c123aae10510061788c6d0ab7",
|
||||||
|
"src/cbb_refresh_verify/session_record.py": "2bc3cff365008864584138a4ff13538bb6b2f90d981e7d008a1300f9102c6e7e",
|
||||||
|
"src/cbb_refresh_verify/status_bridge.py": "05d627d02934a14f5de409472c291d37565a95b836f9c130111aae80612e9196",
|
||||||
|
"src/cbb_refresh_verify/verify_diagnostics.py": "041b77d7d49e4c86338ed5e5741d0d27a2c42bc358f4da54b3efe64af847e9b8",
|
||||||
|
"src/cbb_refresh_verify/verify_probe.py": "3ed743df49d195c74f5045985ab23491d103ee2c42c07b558c1e037176402ed2",
|
||||||
|
"src/cbb_refresh_verify/verify_runner.py": "3027ef7fc1ef6365ff36ae0c83389d869b92ffcd96985d10275bca4dc9483e3f",
|
||||||
|
"src/cbb_refresh_verify/write_admission.py": "c5f879bd5cb70a5dedfc64349c8758bf370daa4240491addd2aecd344f3a935c",
|
||||||
|
"src/cbb_refresh_verify/__init__.py": "75942b10cc5c09f19d5f31bedd0395361642336f52bc9e9872d8483e3b9882f9",
|
||||||
|
"src/cbb_refresh_verify/__main__.py": "dc4be034a0e43d4b659a9300137c29a6a6b7a32b7eaef02b6dff9a88c41305c0",
|
||||||
|
"src/cbb_refresh_verify/ui/backup_notice.py": "1a3fa5ac18a267907faf95f36d61b9f08bcbb939eef4d480dd06af1391a81599",
|
||||||
|
"src/cbb_refresh_verify/ui/backup_recovery_dialog.py": "8a80f584347f3fdefc089169894712746fee85f079b029578f008d6aecec8d90",
|
||||||
|
"src/cbb_refresh_verify/ui/icdb_check_task.py": "ade3bf414aa29b42f4c1535c613b2cacb2735f6abc7900e6da25999390a5891d",
|
||||||
|
"src/cbb_refresh_verify/ui/main_window.py": "f72062cb3d97cbd38f6390b9483e0f3aab619dec0bb2292c02d32b7fc5cd84b9",
|
||||||
|
"src/cbb_refresh_verify/ui/management_dialog.py": "57698f42112b120899dac26c40d2aafb4b5ba719660a302c0460361a7d50609a",
|
||||||
|
"src/cbb_refresh_verify/ui/pcb_open_dialog.py": "1b9689d555d221567263b6b587250b51a11bef276c35d64393e1b3d13803c625",
|
||||||
|
"src/cbb_refresh_verify/ui/pcb_restore_dialog.py": "11479db5520310af37824e083cb678d69d4cfd12f70dcd29ccb906b929e3d9bd",
|
||||||
|
"src/cbb_refresh_verify/ui/residual_release_dialog.py": "a0bdcc091778d508c43a6af96bd6423b25cd029c92b6bcff22d459d09a030d06",
|
||||||
|
"src/cbb_refresh_verify/ui/timed_prompt.py": "71db65febd0aff9117dcee42dde5151a7f13a3337794c77031cf5585f0397d97",
|
||||||
|
"src/cbb_refresh_verify/ui/workers.py": "4cc9360a4820ded27a7d5ef709fc9f04b1d4804cb1e7a614f6c357ed547da888",
|
||||||
|
"src/cbb_refresh_verify/ui/write_owner_dialog.py": "65dc3c8287f4ac5dc767797c13e192f6bd916f9051570a33a2b18f4f8334c3b3",
|
||||||
|
"src/cbb_refresh_verify/ui/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||||
|
"tests/button_simulation.py": "3278868565853001103557d5f7ada42b11b05c03feb9032deed0327b6609de2b",
|
||||||
|
"tests/test_abnormal_shutdown.py": "0abdeaf51e2ffc3f771e09aefa9ec647a72b7f64757c9f3851926fbd392cbbcd",
|
||||||
|
"tests/test_all_buttons.py": "a075cfdf3223b754be351db54844f94a8538519c38a12b1b575ec483c544d57c",
|
||||||
|
"tests/test_application.py": "bba12187fca6fee0f4f8862182bb40d939e2995016af2cdbb3fd756f6a99135d",
|
||||||
|
"tests/test_automation_license.py": "45e9c75d0d3e1a76f997f7da4cc87b5eb1b05a4ea2356408725742eac8a09ffb",
|
||||||
|
"tests/test_background_icdb.py": "df9bd9e8252e0dee4527dc6a740c0c33e76d1fb06a79b816cc15809d95716e44",
|
||||||
|
"tests/test_background_queue_regressions.py": "132866bfccc9a7ac5cb234f97aaf6a290e2e4ef949f31e2f70b0f3eafeb99046",
|
||||||
|
"tests/test_backup_recovery.py": "efd88c0c00440ac915b147c2e6dee8044ca805b03f90ab9f171cbde1db11cb9b",
|
||||||
|
"tests/test_backup_recovery_dialog.py": "24a120e45dee151bc71a2e1a05345936c5063bf0f57a277af02ef3a6bfd753f9",
|
||||||
|
"tests/test_batch_blockers.py": "4387293d3a5820fab630e3c5fe1b424f61ba6947773e5a61125d840433c5c62a",
|
||||||
|
"tests/test_batch_item_yield.py": "ed4be6d1e854b18d054a75c92171cd46b6b64411c2f74e9a3caf31fba3c7366b",
|
||||||
|
"tests/test_batch_status.py": "c1f9af0c7c6f3171b3726fb53346f480b13b8d9cd88111a9c12e2fae2392bbff",
|
||||||
|
"tests/test_batch_status_faults.py": "314e890c9aee439c8a75b4dfd605685240c74f6212da975fd50526bd70b4a0ff",
|
||||||
|
"tests/test_desktop_worker.py": "671d616f04a01d74508b328e3b6fc8f6c7191a91de0dcaa486aa98a3718353ff",
|
||||||
|
"tests/test_diagnostic_open.py": "b44f8f7b171602ad2691ea2e064ac9fe94f2fabb9fcc2eb6760cc1dd365b9423",
|
||||||
|
"tests/test_dialog_agent.py": "8c746e47d55637ca18d7cc998f324a0c2e0a5214dcfe8fcb6458c060619c211c",
|
||||||
|
"tests/test_dialog_models.py": "6902cf5c292458340fb48241b34875e111a0113d706cd82775934a7f72bab7b9",
|
||||||
|
"tests/test_dialog_probe.py": "55c98f6102957a27a96dcfd4f4bf3af499b5055225b77ef93b7b332dfd4ac472",
|
||||||
|
"tests/test_dialog_rules.py": "96bf36493da770679e9207e96b3088ef7f471aea22e17c254f33326ffef0d7f9",
|
||||||
|
"tests/test_dialog_startup_budget.py": "6f23c01836e4894ae82c3345a2383c4f8eb0517056c5b953c43100acd0fc3739",
|
||||||
|
"tests/test_dialog_supervisor.py": "4c1b00050127a65b0a8cf1c7a94fd673431ea3f04b76033a463804d0468ad2d9",
|
||||||
|
"tests/test_extended_safety.py": "7450816abba89aba1f4739f819f43631def82701fe07481279db2b3f3ed96cf6",
|
||||||
|
"tests/test_external_owner_release.py": "675ddbab4a97e86febac3003b9083c259295534941aa0463488a5a1206cfaf92",
|
||||||
|
"tests/test_failed_startup.py": "eca757ea46a4c0aa4fb0368ff53f26822af71612d251ecd87132686fe3c3794b",
|
||||||
|
"tests/test_failure_lifecycle.py": "dfeac56744a44e6f4c7898516749ca478f53d7c7f08b3843a05ef7f448c469a7",
|
||||||
|
"tests/test_icdb_address.py": "cbdc07e5043349c796a4ea1ce3d4989062094cd28929a9ef7d42c5ba75b77907",
|
||||||
|
"tests/test_icdb_batch_check.py": "79b4a8d9576449bde64f06bfd4d30b82ce6fe93e055c238eb1f239e75b472579",
|
||||||
|
"tests/test_icdb_open_check.py": "1f3750169755d0553bac3e0f8bec244038b84f9cd970e17c9f6eb67dee0e3dba",
|
||||||
|
"tests/test_icdb_recovery.py": "298ddac4b79b4400efc99ff27c58ca49fffea1f401a31071451b2fdaca59036e",
|
||||||
|
"tests/test_import_without_export_gate.py": "2f249412736cbe84f0c82db82403212739b7c53355f87cd053587ccdb722b175",
|
||||||
|
"tests/test_incident_safety.py": "52f3ccb04db8971bf38628c2bd334d4fd79795e97de6538f6f66cb35f7123ece",
|
||||||
|
"tests/test_independent_operations.py": "4ba5798df3346bce74c3703c158f1dce1d1ba14df748606fcaf900c8568753e0",
|
||||||
|
"tests/test_integration.py": "9e9d30692607c889e1e3744a63c79c68e3af7d4c86804e0bcebe48e68765086c",
|
||||||
|
"tests/test_late_release_continuation.py": "34c62a628cbc08f4e8b9a1919c13f17772a2d26d1996fae34a35f814725b00e2",
|
||||||
|
"tests/test_library_lock.py": "3d65bd941faa441404045ce0140ea3ea5e58fb7d410b7b76bb9f03a9ea03d3af",
|
||||||
|
"tests/test_library_reader.py": "b39a1dc9d99c2463b744141e3c3489cd49ac4a637e7835559a9c3fe9cbafbb58",
|
||||||
|
"tests/test_lifecycle_supervision.py": "cfe29f1e73c6ef38d11e185e211b6e2fb60247f53a44e99dd1e2f8cf7a009faa",
|
||||||
|
"tests/test_maintenance_diagnosis.py": "0849aef555475a03b061eacf499f261fb75f2e727f35dba3cbceafac92e2a638",
|
||||||
|
"tests/test_maintenance_entry.py": "5ed3cda8e0c829fb2964e27f1bdc6fa8ee8dcde93ec63338959bf754b62d6a0b",
|
||||||
|
"tests/test_maintenance_owner_scope.py": "7cf64dc7f2b126684dcac6e619cbd87eca3d85ec2fc1f70f057154679dad6026",
|
||||||
|
"tests/test_maintenance_review.py": "ba807fd8c25c1b52cf2443d8bcf2f57539819715c0bc6c358d31d8542c2e7ce5",
|
||||||
|
"tests/test_maintenance_startup_gate.py": "4f69d33218483a658b51b2012ae8bfa83aff8a787152a38b19dadc4c0d3ffe36",
|
||||||
|
"tests/test_maintenance_ui.py": "9c604714b0742503dbd55b243161a01f4ae62fa0cae7c4cddec7a2b8c81d07ab",
|
||||||
|
"tests/test_management.py": "cad0fb43eca9e7022a33a5e9ff0a408465b262fd304b146cdc85c28265f2e74f",
|
||||||
|
"tests/test_management_diagnostics.py": "671a9d7c112ededbee332db9b6fbab786fb37e9367d992f902f3ab2c9f60880b",
|
||||||
|
"tests/test_management_native_transaction.py": "7ca227aae6426c4d0d998edfd8620ec18905aaf212f0be20ceba97b1cde3a9a4",
|
||||||
|
"tests/test_management_probe_guards.py": "ae9be3dbd7c6a616478b7d4ea3498c428ff94a985089fe798463c5cab456f151",
|
||||||
|
"tests/test_management_retry_blockers.py": "124dbef291dbe331ba0c3e7de1665c910ea43e37b1563429b387f0f2233953ee",
|
||||||
|
"tests/test_management_source.py": "16e608ed9c8b0aa81cf08d49f165a33a1403c4ea7f2a5be44e8cfc8cb49850ad",
|
||||||
|
"tests/test_management_supervision.py": "2dcadd6551a94c52e5d4e74285959f10144a89c48af87e508abaea945652d1f6",
|
||||||
|
"tests/test_management_ui.py": "3d02dd00f20227aba6eeff40b9c49e34c93f81b02a02370fb0fa6848a1981413",
|
||||||
|
"tests/test_manual_backup_ui.py": "c1d3f7363a18ad3a690854d503199aa703c0a11ef937c933b025fd9b98083ed7",
|
||||||
|
"tests/test_mentor_paths.py": "a05a91812a74b58e76f36d581216ee43969d2576b8a8e7d1cde3e301c52cf4c1",
|
||||||
|
"tests/test_native_add_failures.py": "ceedd60e030628b1af149d08d16216d5f7158a63686729bb357c148da86fb0ec",
|
||||||
|
"tests/test_native_backup.py": "43ec0c6b14b53864553feaf5d9fb498b37866f24edc486c0749160d3f803db5f",
|
||||||
|
"tests/test_native_engineering_identity.py": "a1adcf6883a9b55c2c37d9f491faf40dd4928f4d8db675419fd288dd31552c69",
|
||||||
|
"tests/test_native_export_guard.py": "f8ec4fa1058af55008e9628f79f2dc70b6e551f36815a812d10bfdf955cada51",
|
||||||
|
"tests/test_native_inspection_release_regressions.py": "8f7bb0b2b641d437872f1dd1d0c2547c2522c81e3c0351c31a7125f751d91927",
|
||||||
|
"tests/test_native_management.py": "badf33d4d00104c7e96e336777fb3e49690cc9db5ce1b071f98520aa5b6668f1",
|
||||||
|
"tests/test_native_management_fields.py": "9917ca0910e19bd809c86d0120c652145261528ace33c3b805f5663442c4a973",
|
||||||
|
"tests/test_native_occupancy.py": "56293dbe24bd3cd4f74cf8208e933faab7d737e5a5684a5d38838d063c3aef6d",
|
||||||
|
"tests/test_native_repair.py": "113185ced72d8f4f4eafca99054d97fe80a504d1c6cc91aaf86f55cea1b7e138",
|
||||||
|
"tests/test_navigation_tabs.py": "d7d5bbfc752f73c1b1d4615ffafc1266e772d96f3f3ba3d82c4b4baf678b292d",
|
||||||
|
"tests/test_network_path.py": "f52624391ae78e9b913dace2b1a9a2875a5855f86dc9e12c324ef493e6c7817b",
|
||||||
|
"tests/test_network_release_safety.py": "caef536d0a40b2eb848c1b8ab095ab374af247c03dd44acf8a70f0f500db6dac",
|
||||||
|
"tests/test_operation_lifecycle.py": "c0ce6c86b73021a8b162ae9e67a10aeec8a27a98e382fd82e1449a451a9a8c3c",
|
||||||
|
"tests/test_operation_queue.py": "8137528603f015695ed4d60a0c8fa8e7bf0a1c4659f8dc2a181291f5d500e6a1",
|
||||||
|
"tests/test_owner_probe.py": "deb757e022980f11ef48e57a2fd002ee3e90ec647a4666a0c4d4427313b6f725",
|
||||||
|
"tests/test_packaging.py": "87a6d04419775c0c5c806e0e569a48d7ef199a0bff8736b211443a1f471e7e8a",
|
||||||
|
"tests/test_packaging_status_bridge.py": "cbfaeac070a1494a1d8609fc25e9a779a63354c8914b4c6c57fdc7c31b70d472",
|
||||||
|
"tests/test_pcb_bridge.py": "527fb63147a203a2e9419da989aff600d3e461580989e39e8ede3a8cc57b901a",
|
||||||
|
"tests/test_pcb_open_consent.py": "ec94b5b73790d7e0caf7140783e73e4a32a21b787f80a427e96fc7083f33535a",
|
||||||
|
"tests/test_pcb_restore_prompt.py": "a005691d0296587e520e20c4430e9e55227d767c8e910e950a9f2e93aeccb2c7",
|
||||||
|
"tests/test_pcb_version_choice.py": "0825c28333e4ed4f5a63847b6f5bb11143e922c7203d2770ce9c78fc8edec20f",
|
||||||
|
"tests/test_post_repair_consent.py": "bf417b378255386dc97ad8efdf5003b0691aa5d69da9d9256aa367dc16a2d4bb",
|
||||||
|
"tests/test_post_verify_diagnostics.py": "212857e56581998a3a3cd53635030b68a089fc4d630a8b0ee7ef3f137090dcc4",
|
||||||
|
"tests/test_private_desktop_discovery.py": "5361493313ae6864e252cdb9f2c72e71b39264a1c022beb4cf0c04c143cdd91e",
|
||||||
|
"tests/test_readonly_status_policy.py": "3ed40d7bdf2d3e6f70b38803b89a8b982336556444b45c6ba6b0a7c6df52a97f",
|
||||||
|
"tests/test_reimport_recovery.py": "2c0ecf52cd6c393f572c11b5d998a78ef538f7a277668cdc329a03e267074650",
|
||||||
|
"tests/test_residual_release_dialog.py": "1d5efa03cfe013770e2b81e1fcfb669142f5d6a07957110e56a3cc5eeb57c4a3",
|
||||||
|
"tests/test_residual_sessions.py": "2c51ed1dc95a3afa7ebb24027963dfa9d13aba9c407e508e22ccc6e9f762dfeb",
|
||||||
|
"tests/test_review313_residual_isolation.py": "52a8024ed4e2a7fed219fe46cacdf76fa971166feedd557206716ef7f6d3c914",
|
||||||
|
"tests/test_review326_dispatch_and_receipts.py": "ce4d529246da1c4d53c3dec70ef49542165064404301dec3e32851df62492ecf",
|
||||||
|
"tests/test_review326_queue_guidance.py": "305662f79251669685a618bdd35d524ef2b37eaece4428bb58ae4c5b65abb8ac",
|
||||||
|
"tests/test_review345_ui_cli.py": "795e7e4f9bda8874c6a65a08863cab19f4adb3412287276ee2960588f0fd2fa8",
|
||||||
|
"tests/test_review348_release_comparison.py": "ceccdb3d6f7bc6cb65562c059f13aa2bc5d89d98c6f64b0f11d9b943ebbde165",
|
||||||
|
"tests/test_review381_queue_release.py": "e0d62424cbf70ec9573db78ede0a4c6534775399194eed4c6b28ba8d468307be",
|
||||||
|
"tests/test_review391.py": "304d46d63af87ea4a9bca83834b77cc44c5c9addf7b0f3752431304ee612568c",
|
||||||
|
"tests/test_review414_export_and_audit.py": "ec785c2656bed97de6c8467885f2ad0877b55ee872b02928744d399e8767d8a0",
|
||||||
|
"tests/test_review414_open_and_queue.py": "db065207dacaccd0bd80af52c1f1edaf36a278e7cf2dce7c9b44bc51dd0e1cec",
|
||||||
|
"tests/test_review414_write_admission.py": "732a3683c2e27331cd5a9645e062e22613f848cac1a12745744fe249b48a9ffe",
|
||||||
|
"tests/test_review430.py": "7350f3883ddb9be48cc66fa7b0f612e1b45acf2298c80a7faa3da1f05d6d4c83",
|
||||||
|
"tests/test_review_319.py": "831fd34d426abb4436b9132bfb7ed754994155a34ac60a59378dee0964b54d28",
|
||||||
|
"tests/test_review_backend_followup.py": "2f3f51a72ecd05fc33c6b5a8dddaecfd12d2b50df423c87b4c18d1e52b2609bd",
|
||||||
|
"tests/test_review_foreign_release_evidence.py": "cbf2af02418f6bd3ec720a7a7658cf97f06d1a6e12009fdff2a99f465711591e",
|
||||||
|
"tests/test_review_management_ui_followup.py": "746602a84c3ba9cb041c5dd354b39d344355b71a3666b27a47eb9aee231e171c",
|
||||||
|
"tests/test_review_release_followup.py": "8779bde7aaaf59ecf362990afe1d9e7ed4ecb1f6fd7653c08bffbdc296200837",
|
||||||
|
"tests/test_runtime_timing.py": "7152cd8fedfe165e769dadc1238c347d9f4d3e93cd57f6ed991e14d959e720f7",
|
||||||
|
"tests/test_safety.py": "ccf5febaf0a974d5e5357398a6946d3f121e07a6247c2f0dc5b71d86b39cac52",
|
||||||
|
"tests/test_save_helper_identity.py": "178a68c4a9a8c618dad3d8393e816dd1d2a16aef8d1fb9984117fe9dc8d06add",
|
||||||
|
"tests/test_save_helper_runtime.py": "00b092ec799da4bca424e1ee63a83bee783c81dbcdc20b7526fda8b45bb4b72a",
|
||||||
|
"tests/test_scan_isolation.py": "cab02bfe55ed515f889d3fcba6e6880344f482cc3a78a072b543b7a871cf92ab",
|
||||||
|
"tests/test_scoped_manifest.py": "fe9b2047d2c43812e851dd89ff250a2e5907dda89b3f5d9ae0a4dc4c5f452eac",
|
||||||
|
"tests/test_session_record.py": "6b51b19adfb232275195da7ff1ba91a5ce5e296f9424a7a1a29fc67ecfdfb108",
|
||||||
|
"tests/test_status_bridge.py": "fe1c0632d4d5fd5a1caf221903d4cfe38eda62aaa4298e3438735e31b8459ab2",
|
||||||
|
"tests/test_status_bridge_server.py": "7d8cd72d69afae0f96ebbd9bb3be2ae3c222f01108e45ab51a09e54d4d8527cc",
|
||||||
|
"tests/test_ui.py": "ec0aad6d58b81a42129709b4cbeda9e754be48c6107a5b12384f75170c983463",
|
||||||
|
"tests/test_ui_batch_safety.py": "12a8d82d4aedbeee315a02a49ec0e9888547ad4abd63e181e7f392b2a39e26dc",
|
||||||
|
"tests/test_ui_filters.py": "d542e3d6fbc8cff64229b31ea8d0ed14ae0fe0c2c03b6a6eefed2f57dfbe77c9",
|
||||||
|
"tests/test_ui_lease_lifecycle.py": "18ea8af868373fa795a4911754be55068fe75833ce35579c1212fd7f4713f149",
|
||||||
|
"tests/test_unattended_prompts.py": "9dff94c678af95b796dfc068bb478de720547dad0b341a63195ca97710f2c4af",
|
||||||
|
"tests/test_verify_diagnostics.py": "b6431194e9f4c86a42110cac0d5f712c27b063f43b4ce820327aded81602908c",
|
||||||
|
"tests/test_verify_probe.py": "aeb65b5bd2df14e8a8f3ba5501855b5946e6f8a22f0d26960c00ff1b0daea56b",
|
||||||
|
"tests/test_verify_runner.py": "e58619f55873302c39129ce50e50fb25173a96ab309d975aa4f47f0bd3459fbb",
|
||||||
|
"tests/test_verify_worker_stability.py": "eae03400c2e3c8a0bc339c8dc05d890403c6bfb4c6d70d0361bc1b882b47d618",
|
||||||
|
"tests/support/runtime_lifecycle_frozen_boundaries.py": "bf98533a1c06ccf4453d20b3804323779719e697141b8dc64fa679960a979cfd",
|
||||||
|
"tests/support/runtime_lifecycle_frozen_fixture.py": "b87761c06a300f0d93bce864d3d31e045f2135324b2a9a42f8682ccbff09ad22",
|
||||||
|
"tests/support/runtime_lifecycle_frozen_smoke.py": "65b530d1e18b35918595eddc7cedeb31ff204cc785b1dc3c0d8c0b87f4aba0a5"
|
||||||
|
},
|
||||||
|
"production_logs_read": false,
|
||||||
|
"mentor_started": false,
|
||||||
|
"production_library_modified": false,
|
||||||
|
"published": false,
|
||||||
|
"automatic_icdb_repair": false,
|
||||||
|
"limits": [
|
||||||
|
"Only confirmation-message waiting is changed; global busy/queue/I-O locking design remains unresolved.",
|
||||||
|
"Native write, real occupancy and exact process/window checks still govern continuation.",
|
||||||
|
"Native Mentor unattended end-to-end, Windows 10 and cross-machine SMB not accepted.",
|
||||||
|
"File selection and configuration forms require valid input; unknown native prompts are not guessed."
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
# 无人值守弹窗默认动作
|
||||||
|
|
||||||
|
从 beta.3 主分支 `e4875b4` 开始的本地修改。此记录不是云端发布公告。
|
||||||
|
|
||||||
|
## 之前修复为何仍有阻塞
|
||||||
|
|
||||||
|
此前以局部失败案例逐处增加保护,未完整验证各层的组合。界面 busy、原生队列、库租约、历史检查点和会话释放共同决定能否继续;释放动作还可能等待被阻塞的同一队列。
|
||||||
|
“发生错误”“本任务仍占资源”“外部占用”“界面正在执行”几种状态未充分分开,导致恢复入口也被保护条件禁用。
|
||||||
|
单项失败后继续的用例通过,只覆盖了可返回的失败;没有覆盖首次读库带锁、取消、换库、释放及关闭的完整闭环。
|
||||||
|
|
||||||
|
本轮只消除确认弹窗无限等待,并给出明确默认动作;全局队列及锁的结构问题仍需单独修复。
|
||||||
|
|
||||||
|
## 默认动作
|
||||||
|
|
||||||
|
所有下列消息框显示倒计时,在可见且无人选择时 3 秒后执行指定默认动作。
|
||||||
|
手动选择、关闭窗口会停止本轮倒计时;不会在窗口消失后执行旧操作。
|
||||||
|
|
||||||
|
| 场景 | 默认动作 |
|
||||||
|
| --- | --- |
|
||||||
|
| 已点击执行的普通校验、ICDB 批量检查 | 确认开始 |
|
||||||
|
| 已预览并提交的新增、替换、移除 | 确认执行;原有逐项检查及人工备份提示仍在 |
|
||||||
|
| 已选择完整来源的备份恢复确认 | 确认执行;副本验证及安装前检查仍在 |
|
||||||
|
| 已明确请求的原生取消 | 确认发出原生取消请求 |
|
||||||
|
| 已进入释放流程的“关闭前保存” | 保存后关闭;不默认放弃未保存内容 |
|
||||||
|
| 未知原生客户端占用确认 | 跳过本项,不给未知客户端授予写入许可,不取消整批 |
|
||||||
|
| PCB 提示上次未正常关闭或仍被占用 | 跳过本项;实际释放成功后才能执行下一项 |
|
||||||
|
| 原生历史版本选择 | 沿用用户此前明确偏好的“最后手动保存”;该候选不可用时取消本项,不改选自动保存 |
|
||||||
|
| 强制结束客户端 | 取消,不自动强杀 |
|
||||||
|
| 结果通知、原生详情通知 | 关闭;记录仍保留 |
|
||||||
|
|
||||||
|
选文件及填写来源等配置窗口需要有效输入,不猜测工程路径。
|
||||||
|
未识别的原生弹窗不猜按钮,也不使用鼠标前台抢占。
|
||||||
|
|
||||||
|
## 证据与边界
|
||||||
|
|
||||||
|
OpenChoice / RestoreChoice 保留一次选择,新增 `decision_origin=user/timeout_default`;原生 PCB 选择记录与动作载荷写明来源。
|
||||||
|
未知客户端超时默认跳过,不生成“用户已确认无人使用”的许可;逐项结果保留超时原因。
|
||||||
|
所有原生身份、窗口按钮、地址记录、文件占用、保存和释放证明照常执行。
|
||||||
|
倒计时不会解除真实资源占用,也不代表 ICDB 已修复或工程 READY。
|
||||||
|
|
||||||
|
测试包括实际等待 3 秒、人工提前改选、首选版本不可用、窗口隐藏/关闭后计时失效、一次性决策以及选择来源。
|
||||||
|
测试不使用生产日志,不启动生产 Mentor 工程。
|
||||||
|
|
||||||
|
最终全量 1937 项、逐按钮及弹窗集成 100 项通过,编译及差异检查通过。
|
||||||
|
首轮全量发现通知框重复创建标准按钮导致计时对象失效,已删除重复创建;首轮失败证据保留。
|
||||||
|
完整散列和测试记录见 `2026-11-16-unattended-prompts-validation.json`。
|
||||||
|
当前仅本地源码提交,没有重新冻结、推送或更新生产发布包。
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
# Issue 15 acceptance matrix
|
||||||
|
|
||||||
|
Refs #15. The final grouped review wave is implemented at `c1e2596` (B14). The complete suite passed **2,418 tests in 594.83 seconds**, actual exit code 0, with zero failures, errors or skips. Actual B13 ordinary Verify/Stop with automatic candidate-owned cleanup and cross-owner queued Versions passed; actual B13 CBB recovery passed source and target verification. B14 preserves explicit ordinary release promotion of an existing cold observer; that narrow change has source/real-process coverage and updated frozen checks. Native cases retain B13 identities. The final scoped independent review passed for 32dcd80..8869093: I1-I3 addressed; zero Critical/Important/Minor findings. This is a technical review, not field acceptance or merge/release approval.
|
||||||
|
|
||||||
|
## Executable bindings
|
||||||
|
|
||||||
|
Each case retains its actual executable hash. Rebuilds checked all packaged modules/resources and repeated the affected operation plus common frozen smoke; earlier passes are not relabelled as tests of the newest executable.
|
||||||
|
|
||||||
|
| Build | Code commit | Executable SHA-256 |
|
||||||
|
|---|---|---|
|
||||||
|
| B1 | eaff46e | `24201dac278ea91fbc7f1b50146a10e024d4c4bf0da14ec5ecbeedbac65104a0` |
|
||||||
|
| B2 | fd50805 | `a75414653a399cfc76633cad25544d57749ab5a8b49ef227d0a0833f8828257f` |
|
||||||
|
| B3 | e0bb243 | `aae0039bfcdcb21ea3d25156920a4124a510a10ac499049604550eddc2ab7645` |
|
||||||
|
| B4 | de81bbf | `f87e403ee5a4891cff82649f5fef573cd304e5052aa3954faaaf43fd94b2ae88` |
|
||||||
|
| B5 | 4402486 | `b52b8689dc66cfccbf94d578a23de3021fc6857933d9bea38b77038c3711d721` |
|
||||||
|
| B6 | d5d1a3d | `f60e2eef44462f590ad81c94c0d2479cd017d519a7e176b34ee45258aae14690` |
|
||||||
|
| B7 | 845ae58 | `dcdcd33e7909c8d1d3b616ef722734f630ea2f793e7bd162e7e8e722978baf9b` |
|
||||||
|
| B8 | 7cc65f7 | `e1ba9e057d8147fcf451dd419d63660d507a29c96402b174f8824ed6a8ec159d` |
|
||||||
|
| B9 | a3f69de | `bfd6c122724f71a2aac4748ed01336a9949aa753f9c58aca55db574668140083` |
|
||||||
|
| B10 | 701e5cd | `a6271e4219a02123e301ed1e0ea3109e78307bf1f92574b4a5cacb70690695a4` |
|
||||||
|
| B11 | 8818fa9 | `03452e39f394c3c63113aaa701f64bacf14e817ae3b4e194965f333ecc645b98` |
|
||||||
|
| B12 | 906cfc0 | `7d7929d6621ae6c379205380e06f94eb076135343417d000018a8ab04efea8cc` |
|
||||||
|
| B13 | 5e9509e | `966e00fe57eccbdf4975c624026d39d24d4613f4174a932db248fb444a7caa9d` |
|
||||||
|
| B14 | c1e2596 | `0cd5f37b113802bcf3abd07a94d8c5b9f73d40696b1c56af66fedf39112e2d8c` |
|
||||||
|
|
||||||
|
B9 ZIP SHA-256: `4c589bae6bf7b68732cd7ebe373b2924016c71f6731fd661c1cd0fd848427438`. All 68 packaged modules and required assets/scripts/bridges/icons match the source; all 242 extracted files match the build. Its five pre-cancelled worker entry routes and common GUI/worker/owner-probe/dialog-agent smoke passed without launching Mentor. B8 is separately archived with ZIP SHA-256 `795010cc0b54b995eced859cac1513bf105092e484a44b1231955801deed879f`; B5 retains ZIP SHA-256 `176c7cda89c2a2706f969fa6dca513d2760615491aaf70c19fe7a0688abe471a`.
|
||||||
|
|
||||||
|
B10 ZIP SHA-256: `d4bd42416ea8d12a249ff1d9c8854eb76d2f81bb7ff869ff43dd92a331c647a0`; 68 modules/resources and 242 extracted files match, five pre-cancelled entries and common smoke passed. Only the residual-session module changed from B9. Earlier actual cases retain their original hashes.
|
||||||
|
|
||||||
|
B11 ZIP SHA-256: `34b3646b27afae22ec43a415ca19bbd32a91c0a4c941d37d6289c76cea9ca730`; the same module/resource/file checks, five cancelled entries and common smoke passed. Its only source-module change from B10 records each acknowledged Tip per cleanup intent. Immediate/delayed Tip states with/without prior Close passed focused source tests; no new actual Mentor Tip replay is claimed. The harmless real Win32 adapter probe belongs to the B10 source stage; its unchanged adapter preserves hidden MDI siblings and sends no action with an extra document.
|
||||||
|
|
||||||
|
B14 ZIP SHA-256: `a580e3e9945261761e0eb3968b4e271d9f4745ce982dea96c283af4ab06e565f`; 68 modules/resources, 242 extracted files, five cancelled entries and common smoke passed. B13 actual native cases retain their original hashes. B12 failed late ordinary cancellation remains archived with its exact identity.
|
||||||
|
|
||||||
|
## Reported issues A–H
|
||||||
|
|
||||||
|
| Issue | Source verification | Actual frozen evidence and limits |
|
||||||
|
|---|---|---|
|
||||||
|
| A: cancellation leaves startup prompts/clients | Exact ownership, known prompts, cooperative cancellation, admission and shutdown coverage; late Tip after first Close, held identity, delayed launcher, no second Close, unknown/document/progress/write negatives; single legacy release intent and observer proof. | **REPRODUCED on B5:** Stop 0.797 s after registered PCB startup returned CANCELLED/safe=false with a late Tip and retained PCB/launcher. Manual Tip OK alone completed the existing close; that remains a failure. B8/B9 automatic release and B9 one-confirmation legacy release passed separately, as detailed below. |
|
||||||
|
| B: another project's address blocks release | Scoped resources, exclusive Windows handles, fresh proofs and independent-item continuation. | B5 Release UI confirms zero active sessions and released library ownership. Earlier metadata handoffs and a separate bounded file-probe timeout remain failures; no native lock/address was manually deleted. |
|
||||||
|
| C: Versions conflicts with the parent's lease | Parent/child handoff, worker admission and reopening tests. | B1 official Repair, manual backup, exact-version restore, backup verification and reopening succeeded on the selected copied project. Tool exit alone was not counted as successful repair/restore. |
|
||||||
|
| D: historical records block unrelated/retried work | Legacy evidence is rechecked; a new confirmed operation requires fresh scoped release proof. | B3 corrected 8212 update succeeded in the same data root after the earlier failed operation. The original failed journal remained unchanged; later recovery and B operations continued. |
|
||||||
|
| E: optional LM dispatch returns without starting PCB | Bounded dispatch observation, exact target binding and owned-LM cleanup. | The direct native route passed. The exact optional-LM dispatch failure is **NOT REPRODUCED**; Windows 10 is **NOT RUN**. |
|
||||||
|
| F: Save finishes but library remains pending | Unique project/PCB binding, reference alignment and authoritative READY gate; Save/Close/exit/release are distinct. | B2 B-control first Verify remained PENDING and correctly failed; one explicit retry passed GREEN. B3 recovered 8212 source and installed target both passed GREEN. First-pass noncommit cause remains unconfirmed. |
|
||||||
|
| G: copied database is inconsistent | Diagnostic routing, manual recovery entry and error precedence; automatic Repair stays disabled. | B1 healthy-control Repair passed. Original complete fault-bearing field snapshot is unavailable: **NOT REPRODUCED**. Constructed-copy result is reported separately below. |
|
||||||
|
| H: selection/input/results/confirmation gaps | Real Qt controls, immutable requests, stale-view protection, one-shot defaults and large-table filters. | B1 basic controls/Add, B2 wrong-source rejection and concurrent view changes, B3 stop-after-current/recovery/removal/reimport, B4 restart without replay, and B5 diagnostic handoff/Release were exercised. Conditional controls are identified below. |
|
||||||
|
|
||||||
|
## Important native receipts
|
||||||
|
|
||||||
|
These identifiers locate retained local evidence; raw field files, private machine/user identifiers and production paths are not published.
|
||||||
|
|
||||||
|
| Build / operation | Receipt | Observed result |
|
||||||
|
|---|---|---|
|
||||||
|
| B1 duplicate A then independent B Add | management-c74c9a2b226e4df382be1447d2c9da95; management-4174be063d7843c69406e6610b4cc084 | Duplicate safely rejected; B UPLOADED with native registration/project/top/Layout confirmed. |
|
||||||
|
| B1 manual Repair / backup / restore / verify | native-backup-ed65d2630b3c | Actual native success output; uniquely described archive and restore location checked. Archive SHA-256 `429195ff63fd76e3586a348357009e4638c06d2d2c27c38e5cdee63f6966d26a`. |
|
||||||
|
| B1 Versions reopen | native-backup-de1ef77062a4 | Correct project/backup catalog; normal exit and release. |
|
||||||
|
| B2 fresh-source diagnostic with external observation | icdb-check-455c02cfba8f / verify-d67aa6df8758 | CHECKED/safe; 261 read-only snapshots show Forward Annotation prompt disappearing and loading progress ending before Close. No manual native action. |
|
||||||
|
| B2 B ordinary Verify | verify-491e77340ae2; verify-742c401bec4f | First FAIL/PENDING despite completed Save/Close/release; separate explicit retry PASS/GREEN with reusable-cell save confirmation. |
|
||||||
|
| B3 8212 update and actual stop during Add | management-78e5a9b3f24b4353b778a540c6f67e56 | Stop clicked during exact registered LM NATIVE_CALL. Current item completed Add, authoritative readback and release: UPLOADED/safe. |
|
||||||
|
| B3 CBB backup recovery | backup-restore-4c7aad5bd125 | Source verify-2c4769255397 and target verify-adad45363659 both PASS/GREEN; installed=true; old Work retained; both COMMITTED/CLOSED/EXITED/RELEASED. |
|
||||||
|
| B3 B remove and reimport | management-c156db77b0c449a0b0e034891aeaacff; management-15a95455d14541e4a47a3b4b2126c8a7 | REMOVED with authoritative catalog absence, then UPLOADED from the independent source. Auto-verify off. |
|
||||||
|
| B4 restart | restart-before-06 / restart-after-06 | Operation-root sets unchanged and no native process before explicit Read: no automatic replay. |
|
||||||
|
| B5 diagnostic intent/ack/Close | icdb-check-8683e232ce83 / verify-755f3af6b650 | CHECKED/safe, 38.437 s; exact intent/ack/Close identity and nonce match; intent precedes Close by 0.125 s. |
|
||||||
|
| B5 explicit Release | sessions-e4c27855ec69 | UI and durable RELEASE_CONFIRMED agree; zero active sessions, 7.704 s. Exact file-probe helper returned HELD and exited normally; read-only observation sent no target control action. |
|
||||||
|
| B5 early native Stop — original failure | icdb-check-63f7ee04d30b / verify-719b874e0aaf | Actual Stop 0.797 s after PCB registration, before loaded readiness: CANCELLED at PCB_STARTING, 31.875 s, safe=false, native clients retained. 894 read-only snapshots showed the late Tip. Manual exact Tip OK allowed both clients to exit with no further Close, Save, annotation or force action. |
|
||||||
|
| B6 early native Stop — loaded-target transition | icdb-check-762d0b790c2c / verify-67752f3332dd | Stop 0.813 s after PCB registration: Tip was automatically dismissed before any Close; target then loaded and showed Forward Annotation. CANCELLED/safe=false, 31.625 s; 892 read-only snapshots. Manual exact Forward No, then one normal target Close after progress ended, exited both clients without Save/annotation/force. This failure prompted the bounded cancelled-diagnostic loaded-target cleanup. |
|
||||||
|
| B7 late exit after bounded cleanup | icdb-check-ac97c21a1863 / verify-0a4f641d37d3; sessions-98a1beebfb10 | Automatic one Close and late Tip dismissal; native exit followed the original deadline. Original CANCELLED/safe=false remained. A later manual Release obtained fresh proof, so this did not establish automatic observer release. |
|
||||||
|
| B8 automatic cancellation and prequeued Versions | icdb-check-64348b7f55c5 / verify-505a4f09d4e7; native-backup-073e59195f9b | Versions queued after PCB registration and before Stop; UI terminal 7.125 s. Automatic Tip/Forward No/one Close, natural exit, existing observer RELEASE_CONFIRMED. Queued native client created 2.075 s after proof and catalog loaded. No Release click/manual diagnostic native action; original CANCELLED/safe=false retained. |
|
||||||
|
| B5-to-B8 legacy release — incomplete workflow | icdb-check-17661d31889d / verify-4b7bc47b39f8; sessions-12c1715f5d7f, sessions-38ed41c344f8, sessions-2cca647d90da | Initial inspection handed off before a plan; Recheck succeeded. First confirmation declined Forward but did not close; second closed PCB/launcher while server remained; third obtained fresh proof. No manual native action, but multiple confirmations were required: not accepted as the intended final workflow. |
|
||||||
|
| B9 automatic cancellation and prequeued Versions | icdb-check-b05147dc18bc / verify-3abaddb3e141; native-backup-005da267ebfe | Versions queued before Stop/handoff; UI terminal 6.672 s. Automatic Tip/Forward No/one Close; 307 read-only snapshots and kernel exit. Existing observer obtained fresh library RELEASE_CONFIRMED; queued native client created 1.684 s later and catalog loaded. Zero Release clicks/manual diagnostic native actions. Original CANCELLED/safe=false retained; backend duration 12.829 s is distinct from UI timing. |
|
||||||
|
| B5-to-B9 legacy release — one confirmation | icdb-check-378044ad1122 / verify-d2acda2739c2; sessions-a5a9fe06b7c1 | Real B5 retained loaded target/Forward; old app normally exited. B9 initial inspection succeeded, one normal Confirm, zero Recheck/second confirmation/manual native actions. Forward disappeared after 3.562 s; 210 read-only snapshots show kernel exit. PCB, launcher and server RELEASED, fresh RELEASE_CONFIRMED at 22.634 s; UI agreed and Confirm disabled. Existing cold observer RELEASED; original cancellation result retained. |
|
||||||
|
| B10 I3 setup — second pending item | management-f25df6a207ca4744ab4a0c23ddabb06c | Legitimate exact-name update from the existing healthy source, auto-verify off; UPLOADED/safe, native catalog/readback. Prepared two pending items without fabricated native failure. Selection made before final refresh was cleared; disabled Verify rejected the harness click; reselection afterward succeeded. |
|
||||||
|
| B10 ordinary Stop — historical failure | verify-e464474b7bab; batch-20261117-105152-c3e162 | Actual Stop 0.547 s after PCB registration, no Save evidence: first CANCELLED/safe=false, 29.766 s; second SKIPPED with no native job. Later loaded Forward remained. Exact manual No, no-modal/no-progress check and one normal Close required; sessions-4aadbacb8a93 then fresh release. Not unattended PASS; ordinary cleanup does not have diagnostic-only authority. |
|
||||||
|
| B10 actual Continue, no replay | button-watch-1794884270925407000; verify-f673ac48f600 | Existing summary's three-second Close elapsed before inspection. After main-window Release proof and normal dialog close, production code recreated Continue. Actual button click started only the previously skipped second item, which passed GREEN/safe. First terminal result predates the click and no first-item job was replayed. No in-process method/result injection. |
|
||||||
|
| B10 actual result Release | button-watch-1794884430968047900; verify-4f959f61fbc4 | One bounded same-scenario timing repeat caught actual result Release and opened its residual plan. Ordinary Stop again retained Forward, 32.844 s; this remains a failure. Exact manual No/normal Close, no Save/force; sessions-6bfdf0a26476 fresh release. |
|
||||||
|
| B5-to-B10 affected legacy release | icdb-check-92a3c92f6d6c / verify-9f3856153c79; sessions-82cc60b6eacb | Initial inspection succeeded; one Confirm, zero Recheck/manual native actions. Forward disappeared +6.5 s; 278 read-only samples/kernel exit. Intermediate PARTIAL then fresh RELEASE_CONFIRMED +35.387 s under the same intent; all three clients and existing observer RELEASED, UI agreed. Original CANCELLED/safe=false preserved. Entry was loaded Forward; actual Tip replay is not claimed. |
|
||||||
|
| B12 ordinary Stop — late loaded failure | verify-642171759614 | UI terminal 7.797 s; loaded Forward at 34.406 s after original cleanup deadline. Manual exact No/normal Close required. Failed-run cleanup only; original CANCELLED/safe=false preserved. |
|
||||||
|
| B13 ordinary Stop / cross-owner queue | verify-71aee0603183; native-backup-b63e7f708fd5 | Actual candidate worker No/one Close before first 30 s deadline; late kernel exit and fresh candidate/independent proofs. UI terminal 7.375 s; real Versions creation 5.220 s after candidate proof and 1.506 s after independent proof, catalog loaded. No Release/manual ordinary native action. Retained-phase No/Close branch not replayed in Mentor. |
|
||||||
|
| B13 CBB backup recovery | backup-restore-3f98efb14448; source verify-06c8149375e6; target verify-f902921f2440 | Both PASS/GREEN/safe and COMMITTED/CLOSED/EXITED/RELEASED, installed=true; old Work retained, all 366 original source files unchanged, no native intervention. |
|
||||||
|
|
||||||
|
The B2 diagnostic run supports the implemented sole-handler No sequence through observed windows and verified code; there is no separate startup button acknowledgement event. The hidden-owner-chain save branch did not recur on corrected native runs and remains covered by regression tests plus the original captured chain. The original failed diagnostic required manual cleanup and a native crash acknowledgement; that crash was **NOT REPRODUCED** in the subsequent bounded runs.
|
||||||
|
|
||||||
|
## Buttons and misuse scenarios
|
||||||
|
|
||||||
|
| Controls / scenario | Source coverage | Frozen coverage |
|
||||||
|
|---|---|---|
|
||||||
|
| Tabs, advanced options, optional LM checkbox, runtime log toggle | Actual source UI and Qt tests | B1 actual navigation/toggles. |
|
||||||
|
| Library chooser Open/Cancel and Read CBB | Actual chooser/catalog; invalid-input tests | B1 chooser cancellation and catalog; B3 removal/reimport catalog; B4/B5 explicit reload. |
|
||||||
|
| Select visible, Clear, filter/hidden selection | Actual UI and 381/3,000-row Qt checks | B1/B2 actual controls and view changes; immutable original operation retained. |
|
||||||
|
| Verify selected / visible non-READY | Actual source native verification and Qt admission | B2 ordinary Verify; B3/B13 recovery target verification; B13 actual ordinary Stop and automatic release. READY exclusion remains enforced. |
|
||||||
|
| ICDB batch confirmation No/Yes and stop | Actual source checks; Qt stop/continuation | B1/B2 confirmation cancellation and diagnostic runs; B5 acknowledged close; B8/B9 actual startup Stop and automatic queued continuation. Other cancellation timing remains conditional. |
|
||||||
|
| Manual Repair Cancel/Confirm | Actual native healthy control | B1 native diagnostics/defragmentation; not field-fault recovery proof. |
|
||||||
|
| Versions / create backup / restore Cancel/Confirm / verify / Close/reopen | Actual exact archive and location | B1 native tool operations and reopening. |
|
||||||
|
| Add / source chooser / empty input / auto-verify / logs / No/default Yes | Actual source and Qt | B1 duplicate-plus-independent Add; B3 reimport. |
|
||||||
|
| Same-name update / wrong source / reselection / No/default Yes | Actual source and Qt | B2 mismatch rejected before writing; B3 correct update. |
|
||||||
|
| Remove / hidden source chooser / No/Yes / result | Actual source and Qt | B3 REMOVED and native catalog absence before reimport. |
|
||||||
|
| CBB backup recovery / empty input / chooser Cancel / No/Yes | Actual source and Qt | B3 original controls/full sequence; B13 full serial metadata/source-validation/install/target-validation sequence. |
|
||||||
|
| Management stop-after-current | Two-item Qt/real admission tests verify next item skipped, including failed readback and unknown release | B3 stop during native Add; mandatory current-item readback completed. |
|
||||||
|
| Queued cancellation / active dialog close | Qt queue, close, hard-cancel and shutdown tests | B10 recovery dialog queued behind an owned diagnostic, Cancel queued clicked, UI CANCELLED/no native admission/no recovery job. Underlying diagnostic verify-96d285ffa450 completed CHECKED/safe. Earlier second management submission/active lower Close remained disabled. |
|
||||||
|
| Residual sessions / Recheck / Confirm / Close | Qt exact scope, one-intent observer promotion and real Windows proofs | B5 zero-active-session release; B9 initial inspection and one-confirmation release of a real B5 cancelled session; previous failed/multiple confirmations retained. |
|
||||||
|
| Native details / Save prompt / native Cancel / forced termination | Qt exact ownership/prompt and default-Cancel tests | Disabled with no matching active owned client. No forced native termination claimed. |
|
||||||
|
| Conditional result recovery/release/resume buttons | Qt target binding, stale results and single continuation | B10 actual result Release and Continue/no-replay receipts above. B10 ordinary retained startup required manual cleanup; B13 automatic ordinary Stop acceptance is recorded separately below. Other fault-dependent recovery branches are not blanket passed. |
|
||||||
|
| Three-second defaults / manual-vs-deadline / hidden or closed prompts | One-shot Qt timer tests | Actual management/recovery No and timed Yes; full timing competition covered in Qt. |
|
||||||
|
| Double submission / result remaining open / view changes / restart | Qt and Windows lifecycle tests | Active execute controls disabled; modeless dialogs and view changes observed; B4 no replay. |
|
||||||
|
| Open logs/evidence / shell errors | Qt dispatch and error reporting | B10 actual Open logs/Open exception clicks opened exact application logs and verify-e464474b7bab folders; complete private Explorer breadcrumbs recorded. Only the two task-created Explorer windows normally closed. No shell-error case is claimed. |
|
||||||
|
|
||||||
|
One B1 harness edit targeted the library textbox while a modeless dialog changed control indices. The immutable original-library operation still completed and the changed view was invalidated. This is retained as a harness/misuse event, not a product search failure.
|
||||||
|
|
||||||
|
## Final-wave evidence and limits
|
||||||
|
|
||||||
|
B14 EXE SHA-256: `0cd5f37b113802bcf3abd07a94d8c5b9f73d40696b1c56af66fedf39112e2d8c`. ZIP SHA-256: `a580e3e9945261761e0eb3968b4e271d9f4745ce982dea96c283af4ab06e565f`. All 68 packaged product modules/resources and all 242 extracted files match source/build. Five pre-cancelled frozen routes and common GUI/worker/owner-probe/dialog-agent smoke passed. Full-suite log SHA-256: `d9c57b7998e02154fb703f0fe2ba1f37f73dc4687d116c4b6efc0e5ad7e5c30e`; JUnit SHA-256: `4303cc123e90689103cc4135e483ac936b04a052067e952a1861ae167c7811ea`. Native clients and writer/management mutexes were idle before and after the full suite.
|
||||||
|
|
||||||
|
B13 (`5e9509e`) retains EXE `966e00fe57eccbdf4975c624026d39d24d4613f4174a932db248fb444a7caa9d` and ZIP `7a1da94e05b85873f791cde77907bdc280106768fbf84e5d89066ab8aa57a61b`. A final self-audit found that the new ordinary explicit-release branch bypassed existing cold-observer promotion. Its focused test failed before the two-line ordering correction at `c1e2596`; 110 related tests then passed in 21.96 seconds, including actual harmless worker exit, cold-observer promotion and queue proof. The in-progress B13 full suite was interrupted through its own execution session before editing, and is archived without a completion/JUnit claim. No additional native matrix was run for this narrow B14 delta.
|
||||||
|
|
||||||
|
The three review defects had retained RED evidence: actual MainWindow subprocess exit hung on stalled hash/copy/validation; real recovery callers held the unrelated native channel and could install after abandoned metadata; ordinary cancelled startup failed to clean a later loaded target. B13 related observer coverage passed 232 tests in 34.81 seconds, including an actual two-process mutex/file race between observer and explicit release plus a process restart. These race tests stub the native evidence/action boundary; they are not Mentor window tests.
|
||||||
|
|
||||||
|
B12 (`906cfc0`, EXE `7d7929d6621ae6c379205380e06f94eb076135343417d000018a8ab04efea8cc`, ZIP `bbe68005469d8b6cf87726200ef85646e442de45d164ab2ac0aec23b51d0bd65`) retained a new failure: ordinary `verify-642171759614` returned its visible cancellation terminal state in 7.797 seconds, but Forward loaded at 34.406 seconds, after the worker cleanup budget. Exact manual No/normal Close was used solely to clear that failed run. A later independent queue-helper attempt was refused with sharing violation 32 before native creation while two releasing observers raced for the coordination lease. Both failures are archived and are not relabelled as B13 passes.
|
||||||
|
|
||||||
|
B13 ordinary `verify-71aee0603183` reached the visible terminal state in 7.375 seconds. Its candidate worker acknowledged Tip at 21.359 seconds, Forward No at 27.422 seconds and one Close at 28.750 seconds; native exit followed the original cleanup deadline. Read-only sampling confirmed kernel exit. The original result remains CANCELLED/safe=false. No Release click or manual ordinary native action occurred. The helper stayed observe-only until the actual candidate produced fresh RELEASED proof, then obtained its own independent fresh proof. Its prequeued real Versions client `native-backup-b63e7f708fd5` was created 5.220 seconds after the candidate proof and 1.506 seconds after the independent proof, loaded the backup catalog and closed normally. This is **cross-owner queue acceptance**, using source-hash-pinned production queue/observer/native-worker modules; it is not survival of work in the same app after global Stop. The candidate itself performed every ordinary No/Close action.
|
||||||
|
|
||||||
|
The B13 native run issued Close within the first worker budget, so the new retained-phase No/Close branch was **NOT REPLAYED in Mentor**. That branch has source guard, real process race/restart and existing real Win32 adapter evidence. No repeated cold-start attempts were used to manufacture a slower launch.
|
||||||
|
|
||||||
|
B13 actual recovery `backup-restore-3f98efb14448` used the current pending original target and healthy independent source A. Its isolated source and installed target both returned PASS/GREEN/safe; native save/close/release completed without intervention. The old Work directory is retained and all 366 original source files are unchanged. The 27,689-file complete validation library copy progressed through the serial metadata path without a false inactivity handoff.
|
||||||
|
|
||||||
|
Separate frozen metadata-exit harness EXE SHA-256: `7490be1988d823944307510f7cfd22c85cf8570c7c25f6ee60d97f542bb72753`. All 68 packaged product modules equal final B14. A disposable I/O stall at each of hash/copy/validation exercised actual MainWindow close and interpreter exit before releasing the stall; no late dispatch occurred and partial copies were retained. This uses an acceptance-only entry, **not stall injection into the candidate EXE**. The earlier B12/B13 harnesses and all RED/setup attempts remain archived.
|
||||||
|
|
||||||
|
The original complete fault-bearing field snapshot remains unavailable (**NOT REPRODUCED**); the constructed partial copy remains **COPY_BLOCKED** and was never opened. Windows 10 and production SMB remain **NOT RUN**. The earlier first-pass B-control PENDING result and explicit retry remain separate outcomes. No merge, publication or issue closure is performed.
|
||||||
|
|
||||||
|
## Constructed copy and remaining limits
|
||||||
|
|
||||||
|
Constructed-copy experiment: **COPY_BLOCKED; inconsistency NOT REPRODUCED** (1 attempt, maximum 3). The healthy control passed normal native Verify. On a separate disposable copy, the documented native property write and stock Save actually ran; ordinary Work copying encountered Windows sharing violation 32 at the 113th attempted file, database/icdb.dat, after 0.470 seconds. The source still completed Save/Close and authoritative PASS/GREEN with released resources. The partial clone was never opened and no native Repair claim is made for it. This fault-creation instrumentation did not modify the frozen product and does not reproduce the original field incident.
|
||||||
|
|
||||||
|
The original field inconsistency remains **NOT REPRODUCED**. Windows 10 and production SMB/network behavior are **NOT RUN**. Initial B-control PENDING results, diagnostic/manual-cleanup failures, metadata handoffs and the bounded file-probe timeout remain visible in the evidence. This report does not authorize merging, release publication or issue closure.
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
# Issue 15 runtime and recovery candidate
|
||||||
|
|
||||||
|
Refs #15. This candidate records local Windows 11 acceptance and its limits; it is not a published release or field-acceptance approval.
|
||||||
|
|
||||||
|
The final grouped review wave is implemented at `c1e2596` (B14). The complete suite passed **2,418 tests in 594.83 seconds**, actual exit code 0, with zero failures, errors or skips. Actual B13 ordinary Verify/Stop with automatic candidate-owned cleanup and cross-owner queued Versions passed; actual B13 CBB recovery passed source and target verification. B14 preserves explicit ordinary release promotion of an existing cold observer; that narrow change has source/real-process coverage and updated frozen checks. Native cases retain B13 identities. The final scoped independent review passed for 32dcd80..8869093: I1-I3 addressed; zero Critical/Important/Minor findings. This is a technical review, not field acceptance or merge/release approval.
|
||||||
|
|
||||||
|
The PR base is main at e4875b4. The branch also includes the previously approved efb8cae three-second confirmation defaults.
|
||||||
|
|
||||||
|
The change separates native task execution, client exit, coordination-lease release, data recovery and eligibility for the next write. A completed independent item no longer inherits another project's address or a stale historical blocker. Unknown ownership still requires fresh proof; the application does not delete native address or lock files.
|
||||||
|
|
||||||
|
## Final grouped review fixes
|
||||||
|
|
||||||
|
- Ordinary pre-document cancellation now requires positive supervisor and worker no-write events, a bound prelaunch log baseline, and exact worker/process/project/private-desktop identity. Potentially mutating supervisor actions and integration admission revoke this authority before dispatch. Proven no-write startup uses one 30-second cleanup budget and the existing five-second UI handoff; unproved ordinary cleanup and active-write waiting retain their existing policies. Ordinary global Stop still cancels its own queue.
|
||||||
|
- A late loaded ordinary target may enter one separate retained cleanup phase only after its original worker/helpers have exited and fresh complete loaded evidence is available. The existing observer persists the intent and absolute 30-second deadline in the existing session record before any action, under the existing native management mutex. Duplicate observers, explicit release and process restart cannot start it again. Prior No/Tip acknowledgements and the sole Close remain deduplicated. Unknown or multiple documents, changed identities and active writes authorize no action. Cleanup return never establishes release or successful verification; queued writes still use fresh scoped resource proof.
|
||||||
|
- Manifest hashing/copy/validation now run serially on the existing bounded daemon task. Nested executors no longer keep the Python interpreter alive after real MainWindow closure during stalled metadata I/O. Completed work renews inactivity; cancellation prevents late dispatch and incomplete copies remain available as evidence.
|
||||||
|
- Backup recovery no longer holds the global native mutex during abandonable metadata work. It retains the exact library lease and completed-work fences. Only the short pair of Work renames, rollback and installed-state update is protected from abandonment; the task registry guard is never held over filesystem operations. Cancellation after that pair cannot start target verification. An OS rename that itself never returns cannot be safely interrupted; the implementation preserves ownership rather than claiming cancellation completed.
|
||||||
|
|
||||||
|
## Implementation
|
||||||
|
|
||||||
|
- Resource release uses exact project/database/library scope and observed process identity. Read-only file probes retain exclusive handles through release commitment. Legacy receipts are rechecked; a proof for one block cannot close another block's session.
|
||||||
|
- Each UI operation owns its immutable requests, cancellation signal and view revision. Queued work and late callbacks cannot write into a replacement library view. Native writes stay serial; registered worker handles and event admission protect shutdown handoff.
|
||||||
|
- Fast directory discovery and authoritative native catalog/status reconciliation are separate. Directory-only records are not treated as native entries. READY items remain available for management and are excluded from ordinary verification/maintenance admission.
|
||||||
|
- Manual Repair and version history open the official tool for the exact selected project/database, including recovery-required projects. The application does not submit Repair automatically or treat tool closure as successful recovery or READY.
|
||||||
|
- Results and management/recovery/release dialogs remain nonmodal. Three-second defaults preserve one-shot manual priority; unknown occupancy skips, exit saves, and forced termination defaults to cancellation.
|
||||||
|
- Native acceptance exposed two premature timeouts: successful catalog completion after the metadata deadline, and a progressing complete-library manifest exceeding that deadline. Catalog commit/wait now uses the existing read-only native channel; successful metadata work renews inactivity without changing stalled-I/O limits or native transaction behavior.
|
||||||
|
- A transient incomplete native-window scan is retried within the original open/close deadlines. Partial snapshots never authorize a control action. Persistent incomplete observation, unknown prompts and identity mismatches still fail closed.
|
||||||
|
- Same-name update validates the resolved source project name before native removal. A mismatched source remains selectable in the dialog for correction; the UI preview performs no filesystem resolution. The native Add dialog fields are reread immediately before submission.
|
||||||
|
- Save/Close may close the exact owned Project Integration panel only when all four complete statuses say no changes are pending and the unique Close control is enabled. Native inconsistency/error evidence takes precedence; partial, foreign or pending panels do not authorize closure.
|
||||||
|
- A new explicitly confirmed recovery attempt can proceed after a fresh release proof for the exact library and block is recorded under that new operation. Old failed journals remain unchanged; default requests, cached proofs and proofs for another target cannot authorize a retry.
|
||||||
|
- Hidden native worker failures now write compatible result records and tracebacks before exiting. Admission and entered-worker failures remain distinct, existing save evidence is preserved, and exceptions never establish release. This prevents a cancelled frozen worker from blocking on the packaging runtime's error dialog.
|
||||||
|
- Completed release and occupancy checks now renew the existing metadata inactivity clock. Cancellation and abandoned calls cannot be revived; active native transactions keep their existing continuation rules. This fixes a frozen Add that expired across a successful seven-second release proof followed by two successful occupancy checks before any native write.
|
||||||
|
- Diagnostic opening waits for an enabled target frame with no visible loading progress. After fresh project/PID evidence, its sole handler declines the exact owned Forward Annotation prompt. A close intent containing the current operation, target identity and nonce requires an exact supervisor acknowledgement after any in-flight dialog poll. The worker then rechecks readiness, prompts, native errors and cancellation before posting Close; acknowledgement consumes the original 30-second close budget. Ordinary Verify retains its own confirmation policy. A nested save prompt is accepted only through the captured, bounded chain of same-process, same-desktop, hidden disabled Expedition dialogs to the exact frame.
|
||||||
|
- The management dialog's stop-after-current button and active-window close request now stop the batch at the next item boundary. The current item completes its native writes, required directory readback and result bookkeeping. A queued batch can still be cancelled before admission. Global cancellation, shutdown, process identity checks and worker admission remain separate. Real acceptance exposed the former hard-cancel signal interrupting the readback after successful Remove/Add.
|
||||||
|
- Explicit release renews metadata inactivity after completed process snapshots, owner checks, held-file proofs and durable evidence steps. Multiple successful checks can finish without a false UI handoff; a single stalled step still times out. A late or cancelled proof cannot remove the coordination checkpoint or close the retained lease after its context has been abandoned.
|
||||||
|
- Actual early Stop reproduced a late Tip arriving after the one normal empty-frame Close. Startup cleanup now retains the original process handle and, within the original timeout, can dismiss that exact known Tip after rechecking the private desktop, empty frame, complete windows and lack of progress/documents/unknown prompts. When Close already hid the frame, only the Tip's direct hidden, disabled owner is inspected; hidden MDI documents also veto the action. The deadline and release Stop signal are rechecked immediately before clicking. It never posts another Close. Normal residual release shares this guarded acknowledgement for already-retained sessions, then waits for exit without forced termination or another Close. PCB exit, launcher exit and resource release remain separate requirements.
|
||||||
|
- A second actual cancellation race loaded the target after Tip dismissal, while COM/document admission had already stopped. Cancelled diagnostic startup now uses the existing fresh native path/PID logs and exact target MDI identity to decline Forward Annotation and finish one normal Close. Only exact owned No actions are allowed; unknown siblings, foreign identities, visible progress and writes remain protected. The supervisor completes its last poll before creating the cancellation signal, so cleanup is the sole prompt actor and does not wait for a normal-close acknowledgement. Its diagnostic 30-second cleanup budget starts once; an empty-to-loaded transition does not reset it. Cleanup never establishes CHECKED, READY or successful verification.
|
||||||
|
- Diagnostic cancellation yields to the existing registered observer after a bounded five-second wait; ordinary write waiting is unchanged. If the worker exits before its native clients, the same observer keeps ownership until client exit and fresh scoped release proof. Queue admission waits only for an actual initializing or live observer, so historical caches and unrelated libraries cannot create a permanent wait. The original cancellation result remains historical evidence. Report completion writes only unique application evidence files and can finish while native cleanup continues.
|
||||||
|
- Normal residual release can recover an older cancelled diagnostic startup using its complete existing registration, terminal worker, exact current native identity/command/private desktop/MDI and absence of Save evidence. That authority permits cleanup only; a missing prelaunch log baseline is never fabricated or treated as successful opening validation. The action rechecks binding immediately before each No or Close and respects a previously recorded close. Partial, foreign, active-write or ambiguous evidence remains blocked.
|
||||||
|
- One normal Release confirmation gives that proven legacy diagnostic cleanup one 30-second budget, including the known transition after Forward No. It runs in the existing read-only native phase, then the existing registered observer can obtain fresh release proof after late exit without another confirmation. Observer promotion requires the same operation and current Windows user/session; cleanup requires exactly one target MDI document. Ordinary close remains three seconds and ordinary native-write waiting remains unchanged. Pure residual inspection uses metadata-only admission so it remains available during native finalization.
|
||||||
|
|
||||||
|
## Evidence retained locally
|
||||||
|
|
||||||
|
Task 1's durable findings are consolidated here rather than tracking orchestration scratch files. Its final scoped backend coverage was 420 tests after review fixes; those tests cover real Windows exclusive/duplicated handles, scoped receipt trust, cancellation and unknown export ownership. They do not establish real Mentor behavior. Subsequent task evidence and all failed attempts remain in the local acceptance evidence archive; raw field data, process snapshots, host/user identifiers and production paths are not included in this repository report.
|
||||||
|
|
||||||
|
The initial Task 5 full run had 2,111 passes and one obsolete internal test entry. The test now uses the dedicated catalog-only handler while retaining the original mapping-order assertions. A separate regression reproduced child Python importing another editable checkout; test-session configuration now preserves the active worktree in inherited PYTHONPATH without changing machine configuration.
|
||||||
|
|
||||||
|
## Native acceptance recorded so far
|
||||||
|
|
||||||
|
All native operations use complete, hash-verified local copies with main/PCB/database references bound to the selected copied library. Source and frozen runs use independent copies.
|
||||||
|
|
||||||
|
| Source scenario | Observed outcome |
|
||||||
|
|---|---|
|
||||||
|
| Native catalog | Four original registered entries and authoritative READY statuses confirmed; fast discovery alone was not accepted. |
|
||||||
|
| Batch add with first-item name conflict | Existing name rejected safely; independent next source added and confirmed through native catalog/readback. Auto-verify was disabled; the new item remained pending. |
|
||||||
|
| Manual Repair | Official confirmation cancelled without submission, then explicitly confirmed on the healthy added control. Native diagnostics/defragmentation completed; the native tool also reported a missing optional project file. This is not a reproduced field inconsistency. |
|
||||||
|
| Manual backup and native restore | A uniquely described manual version was created; exact archive identity and restore location checked. Cancel and committed restore exercised; native restore and backup verification reported success. |
|
||||||
|
| Versions reopening | Exact restored project reopened successfully; normal close exited with release confirmed. Tool closure alone did not claim repair/restore validation. |
|
||||||
|
| ICDB check after restore | Initial observation-timeout failure retained; corrected same-button rerun returned CHECKED and safe resource release. It did not claim READY. |
|
||||||
|
| Release observations | No active clients remained; zero active sessions were reported released while old observation records were cleared. Conditional native save/cancel/force controls remained disabled. |
|
||||||
|
| Wrong-source same-name update | Earlier attempt exposed a missing name check and retained recovery-required evidence. The corrected UI rejects that source before submission and permits reselection. An audit of 21 major files in three unrelated blocks found no changes. |
|
||||||
|
| Corrected update after recovery | Exact-name source restored the missing target. A new confirmed update in the original application data root succeeded with a fresh scoped release proof; the old recovery-required journal was preserved. |
|
||||||
|
| Ordinary verification | Recovered target reached PASS/GREEN with native save committed, document closed, helper exited and resources released, without manual intervention. An earlier different target required manual native panel closure and remains classified as manual intervention. |
|
||||||
|
| CBB backup recovery | Actual dialog empty-input rejection, chooser cancellation and No/Yes confirmation were exercised. The isolated source validation and installed target verification both passed with GREEN; the old Work directory was retained. No manual native intervention was needed. |
|
||||||
|
| Automatic Project Integration panel close | The B control's first Verify automatically closed the completed panel and finished Save/Close/release, but authoritative status stayed PENDING and was correctly reported as FAIL. One explicitly requested fresh Verify then confirmed the native reusable-cell save and reached PASS/GREEN. The exact first-pass noncommit cause remains unconfirmed. |
|
||||||
|
|
||||||
|
The first full regression after these changes recorded 2,144 passes and eight fixture failures. Three tests still edited the old project filename, four lifecycle cases used an outdated control-helper signature, and one independent-item test reused a differently named source. The fixture updates preserve the original identity and lifecycle assertions. After the hidden-worker correction and isolation of simulated clients between tests, the full run at that stage passed **2,175 tests in 522.52 seconds**, exit code 0. The previous full regression at code commit 4402486 passed **2,246 tests in 572.82 seconds**, with zero failures, errors or skips and exit code 0. One earlier run was cooperatively interrupted after 2,151 passes when old test doubles contaminated the new entry tests; its stack and interrupted result are retained separately. Compilation and diff checks also passed.
|
||||||
|
|
||||||
|
The previous complete regression at code commit a3f69de passed **2,351 tests in 497.58 seconds**, exit code 0, with zero failures, errors or skips. Log SHA-256: `aa820f1202becd30ee220c8e660fcde0e063d9ed874023ab3487108aedae214d`; JUnit SHA-256: `7d951ad853978e58aabaa481656c15b8610f01fdf9d64f67af0585dda9bc3bbe`. Actual native applications were normally closed and the writer/management mutexes were idle before and after this run.
|
||||||
|
|
||||||
|
The previous candidate B9 is built from code commit a3f69de. All 68 packaged modules, assets, bridge programs, scripts and icon images match; all 242 ZIP-extracted files match the build. Executable SHA-256: `bfd6c122724f71a2aac4748ed01336a9949aa753f9c58aca55db574668140083`. ZIP SHA-256: `4c589bae6bf7b68732cd7ebe373b2924016c71f6731fd661c1cd0fd848427438`. Five actual pre-cancelled frozen entry routes exited without acknowledgement or termination and wrote the expected results. Common GUI, worker, owner-probe and dialog-agent smoke passed.
|
||||||
|
|
||||||
|
B9 repeated the two affected native cases. Versions was queued after exact diagnostic PCB registration and before Stop. The UI reached its cancellation terminal state in 6.672 seconds; the original result remains CANCELLED/safe=false. Automatic guarded Tip/Forward No/Close cleanup and the existing observer produced fresh library release proof; the queued Versions native client started 1.684 seconds after that proof and loaded its backup catalog. No Release click or manual diagnostic native action occurred. Separately, B5 produced a real cancelled, loaded-target legacy session. B9's initial inspection succeeded and one normal Release confirmation released the PCB, launcher and database server with fresh RELEASE_CONFIRMED proof in 22.634 seconds. The UI agreed and disabled Confirm; no Recheck, second confirmation, manual native action, Save, annotation or forced termination occurred. The old cancellation result was retained. The earlier B8 legacy path required multiple confirmations and is preserved as an incomplete workflow, not a final pass.
|
||||||
|
|
||||||
|
The [acceptance matrix](2026-11-17-issue15-acceptance-matrix.md) records each native case against its actual executable hash. Earlier successful cases remain bound to their original builds; they are not relabelled as new-build tests. The constructed-copy experiment ended with Windows sharing violation 32 at database/icdb.dat during native Save. Its source passed GREEN and released normally; the incomplete clone was never opened. The B5 early Stop returned CANCELLED with retained PCB/launcher and safe_to_continue=false; manual Tip OK alone completed the pending Close. That failure is preserved. The late-Tip fix and its new native acceptance are recorded separately.
|
||||||
|
|
||||||
|
## Limits
|
||||||
|
|
||||||
|
Review round 1 corrected two legacy-cleanup defects. The real residual snapshot adapter now retains hidden MDI document siblings before the exact-one-document guard, and a Tip without any previous Close returns to guarded loaded-target observation within the same deadline. A Tip after an actual Close retains wait-only behavior. The focused regressions first reproduced both failures, then 134 related tests passed; an independent harmless real Win32 window probe confirmed hidden-sibling no-action and the single-document normal Close path. This probe is not Mentor acceptance.
|
||||||
|
|
||||||
|
A delayed Tip dismissal regression then exposed repeated OK posts in the new continuation path. A separate set of Tip handles now limits acknowledgement to once per cleanup intent while retaining the original deadline and Forward handling. Final related coverage passed 180 tests in 29.43 seconds. The first round-1 full run retained 2,355 passes and one failed UI-reopen fixture: it claimed its worker had exited while registering the still-live pytest PID, so the real cold observer correctly blocked admission. The fixture now launches a harmless real worker, exercises actual mutex admission refusal, waits for real process exit and retains the original receipt/reopen assertions; its focused run passed. No product queue bypass or UI timeout increase was introduced.
|
||||||
|
|
||||||
|
B10 is built from `701e5cd`, with EXE SHA-256 `a6271e4219a02123e301ed1e0ea3109e78307bf1f92574b4a5cacb70690695a4` and ZIP SHA-256 `d4bd42416ea8d12a249ff1d9c8854eb76d2f81bb7ff869ff43dd92a331c647a0`. All 68 modules/resources and 242 extracted files match; five cancelled frozen entry routes and common smoke passed. Actual B5-to-B10 legacy diagnostic recovery used one confirmation, zero Rechecks/manual native actions, and reached fresh RELEASE_CONFIRMED after an intermediate PARTIAL; final receipt at 35.387 seconds and the UI agreed. This actual native case entered at loaded Forward; both Tip states are covered by focused regression, not claimed as newly replayed Mentor Tip states.
|
||||||
|
|
||||||
|
The final round-1 candidate B11 is built from `8818fa9`: EXE SHA-256 `03452e39f394c3c63113aaa701f64bacf14e817ae3b4e194965f333ecc645b98`, ZIP SHA-256 `34b3646b27afae22ec43a415ca19bbd32a91c0a4c941d37d6289c76cea9ca730`. Module/resource equality, all 242 extracted files, five cancelled frozen entries and common smoke passed. Only the residual-session module changed from B10 to add per-intent Tip acknowledgement tracking. B10 native/button receipts remain bound to B10; B11 delayed Tip behavior has source regression coverage, not a new actual Mentor Tip replay.
|
||||||
|
|
||||||
|
The final round-1 complete suite at `8818fa9` passed **2,358 tests in 451.34 seconds**, exit code 0, with zero failures, errors or skips. Log SHA-256: `5544f2e17f84a74e67faa81403a0b13679728c432ab269f2f5050cfe42103831`; JUnit SHA-256: `8e734b1f6298d368b1b059019e419b687c5284c472ad04a999f0b73e2254cd16`. Compilation/diff checks and the post-suite native-process/writer/management idle checks passed. The earlier failing run and test-harness setup failures remain archived.
|
||||||
|
|
||||||
|
The missing frozen controls were exercised on B10: Open logs and Open exception evidence opened the exact current application folders, verified by private-desktop Explorer breadcrumbs; queued CBB recovery was cancelled before admission and created no recovery job; result Release opened the correct residual plan; Continue started only the second previously skipped item, which passed GREEN, without replaying the terminal first item. The first result summary elapsed under its existing three-second Close default. After ordinary main-window Release and normal dialog closure, production code recreated the Continue summary; the observer clicked that actual enabled control without injecting results or calling application methods. One bounded repeat captured result Release within the default window.
|
||||||
|
|
||||||
|
That B10 button exercise exposed the **historical ordinary-verification cancellation defect**: Stop 0.547 seconds after first PCB registration, before any Save, returned CANCELLED/safe=false at PCB_STARTING; the target later loaded Forward Annotation and remained alive. The B10 automatic loaded-startup cleanup required diagnostic-only authority, so it did not clean this ordinary case. Exact manual Forward No and one normal Close after no-modal/no-progress checks were required before fresh release. The bounded result-button repeat reproduced the same retained state. These are failures of unattended ordinary cancellation, not successful automatic cleanup or protected active-Save cases, and remain preserved as failures; the grouped fix and B13 acceptance are recorded below.
|
||||||
|
|
||||||
|
The exact complete fault-bearing field snapshot is unavailable, so the original field inconsistency remains **NOT REPRODUCED**. Any bounded constructed live-copy experiment is reported separately. Windows 10 and production network/SMB behavior are **NOT RUN**. No merge, published release or issue closure is authorized by this candidate report.
|
||||||
|
|
||||||
|
One local B control required a second explicit verification after an initial completed native Save/Close left it PENDING. Both results are retained; automatic retries were not added and the initial failure is not counted as a pass.
|
||||||
|
|
||||||
|
## Final-wave evidence and limits
|
||||||
|
|
||||||
|
B14 EXE SHA-256: `0cd5f37b113802bcf3abd07a94d8c5b9f73d40696b1c56af66fedf39112e2d8c`. ZIP SHA-256: `a580e3e9945261761e0eb3968b4e271d9f4745ce982dea96c283af4ab06e565f`. All 68 packaged product modules/resources and all 242 extracted files match source/build. Five pre-cancelled frozen routes and common GUI/worker/owner-probe/dialog-agent smoke passed. Full-suite log SHA-256: `d9c57b7998e02154fb703f0fe2ba1f37f73dc4687d116c4b6efc0e5ad7e5c30e`; JUnit SHA-256: `4303cc123e90689103cc4135e483ac936b04a052067e952a1861ae167c7811ea`. Native clients and writer/management mutexes were idle before and after the full suite.
|
||||||
|
|
||||||
|
B13 (`5e9509e`) retains EXE `966e00fe57eccbdf4975c624026d39d24d4613f4174a932db248fb444a7caa9d` and ZIP `7a1da94e05b85873f791cde77907bdc280106768fbf84e5d89066ab8aa57a61b`. A final self-audit found that the new ordinary explicit-release branch bypassed existing cold-observer promotion. Its focused test failed before the two-line ordering correction at `c1e2596`; 110 related tests then passed in 21.96 seconds, including actual harmless worker exit, cold-observer promotion and queue proof. The in-progress B13 full suite was interrupted through its own execution session before editing, and is archived without a completion/JUnit claim. No additional native matrix was run for this narrow B14 delta.
|
||||||
|
|
||||||
|
The three review defects had retained RED evidence: actual MainWindow subprocess exit hung on stalled hash/copy/validation; real recovery callers held the unrelated native channel and could install after abandoned metadata; ordinary cancelled startup failed to clean a later loaded target. B13 related observer coverage passed 232 tests in 34.81 seconds, including an actual two-process mutex/file race between observer and explicit release plus a process restart. These race tests stub the native evidence/action boundary; they are not Mentor window tests.
|
||||||
|
|
||||||
|
B12 (`906cfc0`, EXE `7d7929d6621ae6c379205380e06f94eb076135343417d000018a8ab04efea8cc`, ZIP `bbe68005469d8b6cf87726200ef85646e442de45d164ab2ac0aec23b51d0bd65`) retained a new failure: ordinary `verify-642171759614` returned its visible cancellation terminal state in 7.797 seconds, but Forward loaded at 34.406 seconds, after the worker cleanup budget. Exact manual No/normal Close was used solely to clear that failed run. A later independent queue-helper attempt was refused with sharing violation 32 before native creation while two releasing observers raced for the coordination lease. Both failures are archived and are not relabelled as B13 passes.
|
||||||
|
|
||||||
|
B13 ordinary `verify-71aee0603183` reached the visible terminal state in 7.375 seconds. Its candidate worker acknowledged Tip at 21.359 seconds, Forward No at 27.422 seconds and one Close at 28.750 seconds; native exit followed the original cleanup deadline. Read-only sampling confirmed kernel exit. The original result remains CANCELLED/safe=false. No Release click or manual ordinary native action occurred. The helper stayed observe-only until the actual candidate produced fresh RELEASED proof, then obtained its own independent fresh proof. Its prequeued real Versions client `native-backup-b63e7f708fd5` was created 5.220 seconds after the candidate proof and 1.506 seconds after the independent proof, loaded the backup catalog and closed normally. This is **cross-owner queue acceptance**, using source-hash-pinned production queue/observer/native-worker modules; it is not survival of work in the same app after global Stop. The candidate itself performed every ordinary No/Close action.
|
||||||
|
|
||||||
|
The B13 native run issued Close within the first worker budget, so the new retained-phase No/Close branch was **NOT REPLAYED in Mentor**. That branch has source guard, real process race/restart and existing real Win32 adapter evidence. No repeated cold-start attempts were used to manufacture a slower launch.
|
||||||
|
|
||||||
|
B13 actual recovery `backup-restore-3f98efb14448` used the current pending original target and healthy independent source A. Its isolated source and installed target both returned PASS/GREEN/safe; native save/close/release completed without intervention. The old Work directory is retained and all 366 original source files are unchanged. The 27,689-file complete validation library copy progressed through the serial metadata path without a false inactivity handoff.
|
||||||
|
|
||||||
|
Separate frozen metadata-exit harness EXE SHA-256: `7490be1988d823944307510f7cfd22c85cf8570c7c25f6ee60d97f542bb72753`. All 68 packaged product modules equal final B14. A disposable I/O stall at each of hash/copy/validation exercised actual MainWindow close and interpreter exit before releasing the stall; no late dispatch occurred and partial copies were retained. This uses an acceptance-only entry, **not stall injection into the candidate EXE**. The earlier B12/B13 harnesses and all RED/setup attempts remain archived.
|
||||||
|
|
||||||
|
The original complete fault-bearing field snapshot remains unavailable (**NOT REPRODUCED**); the constructed partial copy remains **COPY_BLOCKED** and was never opened. Windows 10 and production SMB remain **NOT RUN**. The earlier first-pass B-control PENDING result and explicit retry remain separate outcomes. No merge, publication or issue closure is performed.
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# PR 16 small review follow-up
|
||||||
|
|
||||||
|
Refs #15. Follow-up to review comment 446 on `b4737b5`; this does not authorize
|
||||||
|
merging, release publication or issue closure.
|
||||||
|
|
||||||
|
- Verify now propagates a registered `TaskHandoff` instead of recording it as a
|
||||||
|
close error and continuing a second native cleanup. It preserves the cancelled
|
||||||
|
or failed result as evidence before returning cleanup ownership to the observer.
|
||||||
|
- Repair runs local worker cleanup even when observer registration or handoff
|
||||||
|
raises. A live native worker retains its existing observer-owned handles;
|
||||||
|
`DesktopWorker.close()` does not terminate it or claim resources are released.
|
||||||
|
- Starting an ICDB check binds the fallback Stop signal to the task's actual
|
||||||
|
context. The normal global Stop and per-task cancellation policies are unchanged.
|
||||||
|
- Native Versions/Repair errors now explain that the main PRJ must contain exactly
|
||||||
|
one nonempty `iCDBDir` using a project-local relative path. Absolute paths,
|
||||||
|
including absolute paths inside Work, and multiple entries remain unsupported.
|
||||||
|
No PRJ is rewritten and no native tool is launched for rejected input.
|
||||||
|
|
||||||
|
The previously approved three-second defaults remain: submitted execution
|
||||||
|
continues; unknown ownership/read-write confirmation skips; version selection
|
||||||
|
uses the last manual save; exit saves; force termination defaults to cancellation.
|
||||||
|
This follow-up does not add or change those product decisions.
|
||||||
|
|
||||||
|
## Validation
|
||||||
|
|
||||||
|
The unchanged targeted baseline passed 31 tests. New behavior regressions first
|
||||||
|
recorded four failures and four passes; after the fixes all eight passed.
|
||||||
|
Related Verify, Repair, native-entry, observer, ICDB/UI and shutdown regressions
|
||||||
|
passed **363 tests in 157.24 seconds**, exit code 0.
|
||||||
|
Compilation and whitespace checks also passed. Independent scoped review found
|
||||||
|
zero Critical, Important or Minor issues in the follow-up fixes.
|
||||||
|
|
||||||
|
These are source tests with real task contexts and Qt controls; native process
|
||||||
|
boundaries are replaced where the tests require them. This follow-up does not
|
||||||
|
claim a new full-suite run, rebuilt frozen package, or actual Mentor acceptance.
|
||||||
|
The earlier 2,418-test full run and B14 package still belong to source `c1e2596`.
|
||||||
|
Original field inconsistency, the retained-phase native replay, Windows 10 and
|
||||||
|
production SMB acceptance remain outstanding as documented in the main matrix.
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
# CBB 刷新校验 v0.2.4-beta.4
|
||||||
|
|
||||||
|
Refs #15。延续测试版发行,供隔离副本和现场进一步验证。
|
||||||
|
|
||||||
|
## 本版改动
|
||||||
|
|
||||||
|
- 分开任务执行、原生客户端退出、资源释放及数据待恢复状态,减少旧记录和无关工程导致的误阻塞。
|
||||||
|
- 普通校验启动阶段取消时,只有完整未写入证明和准确归属才能处理已知提示并安全收尾;原结果保留为取消,不改成 READY。
|
||||||
|
- 已登记观察者可以持久化接管一次迟到启动的安全收尾;不循环重新打开或自动重放写操作。
|
||||||
|
- 文件哈希、复制、校验不再因嵌套线程池阻止程序退出。恢复准备不长期持有全局原生通道,迟到任务不能继续安装。
|
||||||
|
- 修正交接异常传递、Repair 本地资源清理、ICDB 停止信号绑定,以及管理窗口销毁后的迟到结果回调。
|
||||||
|
- 保留当前图标、三个菜单、READY 操作范围及手动备份政策。版本/Repair 对绝对或多条 iCDBDir 的拒绝原因现在明确显示,不自动修改工程引用。
|
||||||
|
- 沿用已确认的 3 秒默认策略;未知占用和读写确认默认跳过,强制终止默认取消。真实原生写入仍受保护。
|
||||||
|
|
||||||
|
## 发布验证
|
||||||
|
|
||||||
|
本次源码全量 **2,428 项通过,659.54 秒,退出码 0**;JUnit 零失败、零错误、零跳过。
|
||||||
|
管理窗口销毁后的成功/失败回调先复现失败,再通过实际 Qt 信号测试验证修复。
|
||||||
|
生命周期模拟测试隔离无关的机器 WMI/文件探测延迟,真实占用、独占句柄、资源证明和原生写入保护测试继续保留。
|
||||||
|
新增发布改动经独立限定复核,无 Critical、Important 或 Minor 遗留项。
|
||||||
|
|
||||||
|
Windows 包使用合并后的 main 提交构建并上传云端;仓库当前未配置云端打包工作流。
|
||||||
|
最终源码提交、冻结模块/资源及图标核对、冻结冒烟和 ZIP 校验结果见发行附件
|
||||||
|
`release-info.json`、`release-smoke.json` 和 `SHA256SUMS.txt`。
|
||||||
|
发布前因 C 盘耗尽中断的一轮,以及后续失败/修订的测试记录均保留,不计为通过。
|
||||||
|
|
||||||
|
## 使用与范围
|
||||||
|
|
||||||
|
完整解压 Windows ZIP,运行 `CbbRefreshVerify-Background/CbbRefreshVerify.exe`,保留 `_internal`。
|
||||||
|
库写操作前按提示手动备份。程序回滚不能撤销已经完成的中心库写入。
|
||||||
|
|
||||||
|
自动 ICDB Repair 仍关闭。原现场不一致故障未完整复现;独立接管阶段的原生 No/Close 重放、Windows 10、生产 SMB 尚未验收。
|
||||||
|
此前 B13 实际普通取消、后续原生调度与备份恢复的通过记录保留其原始源码/包版本,不能算成本发行包的原生重跑。
|
||||||
|
发布测试版不关闭工单 #15,也不代表这些现场边界已经解决。
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# CBB 刷新校验 v0.2.4-beta.3
|
||||||
|
|
||||||
|
本测试版整合 PR #14:普通 CBB 导入与可选导出诊断解耦、写前未知会话确认、PCB 打开句柄顺序修复、任务绑定中心库,以及审查评论 414/430 的修复。
|
||||||
|
|
||||||
|
- 无效来源、可选 Verify 失败不再阻止已释放的独立条目继续。上传完成、校验通过和 READY 分开报告。
|
||||||
|
- 无法取得写入确认、或恢复安装前跳过,记录为 SKIPPED;取消为 CANCELLED,保留具体原因。
|
||||||
|
- 文件身份采集失败仍为 RECOVERY_REQUIRED;由独立的原生退出和资源证据决定后续资格,禁止自动重放该目标。
|
||||||
|
- 无未知原生客户端时只探测一轮;等待用户确认后仍重新检查进程和资源。
|
||||||
|
- 保留三个横向菜单和当前图标,不自动备份整个中心库;写操作前仍需人工备份。
|
||||||
|
|
||||||
|
下载 Windows ZIP 后完整解压,运行 `CbbRefreshVerify-Background/CbbRefreshVerify.exe`,保留同目录 `_internal`。
|
||||||
|
发布程序由 Windows 主机从合入后的 main 构建并上传云端;不标记为云端 Windows runner 构建。
|
||||||
|
发行附件的 `release-info.json`、`release-smoke.json` 和 `SHA256SUMS.txt` 记录实际提交、验证结果及文件散列。
|
||||||
|
|
||||||
|
导入确认原生注册、名称/分区、工程关联、允许的顶层块及 Layout,未证明原理图语义等价。
|
||||||
|
UPLOADED 不等于 READY;完整 Verify 独立可选。已有其他 LibraryManager 时原生入口仍拒绝,需正常关闭相关会话再继续。
|
||||||
|
|
||||||
|
自动 ICDB Repair 仍关闭。EDIF 崩溃根因、Windows 10、跨机器 SMB 和现场服务器会话失联修复仍未验收;
|
||||||
|
测试版发布不代表这些问题已解决,不自动关闭工单。
|
||||||
|
|
||||||
|
回滚程序时完整解压此前发布包并在关闭新客户端后使用;程序回滚不撤销已完成的中心库写入,工程恢复须依据逐项证据和人工备份。
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
# 工单 #15 实测问题全量修复实施计划
|
||||||
|
|
||||||
|
**Goal:** 消除误阻塞,打通手动修复与版本管理,逐项验证工单全部实测问题。
|
||||||
|
**Architecture:** 复用会话记录、串行队列和原生适配器;区分任务执行、客户端退出、协调租约释放、数据待恢复及下一项写入资格。范围不明时只隔离受影响资源,不冻结界面或无关库。
|
||||||
|
**Tech Stack:** Python 3.12、PySide6、pywin32、Mentor EE7.9.5,不新增依赖。
|
||||||
|
**Spec:** 用户在聊天中批准的五节计划;证据及确认/待确认边界见 `F:/CbbIssue15-20261116/analysis.md`。
|
||||||
|
|
||||||
|
## Global Constraints
|
||||||
|
|
||||||
|
- 基线 efb8cae,独立分支 codex/issue15-runtime-unblock;保留原脏工作区。
|
||||||
|
- 自动 ICDB Repair 继续关闭。明确不一致时报告并跳过,提供实际可用的手动 Repair/历史恢复入口。独立项继续。
|
||||||
|
- 普通校验确认工程唯一归属后,将主 PRJ 和 PCB PRJ 对齐所选中心库,保留原文件证据;ICDB 检查不修改引用。
|
||||||
|
- READY 不进入校验/维护;管理允许 READY。原生写入串行,同名更新 Remove→Add 不被打断。
|
||||||
|
- 手动备份政策;不新增自动整库备份。不手删原生锁/地址,不杀用户程序,不抢前台鼠标。
|
||||||
|
- 默认确认 3 秒:已提交执行继续;未知占用/PCB 读写确认跳过项;历史版本最后手动保存;退出前保存;强制终止取消。人工优先、仅生效一次。
|
||||||
|
- VerifyRequest/VerifyResult 与旧记录兼容。未知旧记录重新核对,不直接采信旧证明。
|
||||||
|
- 先失败复现再最小修复,阶段验证后单独提交。源码回归不冒充冻结包或现场原生验收。
|
||||||
|
- 验收只用隔离完整副本;不改生产库。未复现原故障必须明确。不得自动合并发布或关闭工单。
|
||||||
|
|
||||||
|
## Task 1: 会话资源范围、锁与释放证明
|
||||||
|
|
||||||
|
Owned areas: library_lock/session_record/icdb_ownership/operation_lifecycle/residual_sessions/owner_probe and a bounded file-probe helper/CLI if needed; associated tests. Coordinate shared changes through controller.
|
||||||
|
|
||||||
|
- [ ] 先新增行为回归并见证失败:A 退出而 B 有地址;未知检查点+明确其他工程进程;父句柄保留后子进程获取;迟到观察不能清除新任务;慢 A 探测不挡 B 内存/租约检查。
|
||||||
|
- [ ] 在现有会话和释放证明中增补可选 lease_state/resource_scope/blocked_resources/data_recovery_required,记录目标工程、数据库、实际共享依赖和操作身份;旧记录缺范围重新核对。
|
||||||
|
- [ ] 分开客户端退出、协调租约释放和数据恢复;已退出任务不因为其他块地址永久占有自己的句柄。不将文件存在/PID文本/地址年龄/端点不可达当作权威占用或可写证明。
|
||||||
|
- [ ] release_residual_sessions 传递准确范围;观察项不进入关闭目标、不增加主动释放计数。未知检查点也按实际资源判断,不要求全部 Mentor 进程退出。
|
||||||
|
- [ ] 地址不手动删除;有地址且需判定的目标复用 inspection-only 原生判定。真实目标占用/未返回共享写入依旧保护,健康工程不跑额外 ICDB 扫描。
|
||||||
|
- [ ] 全局锁只保护快照/提交;进程/文件/网络探测移出锁,提交前核对 lease/operation 身份。
|
||||||
|
- [ ] 有阻塞风险的只读文件探测放独立 helper,默认单次最多10秒,支持停止;只能终止纯探测 helper。需要持有证明句柄跨提交时使用握手保持保护,不引入无保护 TOCTOU。
|
||||||
|
- [ ] 相关旧回归及真实 Windows 句柄/父子进程试验通过,写阶段记录并提交。
|
||||||
|
|
||||||
|
## Task 2: 取消、超时、退出与批次继续
|
||||||
|
|
||||||
|
Owned areas: failed_session/verify_runner/desktop_worker/operation_queue and lifecycle integration/tests. UI adoption delegated to Task 4.
|
||||||
|
|
||||||
|
- [ ] 失败用例覆盖晚到每日提示、读写确认、历史版本取消、PCB先退/启动器后退、COM无文档、慢探测、失败后独立项继续、取消后的新任务。
|
||||||
|
- [ ] 正常执行和失败启动收尾复用已知弹窗识别。精确绑定创建身份、工程、私有桌面;未知弹窗不猜按钮。取消收尾最多30秒返回终态或交给独立观察。
|
||||||
|
- [ ] 现有队列增补每批不可变任务上下文(operation_id、library/aliases、targets/resources、stop、state),停止事件不跨任务复用;原生写保持串行,事务不能在Remove与Add间让出。
|
||||||
|
- [ ] 仅资源相关项受保护;安全业务失败继续,未确认范围的后续项记录跳过并结束汇总,不无限等待。回调绑定任务身份,不覆盖新库。
|
||||||
|
- [ ] 准备有界关闭接口:30秒内完成或把原生事务交给有证据监督,禁止线程池析构/文件探测导致无限等。启动和交接记录保障重启可见,不重放写操作。
|
||||||
|
- [ ] 运行覆盖测试并提交;向 Task 4 明确队列状态、停止和关闭接口。
|
||||||
|
|
||||||
|
## Task 3: 版本管理、手动 Repair、工程身份和原生错误
|
||||||
|
|
||||||
|
Owned areas: native_backup/mentor_adapter/library_manager_verify/verify diagnostics/maintenance_entry/native occupancy; may amend runner stage integration after Task 2.
|
||||||
|
|
||||||
|
- [ ] 先写失败测试:版本 worker 前的父保留租约、子启动/登记失败、无备份、关闭再打开、主/PCB引用不同、旧日志不作新诊断、菜单返回但没PCB。
|
||||||
|
- [ ] 版本启动前复核本任务历史租约;使用已有登记/启动门控,先持久登记身份再开原生工具,执行方持实际租约,失败给明确归属与恢复路径。
|
||||||
|
- [ ] 提供绑定准确PRJ/数据库的原生 Repair 入口,保留版本与备份UI;自动Repair关闭。不得绕过活跃事务;数据待恢复本身不得禁用手动恢复入口。
|
||||||
|
- [ ] 普通校验以同一工程归属确认统一两层PRJ,保留编码/原字节;诊断不修改。重新核对实际打开身份。
|
||||||
|
- [ ] 从本轮增量日志提取副本不一致/ICDB/失联及目标DB;只报告“发现问题、未修复”,独立项继续。
|
||||||
|
- [ ] LM派发观察上限min(45秒,用户超时),有PCB再进入正常启动计时;无PCB快速失败并正常收尾,默认不启用前台鼠标替代。
|
||||||
|
- [ ] 保存成功、关闭、资源释放、权威READY独立记录。仍PENDING不得记通过;历史恢复是版本待核对,原生窗口关闭不冒充Repair成功。
|
||||||
|
- [ ] 相关回归与可用的隔离原生路径通过,记录后提交。
|
||||||
|
|
||||||
|
## Task 4: UI、输入、计数与无人值守集成
|
||||||
|
|
||||||
|
Owned areas: ui/main_window/child dialogs/library_reader/models/application settings and queue adoption; associated tests.
|
||||||
|
|
||||||
|
- [ ] 先复现排队禁用全界面、首次读库无法取消、迟到跨库回调、模态结果、证据按钮条件错误、坏库输入和计数问题。
|
||||||
|
- [ ] 接 Task2 上下文,每任务独立停止/回调。排队不置全局不可操作;搜索筛选、换库、证据、取消排队、释放可用。原生操作排队,重复提交同一快照不重复执行。
|
||||||
|
- [ ] 读库失败保留旧表并标失效,禁止旧表写;快速显示目录结果,原生目录复核后台入队。目录发现/原生记录/缺工程分别计数,未复核显示未知。
|
||||||
|
- [ ] 空文件、错误后缀、锁路径是目录、权限失败输出稳定分类;快速读不自称验证了原生格式。
|
||||||
|
- [ ] 结果QMessageBox显式NonModal、3秒默认关闭,失败/取消有证据即可打开;日志入口打开logs。记忆上次成功读取路径,启动仅回填不自动执行。
|
||||||
|
- [ ] 版本/Repair按钮绑定一个可见非READY目标,不能以未校验或数据待恢复直接禁用;真实资源冲突有简短原因。
|
||||||
|
- [ ] 全面复核选择/清空/隐藏项、READY资格、状态刷新、每个条件按钮。现有3秒策略完整集成,人工抢先选择/窗口隐藏/计时竞态不得重复动作。
|
||||||
|
- [ ] 关闭接Task2有界交接;UI只留必要操作/错误,不写开发说明。
|
||||||
|
- [ ] 全部相关Qt测试和381/3000项响应检查通过,记录后提交。
|
||||||
|
|
||||||
|
## Task 5: 全量回归、真实冻结包验收与PR
|
||||||
|
|
||||||
|
- [ ] 全量pytest、compileall、diff检查、模块/资源/PE图标与冻结包一致性;每次失败保留,修订后重验相应范围。
|
||||||
|
- [ ] 逐按钮清单覆盖主窗口、管理、恢复、原生版本/Repair、释放及所有条件按钮;源码Qt与最终冻结包分别执行。
|
||||||
|
- [ ] 非规则点击覆盖双击执行、取消重试、检查中排队/换库、隐藏勾选、结果框存在、关闭原生窗口、3秒边界竞争和主程序退出重启。
|
||||||
|
- [ ] 真实Windows进程/文件锁覆盖无持有LOCK、父子冲突、外部无关进程、真实目标独占句柄、地址残留和慢/失败查询。不能修改或终止其他任务。
|
||||||
|
- [ ] Mentor真实独立副本验证普通校验READY、ICDB批检后独立继续、手动Repair、版本回退后重开、批量新增/同名更新/移除/恢复;原生失败单独列明,不用模拟替代。
|
||||||
|
- [ ] 不一致故障必须对应实际原生特征;没有现场一致副本则标未复现,不拿格式损坏替代。Win10/生产网络未测明确保留。
|
||||||
|
- [ ] 候选包、逐问题/逐按钮验收表、新PR。未经现场验收不自动合并发布、不关工单。
|
||||||
+1
-1
@@ -3,7 +3,7 @@ requires = ["setuptools>=84.1.0"]
|
|||||||
build-backend = "setuptools.build_meta"
|
build-backend = "setuptools.build_meta"
|
||||||
[project]
|
[project]
|
||||||
name = "cbb-refresh-verify"
|
name = "cbb-refresh-verify"
|
||||||
version = "0.2.4b2"
|
version = "0.2.4b4"
|
||||||
requires-python = ">=3.12,<3.13"
|
requires-python = ">=3.12,<3.13"
|
||||||
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<0.7", "Pillow>=13.0.0,<14"]
|
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<0.7", "Pillow>=13.0.0,<14"]
|
||||||
|
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
__version__ = "0.2.4b2"
|
__version__ = "0.2.4b4"
|
||||||
@@ -72,11 +72,71 @@ def _positive_int(value):
|
|||||||
return number
|
return number
|
||||||
|
|
||||||
|
|
||||||
|
def _native_worker_entry(mode, request):
|
||||||
|
"""Contain hidden-worker failures so a frozen bootloader cannot show a modal error."""
|
||||||
|
import contextlib
|
||||||
|
import json
|
||||||
|
import traceback
|
||||||
|
from .desktop_worker import run_native_worker
|
||||||
|
state = {'worker_entered': False}
|
||||||
|
result_name = {'verify': 'outcome.json', 'repair': 'repair-result.json'}.get(mode, 'result.json')
|
||||||
|
try:
|
||||||
|
with request.with_name('worker.log').open('a', encoding='utf-8') as log:
|
||||||
|
with contextlib.redirect_stdout(log), contextlib.redirect_stderr(log):
|
||||||
|
if mode == 'native-backup':
|
||||||
|
from .native_backup import run_native_backup_worker
|
||||||
|
return run_native_backup_worker(request, admission_state=state)
|
||||||
|
if mode == 'management':
|
||||||
|
from .native_management import catalog_worker_main, management_worker_main
|
||||||
|
job = json.loads(request.read_text(encoding='utf-8'))
|
||||||
|
action = catalog_worker_main if job.get('worker_role') == 'catalog_readonly' else management_worker_main
|
||||||
|
elif mode == 'repair':
|
||||||
|
from .native_repair_ui import repair_worker_main
|
||||||
|
action = repair_worker_main
|
||||||
|
else:
|
||||||
|
from .mentor_adapter import worker_main
|
||||||
|
action = worker_main
|
||||||
|
return run_native_worker(action, request, admission_state=state)
|
||||||
|
except Exception as error:
|
||||||
|
trace = traceback.format_exc()
|
||||||
|
entered = state['worker_entered']
|
||||||
|
reason = str(error)
|
||||||
|
cancelled = not entered and reason.startswith('WORKER_CANCELLED:')
|
||||||
|
detail = ('VERIFY_CANCELLED: ' if mode == 'verify' and cancelled else '') + reason
|
||||||
|
path = request.with_name(result_name)
|
||||||
|
try:
|
||||||
|
result = json.loads(path.read_text(encoding='utf-8'))
|
||||||
|
if not isinstance(result, dict): result = {}
|
||||||
|
except (OSError, ValueError):
|
||||||
|
result = {}
|
||||||
|
if mode == 'verify':
|
||||||
|
result.update(status='CANCELLED' if cancelled else 'FAIL', stderr=detail,
|
||||||
|
error_stage='worker' if entered else 'admission', safe_to_continue=False)
|
||||||
|
else:
|
||||||
|
result.update(success=False, status='FAILED', detail=detail, safe_to_continue=False)
|
||||||
|
failure = dict(stage='worker' if entered else 'admission', reason=reason,
|
||||||
|
worker_entered=entered, native_started=None if entered or mode == 'native-backup' else False,
|
||||||
|
safe_to_continue=False)
|
||||||
|
# An exception is never a release proof, and existing Save/Close evidence is retained.
|
||||||
|
for output, value in ((path, result), (request.with_name('worker-failure.json'), failure)):
|
||||||
|
try:
|
||||||
|
output.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
with request.with_name('worker.log').open('a', encoding='utf-8') as log:
|
||||||
|
log.write(trace)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
return 2 if mode == 'management' else 1
|
||||||
|
|
||||||
|
|
||||||
def main(argv: Sequence[str] | None = None) -> int:
|
def main(argv: Sequence[str] | None = None) -> int:
|
||||||
parser = argparse.ArgumentParser(prog="CbbRefreshVerify")
|
parser = argparse.ArgumentParser(prog="CbbRefreshVerify")
|
||||||
parser.add_argument('--verify-worker', type=Path, help=argparse.SUPPRESS)
|
parser.add_argument('--verify-worker', type=Path, help=argparse.SUPPRESS)
|
||||||
parser.add_argument('--repair-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('--owner-probe', type=Path, help=argparse.SUPPRESS)
|
||||||
|
parser.add_argument('--file-probe', type=Path, help=argparse.SUPPRESS)
|
||||||
parser.add_argument('--native-backup-worker', 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('--management-worker', type=Path, help=argparse.SUPPRESS)
|
||||||
parser.add_argument('--dialog-agent', type=Path, help=argparse.SUPPRESS)
|
parser.add_argument('--dialog-agent', type=Path, help=argparse.SUPPRESS)
|
||||||
@@ -89,18 +149,18 @@ def main(argv: Sequence[str] | None = None) -> int:
|
|||||||
parser.add_argument('--mentor-bin', 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)
|
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)
|
args = parser.parse_args(list(argv) if argv is not None else None)
|
||||||
|
if args.file_probe:
|
||||||
|
from .file_probe import file_probe_main
|
||||||
|
return file_probe_main(args.file_probe)
|
||||||
if args.owner_probe:
|
if args.owner_probe:
|
||||||
from .owner_probe import owner_probe_main
|
from .owner_probe import owner_probe_main
|
||||||
return owner_probe_main(args.owner_probe)
|
return owner_probe_main(args.owner_probe)
|
||||||
if args.native_backup_worker:
|
if args.native_backup_worker:
|
||||||
from .native_backup import native_backup_worker_main
|
return _native_worker_entry('native-backup', args.native_backup_worker)
|
||||||
return native_backup_worker_main(args.native_backup_worker)
|
|
||||||
if args.management_worker:
|
if args.management_worker:
|
||||||
from .native_management import management_worker_main
|
return _native_worker_entry('management', args.management_worker)
|
||||||
return management_worker_main(args.management_worker)
|
|
||||||
if args.repair_worker:
|
if args.repair_worker:
|
||||||
from .native_repair_ui import repair_worker_main
|
return _native_worker_entry('repair', args.repair_worker)
|
||||||
return repair_worker_main(args.repair_worker)
|
|
||||||
if args.collect_failure_logs:
|
if args.collect_failure_logs:
|
||||||
from .verify_diagnostics import failure_logs_main
|
from .verify_diagnostics import failure_logs_main
|
||||||
return failure_logs_main(args.collect_failure_logs)
|
return failure_logs_main(args.collect_failure_logs)
|
||||||
@@ -108,11 +168,7 @@ def main(argv: Sequence[str] | None = None) -> int:
|
|||||||
from .dialog_agent import dialog_agent_main
|
from .dialog_agent import dialog_agent_main
|
||||||
return dialog_agent_main(args.dialog_agent)
|
return dialog_agent_main(args.dialog_agent)
|
||||||
if args.verify_worker:
|
if args.verify_worker:
|
||||||
from .mentor_adapter import worker_main
|
return _native_worker_entry('verify', args.verify_worker)
|
||||||
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")
|
context = configure(resolve_data_root(args.data_root)); logger = context.logger; logger.info("application_start")
|
||||||
try:
|
try:
|
||||||
if args.batch_lmc:
|
if args.batch_lmc:
|
||||||
|
|||||||
@@ -28,21 +28,26 @@ def _paths(root):
|
|||||||
return list(_scan(root))
|
return list(_scan(root))
|
||||||
|
|
||||||
|
|
||||||
def _idle_check(library, project, pcb):
|
def _idle_check(library, project, pcb, *, confirmation=None, evidence=None, block=''):
|
||||||
from .mentor_adapter import _process_details
|
from .owner_probe import query_owners
|
||||||
from .icdb_ownership import database_directories, unreleased_addresses
|
from .icdb_ownership import database_directories, unreleased_addresses
|
||||||
from contextlib import ExitStack
|
from contextlib import ExitStack
|
||||||
import win32con, win32file
|
import win32con, win32file
|
||||||
|
from .operation_queue import note_metadata_progress
|
||||||
directories = database_directories(library, project, pcb)
|
directories = database_directories(library, project, pcb)
|
||||||
scope = (Path(project).parent, *directories)
|
scope = (Path(project).parent, *directories)
|
||||||
for name in ('ExpeditionPCB.exe', 'LibraryManager.exe', 'viewdraw.exe',
|
def owners():
|
||||||
'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe'):
|
unknown = []
|
||||||
for pid, executable, command, parent in _process_details(name):
|
names = ('ExpeditionPCB.exe', 'LibraryManager.exe', 'viewdraw.exe',
|
||||||
match = _native_scope_match(command, roots=scope, files=(library, project, pcb))
|
'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe')
|
||||||
|
for row in query_owners(names):
|
||||||
|
match = _native_scope_match(row['command'], roots=scope, files=(library, project, pcb))
|
||||||
if match is True:
|
if match is True:
|
||||||
raise ValueError(f'TARGET_NATIVE_OWNER_ACTIVE: 目标工程或共享库有原生会话,PID={pid}')
|
raise ValueError(f'TARGET_NATIVE_OWNER_ACTIVE: 目标工程或共享库有原生会话,PID={row["pid"]}')
|
||||||
# Pathless clients do not identify this target. The address and
|
if match is None:
|
||||||
# exclusive file probes below still reject actual target occupancy.
|
unknown.append(row)
|
||||||
|
return unknown
|
||||||
|
def resources():
|
||||||
addresses = unreleased_addresses(library, project, pcb)
|
addresses = unreleased_addresses(library, project, pcb)
|
||||||
if addresses:
|
if addresses:
|
||||||
raise ValueError(f'TARGET_DATABASE_ADDRESS_UNCONFIRMED: 地址记录需原生确认;未据此判定正在占用:{addresses}')
|
raise ValueError(f'TARGET_DATABASE_ADDRESS_UNCONFIRMED: 地址记录需原生确认;未据此判定正在占用:{addresses}')
|
||||||
@@ -54,6 +59,21 @@ def _idle_check(library, project, pcb):
|
|||||||
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
|
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
|
||||||
win32con.OPEN_EXISTING, 0, None)
|
win32con.OPEN_EXISTING, 0, None)
|
||||||
stack.callback(handle.Close)
|
stack.callback(handle.Close)
|
||||||
|
unknown = owners()
|
||||||
|
resources() # Never hold exclusive probe handles while waiting for a user.
|
||||||
|
if not unknown:
|
||||||
|
note_metadata_progress()
|
||||||
|
return
|
||||||
|
if confirmation is None:
|
||||||
|
from .write_admission import WriteAdmissionDeclined
|
||||||
|
raise WriteAdmissionDeclined('skip',
|
||||||
|
'TARGET_NATIVE_OWNER_UNCONFIRMED: 原生程序的工程归属未知,未执行;写入前需要确认。')
|
||||||
|
confirmation.confirm(library, unknown, evidence=evidence, block=block)
|
||||||
|
unknown = owners()
|
||||||
|
if unknown and not confirmation.confirmed(library, unknown):
|
||||||
|
raise ValueError('TARGET_NATIVE_OWNER_UNCONFIRMED: 占用确认后出现新的未知进程,请重新检查。')
|
||||||
|
resources()
|
||||||
|
note_metadata_progress()
|
||||||
|
|
||||||
|
|
||||||
def _native_scope_match(command, *, roots=(), files=()):
|
def _native_scope_match(command, *, roots=(), files=()):
|
||||||
@@ -142,17 +162,21 @@ def _align_library(project, pcb, library):
|
|||||||
ensure_project_central_library(path, library)
|
ensure_project_central_library(path, library)
|
||||||
|
|
||||||
|
|
||||||
def recover_from_backup(request, source, *, progress=None, verifier=None, idle_check=None, version_prompt=None):
|
def recover_from_backup(request, source, *, progress=None, verifier=None, idle_check=None, version_prompt=None,stop=None):
|
||||||
"""Validate in copies before changing Work; preserve all recovery evidence."""
|
"""Validate in copies before changing Work; preserve all recovery evidence."""
|
||||||
import pythoncom, win32con, win32event
|
from .operation_queue import check_active, local_commit, note_metadata_progress, QueueCancelled
|
||||||
from .network_path import absolute_preserving_drive
|
from .network_path import absolute_preserving_drive
|
||||||
from .verify_runner import run_verify, read_library_flag_if_available
|
from .verify_runner import run_verify, read_library_flag_if_available
|
||||||
verifier = verifier or run_verify
|
verifier = verifier or run_verify
|
||||||
idle_check = idle_check or _idle_check
|
|
||||||
source = Path(source).resolve()
|
source = Path(source).resolve()
|
||||||
library = absolute_preserving_drive(request.lmc_file)
|
library = absolute_preserving_drive(request.lmc_file)
|
||||||
library_root = library.parent.resolve()
|
library_root = library.parent.resolve()
|
||||||
root = Path(request.evidence_dir).resolve() / ('backup-restore-' + uuid4().hex[:12])
|
root = Path(request.evidence_dir).resolve() / ('backup-restore-' + uuid4().hex[:12])
|
||||||
|
if idle_check is None:
|
||||||
|
from .write_admission import WriteAdmission
|
||||||
|
admission=WriteAdmission(prompt=version_prompt,stop=stop)
|
||||||
|
idle_check=lambda library,project,pcb:_idle_check(library,project,pcb,
|
||||||
|
confirmation=admission,evidence=root,block=request.block_name)
|
||||||
# Packaged desktop apps can redirect AppData to a very deep MSIX path.
|
# Packaged desktop apps can redirect AppData to a very deep MSIX path.
|
||||||
# Keep native EE7.9 files in a genuinely short, user-owned directory.
|
# Keep native EE7.9 files in a genuinely short, user-owned directory.
|
||||||
validation_base = Path.home() / '.cbb-restore'
|
validation_base = Path.home() / '.cbb-restore'
|
||||||
@@ -163,11 +187,16 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
|
|||||||
return VerifyResult('BLOCKED', stderr='恢复记录目录不能位于备份工程内。')
|
return VerifyResult('BLOCKED', stderr='恢复记录目录不能位于备份工程内。')
|
||||||
if validation_dir.is_relative_to(library_root) or validation_dir.is_relative_to(source.parent):
|
if validation_dir.is_relative_to(library_root) or validation_dir.is_relative_to(source.parent):
|
||||||
return VerifyResult('BLOCKED', stderr='本机验证目录不能位于目标库或备份工程内。')
|
return VerifyResult('BLOCKED', stderr='本机验证目录不能位于目标库或备份工程内。')
|
||||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
|
||||||
acquired = False
|
|
||||||
library_lock = None
|
library_lock = None
|
||||||
release_confirmed = True
|
release_confirmed = True
|
||||||
installed = False
|
installed = False
|
||||||
|
def check():
|
||||||
|
check_active()
|
||||||
|
if stop is not None and stop.is_set():
|
||||||
|
raise QueueCancelled('恢复已取消,未提交后续操作。')
|
||||||
|
def completed():
|
||||||
|
check()
|
||||||
|
note_metadata_progress()
|
||||||
record = {'operation': 'same_cbb_complete_project_restore', 'source': str(source),
|
record = {'operation': 'same_cbb_complete_project_restore', 'source': str(source),
|
||||||
'library': str(library), 'block': request.block_name, 'installed': False,
|
'library': str(library), 'block': request.block_name, 'installed': False,
|
||||||
'validation_library': str(validation_dir/library.name), 'backup_policy': 'manual'}
|
'validation_library': str(validation_dir/library.name), 'backup_policy': 'manual'}
|
||||||
@@ -192,23 +221,25 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
|
|||||||
from .com_runtime import initialize_com, uninitialize_com
|
from .com_runtime import initialize_com, uninitialize_com
|
||||||
initialized = initialize_com()
|
initialized = initialize_com()
|
||||||
try:
|
try:
|
||||||
acquired = win32event.WaitForSingleObject(mutex, 0) in (
|
check()
|
||||||
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
|
||||||
if not acquired:
|
|
||||||
return VerifyResult('BLOCKED', stderr='已有 CBB 任务运行,请等待结束。', safe_to_continue=False)
|
|
||||||
from .library_lock import LibraryLock
|
from .library_lock import LibraryLock
|
||||||
library_lock = LibraryLock(library, safe_to_release=lambda: release_confirmed)
|
library_lock = LibraryLock(library, safe_to_release=lambda: release_confirmed)
|
||||||
library_lock.__enter__()
|
library_lock.__enter__()
|
||||||
if source.is_relative_to(library_root):
|
if source.is_relative_to(library_root):
|
||||||
raise ValueError('请选择目标中心库之外的独立备份工程。')
|
raise ValueError('请选择目标中心库之外的独立备份工程。')
|
||||||
project, pcb = preflight(replace(request, lmc_file=library))
|
project, pcb = preflight(replace(request, lmc_file=library))
|
||||||
|
completed()
|
||||||
source_pcb = _source_check(source, request.block_name, project)
|
source_pcb = _source_check(source, request.block_name, project)
|
||||||
idle_check(library, project, pcb)
|
completed()
|
||||||
idle_check(library, source, source_pcb)
|
|
||||||
root.mkdir(parents=True, exist_ok=False)
|
root.mkdir(parents=True, exist_ok=False)
|
||||||
|
idle_check(library, project, pcb)
|
||||||
|
completed()
|
||||||
|
idle_check(library, source, source_pcb)
|
||||||
|
completed()
|
||||||
validation_base.mkdir(parents=True, exist_ok=True)
|
validation_base.mkdir(parents=True, exist_ok=True)
|
||||||
library_size = sum(info.st_size for info in _scan(library_root).values() if stat.S_ISREG(info.st_mode))
|
library_size = sum(info.st_size for info in _scan(library_root).values() if stat.S_ISREG(info.st_mode))
|
||||||
source_size = sum(info.st_size for info in _scan(source.parent).values() if stat.S_ISREG(info.st_mode))
|
source_size = sum(info.st_size for info in _scan(source.parent).values() if stat.S_ISREG(info.st_mode))
|
||||||
|
completed()
|
||||||
same_drive = root.anchor.casefold() == validation_dir.anchor.casefold()
|
same_drive = root.anchor.casefold() == validation_dir.anchor.casefold()
|
||||||
required = (library_size + source_size * 2) if same_drive else 0
|
required = (library_size + source_size * 2) if same_drive else 0
|
||||||
if (shutil.disk_usage(root).free < required
|
if (shutil.disk_usage(root).free < required
|
||||||
@@ -220,6 +251,7 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
|
|||||||
library_scope = ManifestScope.library(request.block_name, library.name)
|
library_scope = ManifestScope.library(request.block_name, library.name)
|
||||||
original_manifest = _copy_verified(library_root, validation_dir, scope=library_scope,
|
original_manifest = _copy_verified(library_root, validation_dir, scope=library_scope,
|
||||||
progress=copy_progress('prepare_source', '正在准备验证库:'))
|
progress=copy_progress('prepare_source', '正在准备验证库:'))
|
||||||
|
completed()
|
||||||
(root/'library-baseline-manifest.json').write_text(json.dumps(original_manifest, indent=2), encoding='utf-8')
|
(root/'library-baseline-manifest.json').write_text(json.dumps(original_manifest, indent=2), encoding='utf-8')
|
||||||
staged_library = validation_dir/library.name
|
staged_library = validation_dir/library.name
|
||||||
staged_work = staged_library.parent/'ReusableBlocksLP'/request.block_name/'Work'
|
staged_work = staged_library.parent/'ReusableBlocksLP'/request.block_name/'Work'
|
||||||
@@ -228,8 +260,10 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
|
|||||||
if not resolved_work.is_relative_to(validation_dir.resolve()):
|
if not resolved_work.is_relative_to(validation_dir.resolve()):
|
||||||
raise ValueError('验证副本工程路径越界。')
|
raise ValueError('验证副本工程路径越界。')
|
||||||
shutil.rmtree(resolved_work)
|
shutil.rmtree(resolved_work)
|
||||||
|
completed()
|
||||||
source_manifest = _copy_verified(source.parent, staged_work,
|
source_manifest = _copy_verified(source.parent, staged_work,
|
||||||
progress=copy_progress('prepare_source', '正在准备备份验证工程:'))
|
progress=copy_progress('prepare_source', '正在准备备份验证工程:'))
|
||||||
|
completed()
|
||||||
(root/'source-manifest.json').write_text(json.dumps(source_manifest, indent=2), encoding='utf-8')
|
(root/'source-manifest.json').write_text(json.dumps(source_manifest, indent=2), encoding='utf-8')
|
||||||
staged_project = staged_work/source.name
|
staged_project = staged_work/source.name
|
||||||
staged_pcb = staged_work/source_pcb.relative_to(source.parent)
|
staged_pcb = staged_work/source_pcb.relative_to(source.parent)
|
||||||
@@ -239,31 +273,44 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
|
|||||||
auto_repair=False, libspec='', dms_login_config='', mapped_drive='', mapped_remote_root='',
|
auto_repair=False, libspec='', dms_login_config='', mapped_drive='', mapped_remote_root='',
|
||||||
native_lm_verify=False, interactive_input=False)
|
native_lm_verify=False, interactive_input=False)
|
||||||
preflight(validation)
|
preflight(validation)
|
||||||
|
completed()
|
||||||
emit('validate_source', '正在副本中打开备份工程并执行原生校验…')
|
emit('validate_source', '正在副本中打开备份工程并执行原生校验…')
|
||||||
|
check()
|
||||||
release_confirmed = False
|
release_confirmed = False
|
||||||
choice_options = {'version_prompt': version_prompt} if version_prompt is not None else {}
|
choice_options = {'version_prompt': version_prompt} if version_prompt is not None else {}
|
||||||
|
if stop is not None:choice_options['stop']=stop
|
||||||
source_result = verifier(validation, progress=progress, flag_reader=read_library_flag_if_available, **choice_options)
|
source_result = verifier(validation, progress=progress, flag_reader=read_library_flag_if_available, **choice_options)
|
||||||
release_confirmed = source_result.safe_to_continue
|
release_confirmed = source_result.safe_to_continue
|
||||||
record['source_validation'] = asdict(source_result)
|
record['source_validation'] = asdict(source_result)
|
||||||
|
completed()
|
||||||
if (source_result.status != 'PASS' or source_result.library_flag != 'GREEN'
|
if (source_result.status != 'PASS' or source_result.library_flag != 'GREEN'
|
||||||
or not source_result.safe_to_continue):
|
or not source_result.safe_to_continue):
|
||||||
return save(replace(source_result, status='FAIL', stderr=
|
return save(replace(source_result, status='FAIL', stderr=
|
||||||
'备份校验未通过,目标未更改。\n' + (source_result.stderr or source_result.library_flag_detail)))
|
'备份校验未通过,目标未更改。\n' + (source_result.stderr or source_result.library_flag_detail)))
|
||||||
idle_check(library, project, pcb)
|
idle_check(library, project, pcb)
|
||||||
|
completed()
|
||||||
idle_check(staged_library, staged_project, staged_pcb)
|
idle_check(staged_library, staged_project, staged_pcb)
|
||||||
|
completed()
|
||||||
token = root.name.removeprefix('backup-restore-')
|
token = root.name.removeprefix('backup-restore-')
|
||||||
work = project.parent.resolve()
|
work = project.parent.resolve()
|
||||||
incoming = work.with_name('Work.restore-' + token)
|
incoming = work.with_name('Work.restore-' + token)
|
||||||
retained = work.with_name('Work.before-restore-' + token)
|
retained = work.with_name('Work.before-restore-' + token)
|
||||||
_copy_verified(staged_work, incoming,
|
_copy_verified(staged_work, incoming,
|
||||||
progress=copy_progress('prepare_source', '正在准备恢复工程:'))
|
progress=copy_progress('prepare_source', '正在准备恢复工程:'))
|
||||||
|
completed()
|
||||||
_align_library(incoming/source.name, incoming/source_pcb.relative_to(source.parent), library)
|
_align_library(incoming/source.name, incoming/source_pcb.relative_to(source.parent), library)
|
||||||
|
completed()
|
||||||
idle_check(library, source, source_pcb)
|
idle_check(library, source, source_pcb)
|
||||||
|
completed()
|
||||||
if _manifest(source.parent) != source_manifest:
|
if _manifest(source.parent) != source_manifest:
|
||||||
raise ValueError('备份来源在验证期间发生变化,目标未更改。')
|
raise ValueError('备份来源在验证期间发生变化,目标未更改。')
|
||||||
|
completed()
|
||||||
if _manifest(library_root, scope=library_scope, exclude=incoming.resolve()) != original_manifest:
|
if _manifest(library_root, scope=library_scope, exclude=incoming.resolve()) != original_manifest:
|
||||||
raise ValueError('目标中心库在验证期间发生变化,停止恢复。')
|
raise ValueError('目标中心库在验证期间发生变化,停止恢复。')
|
||||||
|
completed()
|
||||||
emit('install', '备份已通过验证,正在保留原工程并恢复…')
|
emit('install', '备份已通过验证,正在保留原工程并恢复…')
|
||||||
|
check()
|
||||||
|
with local_commit():
|
||||||
work.rename(retained)
|
work.rename(retained)
|
||||||
try:
|
try:
|
||||||
incoming.rename(work)
|
incoming.rename(work)
|
||||||
@@ -272,7 +319,9 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
|
|||||||
raise
|
raise
|
||||||
installed = True
|
installed = True
|
||||||
record['retained_work'] = str(retained)
|
record['retained_work'] = str(retained)
|
||||||
|
completed()
|
||||||
emit('verify_target', '正在重新打开恢复后的目标工程并校验…')
|
emit('verify_target', '正在重新打开恢复后的目标工程并校验…')
|
||||||
|
check()
|
||||||
release_confirmed = False
|
release_confirmed = False
|
||||||
final = verifier(replace(request, lmc_file=library, evidence_dir=root/'target-verify',
|
final = verifier(replace(request, lmc_file=library, evidence_dir=root/'target-verify',
|
||||||
auto_repair=False, native_lm_verify=False, interactive_input=False),
|
auto_repair=False, native_lm_verify=False, interactive_input=False),
|
||||||
@@ -284,6 +333,10 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
|
|||||||
final = replace(final, stderr=(final.stderr + '\n原 Work 已改名保留;应用未创建完整库备份,请查看恢复记录并使用手动备份。').strip())
|
final = replace(final, stderr=(final.stderr + '\n原 Work 已改名保留;应用未创建完整库备份,请查看恢复记录并使用手动备份。').strip())
|
||||||
return save(final)
|
return save(final)
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
|
from .write_admission import WriteAdmissionDeclined
|
||||||
|
if isinstance(error, WriteAdmissionDeclined) and not installed:
|
||||||
|
status = 'CANCELLED' if error.decision == 'cancel' else 'SKIPPED'
|
||||||
|
return save(VerifyResult(status, stderr=str(error), safe_to_continue=release_confirmed))
|
||||||
return save(VerifyResult('FAIL' if installed else 'BLOCKED', stderr=str(error),
|
return save(VerifyResult('FAIL' if installed else 'BLOCKED', stderr=str(error),
|
||||||
safe_to_continue=release_confirmed))
|
safe_to_continue=release_confirmed))
|
||||||
finally:
|
finally:
|
||||||
@@ -291,7 +344,4 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
|
|||||||
if library_lock is not None:
|
if library_lock is not None:
|
||||||
library_lock.__exit__(None, None, None)
|
library_lock.__exit__(None, None, None)
|
||||||
finally:
|
finally:
|
||||||
if acquired:
|
|
||||||
win32event.ReleaseMutex(mutex)
|
|
||||||
mutex.Close()
|
|
||||||
uninitialize_com(initialized)
|
uninitialize_com(initialized)
|
||||||
@@ -16,6 +16,225 @@ _automation_clients = []
|
|||||||
_automation_clients_lock = threading.Lock()
|
_automation_clients_lock = threading.Lock()
|
||||||
_supervisor_lost = threading.Event()
|
_supervisor_lost = threading.Event()
|
||||||
_native_phases = {}
|
_native_phases = {}
|
||||||
|
WRITER_MUTEX = r'Local\CbbRefreshVerify795NativeWriter'
|
||||||
|
|
||||||
|
|
||||||
|
def assert_native_writer_idle():
|
||||||
|
mutex = win32event.CreateMutex(None, False, WRITER_MUTEX)
|
||||||
|
acquired = False
|
||||||
|
try:
|
||||||
|
acquired = win32event.WaitForSingleObject(mutex, 0) in (
|
||||||
|
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
||||||
|
if not acquired:
|
||||||
|
raise RuntimeError('NATIVE_WRITER_ACTIVE: 原生事务尚未返回,未启动新的写入。')
|
||||||
|
finally:
|
||||||
|
if acquired: win32event.ReleaseMutex(mutex)
|
||||||
|
mutex.Close()
|
||||||
|
|
||||||
|
|
||||||
|
class _RegisteredWriter:
|
||||||
|
def __init__(self, handle):
|
||||||
|
import win32api
|
||||||
|
current = win32api.GetCurrentProcess()
|
||||||
|
self.handle = win32api.DuplicateHandle(current, handle, current, 0, False,
|
||||||
|
win32con.DUPLICATE_SAME_ACCESS)
|
||||||
|
self.returncode = None
|
||||||
|
|
||||||
|
def poll(self):
|
||||||
|
if self.returncode is None and win32event.WaitForSingleObject(self.handle, 0) == win32con.WAIT_OBJECT_0:
|
||||||
|
self.returncode = win32process.GetExitCodeProcess(self.handle)
|
||||||
|
self.handle.Close()
|
||||||
|
return self.returncode
|
||||||
|
|
||||||
|
|
||||||
|
def register_native_writer(process):
|
||||||
|
handle = getattr(process, 'handle', None) or getattr(process, '_handle', None)
|
||||||
|
registered = _RegisteredWriter(handle) if handle is not None else process
|
||||||
|
with _automation_clients_lock:
|
||||||
|
_automation_clients.append(registered)
|
||||||
|
return process
|
||||||
|
|
||||||
|
|
||||||
|
class _PendingNativeOperation:
|
||||||
|
"""One asynchronously submitted operation, including its native descendants."""
|
||||||
|
def __init__(self, job, identities):
|
||||||
|
import win32api
|
||||||
|
from .residual_sessions import _handle_identity, _force_ownership
|
||||||
|
from .session_record import IDENTITY_KEYS
|
||||||
|
self.record = job
|
||||||
|
self.job = win32job.CreateJobObject(None, '') # Deliberately no kill-on-close.
|
||||||
|
self.owners = {}
|
||||||
|
self.recorded = set()
|
||||||
|
self.completed = False
|
||||||
|
self.exited = False
|
||||||
|
self.lock = threading.Lock()
|
||||||
|
try:
|
||||||
|
for identity in identities:
|
||||||
|
pid = identity['pid']
|
||||||
|
handle = win32api.OpenProcess(win32con.SYNCHRONIZE | 0x1000 |
|
||||||
|
win32con.PROCESS_SET_QUOTA | win32con.PROCESS_TERMINATE, False, pid)
|
||||||
|
try:
|
||||||
|
actual = dict(pid=pid, **_handle_identity(handle), **_force_ownership(handle, pid))
|
||||||
|
if any(actual[key] != identity.get(key) for key in IDENTITY_KEYS):
|
||||||
|
raise RuntimeError('NATIVE_OPERATION_IDENTITY_CHANGED')
|
||||||
|
win32job.AssignProcessToJobObject(self.job, handle)
|
||||||
|
self.owners[pid] = _RegisteredWriter(handle)
|
||||||
|
self.recorded.add(pid)
|
||||||
|
finally:
|
||||||
|
handle.Close()
|
||||||
|
except Exception:
|
||||||
|
self._close()
|
||||||
|
raise # Admission failure is not permission to post Add without protection.
|
||||||
|
|
||||||
|
def _close(self):
|
||||||
|
for owner in self.owners.values():
|
||||||
|
if owner.returncode is None:
|
||||||
|
owner.handle.Close()
|
||||||
|
self.job.Close()
|
||||||
|
self.exited = True
|
||||||
|
|
||||||
|
def complete(self):
|
||||||
|
with self.lock:
|
||||||
|
self.completed = True # Only an exact native acknowledgement settles the operation.
|
||||||
|
|
||||||
|
def poll(self):
|
||||||
|
with self.lock:
|
||||||
|
return self._poll()
|
||||||
|
|
||||||
|
def _poll(self):
|
||||||
|
if self.exited:
|
||||||
|
return 0
|
||||||
|
pids = set(win32job.QueryInformationJobObject(self.job, win32job.JobObjectBasicProcessIdList))
|
||||||
|
fresh = pids-self.recorded
|
||||||
|
if fresh:
|
||||||
|
from .session_record import update_worker_state
|
||||||
|
from .residual_sessions import _process_handle, _handle_identity, _force_ownership
|
||||||
|
identities = []
|
||||||
|
for pid in fresh:
|
||||||
|
with _process_handle(pid) as handle:
|
||||||
|
if not win32job.IsProcessInJob(handle, self.job):
|
||||||
|
continue # The snapshot PID may have been reused outside this job.
|
||||||
|
identities.append(('native', dict(pid=pid, **_handle_identity(handle),
|
||||||
|
**_force_ownership(handle, pid))))
|
||||||
|
if identities and update_worker_state(self.record, 'UNCONFIRMED', observed_identities=identities):
|
||||||
|
self.recorded.update(identity['pid'] for _, identity in identities)
|
||||||
|
# An acknowledged Add does not retain an otherwise idle LM shell.
|
||||||
|
# Descendants still need observed exit; PID reuse cannot imitate an owner.
|
||||||
|
idle = {pid for pid, owner in self.owners.items() if owner.poll() is None} if self.completed else set()
|
||||||
|
if not pids-idle:
|
||||||
|
self._close()
|
||||||
|
return 0
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def register_pending_native_operation(job, pids):
|
||||||
|
from .session_record import read_session_record, update_worker_state
|
||||||
|
pids = set(pids)
|
||||||
|
if not pids:
|
||||||
|
raise RuntimeError('NATIVE_OPERATION_OWNER_REQUIRED')
|
||||||
|
# Retain the creation/image/owner identity in the existing bound journal
|
||||||
|
# before asynchronous dispatch, so a restarted UI can validate controls.
|
||||||
|
update_worker_state(job, 'POSTCALL', identities=[('native', pid) for pid in pids], required=True)
|
||||||
|
path = Path(job['session_record_path']).with_name('worker-state.json')
|
||||||
|
record = read_session_record(path, evidence_root=path.parent)
|
||||||
|
identities = [p for p in record.get('processes', ()) if p['pid'] in pids and p.get('role') == 'native']
|
||||||
|
if record['operation_id'] != job['operation_id'] or {p['pid'] for p in identities} != pids:
|
||||||
|
raise RuntimeError('NATIVE_OPERATION_OWNER_UNCONFIRMED')
|
||||||
|
operation = _PendingNativeOperation(job, identities)
|
||||||
|
with _automation_clients_lock:
|
||||||
|
_automation_clients.append(operation)
|
||||||
|
return operation
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def worker_native_channel(*, lease_handle=None, inspection_only=False):
|
||||||
|
"""The native worker, not its disposable supervisor, owns write exclusion."""
|
||||||
|
import win32api
|
||||||
|
mutex = win32event.CreateMutex(None, False, WRITER_MUTEX)
|
||||||
|
acquired = False
|
||||||
|
try:
|
||||||
|
if inspection_only is not True:
|
||||||
|
acquired = win32event.WaitForSingleObject(mutex, 0) in (
|
||||||
|
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
||||||
|
if not acquired:
|
||||||
|
raise RuntimeError('NATIVE_WRITER_ACTIVE: 原生事务尚未返回。')
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
if acquired:
|
||||||
|
# Only registered Save/Close/Repair clients extend the boundary;
|
||||||
|
# an idle PCB shell or a business failure is not a pending write.
|
||||||
|
warned = False
|
||||||
|
while True:
|
||||||
|
with _automation_clients_lock:
|
||||||
|
clients = tuple(_automation_clients)
|
||||||
|
try:
|
||||||
|
released = all(client.poll() is not None for client in clients)
|
||||||
|
except Exception:
|
||||||
|
released = False
|
||||||
|
if not warned:
|
||||||
|
logging.getLogger(__name__).warning('Native writer exit is unconfirmed', exc_info=True)
|
||||||
|
warned = True
|
||||||
|
if released:
|
||||||
|
break
|
||||||
|
threading.Event().wait(.1)
|
||||||
|
win32event.ReleaseMutex(mutex)
|
||||||
|
mutex.Close()
|
||||||
|
if lease_handle is not None:
|
||||||
|
win32api.CloseHandle(int(lease_handle))
|
||||||
|
|
||||||
|
|
||||||
|
def run_native_worker(action, request_path, *, admission_state=None):
|
||||||
|
"""Wait for durable parent admission before acquiring the worker barrier."""
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
job = json.loads(Path(request_path).read_text(encoding='utf-8'))
|
||||||
|
gate = Path(job['start_gate']) if job.get('start_gate') else None
|
||||||
|
if gate is not None:
|
||||||
|
deadline = time.monotonic()+30
|
||||||
|
while not gate.is_file():
|
||||||
|
if (job.get('cancel_signal') and Path(job['cancel_signal']).exists()
|
||||||
|
or time.monotonic() >= deadline):
|
||||||
|
raise RuntimeError('WORKER_CANCELLED: 未取得启动许可。')
|
||||||
|
threading.Event().wait(.05)
|
||||||
|
lease_handle = None
|
||||||
|
record = None
|
||||||
|
if job.get('session_record_path'):
|
||||||
|
from .session_record import read_session_record, process_identity, IDENTITY_KEYS
|
||||||
|
path = Path(job['session_record_path'])
|
||||||
|
record = read_session_record(path, evidence_root=path.parent)
|
||||||
|
identity = process_identity(os.getpid())
|
||||||
|
if (record['operation_id'] != job['operation_id']
|
||||||
|
or any(record.get(key) != job.get(key) for key in (
|
||||||
|
'operation', 'library', 'block', 'desktop', 'worker_role', 'start_gate_protocol', 'start_gate'))
|
||||||
|
or not any(p.get('role') == 'worker' and all(p.get(k) == identity[k] for k in IDENTITY_KEYS)
|
||||||
|
for p in record.get('processes', ()))):
|
||||||
|
raise RuntimeError('WORKER_ADMISSION_IDENTITY_CHANGED')
|
||||||
|
lease_handle = record.get('worker_lease_handle')
|
||||||
|
if job.get('start_gate_protocol') == 'event-v1':
|
||||||
|
import win32api
|
||||||
|
handle = record.get('worker_start_handle') if record else None
|
||||||
|
if not handle:
|
||||||
|
raise RuntimeError('WORKER_ADMISSION_UNCONFIRMED: 缺少启动事件。')
|
||||||
|
try:
|
||||||
|
deadline = time.monotonic()+30
|
||||||
|
while win32event.WaitForSingleObject(int(handle), 50) != win32con.WAIT_OBJECT_0:
|
||||||
|
if (job.get('cancel_signal') and Path(job['cancel_signal']).exists()
|
||||||
|
or time.monotonic() >= deadline):
|
||||||
|
raise RuntimeError('WORKER_CANCELLED: 启动事件未提交。')
|
||||||
|
finally:
|
||||||
|
win32api.CloseHandle(int(handle))
|
||||||
|
if job.get('worker_role') == 'catalog_readonly':
|
||||||
|
from .native_management import catalog_worker_main
|
||||||
|
if action is not catalog_worker_main or job.get('operation') != 'catalog':
|
||||||
|
raise RuntimeError('WORKER_READONLY_ROLE_MISMATCH')
|
||||||
|
inspection = (action.__module__ == 'cbb_refresh_verify.native_repair_ui'
|
||||||
|
and action.__name__ == 'repair_worker_main' and job.get('inspection_only') is True)
|
||||||
|
with worker_native_channel(lease_handle=lease_handle, inspection_only=inspection):
|
||||||
|
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
|
||||||
|
raise RuntimeError('WORKER_CANCELLED: 已取消原生启动。')
|
||||||
|
if admission_state is not None:
|
||||||
|
admission_state['worker_entered'] = True
|
||||||
|
return action(request_path)
|
||||||
|
|
||||||
|
|
||||||
def _phase_pending(phase):
|
def _phase_pending(phase):
|
||||||
@@ -56,6 +275,8 @@ def _record_write_pending(record_path, operation_id=None):
|
|||||||
def launch_save_helper(command, *, start_gate=None, identity_path=None, operation_id=None, **kwargs):
|
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."""
|
"""Register the save client atomically with respect to supervisor loss."""
|
||||||
with _automation_clients_lock:
|
with _automation_clients_lock:
|
||||||
|
from .operation_queue import check_active
|
||||||
|
check_active()
|
||||||
if _supervisor_lost.is_set():
|
if _supervisor_lost.is_set():
|
||||||
raise RuntimeError('VERIFY_CANCELLED: 监督器已退出,未启动新的保存客户端')
|
raise RuntimeError('VERIFY_CANCELLED: 监督器已退出,未启动新的保存客户端')
|
||||||
helper = subprocess.Popen(command, **kwargs)
|
helper = subprocess.Popen(command, **kwargs)
|
||||||
@@ -115,8 +336,11 @@ def start_supervisor_watchdog(supervisor_pid, *, cancel_path=None, stop_clients=
|
|||||||
pending = _record_write_pending(session_record_path, operation_id)
|
pending = _record_write_pending(session_record_path, operation_id)
|
||||||
# The same gate blocks new calls/helpers after loss. A stale
|
# The same gate blocks new calls/helpers after loss. A stale
|
||||||
# POSTCALL on disk cannot override an active in-memory call.
|
# POSTCALL on disk cannot override an active in-memory call.
|
||||||
if (pending is False and _phase_pending(_native_phases.get(operation_id)) is False
|
returned = 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)):
|
clients = tuple(_automation_clients)
|
||||||
|
# Polling can publish a job descendant's exact identity. Never
|
||||||
|
# hold the client registry lock while that journal is updated.
|
||||||
|
if returned and all(helper.poll() is not None for helper in clients):
|
||||||
os._exit(75) # This Python worker only; native children remain untouched.
|
os._exit(75) # This Python worker only; native children remain untouched.
|
||||||
threading.Event().wait(.2)
|
threading.Event().wait(.2)
|
||||||
finally:
|
finally:
|
||||||
@@ -160,6 +384,8 @@ class DesktopWorker:
|
|||||||
startup = win32process.STARTUPINFO()
|
startup = win32process.STARTUPINFO()
|
||||||
# subprocess.STARTUPINFO does NOT pass lpDesktop to CreateProcess.
|
# subprocess.STARTUPINFO does NOT pass lpDesktop to CreateProcess.
|
||||||
startup.lpDesktop = startup_desktop_name(name, interactive_input=self.interactive_input)
|
startup.lpDesktop = startup_desktop_name(name, interactive_input=self.interactive_input)
|
||||||
|
from .operation_queue import check_active
|
||||||
|
check_active()
|
||||||
self.handle, thread, self.pid, _ = win32process.CreateProcess(
|
self.handle, thread, self.pid, _ = win32process.CreateProcess(
|
||||||
command[0], subprocess.list2cmdline(command), None, None, False,
|
command[0], subprocess.list2cmdline(command), None, None, False,
|
||||||
win32con.CREATE_NO_WINDOW, None, None, startup)
|
win32con.CREATE_NO_WINDOW, None, None, startup)
|
||||||
@@ -199,6 +425,8 @@ class DesktopWorker:
|
|||||||
raise
|
raise
|
||||||
|
|
||||||
def start_companion(self, command):
|
def start_companion(self, command):
|
||||||
|
from .operation_queue import check_active
|
||||||
|
check_active()
|
||||||
startup = win32process.STARTUPINFO()
|
startup = win32process.STARTUPINFO()
|
||||||
startup.lpDesktop = startup_desktop_name(
|
startup.lpDesktop = startup_desktop_name(
|
||||||
self.name, interactive_input=getattr(self, 'interactive_input', False))
|
self.name, interactive_input=getattr(self, 'interactive_input', False))
|
||||||
@@ -283,7 +511,10 @@ class DesktopWorker:
|
|||||||
|
|
||||||
def bind_session(self, job):
|
def bind_session(self, job):
|
||||||
from .session_record import register_worker_session
|
from .session_record import register_worker_session
|
||||||
register_worker_session(self, job)
|
from .library_lock import duplicate_worker_lease
|
||||||
|
lease = (None if job.get('inspection_only') is True else
|
||||||
|
duplicate_worker_lease(job['library'], self.handle))
|
||||||
|
register_worker_session(self, {**job, 'worker_lease_handle': lease})
|
||||||
|
|
||||||
def native_write_pending(self):
|
def native_write_pending(self):
|
||||||
return _record_write_pending(getattr(self, 'session_record_path', None))
|
return _record_write_pending(getattr(self, 'session_record_path', None))
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import ctypes
|
|||||||
from ctypes import wintypes
|
from ctypes import wintypes
|
||||||
import heapq
|
import heapq
|
||||||
import hashlib
|
import hashlib
|
||||||
|
import json
|
||||||
import ntpath
|
import ntpath
|
||||||
import os
|
import os
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -138,16 +139,21 @@ def _load_evidence(job, pcb_pid, baseline, *, require_autosave=True):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _target_frame(windows, name):
|
def _target_frame(windows, name, *, require_ready=True):
|
||||||
matches = []
|
matches = []
|
||||||
for window in windows:
|
for window in windows:
|
||||||
if not window['class'].casefold().startswith('afx:') or not window.get('enabled', True):
|
if not window['class'].casefold().startswith('afx:'):
|
||||||
|
continue
|
||||||
|
if require_ready and (not window.get('enabled', True) or any(
|
||||||
|
child['class'].casefold() == 'msctls_progress32' and child.get('visible', False)
|
||||||
|
for child in window['children'])):
|
||||||
continue
|
continue
|
||||||
if not window['text'].casefold().startswith('expedition pcb') or f'[{name}]'.casefold() not in window['text'].casefold():
|
if not window['text'].casefold().startswith('expedition pcb') or f'[{name}]'.casefold() not in window['text'].casefold():
|
||||||
continue
|
continue
|
||||||
mdi = {child['hwnd'] for child in window['children'] if child['class'].casefold() == 'mdiclient'}
|
mdi = {child['hwnd'] for child in window['children'] if child['class'].casefold() == 'mdiclient'}
|
||||||
if any(child.get('parent') in mdi and child['text'].casefold() == name.casefold()
|
documents = [child for child in window['children'] if child.get('parent') in mdi
|
||||||
and child['class'].casefold().startswith('afx:') for child in window['children']):
|
and child['class'].casefold().startswith('afx:')]
|
||||||
|
if len(documents) == 1 and documents[0]['text'].casefold() == name.casefold():
|
||||||
matches.append(window)
|
matches.append(window)
|
||||||
return matches[0] if len(matches) == 1 else None
|
return matches[0] if len(matches) == 1 else None
|
||||||
|
|
||||||
@@ -170,6 +176,23 @@ def _windows(pid):
|
|||||||
# Custom controls may have no cached text; missing evidence fails closed.
|
# Custom controls may have no cached text; missing evidence fails closed.
|
||||||
user.GetWindowTextW(hwnd, buffer, len(buffer))
|
user.GetWindowTextW(hwnd, buffer, len(buffer))
|
||||||
return buffer.value
|
return buffer.value
|
||||||
|
def owner_chain(hwnd):
|
||||||
|
import win32service
|
||||||
|
desktop = win32service.GetUserObjectInformation(win32service.GetThreadDesktop(
|
||||||
|
win32api.GetCurrentThreadId()), 2)
|
||||||
|
chain, seen = [], {hwnd}
|
||||||
|
for _ in range(8):
|
||||||
|
hwnd = int(win32gui.GetWindow(hwnd, 4) or 0)
|
||||||
|
if not hwnd or hwnd in seen: break
|
||||||
|
seen.add(hwnd)
|
||||||
|
thread, owner_pid = win32process.GetWindowThreadProcessId(hwnd)
|
||||||
|
same_desktop = win32service.GetUserObjectInformation(win32service.GetThreadDesktop(thread), 2) == desktop
|
||||||
|
chain.append({'hwnd': hwnd, 'pid': owner_pid, 'class': win32gui.GetClassName(hwnd),
|
||||||
|
'text': text(hwnd), 'visible': bool(win32gui.IsWindowVisible(hwnd)),
|
||||||
|
'enabled': bool(win32gui.IsWindowEnabled(hwnd)), 'same_desktop': same_desktop,
|
||||||
|
'owner': int(win32gui.GetWindow(hwnd, 4) or 0)})
|
||||||
|
if owner_pid != pid or not same_desktop or chain[-1]['visible']: break
|
||||||
|
return chain
|
||||||
result = []
|
result = []
|
||||||
seen = 0
|
seen = 0
|
||||||
def collect(hwnd, _):
|
def collect(hwnd, _):
|
||||||
@@ -191,10 +214,10 @@ def _windows(pid):
|
|||||||
raise RuntimeError('DIAGNOSTIC_WINDOW_LIMIT: too many controls')
|
raise RuntimeError('DIAGNOSTIC_WINDOW_LIMIT: too many controls')
|
||||||
child_cls = win32gui.GetClassName(ch)
|
child_cls = win32gui.GetClassName(ch)
|
||||||
if (cls == '#32770' or cls.casefold() == 'internet explorer_hidden'
|
if (cls == '#32770' or cls.casefold() == 'internet explorer_hidden'
|
||||||
or child_cls.casefold() == 'mdiclient' or child_cls.casefold().startswith('afx:')):
|
or child_cls.casefold() in ('mdiclient', 'msctls_progress32') or child_cls.casefold().startswith('afx:')):
|
||||||
children.append({'hwnd': ch, 'class': child_cls, 'text': text(ch),
|
children.append({'hwnd': ch, 'class': child_cls, 'text': text(ch),
|
||||||
'id': win32gui.GetDlgCtrlID(ch), 'parent': win32gui.GetParent(ch),
|
'id': win32gui.GetDlgCtrlID(ch), 'parent': win32gui.GetParent(ch),
|
||||||
'enabled': bool(win32gui.IsWindowEnabled(ch))})
|
'enabled': bool(win32gui.IsWindowEnabled(ch)), 'visible': bool(win32gui.IsWindowVisible(ch))})
|
||||||
return True
|
return True
|
||||||
if cls == '#32770' or cls.casefold().startswith('afx:') or cls.casefold() == 'internet explorer_hidden':
|
if cls == '#32770' or cls.casefold().startswith('afx:') or cls.casefold() == 'internet explorer_hidden':
|
||||||
win32gui.EnumChildWindows(hwnd, child, None)
|
win32gui.EnumChildWindows(hwnd, child, None)
|
||||||
@@ -205,7 +228,8 @@ def _windows(pid):
|
|||||||
return True
|
return True
|
||||||
result.append({'hwnd': hwnd, 'pid': pid, 'class': cls, 'text': caption,
|
result.append({'hwnd': hwnd, 'pid': pid, 'class': cls, 'text': caption,
|
||||||
'enabled': bool(win32gui.IsWindowEnabled(hwnd)), 'children': children,
|
'enabled': bool(win32gui.IsWindowEnabled(hwnd)), 'children': children,
|
||||||
'owner': int(win32gui.GetWindow(hwnd, 4) or 0)})
|
'owner': int(win32gui.GetWindow(hwnd, 4) or 0),
|
||||||
|
'owner_chain': owner_chain(hwnd) if cls == '#32770' else []})
|
||||||
return True
|
return True
|
||||||
win32api.SetLastError(0)
|
win32api.SetLastError(0)
|
||||||
try:
|
try:
|
||||||
@@ -261,6 +285,50 @@ def _cancel(job):
|
|||||||
raise RuntimeError('VERIFY_CANCELLED: native opening check cancelled')
|
raise RuntimeError('VERIFY_CANCELLED: native opening check cancelled')
|
||||||
|
|
||||||
|
|
||||||
|
def _request_close_handoff(job, pcb_pid, frame, session, emit, deadline):
|
||||||
|
from uuid import uuid4
|
||||||
|
intent = dict(pcb_pid=int(pcb_pid), hwnd=frame['hwnd'], operation_id=job['operation_id'],
|
||||||
|
desktop=job['desktop'], project=job['project'], pcb=job['pcb'], close_id=uuid4().hex)
|
||||||
|
ack = Path(job['root'])/'diagnostic-close-ack.json'
|
||||||
|
emit(stage='diagnostic_close_requested', **intent)
|
||||||
|
def read_ack():
|
||||||
|
try:
|
||||||
|
with ack.open(encoding='utf-8') as stream:
|
||||||
|
return json.loads(stream.read(8192))
|
||||||
|
except (OSError, ValueError):
|
||||||
|
return None
|
||||||
|
while True:
|
||||||
|
_cancel(job)
|
||||||
|
remaining = deadline-time.monotonic()
|
||||||
|
if remaining <= 0 or not session.pcb_alive():
|
||||||
|
raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: supervisor handoff not acknowledged')
|
||||||
|
try:
|
||||||
|
acknowledged = _bounded_call(read_ack, min(2, remaining))
|
||||||
|
except TimeoutError as error:
|
||||||
|
raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: supervisor acknowledgement read timed out') from error
|
||||||
|
if acknowledged == intent:
|
||||||
|
return intent
|
||||||
|
time.sleep(min(.1, max(0, deadline-time.monotonic())))
|
||||||
|
|
||||||
|
|
||||||
|
def _owned_by_frame(window, frame):
|
||||||
|
if frame is None or window['pid'] != frame['pid']: return False
|
||||||
|
if window.get('owner') == frame['hwnd']: return True
|
||||||
|
chain = window.get('owner_chain', ())
|
||||||
|
expected, seen = window.get('owner'), {window['hwnd']}
|
||||||
|
if not chain or len(chain) > 8: return False
|
||||||
|
for index, owner in enumerate(chain):
|
||||||
|
if (owner['hwnd'] != expected or owner['hwnd'] in seen or owner['pid'] != frame['pid']
|
||||||
|
or owner.get('same_desktop') is not True): return False
|
||||||
|
seen.add(owner['hwnd'])
|
||||||
|
if owner['hwnd'] == frame['hwnd']:
|
||||||
|
return (index == len(chain)-1 and owner['class'] == frame['class'] and owner['text'] == frame['text'])
|
||||||
|
if (owner['class'] != '#32770' or owner['text'] != 'Expedition PCB'
|
||||||
|
or owner['visible'] or owner['enabled']): return False
|
||||||
|
expected = owner['owner']
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def _pending_prompt(windows, *, closing=False, frame=None, session=None, clicked=None, pcb_name=''):
|
def _pending_prompt(windows, *, closing=False, frame=None, session=None, clicked=None, pcb_name=''):
|
||||||
for window in windows:
|
for window in windows:
|
||||||
known_titles = {'expedition pcb', 'expedition pcb - reusable block'}
|
known_titles = {'expedition pcb', 'expedition pcb - reusable block'}
|
||||||
@@ -276,14 +344,21 @@ def _pending_prompt(windows, *, closing=False, frame=None, session=None, clicked
|
|||||||
and child['text'].strip().casefold() == f'Save changes to {pcb_name}?'.casefold()
|
and child['text'].strip().casefold() == f'Save changes to {pcb_name}?'.casefold()
|
||||||
for child in window['children'])
|
for child in window['children'])
|
||||||
and {child.get('id') for child in window['children'] if child['class'].casefold() == 'button'} == {2, 6, 7})
|
and {child.get('id') for child in window['children'] if child['class'].casefold() == 'button'} == {2, 6, 7})
|
||||||
if closing and window.get('owner') == frame['hwnd'] and (standard_save or 'do you want to save the reusable block cell' in text):
|
forward = (window['class'] == '#32770' and window['text'] == 'Expedition PCB'
|
||||||
|
and any(child['class'].casefold() == 'static' and child.get('id') == 6172
|
||||||
|
and ' '.join(child['text'].split()) == 'New changes are ready for Forward Annotation. Do you want to Forward Annotate now?'
|
||||||
|
for child in window['children'])
|
||||||
|
and {child.get('id') for child in window['children'] if child['class'].casefold() == 'button'} in ({6,7}, {6,7,6171}))
|
||||||
|
if _owned_by_frame(window, frame) and (forward or closing and (standard_save or 'do you want to save the reusable block cell' in text)):
|
||||||
targets = [child for child in window['children'] if child['class'].casefold() == 'button'
|
targets = [child for child in window['children'] if child['class'].casefold() == 'button'
|
||||||
and child.get('id') == 7 and child['text'].replace('&', '').strip().casefold() in {'no', '否(n)', '否'}
|
and child.get('id') == 7 and child['text'].replace('&', '').strip().casefold() in {'no', '否(n)', '否'}
|
||||||
and child.get('enabled', True)]
|
and child.get('enabled', True)]
|
||||||
if len(targets) == 1:
|
if len(targets) == 1:
|
||||||
|
if session is None: return True
|
||||||
if window['hwnd'] not in clicked:
|
if window['hwnd'] not in clicked:
|
||||||
session.post(targets[0]['hwnd'], 0xF5)
|
session.post(targets[0]['hwnd'], 0xF5)
|
||||||
clicked.add(window['hwnd'])
|
clicked.add(window['hwnd'])
|
||||||
|
if not closing: return True
|
||||||
continue
|
continue
|
||||||
raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: unknown native prompt preserved; '
|
raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: unknown native prompt preserved; '
|
||||||
f"pid={window['pid']} hwnd={window['hwnd']} class={window['class']!r} "
|
f"pid={window['pid']} hwnd={window['hwnd']} class={window['class']!r} "
|
||||||
@@ -291,6 +366,68 @@ def _pending_prompt(windows, *, closing=False, frame=None, session=None, clicked
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def cancelled_startup_step(job, pcb_pid, state, *, closed_frame, deadline, post, emit,
|
||||||
|
read_windows=None, identity_check=None):
|
||||||
|
"""Finish only the owned no-write diagnostic startup; never establish PASS.
|
||||||
|
|
||||||
|
Cancellation already ended supervisor polling. Cleanup is its sole prompt
|
||||||
|
actor and uses the caller's original deadline and single-close state.
|
||||||
|
"""
|
||||||
|
from types import SimpleNamespace
|
||||||
|
read_windows = read_windows or (lambda: _windows(pcb_pid))
|
||||||
|
windows = read_windows()
|
||||||
|
if any(window['pid'] != pcb_pid for window in windows):
|
||||||
|
raise RuntimeError('STARTUP_PROCESS_UNCONFIRMED')
|
||||||
|
current = _target_frame(windows, Path(job['pcb']).stem, require_ready=False)
|
||||||
|
frame = current
|
||||||
|
if frame is None and closed_frame is not None:
|
||||||
|
frame = state.get('frame')
|
||||||
|
if frame is None:
|
||||||
|
return closed_frame, False
|
||||||
|
old = state.get('frame')
|
||||||
|
if old is not None and any(frame[k] != old[k] for k in ('hwnd', 'pid', 'class', 'text')):
|
||||||
|
raise RuntimeError('STARTUP_DOCUMENT_CHANGED')
|
||||||
|
if closed_frame is not None and frame['hwnd'] != closed_frame:
|
||||||
|
raise RuntimeError('STARTUP_DOCUMENT_CHANGED')
|
||||||
|
if old is None:
|
||||||
|
# Explicit legacy cleanup supplies already checked registration. It is
|
||||||
|
# revalidated immediately before every action, never used as open proof.
|
||||||
|
confirmed = (identity_check is not None or
|
||||||
|
_load_evidence(job, pcb_pid, job['diagnostic_log_baseline'], require_autosave=False) is not None)
|
||||||
|
if not confirmed:
|
||||||
|
return closed_frame, False
|
||||||
|
state['frame'] = frame
|
||||||
|
# Validate every window before allowing a known No. An unknown sibling
|
||||||
|
# must not be hidden by the first recognized modal in enumeration order.
|
||||||
|
try:
|
||||||
|
for window in windows:
|
||||||
|
_pending_prompt([window], closing=closed_frame is not None, frame=frame,
|
||||||
|
pcb_name=Path(job['pcb']).name)
|
||||||
|
except RuntimeError as error:
|
||||||
|
if str(error).startswith('DIAGNOSTIC_CLOSE_UNCONFIRMED: unknown native prompt'):
|
||||||
|
return closed_frame, False
|
||||||
|
raise
|
||||||
|
actions = []
|
||||||
|
def act(hwnd, message):
|
||||||
|
if read_windows() != windows:
|
||||||
|
raise RuntimeError('STARTUP_WINDOW_CHANGED: native snapshot changed before action')
|
||||||
|
if identity_check is not None and not identity_check():
|
||||||
|
raise RuntimeError('STARTUP_IDENTITY_UNCONFIRMED: registered cleanup binding changed')
|
||||||
|
if time.monotonic() >= deadline:
|
||||||
|
raise RuntimeError('STARTUP_CLEANUP_TIMEOUT: original cleanup deadline reached')
|
||||||
|
post(hwnd, message)
|
||||||
|
actions.append((hwnd, message))
|
||||||
|
if message == 0xF5:
|
||||||
|
emit(stage='startup_prompt_no', pcb_pid=pcb_pid, hwnd=hwnd, control_id=7)
|
||||||
|
pending = _pending_prompt(windows, closing=closed_frame is not None, frame=frame,
|
||||||
|
session=SimpleNamespace(post=act), clicked=state['clicked'], pcb_name=Path(job['pcb']).name)
|
||||||
|
if (closed_frame is None and not pending
|
||||||
|
and _target_frame(windows, Path(job['pcb']).stem) is not None):
|
||||||
|
act(frame['hwnd'], 0x10)
|
||||||
|
closed_frame = frame['hwnd']
|
||||||
|
return closed_frame, bool(actions)
|
||||||
|
|
||||||
|
|
||||||
def check_target_window(job, pcb_pid, *, emit, error_reader, launcher_process=None) -> dict:
|
def check_target_window(job, pcb_pid, *, emit, error_reader, launcher_process=None) -> dict:
|
||||||
"""Prove this launch opened its native document, close it, and prove exit.
|
"""Prove this launch opened its native document, close it, and prove exit.
|
||||||
|
|
||||||
@@ -301,8 +438,23 @@ def check_target_window(job, pcb_pid, *, emit, error_reader, launcher_process=No
|
|||||||
if not isinstance(baseline, dict) or 'started_ns' not in baseline or 'files' not in baseline:
|
if not isinstance(baseline, dict) or 'started_ns' not in baseline or 'files' not in baseline:
|
||||||
raise RuntimeError('DIAGNOSTIC_BASELINE_REQUIRED: snapshot before native launch')
|
raise RuntimeError('DIAGNOSTIC_BASELINE_REQUIRED: snapshot before native launch')
|
||||||
session = _NativeSession(job, int(pcb_pid), launcher_process)
|
session = _NativeSession(job, int(pcb_pid), launcher_process)
|
||||||
|
def scan(deadline, *, closing=False):
|
||||||
|
while True:
|
||||||
|
if not closing:
|
||||||
|
_cancel(job)
|
||||||
|
try:
|
||||||
|
return _windows(int(pcb_pid))
|
||||||
|
except RuntimeError as error:
|
||||||
|
if str(error) != 'DIAGNOSTIC_WINDOW_LIMIT: window scan exceeded 0.2s':
|
||||||
|
raise
|
||||||
|
# Discard the incomplete snapshot; no control action may use it.
|
||||||
|
emit(stage='diagnostic_window_retry', detail=str(error))
|
||||||
|
if time.monotonic() >= deadline:
|
||||||
|
raise
|
||||||
|
time.sleep(min(.1, max(0, deadline-time.monotonic())))
|
||||||
try:
|
try:
|
||||||
deadline = time.monotonic() + max(.01, float(job['timeout']))
|
deadline = time.monotonic() + max(.01, float(job['timeout']))
|
||||||
|
startup_clicked = set()
|
||||||
while True:
|
while True:
|
||||||
_cancel(job)
|
_cancel(job)
|
||||||
error = _read_bounded(error_reader) if error_reader else None
|
error = _read_bounded(error_reader) if error_reader else None
|
||||||
@@ -310,38 +462,44 @@ def check_target_window(job, pcb_pid, *, emit, error_reader, launcher_process=No
|
|||||||
raise RuntimeError(str(error))
|
raise RuntimeError(str(error))
|
||||||
if not session.pcb_alive():
|
if not session.pcb_alive():
|
||||||
raise RuntimeError('DIAGNOSTIC_OPEN_UNCONFIRMED: target PCB exited before loaded evidence')
|
raise RuntimeError('DIAGNOSTIC_OPEN_UNCONFIRMED: target PCB exited before loaded evidence')
|
||||||
windows = _windows(int(pcb_pid))
|
windows = scan(deadline)
|
||||||
if any(window['pid'] != int(pcb_pid) for window in windows):
|
if any(window['pid'] != int(pcb_pid) for window in windows):
|
||||||
raise RuntimeError('DIAGNOSTIC_PID_MISMATCH')
|
raise RuntimeError('DIAGNOSTIC_PID_MISMATCH')
|
||||||
frame = _target_frame(windows, Path(job['pcb']).stem)
|
frame = _target_frame(windows, Path(job['pcb']).stem, require_ready=False)
|
||||||
# Startup splash/control windows are transient. Unknown windows
|
# Startup splash/control windows are transient. Unknown windows
|
||||||
# veto closing only once the target actually has loaded evidence.
|
# veto closing only once the target actually has loaded evidence.
|
||||||
pending = (_pending_prompt(windows, frame=frame, pcb_name=Path(job['pcb']).name)
|
|
||||||
if frame is not None else True)
|
|
||||||
evidence = (_load_evidence(job, int(pcb_pid), baseline, require_autosave=False)
|
evidence = (_load_evidence(job, int(pcb_pid), baseline, require_autosave=False)
|
||||||
if frame is not None and not pending else None)
|
if frame is not None else None)
|
||||||
if evidence is not None:
|
pending = (_pending_prompt(windows, frame=frame, session=session if evidence else None,
|
||||||
|
clicked=startup_clicked, pcb_name=Path(job['pcb']).name) if frame is not None else True)
|
||||||
|
if evidence is not None and not pending and _target_frame(windows, Path(job['pcb']).stem) is not None:
|
||||||
emit(stage='diagnostic_native_loaded_candidate', **evidence)
|
emit(stage='diagnostic_native_loaded_candidate', **evidence)
|
||||||
break
|
break
|
||||||
if time.monotonic() >= deadline:
|
if time.monotonic() >= deadline:
|
||||||
raise RuntimeError('DIAGNOSTIC_OPEN_UNCONFIRMED: current target MDI/path/PID logs missing')
|
raise RuntimeError('DIAGNOSTIC_OPEN_UNCONFIRMED: current target MDI/path/PID logs missing')
|
||||||
time.sleep(.1)
|
time.sleep(.1)
|
||||||
# Re-read the exact PID/frame before the sole close request.
|
# Finish any in-flight supervisor poll before WM_CLOSE can create a prompt.
|
||||||
_cancel(job)
|
|
||||||
windows = _windows(int(pcb_pid))
|
|
||||||
_pending_prompt(windows, frame=frame, pcb_name=Path(job['pcb']).name)
|
|
||||||
current = _target_frame(windows, Path(job['pcb']).stem)
|
|
||||||
if current is None or current['hwnd'] != frame['hwnd']:
|
|
||||||
raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: target frame changed')
|
|
||||||
session.post(frame['hwnd'], 0x10)
|
|
||||||
emit(stage='diagnostic_wm_close', pcb_pid=int(pcb_pid), hwnd=frame['hwnd'])
|
|
||||||
close_deadline = time.monotonic() + 30
|
close_deadline = time.monotonic() + 30
|
||||||
|
intent = _request_close_handoff(job, pcb_pid, frame, session, emit, close_deadline)
|
||||||
|
# Re-read the exact PID/frame after acknowledgement and before the sole close.
|
||||||
|
_cancel(job)
|
||||||
|
error = _read_bounded(error_reader) if error_reader else None
|
||||||
|
if error: raise RuntimeError(str(error))
|
||||||
|
windows = scan(close_deadline)
|
||||||
|
pending = _pending_prompt(windows, frame=frame, pcb_name=Path(job['pcb']).name)
|
||||||
|
current = _target_frame(windows, Path(job['pcb']).stem)
|
||||||
|
if (pending or time.monotonic() >= close_deadline or current is None
|
||||||
|
or any(current[key] != frame[key] for key in ('hwnd', 'pid', 'class', 'text'))):
|
||||||
|
raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: target frame changed')
|
||||||
|
_cancel(job)
|
||||||
|
session.post(frame['hwnd'], 0x10)
|
||||||
|
emit(stage='diagnostic_wm_close', **intent)
|
||||||
clicked = set()
|
clicked = set()
|
||||||
last_pending = ''
|
last_pending = ''
|
||||||
while session.pcb_alive() or session.launcher_alive():
|
while session.pcb_alive() or session.launcher_alive():
|
||||||
# Cancellation stops future work; an accepted normal close must
|
# Cancellation stops future work; an accepted normal close must
|
||||||
# still finish before its queue slot can be safely released.
|
# still finish before its queue slot can be safely released.
|
||||||
windows = _windows(int(pcb_pid)) if session.pcb_alive() else []
|
windows = scan(close_deadline, closing=True) if session.pcb_alive() else []
|
||||||
previous_clicks = set(clicked)
|
previous_clicks = set(clicked)
|
||||||
pending_error = None
|
pending_error = None
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -238,6 +238,11 @@ class WindowProbe:
|
|||||||
process_name = ""
|
process_name = ""
|
||||||
controls = tuple(self._win32_control(child) for child in self._children(hwnd))
|
controls = tuple(self._win32_control(child) for child in self._children(hwnd))
|
||||||
diagnostics = []
|
diagnostics = []
|
||||||
|
native_panel = (process_name.casefold() == 'expeditionpcb.exe'
|
||||||
|
and phase in (DialogPhase.SAVE, DialogPhase.CLOSE)
|
||||||
|
and gui.GetClassName(hwnd) == '#32770' and gui.GetWindowText(hwnd) == 'Project Integration')
|
||||||
|
# This native panel's exact control IDs/text are sufficient; its UIA tree can stall Save.
|
||||||
|
if not native_panel:
|
||||||
try:
|
try:
|
||||||
uia_records = _bounded_call(lambda: self.uia.controls(hwnd), self.uia_timeout_seconds)
|
uia_records = _bounded_call(lambda: self.uia.controls(hwnd), self.uia_timeout_seconds)
|
||||||
controls = self._merge_controls(controls, uia_records)
|
controls = self._merge_controls(controls, uia_records)
|
||||||
|
|||||||
@@ -116,7 +116,7 @@ def _read_document(path: Path) -> list[dict[str, Any]]:
|
|||||||
return rules
|
return rules
|
||||||
|
|
||||||
|
|
||||||
def load_rules(default_path: Path, override_path: Path | None = None) -> tuple[DialogRule, ...]:
|
def load_rules(default_path: Path, override_path: Path | None = None, *, diagnostic_only=False) -> tuple[DialogRule, ...]:
|
||||||
ordered: list[str] = []
|
ordered: list[str] = []
|
||||||
raw_by_id: dict[str, dict[str, Any]] = {}
|
raw_by_id: dict[str, dict[str, Any]] = {}
|
||||||
for raw in _read_document(default_path):
|
for raw in _read_document(default_path):
|
||||||
@@ -137,7 +137,12 @@ def load_rules(default_path: Path, override_path: Path | None = None) -> tuple[D
|
|||||||
else:
|
else:
|
||||||
ordered.append(rule_id)
|
ordered.append(rule_id)
|
||||||
raw_by_id[rule_id] = dict(override)
|
raw_by_id[rule_id] = dict(override)
|
||||||
return tuple(_parse_rule(raw_by_id[rule_id]) for rule_id in ordered)
|
rules = tuple(_parse_rule(raw_by_id[rule_id]) for rule_id in ordered)
|
||||||
|
if diagnostic_only:
|
||||||
|
# The process-bound diagnostic checker declines this prompt after proving the loaded project.
|
||||||
|
rules = tuple(replace(rule, category='OBSERVE_PROGRESS', action='', channels=(), target=())
|
||||||
|
if rule.rule_id == 'forward-annotation-confirm' else rule for rule in rules)
|
||||||
|
return rules
|
||||||
|
|
||||||
|
|
||||||
def _semantic_text(snapshot: WindowSnapshot) -> str:
|
def _semantic_text(snapshot: WindowSnapshot) -> str:
|
||||||
@@ -253,6 +258,22 @@ def decide(snapshot: WindowSnapshot, rules: Sequence[DialogRule]) -> RuleDecisio
|
|||||||
channels=('win32_button_click', 'uia_invoke'),
|
channels=('win32_button_click', 'uia_invoke'),
|
||||||
target=(('control_id', 7),), postcondition='window_gone',
|
target=(('control_id', 7),), postcondition='window_gone',
|
||||||
error_code='MENTOR_DATABASE_LOAD_FAILED', detail=' | '.join(snapshot.texts))
|
error_code='MENTOR_DATABASE_LOAD_FAILED', detail=' | '.join(snapshot.texts))
|
||||||
|
if (snapshot.title == 'Project Integration' and snapshot.phase in (DialogPhase.SAVE, DialogPhase.CLOSE)
|
||||||
|
and snapshot.process_name.casefold() == 'expeditionpcb.exe' and snapshot.process_role == 'pcb'
|
||||||
|
and snapshot.window_class == '#32770' and snapshot.owner_hwnd and not snapshot.diagnostics
|
||||||
|
and not re.search(r'\b(?:errors?|failed|inconsistent)\b', combined)):
|
||||||
|
idle = {1033: 'No connectivity changes to be forward annotated',
|
||||||
|
1032: 'No pending schematic CES changes to load into PCB',
|
||||||
|
1035: 'No pending PCB changes to be back annotated',
|
||||||
|
1034: 'No pending CES changes to load into PCB'}
|
||||||
|
complete = all(len(matches := [c for c in snapshot.controls if c.control_id == identifier]) == 1
|
||||||
|
and matches[0].class_name == 'Static' and matches[0].name == text for identifier, text in idle.items())
|
||||||
|
close = [c for c in snapshot.controls if c.control_id == 2]
|
||||||
|
if (complete and len(close) == 1 and close[0].class_name == 'Button'
|
||||||
|
and close[0].name.replace('&', '') == 'Close' and close[0].enabled):
|
||||||
|
return RuleDecision(rule_id='completed-integration-panel', category='SAFE_CONFIRM',
|
||||||
|
action='close_completed_integration', channels=('win32_button_click',),
|
||||||
|
target=(('control_id', 2),), postcondition='window_gone')
|
||||||
matches = [rule for rule in rules if _matches(rule, snapshot, include_phase=True)]
|
matches = [rule for rule in rules if _matches(rule, snapshot, include_phase=True)]
|
||||||
if matches:
|
if matches:
|
||||||
best_priority = max(rule.priority for rule in matches)
|
best_priority = max(rule.priority for rule in matches)
|
||||||
|
|||||||
@@ -100,9 +100,10 @@ class DialogBackend(Protocol):
|
|||||||
class AgentDialogBackend:
|
class AgentDialogBackend:
|
||||||
"""Adapt the private-desktop JSONL client to the supervisor backend."""
|
"""Adapt the private-desktop JSONL client to the supervisor backend."""
|
||||||
|
|
||||||
def __init__(self, client, *, pids=None) -> None:
|
def __init__(self, client, *, pids=None, before_action=None) -> None:
|
||||||
self.client = client
|
self.client = client
|
||||||
self.pids = pids
|
self.pids = pids
|
||||||
|
self.before_action = before_action
|
||||||
|
|
||||||
def observe(self, phase: DialogPhase):
|
def observe(self, phase: DialogPhase):
|
||||||
if self.pids is None:
|
if self.pids is None:
|
||||||
@@ -111,6 +112,7 @@ class AgentDialogBackend:
|
|||||||
return tuple(w for w in self.client.observe(phase, pids=pids) if w.pid in pids)
|
return tuple(w for w in self.client.observe(phase, pids=pids) if w.pid in pids)
|
||||||
|
|
||||||
def perform(self, snapshot: WindowSnapshot, action: dict, phase: DialogPhase) -> ActionResult:
|
def perform(self, snapshot: WindowSnapshot, action: dict, phase: DialogPhase) -> ActionResult:
|
||||||
|
if self.before_action is not None:self.before_action(snapshot,action)
|
||||||
return self.client.perform(
|
return self.client.perform(
|
||||||
hwnd=snapshot.hwnd,
|
hwnd=snapshot.hwnd,
|
||||||
fingerprint=stable_fingerprint(snapshot),
|
fingerprint=stable_fingerprint(snapshot),
|
||||||
@@ -123,7 +125,7 @@ class Win32DialogBackend:
|
|||||||
"""Observe and act on dialogs without moving focus, cursor, or desktop."""
|
"""Observe and act on dialogs without moving focus, cursor, or desktop."""
|
||||||
|
|
||||||
def __init__(self, pids, *, desktop=None, win32gui=None, win32process=None,
|
def __init__(self, pids, *, desktop=None, win32gui=None, win32process=None,
|
||||||
win32con=None) -> None:
|
win32con=None, before_action=None) -> None:
|
||||||
if win32gui is None:
|
if win32gui is None:
|
||||||
import win32gui as win32gui_module
|
import win32gui as win32gui_module
|
||||||
win32gui = win32gui_module
|
win32gui = win32gui_module
|
||||||
@@ -138,6 +140,7 @@ class Win32DialogBackend:
|
|||||||
self.win32gui = win32gui
|
self.win32gui = win32gui
|
||||||
self.win32process = win32process
|
self.win32process = win32process
|
||||||
self.win32con = win32con
|
self.win32con = win32con
|
||||||
|
self.before_action = before_action
|
||||||
|
|
||||||
def _allowed_pids(self) -> set[int]:
|
def _allowed_pids(self) -> set[int]:
|
||||||
values = self.pids() if callable(self.pids) else self.pids
|
values = self.pids() if callable(self.pids) else self.pids
|
||||||
@@ -256,6 +259,7 @@ class Win32DialogBackend:
|
|||||||
return control.control_id
|
return control.control_id
|
||||||
|
|
||||||
def perform(self, snapshot: DialogSnapshot, action: str) -> tuple[int, ...]:
|
def perform(self, snapshot: DialogSnapshot, action: str) -> tuple[int, ...]:
|
||||||
|
if self.before_action is not None:self.before_action(snapshot,action)
|
||||||
buttons = self._buttons(snapshot)
|
buttons = self._buttons(snapshot)
|
||||||
positive = ("yes", "ok", "continue", "retry", "restore", "open", "use", "load",
|
positive = ("yes", "ok", "continue", "retry", "restore", "open", "use", "load",
|
||||||
"是", "确定", "继续", "重试", "恢复", "打开", "使用", "加载")
|
"是", "确定", "继续", "重试", "恢复", "打开", "使用", "加载")
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
"""Close only an idle document whose native identity was already established."""
|
"""Close only an idle document whose native identity was already established."""
|
||||||
import json
|
import json
|
||||||
|
from contextlib import ExitStack
|
||||||
import os
|
import os
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import time
|
import time
|
||||||
@@ -53,24 +54,79 @@ def _cancel_target(snapshot):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _tip_target(snapshot):
|
||||||
|
from .dialog_agent import DialogActionExecutor
|
||||||
|
if snapshot.title != 'Tip of the Day' or snapshot.window_class != '#32770':
|
||||||
|
return None
|
||||||
|
target = DialogActionExecutor._target(snapshot, {'control_id': 1})
|
||||||
|
return target if target is not None and target.class_name == 'Button' else None
|
||||||
|
|
||||||
|
|
||||||
|
def cancelled_prewrite_startup(job, pcb_pid=None):
|
||||||
|
"""Positive ordinary pre-document cancellation proof; absence of Save is insufficient."""
|
||||||
|
from .session_record import IDENTITY_KEYS, read_session_record
|
||||||
|
try:
|
||||||
|
if (job.get('diagnostic_only') is not False or job.get('interactive_input')
|
||||||
|
or job.get('native_lm_verify') or job.get('post_repair_consent')
|
||||||
|
or job.get('operation') != 'verify' or not job.get('operation_id')
|
||||||
|
or not job.get('desktop', '').startswith('CbbVerify_')):
|
||||||
|
return None
|
||||||
|
root=Path(job['root'])
|
||||||
|
if not Path(job['cancel_signal']).is_file() or (root/'save.log').exists():return None
|
||||||
|
path=root/'events.jsonl'
|
||||||
|
if path.stat().st_size>1024*1024:return None
|
||||||
|
events=[json.loads(line) for line in path.read_text(encoding='utf-8').splitlines()]
|
||||||
|
if any(str(e.get('stage','')).startswith(('save','integration','validate','failure_close'))
|
||||||
|
or e.get('stage') in ('startup_write_admitted','startup_supervisor_write_possible','identity_verified')
|
||||||
|
for e in events):return None
|
||||||
|
stages=('startup_supervisor_no_write','startup_prewrite_ready','startup_cancelled_prewrite')
|
||||||
|
selected=[]
|
||||||
|
for stage in stages:
|
||||||
|
matches=[(i,e) for i,e in enumerate(events) if e.get('stage')==stage]
|
||||||
|
if len(matches)!=1:return None
|
||||||
|
selected.append(matches[0])
|
||||||
|
if [i for i,_ in selected]!=sorted(i for i,_ in selected):return None
|
||||||
|
binding={k:job[k] for k in ('operation_id','project','pcb','desktop')}
|
||||||
|
if any(any(e.get(k)!=v for k,v in binding.items()) for _,e in selected):return None
|
||||||
|
ready,cancelled=selected[1][1],selected[2][1]
|
||||||
|
pid=cancelled.get('pcb_pid')
|
||||||
|
if (not pid or pcb_pid is not None and pid!=pcb_pid
|
||||||
|
or cancelled.get('identity_verified') is not False or cancelled.get('write_admitted') is not False):return None
|
||||||
|
if not any(e.get('stage')=='pcb_worker_started' and e.get('pcb_pid')==pid
|
||||||
|
for e in events[selected[1][0]+1:selected[2][0]]):return None
|
||||||
|
session=read_session_record(Path(job['session_record_path']),evidence_root=root)
|
||||||
|
workers=[p for p in session.get('processes',()) if p.get('role')=='worker']
|
||||||
|
if (session.get('operation_id')!=job['operation_id'] or session.get('desktop')!=job['desktop']
|
||||||
|
or session.get('library')!=job['library'] or len(workers)!=1
|
||||||
|
or not set(IDENTITY_KEYS)<=ready.get('worker_identity',{}).keys()
|
||||||
|
or any(ready.get('worker_identity',{}).get(k)!=workers[0].get(k) for k in IDENTITY_KEYS)):return None
|
||||||
|
baseline=ready.get('baseline')
|
||||||
|
if not isinstance(baseline,dict) or not {'started_ns','files'}<=baseline.keys():return None
|
||||||
|
return baseline
|
||||||
|
except (OSError,ValueError,KeyError,TypeError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event: None,
|
def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event: None,
|
||||||
timeout_seconds=20, launcher_process=None):
|
timeout_seconds=None, launcher_process=None):
|
||||||
"""Normally close our empty PCB after a diagnosed database startup failure.
|
"""Normally close our empty PCB after a diagnosed database startup failure.
|
||||||
|
|
||||||
No COM attach: the global ROT can name another session. Only the exact
|
No COM attach: the global ROT can name another session. Only the exact
|
||||||
read/write question is declined; no ownership is taken or version restored.
|
read/write question is declined; no ownership is taken or version restored.
|
||||||
Unknown windows and documents are retained. WM_CLOSE is cooperative.
|
Unknown windows and documents are retained. WM_CLOSE is cooperative.
|
||||||
"""
|
"""
|
||||||
import win32api, win32con, win32gui, win32process
|
import win32api, win32con, win32gui, win32process, win32event
|
||||||
from .mentor_adapter import _process_details
|
from .mentor_adapter import _process_details
|
||||||
from .native_repair_ui import _current_desktop_name
|
from .native_repair_ui import _current_desktop_name
|
||||||
from .icdb_ownership import unreleased_addresses
|
from .icdb_ownership import unreleased_addresses
|
||||||
|
from . import residual_sessions
|
||||||
root = Path(job['root'])
|
root = Path(job['root'])
|
||||||
result = {'status': 'RETAINED', 'pcb_pid': pcb_pid}
|
result = {'status': 'RETAINED', 'pcb_pid': pcb_pid}
|
||||||
result['release'] = {'pcb_exited': False, 'launcher_exited': launcher_process is None,
|
result['release'] = {'pcb_exited': False, 'launcher_exited': launcher_process is None,
|
||||||
'safe_to_continue': False}
|
'safe_to_continue': False}
|
||||||
if launcher_process is not None:
|
if launcher_process is not None:
|
||||||
result['launcher_pid'] = launcher_process.pid
|
result['launcher_pid'] = launcher_process.pid
|
||||||
|
handles = ExitStack()
|
||||||
try:
|
try:
|
||||||
desktop = job.get('desktop', '')
|
desktop = job.get('desktop', '')
|
||||||
if (job.get('interactive_input') or not desktop.startswith('CbbVerify_')
|
if (job.get('interactive_input') or not desktop.startswith('CbbVerify_')
|
||||||
@@ -79,14 +135,45 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
|||||||
if not pcb_pid or pcb_pid in baseline_pids:
|
if not pcb_pid or pcb_pid in baseline_pids:
|
||||||
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
|
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
|
||||||
expected = os.path.normcase(os.path.abspath(job['pcb']))
|
expected = os.path.normcase(os.path.abspath(job['pcb']))
|
||||||
|
cancelled_diagnostic = (job.get('diagnostic_only') is True
|
||||||
|
and bool(job.get('cancel_signal')) and Path(job['cancel_signal']).exists()
|
||||||
|
and isinstance(job.get('diagnostic_log_baseline'), dict)
|
||||||
|
and {'started_ns', 'files'} <= job['diagnostic_log_baseline'].keys()
|
||||||
|
and not (root/'save.log').exists())
|
||||||
|
ordinary_baseline=cancelled_prewrite_startup(job,pcb_pid)
|
||||||
|
cancelled_prewrite=ordinary_baseline is not None
|
||||||
|
# Diagnostic close already owns a 30-second cleanup budget. Start it
|
||||||
|
# once here; the empty-to-loaded transition never resets that deadline.
|
||||||
|
if timeout_seconds is None:
|
||||||
|
timeout_seconds = 30 if cancelled_diagnostic or cancelled_prewrite else 20
|
||||||
deadline = time.monotonic() + max(0, timeout_seconds)
|
deadline = time.monotonic() + max(0, timeout_seconds)
|
||||||
sent = False
|
sent = False
|
||||||
declined_hwnd = None
|
declined_hwnd = None
|
||||||
declined_kind = None
|
declined_kind = None
|
||||||
cancelled_open = False
|
cancelled_open = False
|
||||||
|
dismissed_tips = set()
|
||||||
|
close_handle = None
|
||||||
|
close_identity = None
|
||||||
|
close_frame = None
|
||||||
|
diagnostic_state = {'clicked': set()}
|
||||||
|
def cleanup_post(hwnd, message):
|
||||||
|
if (time.monotonic() >= deadline or _current_desktop_name() != desktop
|
||||||
|
or cancelled_prewrite and cancelled_prewrite_startup(job,pcb_pid)!=ordinary_baseline
|
||||||
|
or win32event.WaitForSingleObject(close_handle, 0) != win32con.WAIT_TIMEOUT
|
||||||
|
or residual_sessions._handle_identity(close_handle) != close_identity
|
||||||
|
or win32process.GetWindowThreadProcessId(hwnd)[1] != pcb_pid):
|
||||||
|
raise ValueError('STARTUP_ACTION_UNCONFIRMED')
|
||||||
|
win32gui.PostMessage(hwnd, message, 0, 0)
|
||||||
while True:
|
while True:
|
||||||
records = [r for r in _process_details('ExpeditionPCB.exe') if r[0] == pcb_pid]
|
records = [r for r in _process_details('ExpeditionPCB.exe') if r[0] == pcb_pid]
|
||||||
if not records:
|
if not records:
|
||||||
|
if (close_handle is not None
|
||||||
|
and win32event.WaitForSingleObject(close_handle, 0) != win32con.WAIT_OBJECT_0):
|
||||||
|
result['detail'] = 'STARTUP_EXIT_UNCONFIRMED: 原进程句柄尚未确认退出'
|
||||||
|
if time.monotonic() >= deadline:
|
||||||
|
break
|
||||||
|
time.sleep(.2)
|
||||||
|
continue
|
||||||
if declined_hwnd is not None:
|
if declined_hwnd is not None:
|
||||||
cancelled_open = True
|
cancelled_open = True
|
||||||
result['cancelled_prompt'] = declined_kind
|
result['cancelled_prompt'] = declined_kind
|
||||||
@@ -111,6 +198,34 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
|||||||
or '-reusablecircuit' not in [a.casefold() for a in args]
|
or '-reusablecircuit' not in [a.casefold() for a in args]
|
||||||
or expected not in [os.path.normcase(os.path.abspath(a)) for a in args[1:]]):
|
or expected not in [os.path.normcase(os.path.abspath(a)) for a in args[1:]]):
|
||||||
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
|
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
|
||||||
|
if cancelled_diagnostic or cancelled_prewrite:
|
||||||
|
if time.monotonic() >= deadline:
|
||||||
|
result['detail']='STARTUP_CLEANUP_TIMEOUT: original cleanup deadline reached'
|
||||||
|
break
|
||||||
|
if cancelled_prewrite and cancelled_prewrite_startup(job,pcb_pid)!=ordinary_baseline:
|
||||||
|
raise ValueError('STARTUP_IDENTITY_UNCONFIRMED: pre-write phase proof changed')
|
||||||
|
if (cancelled_diagnostic or cancelled_prewrite) and time.monotonic() < deadline:
|
||||||
|
if close_handle is None:
|
||||||
|
close_handle = handles.enter_context(residual_sessions._process_handle(pcb_pid))
|
||||||
|
close_identity = residual_sessions._handle_identity(close_handle)
|
||||||
|
if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe':
|
||||||
|
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
|
||||||
|
from .diagnostic_open import cancelled_startup_step
|
||||||
|
def ordinary_identity():
|
||||||
|
from .diagnostic_open import _load_evidence
|
||||||
|
return (cancelled_prewrite_startup(job,pcb_pid)==ordinary_baseline
|
||||||
|
and _load_evidence(job,pcb_pid,ordinary_baseline,require_autosave=False) is not None)
|
||||||
|
closed, acted = cancelled_startup_step(job, pcb_pid, diagnostic_state,
|
||||||
|
closed_frame=close_frame, deadline=deadline, post=cleanup_post, emit=emit,
|
||||||
|
identity_check=ordinary_identity if cancelled_prewrite else None)
|
||||||
|
if closed is not None and not sent:
|
||||||
|
sent, close_frame = True, closed
|
||||||
|
emit(stage='startup_close_requested', pcb_pid=pcb_pid, hwnd=closed,
|
||||||
|
document_identity='native_path_pid_logs',
|
||||||
|
cleanup='cancelled_prewrite' if cancelled_prewrite else 'cancelled_diagnostic')
|
||||||
|
if acted:
|
||||||
|
continue
|
||||||
|
if not sent:
|
||||||
windows = []
|
windows = []
|
||||||
def observe(hwnd, _):
|
def observe(hwnd, _):
|
||||||
if (win32process.GetWindowThreadProcessId(hwnd)[1] == pcb_pid
|
if (win32process.GetWindowThreadProcessId(hwnd)[1] == pcb_pid
|
||||||
@@ -121,6 +236,27 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
|||||||
if declined_hwnd is not None and declined_hwnd not in windows:
|
if declined_hwnd is not None and declined_hwnd not in windows:
|
||||||
cancelled_open = True
|
cancelled_open = True
|
||||||
result['cancelled_prompt'] = declined_kind
|
result['cancelled_prompt'] = declined_kind
|
||||||
|
dismissed = False
|
||||||
|
for hwnd in windows:
|
||||||
|
if hwnd in dismissed_tips or win32gui.GetClassName(hwnd) != '#32770':
|
||||||
|
continue
|
||||||
|
snapshot = _startup_snapshot(hwnd, pcb_pid)
|
||||||
|
target = _tip_target(snapshot)
|
||||||
|
if target is None:
|
||||||
|
continue
|
||||||
|
current = _startup_snapshot(hwnd, pcb_pid)
|
||||||
|
if current != snapshot or _tip_target(current) != target:
|
||||||
|
raise ValueError('STARTUP_TIP_CHANGED')
|
||||||
|
if cancelled_diagnostic or cancelled_prewrite:
|
||||||
|
cleanup_post(target.handle,win32con.BM_CLICK)
|
||||||
|
else:
|
||||||
|
win32gui.PostMessage(target.handle, win32con.BM_CLICK, 0, 0)
|
||||||
|
dismissed_tips.add(hwnd)
|
||||||
|
dismissed = True
|
||||||
|
emit(stage='startup_tip_dismissed', pcb_pid=pcb_pid, hwnd=hwnd)
|
||||||
|
break
|
||||||
|
if dismissed:
|
||||||
|
continue # Prove the Tip disappeared; it does not prove a cancelled open.
|
||||||
if declined_hwnd is None:
|
if declined_hwnd is None:
|
||||||
for hwnd in windows:
|
for hwnd in windows:
|
||||||
if win32gui.GetClassName(hwnd) != '#32770':
|
if win32gui.GetClassName(hwnd) != '#32770':
|
||||||
@@ -134,6 +270,9 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
|||||||
if _cancel_target(current) != target or current != snapshot:
|
if _cancel_target(current) != target or current != snapshot:
|
||||||
raise ValueError('STARTUP_CANCEL_PROMPT_CHANGED')
|
raise ValueError('STARTUP_CANCEL_PROMPT_CHANGED')
|
||||||
declined_kind, cancel = target
|
declined_kind, cancel = target
|
||||||
|
if cancelled_diagnostic or cancelled_prewrite:
|
||||||
|
cleanup_post(cancel.handle,win32con.BM_CLICK)
|
||||||
|
else:
|
||||||
win32gui.PostMessage(cancel.handle, win32con.BM_CLICK, 0, 0)
|
win32gui.PostMessage(cancel.handle, win32con.BM_CLICK, 0, 0)
|
||||||
declined_hwnd = hwnd
|
declined_hwnd = hwnd
|
||||||
emit(stage='startup_open_declined', pcb_pid=pcb_pid, hwnd=hwnd,
|
emit(stage='startup_open_declined', pcb_pid=pcb_pid, hwnd=hwnd,
|
||||||
@@ -173,15 +312,38 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
|||||||
win32gui.EnumChildWindows(main[0], child, None)
|
win32gui.EnumChildWindows(main[0], child, None)
|
||||||
addresses = unreleased_addresses(job['lmc_file'], job['project'], job['pcb'])
|
addresses = unreleased_addresses(job['lmc_file'], job['project'], job['pcb'])
|
||||||
if len(main) == 1 and not unknown and not documents and (cancelled_open or not addresses):
|
if len(main) == 1 and not unknown and not documents and (cancelled_open or not addresses):
|
||||||
|
if close_handle is None:
|
||||||
|
close_handle = handles.enter_context(residual_sessions._process_handle(pcb_pid))
|
||||||
|
close_identity = residual_sessions._handle_identity(close_handle)
|
||||||
|
if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe':
|
||||||
|
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
|
||||||
|
if cancelled_diagnostic or cancelled_prewrite:
|
||||||
|
cleanup_post(main[0],win32con.WM_CLOSE)
|
||||||
|
else:
|
||||||
win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0)
|
win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0)
|
||||||
|
close_frame = main[0]
|
||||||
sent = True
|
sent = True
|
||||||
emit(stage='startup_close_requested', pcb_pid=pcb_pid, hwnd=main[0])
|
emit(stage='startup_close_requested', pcb_pid=pcb_pid, hwnd=main[0])
|
||||||
# Observe exit even when the caller requested no extra wait.
|
# Observe exit even when the caller requested no extra wait.
|
||||||
continue
|
continue
|
||||||
result['detail'] = 'STARTUP_IDLE_UNCONFIRMED: 等待空闲窗口和数据库释放'
|
result['detail'] = 'STARTUP_IDLE_UNCONFIRMED: 等待空闲窗口和数据库释放'
|
||||||
# After the single owned WM_CLOSE, WMI may lose the executable/
|
# WMI fields can disappear during teardown. The held identity binds
|
||||||
# command fields before removing the PID. Only observe exit here;
|
# any late Tip action to the original process, never a reused PID.
|
||||||
# never issue another close or treat missing fields as release.
|
if sent and time.monotonic() < deadline:
|
||||||
|
if _current_desktop_name() != desktop:
|
||||||
|
raise ValueError('STARTUP_DESKTOP_UNCONFIRMED')
|
||||||
|
snapshot = residual_sessions._process_windows({pcb_pid})
|
||||||
|
windows = snapshot.get(pcb_pid, [])
|
||||||
|
if all(w.get('desktop') == desktop for w in windows):
|
||||||
|
dismissed = residual_sessions._dismiss_startup_tip(
|
||||||
|
dict(pid=pcb_pid, name='ExpeditionPCB.exe', scope_confirmed=True, startup_frame=close_frame,
|
||||||
|
**close_identity), close_handle, windows,
|
||||||
|
incomplete=residual_sessions._window_error(snapshot, pcb_pid),
|
||||||
|
dismissed=dismissed_tips, deadline=deadline)
|
||||||
|
if dismissed is not None:
|
||||||
|
dismissed_tips.add(dismissed)
|
||||||
|
emit(stage='startup_tip_dismissed', pcb_pid=pcb_pid, hwnd=dismissed)
|
||||||
|
continue
|
||||||
if time.monotonic() >= deadline:
|
if time.monotonic() >= deadline:
|
||||||
if sent:
|
if sent:
|
||||||
result['detail'] = 'STARTUP_EXIT_UNCONFIRMED: 已请求正常关闭,但 PCB 尚未退出'
|
result['detail'] = 'STARTUP_EXIT_UNCONFIRMED: 已请求正常关闭,但 PCB 尚未退出'
|
||||||
@@ -189,6 +351,8 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
|||||||
time.sleep(.2)
|
time.sleep(.2)
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
result['detail'] = str(error)
|
result['detail'] = str(error)
|
||||||
|
finally:
|
||||||
|
handles.close()
|
||||||
(root/'startup-close.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
|
(root/'startup-close.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||||
emit(stage='startup_close_result', **result)
|
emit(stage='startup_close_result', **result)
|
||||||
return result
|
return result
|
||||||
|
|||||||
@@ -0,0 +1,151 @@
|
|||||||
|
"""Bound read-only filesystem probes; keep proof handles alive through commit."""
|
||||||
|
from contextlib import contextmanager, ExitStack
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import stat
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def hold_release_files(library, roots=None, *, timeout_seconds=10, stop=None):
|
||||||
|
"""Only this pure probe may be terminated. stdin EOF releases its handles."""
|
||||||
|
with tempfile.TemporaryDirectory(prefix='cbb-file-probe-') as folder:
|
||||||
|
job = Path(folder)/'request.json'
|
||||||
|
token = uuid4().hex
|
||||||
|
job.write_text(json.dumps({'token': token, 'library': str(library),
|
||||||
|
'roots': [str(p) for p in roots] if roots is not None else None}), 'utf-8')
|
||||||
|
command = ([sys.executable] if getattr(sys, 'frozen', False) else
|
||||||
|
[sys.executable, '-m', 'cbb_refresh_verify']) + ['--file-probe', str(job)]
|
||||||
|
process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL,
|
||||||
|
stderr=subprocess.DEVNULL, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
||||||
|
try:
|
||||||
|
deadline = time.monotonic()+max(.1, min(10, timeout_seconds))
|
||||||
|
result_path = job.with_name('result.json')
|
||||||
|
while not result_path.exists():
|
||||||
|
if stop is not None and stop.is_set():
|
||||||
|
raise InterruptedError('FILE_PROBE_CANCELLED')
|
||||||
|
if time.monotonic() >= deadline:
|
||||||
|
raise TimeoutError('FILE_PROBE_TIMEOUT: 文件占用检查超时,未证明释放')
|
||||||
|
if process.poll() is not None:
|
||||||
|
raise OSError('FILE_PROBE_UNCONFIRMED: 文件探测未返回证据')
|
||||||
|
time.sleep(.02)
|
||||||
|
if stop is not None and stop.is_set():
|
||||||
|
raise InterruptedError('FILE_PROBE_CANCELLED')
|
||||||
|
record = json.loads(result_path.read_text('utf-8'))
|
||||||
|
if record.get('token') != token or record.get('status') != 'HELD' or process.poll() is not None:
|
||||||
|
error = OSError('FILE_PROBE_UNCONFIRMED: '+str(record.get('error', '探测身份或句柄失效')))
|
||||||
|
error.winerror = record.get('winerror')
|
||||||
|
raise error
|
||||||
|
# Duplicate the already-open handles before acknowledging the probe.
|
||||||
|
# Its exit can never create a gap in the parent's commit protection.
|
||||||
|
import win32api, win32con
|
||||||
|
with ExitStack() as protection:
|
||||||
|
child = win32api.OpenProcess(win32con.PROCESS_DUP_HANDLE, False, process.pid)
|
||||||
|
protection.callback(child.Close)
|
||||||
|
if len(record['handles']) != len(record['exclusive_files'])+len(record['binding_files']):
|
||||||
|
raise OSError('FILE_PROBE_UNCONFIRMED: 证明句柄数量不符')
|
||||||
|
for handle in record['handles']:
|
||||||
|
owned = win32api.DuplicateHandle(child, handle, win32api.GetCurrentProcess(),
|
||||||
|
0, False, win32con.DUPLICATE_SAME_ACCESS)
|
||||||
|
protection.callback(owned.Close)
|
||||||
|
yield {k: v for k, v in record.items() if k != 'handles'}
|
||||||
|
finally:
|
||||||
|
process.stdin.close()
|
||||||
|
try:
|
||||||
|
process.wait(.5)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
process.terminate() # This executable only scans and opens read handles.
|
||||||
|
process.wait(3)
|
||||||
|
|
||||||
|
|
||||||
|
def _snapshot(library, roots):
|
||||||
|
from .scoped_manifest import scan_tree
|
||||||
|
entries = {library: library.lstat()}
|
||||||
|
for root in roots:
|
||||||
|
if root.exists():
|
||||||
|
entries.update(scan_tree(root))
|
||||||
|
native = sorted(path for path, info in entries.items() if stat.S_ISREG(info.st_mode)
|
||||||
|
and (path == library or path.name.casefold() in ('icdb.dat', 'layoutdb.lyt')))
|
||||||
|
if library not in native:
|
||||||
|
raise ValueError('目标库身份缺失')
|
||||||
|
addresses = sorted(path for path in entries if path.name.casefold() == 'saddress.adr')
|
||||||
|
targets, signatures = [], {}
|
||||||
|
for address in addresses:
|
||||||
|
data = address.read_bytes()
|
||||||
|
signatures[str(address)] = hashlib.sha256(data).hexdigest()
|
||||||
|
database = address.parent.parent
|
||||||
|
matches = []
|
||||||
|
for project in database.parent.glob('*.prj'):
|
||||||
|
if project not in entries or project.stat().st_size > 1024*1024:
|
||||||
|
continue
|
||||||
|
from .backup_recovery import _project_text
|
||||||
|
text = _project_text(project)
|
||||||
|
references = re.findall(r'^KEY iCDBDir "([^"\r\n]+)"', text, re.M)
|
||||||
|
if len(references) == 1 and (project.parent/references[0]).resolve() == database:
|
||||||
|
matches.append(project)
|
||||||
|
if len(matches) != 1 or database/'icdb.dat' not in native:
|
||||||
|
raise ValueError(f'地址未绑定唯一工程数据库,需人工核对:{address}')
|
||||||
|
targets.append({'project': str(matches[0]), 'database': str(database)})
|
||||||
|
signatures[str(matches[0])] = hashlib.sha256(matches[0].read_bytes()).hexdigest()
|
||||||
|
return {'exclusive_files': [str(p) for p in native], 'addresses': [str(p) for p in addresses],
|
||||||
|
'inspection_targets': targets, 'signatures': signatures, 'binding_files': sorted(signatures),
|
||||||
|
'resource_scope': {'library': str(library), 'roots': [str(p) for p in roots],
|
||||||
|
'projects': sorted(str(p) for p in entries if p.suffix.casefold() == '.prj'),
|
||||||
|
'shared_dependencies': sorted(str(p.parent) for p in native
|
||||||
|
if p.is_relative_to(library.parent/'SymbolLibs') and p.name.casefold() == 'icdb.dat'),
|
||||||
|
'databases': sorted({str(p.parent) for p in native if p.name.casefold() == 'icdb.dat'})}}
|
||||||
|
|
||||||
|
|
||||||
|
def file_probe_main(job):
|
||||||
|
"""No native launch, writes, repair, address deletion or process termination."""
|
||||||
|
import win32con, win32file
|
||||||
|
job = Path(job)
|
||||||
|
request = json.loads(job.read_text('utf-8'))
|
||||||
|
result = {'token': request['token'], 'status': 'UNCONFIRMED'}
|
||||||
|
try:
|
||||||
|
def checked_path(value):
|
||||||
|
path = Path(value).absolute()
|
||||||
|
for part in (path, *path.parents):
|
||||||
|
try:
|
||||||
|
info = part.lstat()
|
||||||
|
except FileNotFoundError:
|
||||||
|
continue
|
||||||
|
if info.st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
|
||||||
|
raise ValueError(f'资源范围含重解析点:{part}')
|
||||||
|
return path.resolve()
|
||||||
|
library = checked_path(request['library'])
|
||||||
|
roots = [checked_path(p) for p in request['roots']] if request['roots'] is not None else [library.parent]
|
||||||
|
if library.suffix.casefold() != '.lmc' or any(not p.is_relative_to(library.parent) for p in roots):
|
||||||
|
raise ValueError('文件探测范围不属于所选库')
|
||||||
|
snapshot = _snapshot(library, roots)
|
||||||
|
with ExitStack() as stack:
|
||||||
|
handles = []
|
||||||
|
for path in snapshot['exclusive_files']:
|
||||||
|
handle = win32file.CreateFile(path, win32con.GENERIC_READ, 0, None,
|
||||||
|
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
||||||
|
stack.callback(handle.Close)
|
||||||
|
handles.append(int(handle))
|
||||||
|
for path in snapshot['binding_files']:
|
||||||
|
handle = win32file.CreateFile(path, win32con.GENERIC_READ, win32con.FILE_SHARE_READ,
|
||||||
|
None, win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
||||||
|
stack.callback(handle.Close)
|
||||||
|
handles.append(int(handle))
|
||||||
|
if _snapshot(library, roots) != snapshot:
|
||||||
|
raise ValueError('占用检查期间资源集合变化')
|
||||||
|
pending = job.with_name('result.pending')
|
||||||
|
pending.write_text(json.dumps({**result, **snapshot, 'status': 'HELD', 'handles': handles}), 'utf-8')
|
||||||
|
pending.replace(job.with_name('result.json'))
|
||||||
|
sys.stdin.buffer.read(1) # Parent keeps stdin open until its commit finishes.
|
||||||
|
return 0
|
||||||
|
except Exception as error:
|
||||||
|
pending = job.with_name('result.pending')
|
||||||
|
pending.write_text(json.dumps({**result, 'error': str(error),
|
||||||
|
'winerror': getattr(error, 'winerror', None)}), 'utf-8')
|
||||||
|
pending.replace(job.with_name('result.json'))
|
||||||
|
return 1
|
||||||
@@ -2,6 +2,19 @@
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def session_resource_scope(job):
|
||||||
|
"""Persist declared targets; only fresh proof promotes them to observed scope."""
|
||||||
|
library = Path(job['library'])
|
||||||
|
project, pcb = job.get('project'), job.get('pcb')
|
||||||
|
projects = [str(Path(project))] if project else []
|
||||||
|
databases = [str(Path(p).parent/'database') for p in (project, pcb) if p]
|
||||||
|
shared = library.parent/'SymbolLibs/__ReusableBlocksSymb'
|
||||||
|
return {'scope_state': 'DECLARED' if project else 'RECHECK_REQUIRED',
|
||||||
|
'library': str(library), 'operation_id': job.get('operation_id'),
|
||||||
|
'block_name': job.get('block'), 'projects': projects,
|
||||||
|
'databases': list(dict.fromkeys(databases)), 'shared_dependencies': [str(shared)]}
|
||||||
|
|
||||||
|
|
||||||
def database_directories(lmc_file, project, pcb):
|
def database_directories(lmc_file, project, pcb):
|
||||||
return tuple(dict.fromkeys((
|
return tuple(dict.fromkeys((
|
||||||
Path(project).parent/'database',
|
Path(project).parent/'database',
|
||||||
@@ -14,3 +27,20 @@ def unreleased_addresses(lmc_file, project, pcb):
|
|||||||
return [str(path/'cdbsvr/sAddress.adr')
|
return [str(path/'cdbsvr/sAddress.adr')
|
||||||
for path in database_directories(lmc_file, project, pcb)
|
for path in database_directories(lmc_file, project, pcb)
|
||||||
if (path/'cdbsvr/sAddress.adr').exists()]
|
if (path/'cdbsvr/sAddress.adr').exists()]
|
||||||
|
|
||||||
|
|
||||||
|
def inspect_release_addresses(snapshot, *, stop=None):
|
||||||
|
"""An address is a reason for native inspection, never an occupancy verdict."""
|
||||||
|
import tempfile
|
||||||
|
from .native_repair import RepairTarget, run_native_repair
|
||||||
|
from .native_occupancy import confirmed_inspection
|
||||||
|
from .library_lock import LibraryBusy
|
||||||
|
results = []
|
||||||
|
for item in snapshot['inspection_targets']:
|
||||||
|
target = RepairTarget(Path(item['project']), Path(item['database']))
|
||||||
|
root = Path(tempfile.mkdtemp(prefix='cbb-release-inspection-'))
|
||||||
|
result = run_native_repair(target, root, inspection_only=True, stop=stop)
|
||||||
|
if not confirmed_inspection(target, result) or result['status'] != 'NOT_IN_USE':
|
||||||
|
raise LibraryBusy(f'目标数据库未确认释放:{target.database};检查证据:{root}')
|
||||||
|
results.append(result)
|
||||||
|
return results
|
||||||
@@ -8,7 +8,7 @@ import re
|
|||||||
ERROR_CODE = 'ICDB_REPAIR_REQUIRED'
|
ERROR_CODE = 'ICDB_REPAIR_REQUIRED'
|
||||||
LOG_LIMIT = 128 * 1024
|
LOG_LIMIT = 128 * 1024
|
||||||
RECOVERY_ACTION = (
|
RECOVERY_ACTION = (
|
||||||
'停止批次并确认原服务器及其他客户端已正常关闭;保留完整一致副本后,'
|
'停止受影响工程的写入并确认原服务器及其他客户端已正常关闭;保留完整一致副本后,'
|
||||||
"使用同版本 iCDB Project Backup 的 Repair project 检查并修复正确目标。"
|
"使用同版本 iCDB Project Backup 的 Repair project 检查并修复正确目标。"
|
||||||
'共享符号库问题需核对中心库,不能只修复单个 CBB 的 Work 工程。'
|
'共享符号库问题需核对中心库,不能只修复单个 CBB 的 Work 工程。'
|
||||||
'不要删除 sAddress.adr/锁文件;修复后重新打开、校验并确认权威 READY。'
|
'不要删除 sAddress.adr/锁文件;修复后重新打开、校验并确认权威 READY。'
|
||||||
@@ -16,6 +16,9 @@ RECOVERY_ACTION = (
|
|||||||
_SESSION_LOSS = re.compile(
|
_SESSION_LOSS = re.compile(
|
||||||
r'\bthe\s+last\s+server\s+session\s+on\s+different\s+server\s+machine\s+'
|
r'\bthe\s+last\s+server\s+session\s+on\s+different\s+server\s+machine\s+'
|
||||||
r'lost\s+the\s+connection\s+to\s+the\s+database\b', re.IGNORECASE)
|
r'lost\s+the\s+connection\s+to\s+the\s+database\b', re.IGNORECASE)
|
||||||
|
_INCONSISTENT = re.compile(
|
||||||
|
r"Project database \[([^\]\r\n]+)\] is inconsistent\. It has been manually copied while the iCDB Server was running\.\s*"
|
||||||
|
r"Please use iCDB Project Backup 'Repair project' functionality to fix this issue\.", re.I)
|
||||||
|
|
||||||
_ICDB_MESSAGE = re.compile(r'(?<![A-Za-z0-9_])icdb(?![A-Za-z0-9_.\\/])', re.I)
|
_ICDB_MESSAGE = re.compile(r'(?<![A-Za-z0-9_])icdb(?![A-Za-z0-9_.\\/])', re.I)
|
||||||
_FAILURE_MESSAGE = re.compile(
|
_FAILURE_MESSAGE = re.compile(
|
||||||
@@ -78,11 +81,25 @@ def parse_session_loss(text):
|
|||||||
return record
|
return record
|
||||||
|
|
||||||
|
|
||||||
|
def parse_recovery_request(text):
|
||||||
|
record = parse_session_loss(text)
|
||||||
|
if record is not None:
|
||||||
|
return record
|
||||||
|
match = _INCONSISTENT.search(str(text or ''))
|
||||||
|
if match is not None:
|
||||||
|
shared = 'symbollibs' in ntpath.normpath(match[1]).casefold().split('\\')
|
||||||
|
return {'error_code': ERROR_CODE, 'kind': 'database_inconsistent',
|
||||||
|
'native_message': match[0], 'database_path': match[1], 'scope': 'central_library' if shared else 'project',
|
||||||
|
'machine': '', 'session': ''}
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def recovery_detail(record):
|
def recovery_detail(record):
|
||||||
target = ('中心库共享符号数据库' if record['scope'] == 'central_library' else
|
target = ('中心库共享符号数据库' if record['scope'] == 'central_library' else
|
||||||
'工程数据库' if record['scope'] == 'project' else '报错中指定的数据库')
|
'工程数据库' if record['scope'] == 'project' else '报错中指定的数据库')
|
||||||
|
reason = '数据库副本不一致' if record.get('kind') == 'database_inconsistent' else '上次服务器会话失联'
|
||||||
return (
|
return (
|
||||||
f"{ERROR_CODE}: {target}的上次服务器会话失联。\n"
|
f"{ERROR_CODE}: {target}{reason};发现问题,未修复。\n"
|
||||||
f"{record['native_message']}\n"
|
f"{record['native_message']}\n"
|
||||||
f'{RECOVERY_ACTION}'
|
f'{RECOVERY_ACTION}'
|
||||||
)
|
)
|
||||||
@@ -100,7 +117,8 @@ def snapshot_log(path):
|
|||||||
return {'size': size, 'tail_sha256': hashlib.sha256(tail).hexdigest(),
|
return {'size': size, 'tail_sha256': hashlib.sha256(tail).hexdigest(),
|
||||||
'truncated': size > LOG_LIMIT,
|
'truncated': size > LOG_LIMIT,
|
||||||
'icdb_errors': [' '.join(message.split()) for message in _icdb_error_paragraphs(decode_log(tail))],
|
'icdb_errors': [' '.join(message.split()) for message in _icdb_error_paragraphs(decode_log(tail))],
|
||||||
'session_losses': losses}
|
'session_losses': losses,
|
||||||
|
'inconsistent_databases': [match[1] for match in _INCONSISTENT.finditer(decode_log(tail))]}
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
return {'size': 0, 'tail_sha256': hashlib.sha256(b'').hexdigest(), 'icdb_errors': []}
|
return {'size': 0, 'tail_sha256': hashlib.sha256(b'').hexdigest(), 'icdb_errors': []}
|
||||||
except OSError as error:
|
except OSError as error:
|
||||||
@@ -161,6 +179,12 @@ def read_log_failure(path, baseline):
|
|||||||
historical = baseline.get('session_losses', []) if baseline else []
|
historical = baseline.get('session_losses', []) if baseline else []
|
||||||
recovery = next((record for record in _session_losses(text)
|
recovery = next((record for record in _session_losses(text)
|
||||||
if appended or _session_identity(record) not in historical), None)
|
if appended or _session_identity(record) not in historical), None)
|
||||||
|
if recovery is None:
|
||||||
|
old = baseline.get('inconsistent_databases') if baseline else None
|
||||||
|
match = next((match for match in _INCONSISTENT.finditer(text)
|
||||||
|
if appended or old is not None and match[1] not in old), None)
|
||||||
|
if match is not None:
|
||||||
|
recovery = parse_recovery_request(match[0])
|
||||||
return text, recovery
|
return text, recovery
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -11,6 +11,28 @@ from uuid import uuid4
|
|||||||
|
|
||||||
_guard = threading.RLock()
|
_guard = threading.RLock()
|
||||||
_owners = {}
|
_owners = {}
|
||||||
|
_library_guards = {}
|
||||||
|
|
||||||
|
|
||||||
|
def _library_guard(key):
|
||||||
|
"""Serialize one lease without making slow resource probes global."""
|
||||||
|
with _guard:
|
||||||
|
return _library_guards.setdefault(key, threading.RLock())
|
||||||
|
|
||||||
|
|
||||||
|
def duplicate_worker_lease(library, process_handle):
|
||||||
|
"""Keep the exact admitted exclusive file object alive across parent exit."""
|
||||||
|
import win32api, win32con
|
||||||
|
lease = LibraryLock(library)
|
||||||
|
with _library_guard(lease.key):
|
||||||
|
owner = _owners.get(lease.key)
|
||||||
|
if owner is None:
|
||||||
|
return None
|
||||||
|
if owner['thread'] != threading.get_ident() or owner['retained'] or not owner['depth']:
|
||||||
|
raise LibraryBusy('不能将其他任务的库锁交给工作进程。')
|
||||||
|
remote = win32api.DuplicateHandle(win32api.GetCurrentProcess(), owner['handle'],
|
||||||
|
process_handle, 0, False, win32con.DUPLICATE_SAME_ACCESS)
|
||||||
|
return remote.Detach() # This handle belongs to the target process only.
|
||||||
|
|
||||||
|
|
||||||
class LibraryBusy(OSError):
|
class LibraryBusy(OSError):
|
||||||
@@ -82,10 +104,10 @@ def has_retained_library(library):
|
|||||||
return bool(owner and owner['retained'])
|
return bool(owner and owner['retained'])
|
||||||
|
|
||||||
|
|
||||||
def recheck_previous_release(library, evidence_dir, *, block_name=None, required=False, progress=None):
|
def recheck_previous_release(library, evidence_dir, *, block_name=None, required=False, progress=None, stop=None):
|
||||||
"""Historical records trigger fresh proof, never process termination or repair."""
|
"""Historical records trigger fresh proof, never process termination or repair."""
|
||||||
if not required:
|
if not required:
|
||||||
with _guard:
|
with _library_guard(LibraryLock(library).key):
|
||||||
owner = _owners.get(LibraryLock(library).key)
|
owner = _owners.get(LibraryLock(library).key)
|
||||||
marker = blocker_path(library)
|
marker = blocker_path(library)
|
||||||
record = checkpoint_record(marker)
|
record = checkpoint_record(marker)
|
||||||
@@ -108,10 +130,13 @@ def recheck_previous_release(library, evidence_dir, *, block_name=None, required
|
|||||||
logging.getLogger(__name__).warning('Release progress observer failed', exc_info=True)
|
logging.getLogger(__name__).warning('Release progress observer failed', exc_info=True)
|
||||||
notify('previous_release_check', detail='正在复核历史记录对应的实际占用')
|
notify('previous_release_check', detail='正在复核历史记录对应的实际占用')
|
||||||
try:
|
try:
|
||||||
proof = release_retained_library(library, evidence_dir, block_name=block_name)
|
options = {'stop': stop} if stop is not None else {}
|
||||||
|
proof = release_retained_library(library, evidence_dir, block_name=block_name, **options)
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
notify('previous_release_unconfirmed', detail=str(error))
|
notify('previous_release_unconfirmed', detail=str(error))
|
||||||
raise
|
raise
|
||||||
|
from .operation_queue import note_metadata_progress
|
||||||
|
note_metadata_progress()
|
||||||
notify('previous_release_confirmed', release_proof=proof,
|
notify('previous_release_confirmed', release_proof=proof,
|
||||||
detail='已确认会话释放并归档历史记录;这不表示历史数据已恢复')
|
detail='已确认会话释放并归档历史记录;这不表示历史数据已恢复')
|
||||||
return proof
|
return proof
|
||||||
@@ -128,9 +153,14 @@ def _persist_blocker(library, status='OWNER_RELEASE_UNCONFIRMED', *, lease_id, b
|
|||||||
export_record['block_name'] = block_name
|
export_record['block_name'] = block_name
|
||||||
elif previous and previous['lease_id'] == lease_id and 'block_name' in previous:
|
elif previous and previous['lease_id'] == lease_id and 'block_name' in previous:
|
||||||
export_record['block_name'] = previous['block_name']
|
export_record['block_name'] = previous['block_name']
|
||||||
|
from .icdb_ownership import session_resource_scope
|
||||||
|
scope = (previous.get('resource_scope') if previous and previous['lease_id'] == lease_id else None)
|
||||||
|
scope = scope or session_resource_scope({'library': library, 'block': export_record.get('block_name')})
|
||||||
with pending.open('w', encoding='utf-8') as stream:
|
with pending.open('w', encoding='utf-8') as stream:
|
||||||
json.dump({**export_record, 'protocol': 'cbb-refresh-verify-library-lease', 'version': 1,
|
json.dump({**export_record, 'protocol': 'cbb-refresh-verify-library-lease', 'version': 1,
|
||||||
'lease_id': lease_id, 'library': str(library), 'status': status,
|
'lease_id': lease_id, 'library': str(library), 'status': status,
|
||||||
|
'lease_state': 'ACTIVE' if status == 'OPERATION_IN_PROGRESS' else 'RETAINED',
|
||||||
|
'resource_scope': scope, 'blocked_resources': [], 'data_recovery_required': None,
|
||||||
'machine': socket.gethostname(),
|
'machine': socket.gethostname(),
|
||||||
'supervisor_created': win32process.GetProcessTimes(win32api.GetCurrentProcess())['CreationTime'].isoformat(),
|
'supervisor_created': win32process.GetProcessTimes(win32api.GetCurrentProcess())['CreationTime'].isoformat(),
|
||||||
'pid': os.getpid(), 'time': datetime.now(timezone.utc).isoformat()}, stream)
|
'pid': os.getpid(), 'time': datetime.now(timezone.utc).isoformat()}, stream)
|
||||||
@@ -159,7 +189,7 @@ class LibraryLock:
|
|||||||
return lease
|
return lease
|
||||||
|
|
||||||
def __enter__(self):
|
def __enter__(self):
|
||||||
with _guard:
|
with _library_guard(self.key):
|
||||||
owner = _owners.get(self.key)
|
owner = _owners.get(self.key)
|
||||||
if owner and owner['retained'] and owner['depth'] == 0 and owner.get('release_probe'):
|
if owner and owner['retained'] and owner['depth'] == 0 and owner.get('release_probe'):
|
||||||
try:
|
try:
|
||||||
@@ -180,7 +210,7 @@ class LibraryLock:
|
|||||||
if self.maintenance_guard is not None:
|
if self.maintenance_guard is not None:
|
||||||
return _enter_maintenance(self)
|
return _enter_maintenance(self)
|
||||||
import win32con, win32file
|
import win32con, win32file
|
||||||
with _guard:
|
with _library_guard(self.key):
|
||||||
owner = _owners.get(self.key)
|
owner = _owners.get(self.key)
|
||||||
if owner:
|
if owner:
|
||||||
if owner['thread'] != threading.get_ident() or owner['retained']:
|
if owner['thread'] != threading.get_ident() or owner['retained']:
|
||||||
@@ -246,7 +276,7 @@ class LibraryLock:
|
|||||||
self.maintenance_mutex = None
|
self.maintenance_mutex = None
|
||||||
|
|
||||||
def _exit_owned(self):
|
def _exit_owned(self):
|
||||||
with _guard:
|
with _library_guard(self.key):
|
||||||
if not self.entered:
|
if not self.entered:
|
||||||
return
|
return
|
||||||
owner = _owners[self.key]
|
owner = _owners[self.key]
|
||||||
@@ -394,15 +424,13 @@ def _owner_is_blocking(item, library, roots):
|
|||||||
|
|
||||||
def _enter_maintenance(lease):
|
def _enter_maintenance(lease):
|
||||||
"""Transfer only a valid known lease, after project admission under lock."""
|
"""Transfer only a valid known lease, after project admission under lock."""
|
||||||
import win32con, win32event, win32file
|
import win32con, win32file
|
||||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
from .operation_queue import check_active
|
||||||
acquired = False
|
|
||||||
handle = None
|
handle = None
|
||||||
existing = None
|
existing = None
|
||||||
try:
|
try:
|
||||||
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
check_active()
|
||||||
if not acquired: raise LibraryBusy('已有 CBB 操作运行,维护不能接续')
|
with _library_guard(lease.key):
|
||||||
with _guard:
|
|
||||||
marker = blocker_path(lease.library)
|
marker = blocker_path(lease.library)
|
||||||
if marker.with_suffix('.pending').exists():
|
if marker.with_suffix('.pending').exists():
|
||||||
raise LibraryBusy('未完成检查点写入,不能自动接续')
|
raise LibraryBusy('未完成检查点写入,不能自动接续')
|
||||||
@@ -436,6 +464,7 @@ def _enter_maintenance(lease):
|
|||||||
with saved.open('xb') as stream:
|
with saved.open('xb') as stream:
|
||||||
stream.write(old); stream.flush(); os.fsync(stream.fileno())
|
stream.write(old); stream.flush(); os.fsync(stream.fileno())
|
||||||
if saved.read_bytes() != old: raise OSError('原检查点归档校验失败')
|
if saved.read_bytes() != old: raise OSError('原检查点归档校验失败')
|
||||||
|
check_active()
|
||||||
lease_id = uuid4().hex
|
lease_id = uuid4().hex
|
||||||
_persist_blocker(lease.library, 'OPERATION_IN_PROGRESS', lease_id=lease_id)
|
_persist_blocker(lease.library, 'OPERATION_IN_PROGRESS', lease_id=lease_id)
|
||||||
_owners[lease.key] = {'thread': threading.get_ident(), 'depth': 1, 'handle': handle,
|
_owners[lease.key] = {'thread': threading.get_ident(), 'depth': 1, 'handle': handle,
|
||||||
@@ -443,19 +472,16 @@ def _enter_maintenance(lease):
|
|||||||
'release_probe': lease.safe_to_release, 'block_name': None}
|
'release_probe': lease.safe_to_release, 'block_name': None}
|
||||||
lease.maintenance_proof = proof
|
lease.maintenance_proof = proof
|
||||||
lease.entered = True
|
lease.entered = True
|
||||||
lease.maintenance_mutex = mutex
|
|
||||||
return lease
|
return lease
|
||||||
except Exception:
|
except Exception:
|
||||||
if handle is not None and existing is None: handle.Close()
|
if handle is not None and existing is None: handle.Close()
|
||||||
if acquired: win32event.ReleaseMutex(mutex)
|
|
||||||
mutex.Close()
|
|
||||||
raise
|
raise
|
||||||
|
|
||||||
|
|
||||||
def owned_snapshot(path):
|
def owned_snapshot(path):
|
||||||
"""Read only a lease held by this thread, never reopen an exclusive file."""
|
"""Read only a lease held by this thread, never reopen an exclusive file."""
|
||||||
import win32con, win32file
|
import win32con, win32file
|
||||||
with _guard:
|
with _library_guard(_key(path)):
|
||||||
owner = _owners.get(_key(path))
|
owner = _owners.get(_key(path))
|
||||||
if not owner or owner['thread'] != threading.get_ident() or owner['retained']:
|
if not owner or owner['thread'] != threading.get_ident() or owner['retained']:
|
||||||
return None
|
return None
|
||||||
@@ -470,19 +496,17 @@ def owned_snapshot(path):
|
|||||||
|
|
||||||
|
|
||||||
@contextmanager
|
@contextmanager
|
||||||
def _prove_library_released(library, block_name=None, *, allow_unknown_checkpoint=False):
|
def _prove_library_released(library, block_name=None, *, block_names=(), allow_unknown_checkpoint=False, stop=None):
|
||||||
"""Hold all native database read handles during explicit lease release."""
|
"""Hold all native database read handles during explicit lease release."""
|
||||||
import stat
|
from .operation_queue import note_metadata_progress
|
||||||
import win32con, win32file
|
|
||||||
from .owner_probe import query_owners
|
from .owner_probe import query_owners
|
||||||
from .scoped_manifest import scan_tree
|
|
||||||
from .native_management import _retained_workers
|
from .native_management import _retained_workers
|
||||||
from .native_export_guard import assert_retained_exports_idle, prove_export_copies_released
|
from .native_export_guard import assert_retained_exports_idle, prove_export_copies_released
|
||||||
from .native_engineering_identity import _OWNER_NAMES
|
from .native_engineering_identity import _OWNER_NAMES
|
||||||
library = Path(library).resolve()
|
library = Path(library).resolve()
|
||||||
assert_retained_exports_idle(library)
|
assert_retained_exports_idle(library)
|
||||||
if any(worker.poll() is None and (allow_unknown_checkpoint
|
if any(worker.poll() is None and (not getattr(worker, 'cbb_library', None)
|
||||||
or not getattr(worker, 'cbb_library', None) or _key(worker.cbb_library) == _key(library))
|
or _key(worker.cbb_library) == _key(library))
|
||||||
for worker in _retained_workers):
|
for worker in _retained_workers):
|
||||||
raise LibraryBusy('原生管理工作进程尚未返回,不能解除协调阻止。')
|
raise LibraryBusy('原生管理工作进程尚未返回,不能解除协调阻止。')
|
||||||
from .com_runtime import initialize_com, uninitialize_com
|
from .com_runtime import initialize_com, uninitialize_com
|
||||||
@@ -492,12 +516,17 @@ def _prove_library_released(library, block_name=None, *, allow_unknown_checkpoin
|
|||||||
'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe', 'CleanWGLib.exe',
|
'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe', 'CleanWGLib.exe',
|
||||||
'cscript.exe', 'wscript.exe', 'python.exe', 'pythonw.exe',
|
'cscript.exe', 'wscript.exe', 'python.exe', 'pythonw.exe',
|
||||||
'CbbRefreshVerify.exe', *sorted(_OWNER_NAMES))
|
'CbbRefreshVerify.exe', *sorted(_OWNER_NAMES))
|
||||||
scope_root = (Path(library).resolve().parent/'ReusableBlocksLP'/block_name/'Work').resolve() if block_name else None
|
blocks = tuple(dict.fromkeys(block_names or ((block_name,) if block_name else ())))
|
||||||
|
if any(not name or name in ('.', '..') or any(c in name for c in '\\/:*?"<>|') for name in blocks):
|
||||||
|
raise ValueError('释放检查的工程名称无效')
|
||||||
|
scope_roots = tuple(library.parent/'ReusableBlocksLP'/name/'Work' for name in blocks)
|
||||||
shared_root = Path(library).resolve().parent/'SymbolLibs'
|
shared_root = Path(library).resolve().parent/'SymbolLibs'
|
||||||
if allow_unknown_checkpoint and scope_root is not None:
|
if allow_unknown_checkpoint and scope_roots:
|
||||||
raise LibraryBusy('未知检查点必须执行完整库释放证明。')
|
raise LibraryBusy('未知检查点必须执行完整库释放证明。')
|
||||||
observed = []
|
observed = []
|
||||||
def check_owners():
|
def check_owners():
|
||||||
|
if stop is not None and stop.is_set():
|
||||||
|
raise InterruptedError('已停止释放检查')
|
||||||
owners = []
|
owners = []
|
||||||
observed.clear()
|
observed.clear()
|
||||||
from .session_record import active_write_records
|
from .session_record import active_write_records
|
||||||
@@ -506,8 +535,7 @@ def _prove_library_released(library, block_name=None, *, allow_unknown_checkpoin
|
|||||||
for item in query_owners(names):
|
for item in query_owners(names):
|
||||||
if item['pid'] == os.getpid():
|
if item['pid'] == os.getpid():
|
||||||
continue
|
continue
|
||||||
if not allow_unknown_checkpoint:
|
roots = (*scope_roots, shared_root) if scope_roots else (library.parent,)
|
||||||
roots = (scope_root, shared_root) if scope_root is not None else (Path(library).parent,)
|
|
||||||
if not _owner_is_blocking(item, library, roots):
|
if not _owner_is_blocking(item, library, roots):
|
||||||
if _owner_matches_scope(item, library, roots) is None:
|
if _owner_matches_scope(item, library, roots) is None:
|
||||||
observed.append(item)
|
observed.append(item)
|
||||||
@@ -519,68 +547,80 @@ def _prove_library_released(library, block_name=None, *, allow_unknown_checkpoin
|
|||||||
owners.append(item)
|
owners.append(item)
|
||||||
if owners:
|
if owners:
|
||||||
raise LibraryBusy(f'原生进程仍存在,不能解除协调阻止:{owners}')
|
raise LibraryBusy(f'原生进程仍存在,不能解除协调阻止:{owners}')
|
||||||
|
note_metadata_progress()
|
||||||
return owners
|
return owners
|
||||||
check_owners()
|
check_owners()
|
||||||
if scope_root is None:
|
from .file_probe import hold_release_files
|
||||||
entries = scan_tree(Path(library).parent)
|
roots = (*scope_roots, shared_root) if scope_roots else None
|
||||||
else:
|
inspections = []
|
||||||
entries = {Path(library): Path(library).lstat()}
|
|
||||||
for root in (scope_root, shared_root):
|
|
||||||
if root.exists():
|
|
||||||
entries.update(scan_tree(root))
|
|
||||||
addresses = [str(path) for path in entries if path.name.casefold() == 'saddress.adr'
|
|
||||||
and (scope_root is None or path.is_relative_to(scope_root)
|
|
||||||
or path.is_relative_to(shared_root))]
|
|
||||||
if addresses:
|
|
||||||
raise LibraryBusy(f'库中仍有数据库地址记录,不能自动解除:{addresses}')
|
|
||||||
# scan_tree already rejects links; only native candidates need file opens.
|
|
||||||
native = [path for path, metadata in entries.items() if stat.S_ISREG(metadata.st_mode) and (
|
|
||||||
path == library
|
|
||||||
or (path.name.casefold() in ('icdb.dat', 'layoutdb.lyt')
|
|
||||||
and (scope_root is None or path.is_relative_to(scope_root)
|
|
||||||
or path.is_relative_to(shared_root))))]
|
|
||||||
if library not in native:
|
|
||||||
raise LibraryBusy('目标库身份缺失,不能解除协调阻止。')
|
|
||||||
with ExitStack() as stack:
|
with ExitStack() as stack:
|
||||||
|
try:
|
||||||
|
files = stack.enter_context(hold_release_files(library, roots, stop=stop))
|
||||||
|
except OSError as error:
|
||||||
|
blocked = LibraryBusy(str(error))
|
||||||
|
blocked.winerror = getattr(error, 'winerror', None)
|
||||||
|
raise blocked from error
|
||||||
|
note_metadata_progress()
|
||||||
|
if files['addresses']:
|
||||||
|
# Native inspection needs the database; reacquire proof handles
|
||||||
|
# and compare the exact address/project binding before commit.
|
||||||
|
stack.close()
|
||||||
|
from .icdb_ownership import inspect_release_addresses
|
||||||
|
# Checkpoint I/O is per-library; only native inspection owns
|
||||||
|
# the host channel. The sidecar still excludes other writers.
|
||||||
|
if stop is not None and stop.is_set():
|
||||||
|
raise InterruptedError('已停止释放检查')
|
||||||
|
inspections = inspect_release_addresses(files, stop=stop)
|
||||||
|
try:
|
||||||
|
current = stack.enter_context(hold_release_files(library, roots, stop=stop))
|
||||||
|
except OSError as error:
|
||||||
|
blocked = LibraryBusy(str(error))
|
||||||
|
blocked.winerror = getattr(error, 'winerror', None)
|
||||||
|
raise blocked from error
|
||||||
|
if any(current[key] != files[key] for key in (
|
||||||
|
'exclusive_files', 'addresses', 'signatures', 'inspection_targets')):
|
||||||
|
raise LibraryBusy('原生检查期间资源范围或地址身份变化。')
|
||||||
|
files = current
|
||||||
|
note_metadata_progress()
|
||||||
export_proof = (prove_export_copies_released(library, allow_unknown_checkpoint=True)
|
export_proof = (prove_export_copies_released(library, allow_unknown_checkpoint=True)
|
||||||
if allow_unknown_checkpoint else prove_export_copies_released(library))
|
if allow_unknown_checkpoint else prove_export_copies_released(library))
|
||||||
export_copies = stack.enter_context(export_proof)
|
export_copies = stack.enter_context(export_proof)
|
||||||
for path in native:
|
|
||||||
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
|
|
||||||
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
|
||||||
stack.callback(handle.Close)
|
|
||||||
owners = check_owners()
|
owners = check_owners()
|
||||||
yield {'native_owners': owners, 'observed_owners': list(observed),
|
yield {**{k: v for k, v in files.items() if k not in ('status', 'token')},
|
||||||
'addresses': addresses, 'export_copies': export_copies,
|
'native_owners': owners, 'observed_owners': list(observed),
|
||||||
'unknown_checkpoint_recovery': allow_unknown_checkpoint,
|
'export_copies': export_copies, 'native_inspections': inspections,
|
||||||
'exclusive_files': [str(path) for path in native]}
|
'data_recovery_required': any(item['repair_required'] for item in inspections) if inspections else None,
|
||||||
|
'data_recovery_resources': [item['database'] for item in inspections if item['repair_required']],
|
||||||
|
'unknown_checkpoint_recovery': allow_unknown_checkpoint}
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
uninitialize_com(initialized)
|
uninitialize_com(initialized)
|
||||||
|
|
||||||
|
|
||||||
def release_retained_library(library, evidence_dir, *, block_name=None):
|
def release_retained_library(library, evidence_dir, *, block_name=None, block_names=(), stop=None):
|
||||||
"""Reconcile historical leases after fresh owner/address/access proof.
|
"""Reconcile historical leases after fresh owner/address/access proof.
|
||||||
|
|
||||||
The upload sidecar is never deleted. This acknowledges process release,
|
The upload sidecar is never deleted. This acknowledges process release,
|
||||||
not the correctness of a partially changed library or its recovery state.
|
not the correctness of a partially changed library or its recovery state.
|
||||||
"""
|
"""
|
||||||
import win32con, win32event, win32file
|
import win32con, win32file
|
||||||
|
from .operation_queue import note_metadata_progress
|
||||||
library = Path(library).resolve(strict=True)
|
library = Path(library).resolve(strict=True)
|
||||||
from .session_record import (retained_session_snapshot, acknowledge_library_release,
|
from .session_record import (retained_session_snapshot, acknowledge_library_release,
|
||||||
reconciled_retained_sessions)
|
reconciled_retained_sessions)
|
||||||
retained = retained_session_snapshot(library)
|
retained = retained_session_snapshot(library)
|
||||||
|
requested_blocks = tuple(dict.fromkeys(block_names or ((block_name,) if block_name else ())))
|
||||||
|
if any(not name or name in ('.', '..') or any(c in name for c in '\\/:*?"<>|') for name in requested_blocks):
|
||||||
|
raise ValueError('释放检查的工程名称无效')
|
||||||
evidence = Path(evidence_dir).resolve()
|
evidence = Path(evidence_dir).resolve()
|
||||||
if evidence.is_relative_to(library.parent) or library.parent.is_relative_to(evidence):
|
if evidence.is_relative_to(library.parent) or library.parent.is_relative_to(evidence):
|
||||||
raise ValueError('释放检查证据必须位于目标库之外。')
|
raise ValueError('释放检查证据必须位于目标库之外。')
|
||||||
lease = LibraryLock(library)
|
lease = LibraryLock(library)
|
||||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
|
||||||
acquired = False
|
|
||||||
external = None
|
external = None
|
||||||
try:
|
try:
|
||||||
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
if stop is not None and stop.is_set():
|
||||||
if not acquired:
|
raise InterruptedError('已停止释放检查')
|
||||||
raise LibraryBusy('另一个 CBB 操作仍在运行。')
|
with _library_guard(lease.key):
|
||||||
with _guard:
|
|
||||||
owner = _owners.get(lease.key)
|
owner = _owners.get(lease.key)
|
||||||
if owner and (not owner['retained'] or owner['depth']):
|
if owner and (not owner['retained'] or owner['depth']):
|
||||||
raise LibraryBusy('本应用操作仍在使用库锁。')
|
raise LibraryBusy('本应用操作仍在使用库锁。')
|
||||||
@@ -598,8 +638,10 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
|
|||||||
before = {path: path.read_bytes() if path.exists() else None for path in checkpoints}
|
before = {path: path.read_bytes() if path.exists() else None for path in checkpoints}
|
||||||
unknown = any(data is not None and checkpoint_record(path) is None for path, data in before.items())
|
unknown = any(data is not None and checkpoint_record(path) is None for path, data in before.items())
|
||||||
records = [checkpoint_record(path) for path, data in before.items() if data is not None]
|
records = [checkpoint_record(path) for path, data in before.items() if data is not None]
|
||||||
scoped = (block_name if block_name and all(record and record.get('block_name') == block_name
|
scoped_blocks = (requested_blocks if requested_blocks and all(record
|
||||||
for record in records) and (owner is None or owner.get('block_name') == block_name) else None)
|
and record.get('block_name') in requested_blocks for record in records)
|
||||||
|
and (owner is None or owner.get('block_name') in requested_blocks) else ())
|
||||||
|
scoped = scoped_blocks[0] if len(scoped_blocks) == 1 else None
|
||||||
reconciled = [{'kind': 'checkpoint', 'path': str(path), 'recognized': metadata is not None,
|
reconciled = [{'kind': 'checkpoint', 'path': str(path), 'recognized': metadata is not None,
|
||||||
**{key: (metadata or {}).get(key) for key in ('block_name', 'lease_id', 'pid', 'status', 'time')}}
|
**{key: (metadata or {}).get(key) for key in ('block_name', 'lease_id', 'pid', 'status', 'time')}}
|
||||||
for path, data in before.items() if data is not None
|
for path, data in before.items() if data is not None
|
||||||
@@ -610,28 +652,49 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
|
|||||||
'status': 'OWNER_RELEASE_UNCONFIRMED'})
|
'status': 'OWNER_RELEASE_UNCONFIRMED'})
|
||||||
foreign = sorted({item['block_name'] for item in reconciled
|
foreign = sorted({item['block_name'] for item in reconciled
|
||||||
if block_name and item.get('block_name') and item['block_name'] != block_name})
|
if block_name and item.get('block_name') and item['block_name'] != block_name})
|
||||||
proof_context = (_prove_library_released(library, allow_unknown_checkpoint=True) if unknown else
|
options = {'stop': stop} if stop is not None else {}
|
||||||
_prove_library_released(library, block_name=scoped)
|
if len(scoped_blocks) > 1:
|
||||||
if scoped else _prove_library_released(library))
|
options['block_names'] = scoped_blocks
|
||||||
|
proof_context = (_prove_library_released(library, allow_unknown_checkpoint=True, **options) if unknown else
|
||||||
|
_prove_library_released(library, block_name=scoped, **options)
|
||||||
|
if scoped else _prove_library_released(library, **options))
|
||||||
with proof_context as proof:
|
with proof_context as proof:
|
||||||
|
if stop is not None and stop.is_set():
|
||||||
|
raise InterruptedError('已停止释放检查')
|
||||||
|
with _guard:
|
||||||
|
if _owners.get(lease.key) is not owner:
|
||||||
|
raise LibraryBusy('释放检查期间租约身份变化,保留当前任务。')
|
||||||
if unknown and proof.get('unknown_checkpoint_recovery') is not True:
|
if unknown and proof.get('unknown_checkpoint_recovery') is not True:
|
||||||
raise LibraryBusy('未知检查点缺少完整库释放证明,保留原文件。')
|
raise LibraryBusy('未知检查点缺少完整库释放证明,保留原文件。')
|
||||||
if any((path.read_bytes() if path.exists() else None) != data for path, data in before.items()):
|
if any((path.read_bytes() if path.exists() else None) != data for path, data in before.items()):
|
||||||
raise LibraryBusy('释放检查期间协调检查点变化,保留原文件。')
|
raise LibraryBusy('释放检查期间协调检查点变化,保留原文件。')
|
||||||
root = evidence/('release-' + uuid4().hex)
|
root = evidence/('release-' + uuid4().hex)
|
||||||
root.mkdir(parents=True, exist_ok=False)
|
root.mkdir(parents=True, exist_ok=False)
|
||||||
reconciled_sessions = reconciled_retained_sessions(retained, block_name=scoped)
|
matching_retained = ({path: value for path, value in retained.items()
|
||||||
|
if value[1] in scoped_blocks} if scoped_blocks else retained)
|
||||||
|
reconciled_sessions = reconciled_retained_sessions(matching_retained, block_name=scoped)
|
||||||
reconciled_blocks = sorted({item['block_name'] for item in (*reconciled, *reconciled_sessions)
|
reconciled_blocks = sorted({item['block_name'] for item in (*reconciled, *reconciled_sessions)
|
||||||
if item.get('block_name')})
|
if item.get('block_name')})
|
||||||
record = {'library': str(library), 'status': 'RELEASE_CONFIRMED', **proof,
|
record = {'library': str(library), 'status': 'RELEASE_CONFIRMED', **proof,
|
||||||
'requested_block_name': block_name, 'proof_scope': 'BLOCK' if scoped else 'LIBRARY',
|
'requested_block_name': block_name, 'requested_block_names': list(requested_blocks),
|
||||||
'proof_block_name': scoped, 'reconciled_checkpoints': reconciled,
|
'proof_scope': 'BLOCK' if scoped else 'BLOCKS' if scoped_blocks else 'LIBRARY',
|
||||||
|
'proof_block_name': scoped, 'proof_block_names': list(scoped_blocks),
|
||||||
|
'reconciled_checkpoints': reconciled,
|
||||||
'reconciled_foreign_blockers': sorted(set(foreign) | {
|
'reconciled_foreign_blockers': sorted(set(foreign) | {
|
||||||
block for block in reconciled_blocks if block_name and block != block_name}),
|
block for block in reconciled_blocks if block_name and block != block_name}),
|
||||||
'reconciled_blocks': reconciled_blocks, 'reconciled_sessions': reconciled_sessions,
|
'reconciled_blocks': reconciled_blocks, 'reconciled_sessions': reconciled_sessions,
|
||||||
'unknown_checkpoint_archived': unknown,
|
'unknown_checkpoint_archived': unknown,
|
||||||
|
'lease_state': 'RELEASED', 'blocked_resources': [],
|
||||||
|
'data_recovery_required': proof.get('data_recovery_required', None),
|
||||||
'data_recovery_confirmed': False, 'evidence_path': str(root/'release.json')}
|
'data_recovery_confirmed': False, 'evidence_path': str(root/'release.json')}
|
||||||
(root/'release.json').write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
|
record['resource_scope'] = {**proof.get('resource_scope', {}),
|
||||||
|
'scope_state': 'OBSERVED', 'library': str(library), 'block_name': scoped,
|
||||||
|
'block_names': list(scoped_blocks),
|
||||||
|
'lease_id': owner['lease_id'] if owner else None,
|
||||||
|
'operation_ids': [item['operation_id'] for item in reconciled_sessions]}
|
||||||
|
pending = {**record, 'status': 'RELEASE_PENDING', 'lease_state': 'PENDING'}
|
||||||
|
(root/'release.json').write_text(json.dumps(pending, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||||
|
note_metadata_progress()
|
||||||
for index, checkpoint in enumerate(checkpoints):
|
for index, checkpoint in enumerate(checkpoints):
|
||||||
if checkpoint.exists():
|
if checkpoint.exists():
|
||||||
data = checkpoint.read_bytes()
|
data = checkpoint.read_bytes()
|
||||||
@@ -639,15 +702,16 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
|
|||||||
archived.write_bytes(data)
|
archived.write_bytes(data)
|
||||||
if archived.read_bytes() != data:
|
if archived.read_bytes() != data:
|
||||||
raise OSError('阻止记录归档校验失败,保持库锁。')
|
raise OSError('阻止记录归档校验失败,保持库锁。')
|
||||||
|
note_metadata_progress()
|
||||||
|
if stop is not None and stop.is_set():
|
||||||
|
raise InterruptedError('已停止释放检查')
|
||||||
checkpoint.unlink() # Checkpoint JSON only; never .lock.
|
checkpoint.unlink() # Checkpoint JSON only; never .lock.
|
||||||
if owner:
|
if owner:
|
||||||
owner['handle'].Close()
|
owner['handle'].Close()
|
||||||
del _owners[lease.key]
|
del _owners[lease.key]
|
||||||
acknowledge_library_release(record, retained, block_name=scoped)
|
(root/'release.json').write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||||
|
acknowledge_library_release(record, matching_retained, block_name=scoped)
|
||||||
return record
|
return record
|
||||||
finally:
|
finally:
|
||||||
if external is not None:
|
if external is not None:
|
||||||
external.Close()
|
external.Close()
|
||||||
if acquired:
|
|
||||||
win32event.ReleaseMutex(mutex)
|
|
||||||
mutex.Close()
|
|
||||||
@@ -203,20 +203,22 @@ def filesystem_status_map(library: Path, names):
|
|||||||
return {name: details['status'] for name, details in filesystem_evidence_map(library, names).items()}
|
return {name: details['status'] for name, details in filesystem_evidence_map(library, names).items()}
|
||||||
|
|
||||||
def read_library_fast(path: Path, *, status_reader=None):
|
def read_library_fast(path: Path, *, status_reader=None):
|
||||||
"""List CBBs from ReusableBlocksLP without touching COM or the .lmc.
|
"""Discover directories; this does not validate native format/registration."""
|
||||||
|
|
||||||
Useful when Library Manager is unavailable or already running: the folder
|
|
||||||
is the same source the LM tree shows, and an optional status_reader can
|
|
||||||
supply each item's flag without a full COM session.
|
|
||||||
"""
|
|
||||||
try:
|
try:
|
||||||
path = Path(path)
|
path = Path(path)
|
||||||
|
if path.suffix.casefold() != '.lmc':
|
||||||
|
return LibraryReadResult((), 'INPUT_SUFFIX: 请选择 .lmc 中心库文件。')
|
||||||
if not path.is_file():
|
if not path.is_file():
|
||||||
return LibraryReadResult((), f'中心库不存在: {path}')
|
return LibraryReadResult((), f'INPUT_MISSING: 中心库不存在或不是文件: {path}')
|
||||||
|
with path.open('rb') as stream:
|
||||||
|
if not stream.read(1):
|
||||||
|
return LibraryReadResult((), 'INPUT_EMPTY: 中心库文件为空。')
|
||||||
|
if any(lock.is_dir() for lock in (path.with_suffix('.lock'), path.with_name('.'+path.stem+'.cbb-upload.lock'))):
|
||||||
|
return LibraryReadResult((), 'INPUT_LOCK_DIRECTORY: 中心库锁路径是目录。')
|
||||||
folder = path.parent/'ReusableBlocksLP'
|
folder = path.parent/'ReusableBlocksLP'
|
||||||
if not folder.is_dir():
|
if folder.exists() and not folder.is_dir():
|
||||||
return LibraryReadResult((), f'缺少 ReusableBlocksLP 目录: {folder}')
|
return LibraryReadResult((), f'INPUT_DIRECTORY: ReusableBlocksLP 不是目录: {folder}')
|
||||||
entries = [entry for entry in folder.iterdir() if entry.is_dir()]
|
entries = [entry for entry in folder.iterdir() if entry.is_dir()] if folder.is_dir() else []
|
||||||
names = tuple(sorted((entry.name for entry in entries), key=str.casefold))
|
names = tuple(sorted((entry.name for entry in entries), key=str.casefold))
|
||||||
statuses = {}
|
statuses = {}
|
||||||
if status_reader is not None and names:
|
if status_reader is not None and names:
|
||||||
@@ -240,8 +242,11 @@ def read_library_fast(path: Path, *, status_reader=None):
|
|||||||
status = str(statuses.get(entry.name, 'UNKNOWN') or 'UNKNOWN')
|
status = str(statuses.get(entry.name, 'UNKNOWN') or 'UNKNOWN')
|
||||||
if status not in {'READY', 'PENDING', 'UNKNOWN', 'UNAVAILABLE', 'ERROR', 'TIMEOUT'}:
|
if status not in {'READY', 'PENDING', 'UNKNOWN', 'UNAVAILABLE', 'ERROR', 'TIMEOUT'}:
|
||||||
status = 'UNKNOWN'
|
status = 'UNKNOWN'
|
||||||
records.append(CbbRecord(entry.name, 'Reusable Blocks', status=status))
|
records.append(CbbRecord(entry.name, 'Reusable Blocks', status=status,
|
||||||
return LibraryReadResult(tuple(sorted(records, key=lambda item: item.name)))
|
catalog_source='directory', status_source='status_reader' if status_reader else 'unknown'))
|
||||||
|
return LibraryReadResult(tuple(sorted(records, key=lambda item: item.name)), directory_count=len(entries))
|
||||||
|
except PermissionError as error:
|
||||||
|
return LibraryReadResult((), f'INPUT_PERMISSION: 无权读取中心库: {error}')
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
return LibraryReadResult((), str(error))
|
return LibraryReadResult((), str(error))
|
||||||
|
|
||||||
|
|||||||
@@ -19,11 +19,14 @@ def assert_native_idle(target=None):
|
|||||||
from .native_export_guard import assert_retained_exports_idle
|
from .native_export_guard import assert_retained_exports_idle
|
||||||
from .native_engineering_identity import _OWNER_NAMES
|
from .native_engineering_identity import _OWNER_NAMES
|
||||||
from .library_lock import _key, _owner_matches_scope
|
from .library_lock import _key, _owner_matches_scope
|
||||||
library = None
|
library = Path(target.library) if target is not None and getattr(target, 'library', None) else None
|
||||||
roots = ()
|
roots = ()
|
||||||
if target is not None:
|
if target is not None:
|
||||||
from .backup_recovery import _project_text
|
from .backup_recovery import _project_text
|
||||||
roots = (Path(target.project).parent, Path(target.database))
|
roots = (Path(target.project).parent, Path(target.database))
|
||||||
|
if library is not None:
|
||||||
|
roots += (library.parent/'SymbolLibs',)
|
||||||
|
else:
|
||||||
try:
|
try:
|
||||||
lines = re.findall(r'^KEY CentralLibrary\b[^\r\n]*', _project_text(target.project), re.M)
|
lines = re.findall(r'^KEY CentralLibrary\b[^\r\n]*', _project_text(target.project), re.M)
|
||||||
references = [re.fullmatch(r'KEY CentralLibrary "([^"\r\n]+)"\s*', line) for line in lines]
|
references = [re.fullmatch(r'KEY CentralLibrary "([^"\r\n]+)"\s*', line) for line in lines]
|
||||||
|
|||||||
@@ -169,23 +169,29 @@ def _may_have_mutated(record):
|
|||||||
or any(not isinstance(item, dict) or item.get('stage') not in prewrite for item in history))
|
or any(not isinstance(item, dict) or item.get('stage') not in prewrite for item in history))
|
||||||
|
|
||||||
|
|
||||||
def run_management(request, *, adapter=None, verifier=None, idle_check=None, progress=None, stop=None, version_prompt=None):
|
def run_management(request, *, adapter=None, verifier=None, idle_check=None, progress=None, stop=None, version_prompt=None,
|
||||||
|
write_admission=None):
|
||||||
from .verify_runner import VerifyRequest, run_verify
|
from .verify_runner import VerifyRequest, run_verify
|
||||||
from .backup_recovery import _idle_check
|
from .backup_recovery import _idle_check
|
||||||
import win32con, win32event
|
from contextlib import ExitStack
|
||||||
|
from .operation_queue import check_active, native_channel, task_stop, remember_result
|
||||||
|
stop = task_stop(stop)
|
||||||
import pythoncom
|
import pythoncom
|
||||||
if adapter is None:
|
if adapter is None:
|
||||||
from .native_management import NativeManagementAdapter
|
from .native_management import NativeManagementAdapter
|
||||||
adapter = NativeManagementAdapter()
|
adapter = NativeManagementAdapter()
|
||||||
verifier = verifier or run_verify
|
verifier = verifier or run_verify
|
||||||
idle_check = idle_check or _idle_check
|
|
||||||
root = report = None
|
root = report = None
|
||||||
|
native_idle_check = idle_check is None
|
||||||
|
if native_idle_check:
|
||||||
|
from .write_admission import WriteAdmission
|
||||||
|
write_admission=write_admission or WriteAdmission(prompt=version_prompt,stop=stop)
|
||||||
|
idle_check=lambda library,project,pcb:_idle_check(library,project,pcb,
|
||||||
|
confirmation=write_admission,evidence=root,block=request.name)
|
||||||
stage = 'preflight'
|
stage = 'preflight'
|
||||||
history = []
|
history = []
|
||||||
mutated = uploaded = removed = False
|
mutated = uploaded = removed = False
|
||||||
owner_safe = True
|
owner_safe = True
|
||||||
mutex = None
|
|
||||||
acquired = False
|
|
||||||
release_proof = None
|
release_proof = None
|
||||||
original = None
|
original = None
|
||||||
change_report = None
|
change_report = None
|
||||||
@@ -193,6 +199,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
|||||||
nonlocal owner_safe
|
nonlocal owner_safe
|
||||||
if stop is not None and stop.is_set():
|
if stop is not None and stop.is_set():
|
||||||
raise InterruptedError('MANAGEMENT_CANCELLED: 已停止后续原生操作')
|
raise InterruptedError('MANAGEMENT_CANCELLED: 已停止后续原生操作')
|
||||||
|
with native_channel():
|
||||||
owner_safe = False
|
owner_safe = False
|
||||||
try:
|
try:
|
||||||
result = callback(*args)
|
result = callback(*args)
|
||||||
@@ -212,11 +219,15 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
|||||||
progress({'stage': stage, 'block': request.name, 'operation': request.operation, **details})
|
progress({'stage': stage, 'block': request.name, 'operation': request.operation, **details})
|
||||||
def finish(status, detail='', safe=True):
|
def finish(status, detail='', safe=True):
|
||||||
nonlocal change_report
|
nonlocal change_report
|
||||||
|
remember_result(ManagementResult(request.operation, request.library, request.name, request.partition,
|
||||||
|
request.source, request.auto_verify, 'complete', status, safe, detail, report, release_proof, change_report))
|
||||||
if mutated and original is not None and change_report is None:
|
if mutated and original is not None and change_report is None:
|
||||||
change_report = {'status': 'UNCONFIRMED', 'scope': original['scope'],
|
change_report = {'status': 'UNCONFIRMED', 'scope': original['scope'],
|
||||||
**comparison_rules(scope),
|
**comparison_rules(scope),
|
||||||
'unrelated_cbb_content_checked': False,
|
'unrelated_cbb_content_checked': False,
|
||||||
'detail': '原生会话尚未释放,未读取写后内容'}
|
'detail': '原生会话尚未释放,未读取写后内容'}
|
||||||
|
remember_result(ManagementResult(request.operation, request.library, request.name, request.partition,
|
||||||
|
request.source, request.auto_verify, 'complete', status, safe, detail, report, release_proof, change_report))
|
||||||
if safe:
|
if safe:
|
||||||
try:
|
try:
|
||||||
after = build_exclusive_library_manifest(library_root, scope=scope, progress=progress)
|
after = build_exclusive_library_manifest(library_root, scope=scope, progress=progress)
|
||||||
@@ -238,12 +249,13 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
|||||||
detail = (detail+'\n'+change_report['detail']).strip()
|
detail = (detail+'\n'+change_report['detail']).strip()
|
||||||
result = ManagementResult(request.operation, request.library, request.name, request.partition,
|
result = ManagementResult(request.operation, request.library, request.name, request.partition,
|
||||||
request.source, request.auto_verify, 'complete', status, safe, detail, report, release_proof, change_report)
|
request.source, request.auto_verify, 'complete', status, safe, detail, report, release_proof, change_report)
|
||||||
|
remember_result(result)
|
||||||
if report:
|
if report:
|
||||||
try:
|
try:
|
||||||
_write_json(report, {**asdict(result), 'history': history, 'backup_policy': 'manual'})
|
_write_json(report, {**asdict(result), 'history': history, 'backup_policy': 'manual'})
|
||||||
except OSError as error:
|
except OSError as error:
|
||||||
result = replace(result, detail=f'{detail}\n操作记录写入失败:{error}'.strip())
|
result = replace(result, detail=f'{detail}\n操作记录写入失败:{error}'.strip())
|
||||||
return result
|
return remember_result(result)
|
||||||
from .com_runtime import initialize_com, uninitialize_com
|
from .com_runtime import initialize_com, uninitialize_com
|
||||||
initialized = initialize_com()
|
initialized = initialize_com()
|
||||||
try:
|
try:
|
||||||
@@ -277,6 +289,8 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
|||||||
if request.operation in ('add', 'update'):
|
if request.operation in ('add', 'update'):
|
||||||
if request.source is None:
|
if request.source is None:
|
||||||
raise ValueError('新增/更新需要完整来源工程。')
|
raise ValueError('新增/更新需要完整来源工程。')
|
||||||
|
if hasattr(adapter, 'validate_source'):
|
||||||
|
adapter.validate_source(request)
|
||||||
source, pcb, top = source_project(request.source, request.top_level_block)
|
source, pcb, top = source_project(request.source, request.top_level_block)
|
||||||
if (source.parent.is_relative_to(library_root) or library_root.is_relative_to(source.parent)
|
if (source.parent.is_relative_to(library_root) or library_root.is_relative_to(source.parent)
|
||||||
or evidence.is_relative_to(source.parent)
|
or evidence.is_relative_to(source.parent)
|
||||||
@@ -286,22 +300,30 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
|||||||
root.mkdir(parents=True, exist_ok=False)
|
root.mkdir(parents=True, exist_ok=False)
|
||||||
report = root/'checkpoint.json'
|
report = root/'checkpoint.json'
|
||||||
checkpoint('release_check')
|
checkpoint('release_check')
|
||||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
|
||||||
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
|
||||||
if not acquired:
|
|
||||||
return finish('BLOCKED', '已有 CBB 校验/管理/恢复任务运行;本次未启动。')
|
|
||||||
from .library_lock import recheck_previous_release
|
from .library_lock import recheck_previous_release
|
||||||
release_proof = recheck_previous_release(library, root/'previous-release', block_name=request.name,
|
release_proof = recheck_previous_release(library, root/'previous-release', block_name=request.name,
|
||||||
required=request.check_previous_release or bool(unfinished_target
|
required=request.check_previous_release or bool(unfinished_target
|
||||||
and unfinished_target.get('safe_to_continue') is not True), progress=progress)
|
and unfinished_target.get('safe_to_continue') is not True), progress=progress, stop=stop)
|
||||||
if release_proof is not None:
|
if release_proof is not None:
|
||||||
checkpoint('release_check', release_proof=release_proof)
|
checkpoint('release_check', release_proof=release_proof)
|
||||||
if unfinished_target:
|
if unfinished_target:
|
||||||
|
from .session_record import _proof_covers_session
|
||||||
|
fresh = (request.check_previous_release and isinstance(release_proof, dict)
|
||||||
|
and _proof_covers_session(release_proof, {'library': str(library), 'block': request.name})
|
||||||
|
and bool(release_proof.get('evidence_path'))
|
||||||
|
and Path(release_proof['evidence_path']).resolve().is_relative_to((root/'previous-release').resolve())
|
||||||
|
and Path(release_proof['evidence_path']).is_file())
|
||||||
|
if not fresh:
|
||||||
return finish('BLOCKED', f'存在未完成/需恢复任务,禁止自动重放:{unfinished_target["evidence_path"]}')
|
return finish('BLOCKED', f'存在未完成/需恢复任务,禁止自动重放:{unfinished_target["evidence_path"]}')
|
||||||
|
checkpoint('release_check', confirmed_new_request=True,
|
||||||
|
previous_failed_operation=unfinished_target['evidence_path'])
|
||||||
if hasattr(adapter, 'bind_library_mapping'):
|
if hasattr(adapter, 'bind_library_mapping'):
|
||||||
adapter.bind_library_mapping(request.mapped_drive, request.mapped_remote_root)
|
adapter.bind_library_mapping(request.mapped_drive, request.mapped_remote_root)
|
||||||
|
if hasattr(adapter,'bind_write_admission'):
|
||||||
|
adapter.bind_write_admission(write_admission if native_idle_check else None)
|
||||||
|
check_active()
|
||||||
with LibraryLock(library, block_name=request.name, safe_to_release=lambda: owner_safe or (
|
with LibraryLock(library, block_name=request.name, safe_to_release=lambda: owner_safe or (
|
||||||
callable(getattr(adapter, 'release_confirmed', None)) and adapter.release_confirmed(library))):
|
callable(getattr(adapter, 'release_confirmed', None)) and adapter.release_confirmed(library))), ExitStack() as native_stack:
|
||||||
work = library.parent/'ReusableBlocksLP'/request.name/'Work'
|
work = library.parent/'ReusableBlocksLP'/request.name/'Work'
|
||||||
target_project, target_pcb = work/(request.name+'.prj'), work/'PCB/pcb.pcb'
|
target_project, target_pcb = work/(request.name+'.prj'), work/'PCB/pcb.pcb'
|
||||||
if request.operation != 'add':
|
if request.operation != 'add':
|
||||||
@@ -316,7 +338,6 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
|||||||
if source:
|
if source:
|
||||||
idle_check(library, source, pcb)
|
idle_check(library, source, pcb)
|
||||||
checkpoint('catalog_before')
|
checkpoint('catalog_before')
|
||||||
owner_safe = False
|
|
||||||
before = invoke(adapter.catalog, library, root/'before')
|
before = invoke(adapter.catalog, library, root/'before')
|
||||||
owner_safe = before.safe_to_continue
|
owner_safe = before.safe_to_continue
|
||||||
if not owner_safe or Path(before.library).resolve() != canonical_library or before.flow != 1:
|
if not owner_safe or Path(before.library).resolve() != canonical_library or before.flow != 1:
|
||||||
@@ -358,6 +379,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
|||||||
if request.operation in ('remove', 'update'):
|
if request.operation in ('remove', 'update'):
|
||||||
if stop is not None and stop.is_set():
|
if stop is not None and stop.is_set():
|
||||||
return finish('CANCELLED', '已取消,未开始移除', owner_safe)
|
return finish('CANCELLED', '已取消,未开始移除', owner_safe)
|
||||||
|
native_stack.enter_context(native_channel())
|
||||||
checkpoint('native_remove')
|
checkpoint('native_remove')
|
||||||
mutated = True; owner_safe = False
|
mutated = True; owner_safe = False
|
||||||
native = invoke(adapter.remove, request, root/'remove')
|
native = invoke(adapter.remove, request, root/'remove')
|
||||||
@@ -377,6 +399,8 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
|||||||
if stop is not None and stop.is_set():
|
if stop is not None and stop.is_set():
|
||||||
return finish('RECOVERY_REQUIRED' if mutated else 'CANCELLED',
|
return finish('RECOVERY_REQUIRED' if mutated else 'CANCELLED',
|
||||||
'已停止后续导入;已发生的原生变更需要核对', owner_safe)
|
'已停止后续导入;已发生的原生变更需要核对', owner_safe)
|
||||||
|
if not removed:
|
||||||
|
native_stack.enter_context(native_channel())
|
||||||
checkpoint('native_add')
|
checkpoint('native_add')
|
||||||
mutated = True; owner_safe = False
|
mutated = True; owner_safe = False
|
||||||
native = invoke(adapter.add, staged, root/'add')
|
native = invoke(adapter.add, staged, root/'add')
|
||||||
@@ -389,16 +413,25 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
|||||||
owner_safe = after.safe_to_continue
|
owner_safe = after.safe_to_continue
|
||||||
matches = [entry for entry in after.entries if entry.name == request.name
|
matches = [entry for entry in after.entries if entry.name == request.name
|
||||||
and entry.partition == request.partition]
|
and entry.partition == request.partition]
|
||||||
proof_matches = (native.identity_matches is True and native.identity_proof == identity
|
expected_proof, registered_proof = identity, native.identity_proof
|
||||||
|
if isinstance(identity, dict) and identity.get('policy') == 'mentor795-import-assets-v1':
|
||||||
|
expected_proof = {key: value for key, value in identity.items() if key != 'assets'}
|
||||||
|
registered_proof = ({key: value for key, value in registered_proof.items() if key != 'assets'}
|
||||||
|
if isinstance(registered_proof, dict) else None)
|
||||||
|
# Library Manager may name the imported top block after the CBB.
|
||||||
|
if registered_proof is not None and registered_proof.get('top_level_block') == request.name:
|
||||||
|
expected_proof['top_level_block'] = request.name
|
||||||
|
proof_matches = (native.identity_matches is True and registered_proof == expected_proof
|
||||||
if hasattr(adapter, 'prepare_add_transaction') else
|
if hasattr(adapter, 'prepare_add_transaction') else
|
||||||
len(matches) == 1 and matches[0].engineering_identity == identity)
|
len(matches) == 1 and matches[0].engineering_identity == identity)
|
||||||
if (not owner_safe or Path(after.library).resolve() != canonical_library or after.flow != 1
|
if (not owner_safe or Path(after.library).resolve() != canonical_library or after.flow != 1
|
||||||
or len(matches) != 1 or not proof_matches):
|
or len(matches) != 1 or not proof_matches):
|
||||||
return finish('RECOVERY_REQUIRED', '原生新增后名称、分区或来源工程内容未确认一致。', owner_safe)
|
return finish('RECOVERY_REQUIRED', '原生新增后名称、分区或工程关联未确认一致。\n'+native.detail, owner_safe)
|
||||||
uploaded = True
|
uploaded = True
|
||||||
checkpoint('uploaded')
|
checkpoint('uploaded')
|
||||||
|
native_stack.close()
|
||||||
if not request.auto_verify:
|
if not request.auto_verify:
|
||||||
return finish('UPLOADED', '上传已确认;本批次未启用自动校验。')
|
return finish('UPLOADED', '上传已确认;本批次未启用自动校验。\n'+native.detail)
|
||||||
# Adapter catalog cannot return until its exact native owner exits.
|
# Adapter catalog cannot return until its exact native owner exits.
|
||||||
checkpoint('verify')
|
checkpoint('verify')
|
||||||
owner_safe = False
|
owner_safe = False
|
||||||
@@ -410,8 +443,12 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
|||||||
checkpoint('verified', verification=asdict(verified))
|
checkpoint('verified', verification=asdict(verified))
|
||||||
good = verified.status == 'PASS' and verified.library_flag == 'GREEN' and owner_safe
|
good = verified.status == 'PASS' and verified.library_flag == 'GREEN' and owner_safe
|
||||||
return finish('UPLOADED_VERIFIED' if good else 'UPLOADED_VERIFY_FAILED',
|
return finish('UPLOADED_VERIFIED' if good else 'UPLOADED_VERIFY_FAILED',
|
||||||
verified.stderr or verified.library_flag_detail, owner_safe)
|
'\n'.join(filter(None, (native.detail, verified.stderr or verified.library_flag_detail))), owner_safe)
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
|
from .write_admission import WriteAdmissionDeclined
|
||||||
|
if isinstance(error,WriteAdmissionDeclined):
|
||||||
|
return finish('RECOVERY_REQUIRED' if mutated else
|
||||||
|
'CANCELLED' if error.decision=='cancel' else 'SKIPPED',str(error),owner_safe)
|
||||||
if uploaded:
|
if uploaded:
|
||||||
return finish('UPLOADED_VERIFY_FAILED', str(error), owner_safe)
|
return finish('UPLOADED_VERIFY_FAILED', str(error), owner_safe)
|
||||||
status = 'RECOVERY_REQUIRED' if mutated else ('UPLOAD_FAILED' if request.operation in ('add', 'update') else 'BLOCKED')
|
status = 'RECOVERY_REQUIRED' if mutated else ('UPLOAD_FAILED' if request.operation in ('add', 'update') else 'BLOCKED')
|
||||||
@@ -422,45 +459,63 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
|||||||
status = 'BLOCKED'
|
status = 'BLOCKED'
|
||||||
return finish(status, str(error), owner_safe)
|
return finish(status, str(error), owner_safe)
|
||||||
finally:
|
finally:
|
||||||
if mutex is not None:
|
|
||||||
if acquired:
|
|
||||||
win32event.ReleaseMutex(mutex)
|
|
||||||
mutex.Close()
|
|
||||||
uninitialize_com(initialized)
|
uninitialize_com(initialized)
|
||||||
|
|
||||||
|
|
||||||
def run_management_batch(requests, *, stop=None, progress=None, item_executor=None, **kwargs):
|
def run_management_batch(requests, *, stop=None, progress=None, item_executor=None, context=None, **kwargs):
|
||||||
|
from threading import Event
|
||||||
|
from .write_admission import WriteAdmission
|
||||||
|
from .operation_queue import QueueCancelled, TaskHandoff, request_library_keys, remember_result, current_context
|
||||||
|
context = context or current_context()
|
||||||
|
if context is not None:
|
||||||
|
stop = stop if stop is not None else context.stop
|
||||||
|
progress = context.guard_callback(progress) if progress else None
|
||||||
|
if stop is None:
|
||||||
|
stop = Event()
|
||||||
|
kwargs.setdefault('write_admission',WriteAdmission(prompt=kwargs.get('version_prompt'),stop=stop))
|
||||||
results = []
|
results = []
|
||||||
retained_libraries = set()
|
retained_libraries = set()
|
||||||
|
cancelled = False
|
||||||
for request in requests:
|
for request in requests:
|
||||||
if stop is not None and stop.is_set():
|
keys = request_library_keys(request, context)
|
||||||
break
|
stopped = (cancelled or stop.is_set() or context is not None
|
||||||
key = str(request.library).casefold()
|
and (context.stop.is_set() or context.stop_after_current.is_set()))
|
||||||
if key in retained_libraries:
|
if stopped or keys.intersection(retained_libraries):
|
||||||
result = ManagementResult(request.operation, request.library, request.name, request.partition,
|
result = ManagementResult(request.operation, request.library, request.name, request.partition,
|
||||||
request.source, request.auto_verify, 'complete', 'SKIPPED', True,
|
request.source, request.auto_verify, 'complete', 'SKIPPED', True,
|
||||||
'同库原生会话尚未释放,未启动新的写入')
|
'队列已停止,未操作此 CBB' if stopped else '同库原生会话尚未释放,未启动新的写入')
|
||||||
results.append(result)
|
results.append(result)
|
||||||
if progress:
|
if progress:
|
||||||
progress({'stage': result.status, 'block': result.name, 'detail': result.detail})
|
progress({'stage': result.status, 'block': result.name, 'detail': result.detail})
|
||||||
continue
|
continue
|
||||||
def action():
|
def action():
|
||||||
result = run_management(request, progress=progress, stop=stop, **kwargs)
|
result = run_management(request, progress=progress, stop=stop, **kwargs)
|
||||||
|
remember_result(result)
|
||||||
if not result.safe_to_continue:
|
if not result.safe_to_continue:
|
||||||
from .operation_lifecycle import recheck_failed_release
|
from .operation_lifecycle import recheck_failed_release
|
||||||
result = recheck_failed_release(request.library, request.name, result)
|
result = recheck_failed_release(request.library, request.name, result, stop=stop)
|
||||||
return result
|
return result
|
||||||
from .operation_queue import QueueCancelled
|
|
||||||
try:
|
try:
|
||||||
result = item_executor(request, action) if item_executor is not None else action()
|
result = item_executor(request, action) if item_executor is not None else action()
|
||||||
except QueueCancelled as error:
|
except QueueCancelled as error:
|
||||||
results.append(ManagementResult(request.operation, request.library, request.name, request.partition,
|
known = error.result if isinstance(error, TaskHandoff) else None
|
||||||
request.source, request.auto_verify, 'complete', 'CANCELLED', True, str(error)))
|
if isinstance(known, ManagementResult):
|
||||||
break
|
result = replace(known, safe_to_continue=False,
|
||||||
|
status='RECOVERY_REQUIRED' if known.status in ('PASS', 'UPLOADED', 'UPLOADED_VERIFIED', 'REMOVED')
|
||||||
|
else known.status,
|
||||||
|
release_proof=dict(status='RELEASE_PENDING', lease_state='PENDING',
|
||||||
|
resource_scope=error.scope, previous_release_proof=known.release_proof))
|
||||||
|
else:
|
||||||
|
result = ManagementResult(request.operation, request.library, request.name, request.partition,
|
||||||
|
request.source, request.auto_verify, 'complete',
|
||||||
|
'TIMEOUT' if isinstance(error, TaskHandoff) and not error.cancelled else 'CANCELLED',
|
||||||
|
not isinstance(error, TaskHandoff), str(error))
|
||||||
results.append(result)
|
results.append(result)
|
||||||
if progress:
|
if progress:
|
||||||
progress({'stage': result.status, 'block': result.name, 'detail': result.detail,
|
progress({'stage': result.status, 'block': result.name, 'detail': result.detail,
|
||||||
'evidence_path': str(result.evidence_path or '')})
|
'evidence_path': str(result.evidence_path or '')})
|
||||||
if not result.safe_to_continue:
|
if not result.safe_to_continue:
|
||||||
retained_libraries.add(key)
|
retained_libraries.update(keys)
|
||||||
|
if result.status == 'CANCELLED':
|
||||||
|
cancelled = True
|
||||||
return results
|
return results
|
||||||
@@ -25,9 +25,9 @@ def fixture_authority(root, library, token):
|
|||||||
|
|
||||||
|
|
||||||
def current_lease(library):
|
def current_lease(library):
|
||||||
from .library_lock import LibraryLock, _guard, _owners, blocker_path, checkpoint_record
|
from .library_lock import LibraryLock, _library_guard, _owners, blocker_path, checkpoint_record
|
||||||
lease = LibraryLock(library)
|
lease = LibraryLock(library)
|
||||||
with _guard:
|
with _library_guard(lease.key):
|
||||||
owner = _owners.get(lease.key)
|
owner = _owners.get(lease.key)
|
||||||
guard = checkpoint_record(blocker_path(library))
|
guard = checkpoint_record(blocker_path(library))
|
||||||
if (owner is None or owner['retained'] or owner['thread'] != threading.get_ident()
|
if (owner is None or owner['retained'] or owner['thread'] != threading.get_ident()
|
||||||
|
|||||||
@@ -68,6 +68,10 @@ def pcb_startup_timeout_seconds(timeout_seconds):
|
|||||||
return max(60.0, float(timeout_seconds))
|
return max(60.0, float(timeout_seconds))
|
||||||
|
|
||||||
|
|
||||||
|
def lm_dispatch_timeout_seconds(timeout_seconds):
|
||||||
|
return max(.1, min(45.0, float(timeout_seconds)))
|
||||||
|
|
||||||
|
|
||||||
def same_path(first, second):
|
def same_path(first, second):
|
||||||
return os.path.normcase(os.path.abspath(str(first))) == os.path.normcase(os.path.abspath(str(second)))
|
return os.path.normcase(os.path.abspath(str(first))) == os.path.normcase(os.path.abspath(str(second)))
|
||||||
|
|
||||||
@@ -680,6 +684,11 @@ def execute_job(job, emit):
|
|||||||
launcher_process = None
|
launcher_process = None
|
||||||
completed = False
|
completed = False
|
||||||
identity_verified = False
|
identity_verified = False
|
||||||
|
write_admitted = False
|
||||||
|
prewrite_eligible = (job.get('diagnostic_only') is False and not job.get('native_lm_verify')
|
||||||
|
and not job.get('post_repair_consent') and not job.get('interactive_input')
|
||||||
|
and all(job.get(k) for k in ('operation_id','session_record_path','desktop')))
|
||||||
|
startup_binding={k:job.get(k) for k in ('operation_id','project','pcb','desktop')}
|
||||||
diagnostic_close_attempted = False
|
diagnostic_close_attempted = False
|
||||||
helper = None
|
helper = None
|
||||||
app = doc = pi = None
|
app = doc = pi = None
|
||||||
@@ -698,12 +707,15 @@ def execute_job(job, emit):
|
|||||||
from .diagnostic_open import snapshot_diagnostic_logs
|
from .diagnostic_open import snapshot_diagnostic_logs
|
||||||
job['diagnostic_log_baseline'] = snapshot_diagnostic_logs(job)
|
job['diagnostic_log_baseline'] = snapshot_diagnostic_logs(job)
|
||||||
else:
|
else:
|
||||||
ensure_pcb_central_library(
|
from .maintenance_entry import maintenance_project_files
|
||||||
job['pcb'],
|
for index, config in enumerate(maintenance_project_files(job['project'], job['pcb'])):
|
||||||
job['lmc_file'],
|
ensure_project_central_library(config, job['lmc_file'],
|
||||||
evidence_dir=Path(root) / 'diagnostics',
|
evidence_dir=Path(root)/'diagnostics'/f'project-{index}', emit=emit)
|
||||||
emit=emit,
|
if prewrite_eligible:
|
||||||
)
|
from .diagnostic_open import snapshot_diagnostic_logs
|
||||||
|
from .session_record import process_identity
|
||||||
|
emit(stage='startup_prewrite_ready',baseline=snapshot_diagnostic_logs(job),
|
||||||
|
worker_identity=process_identity(os.getpid()),**startup_binding)
|
||||||
emit(
|
emit(
|
||||||
stage='verify_mode',
|
stage='verify_mode',
|
||||||
mode=('library_manager_native' if bool(job.get('native_lm_verify', False))
|
mode=('library_manager_native' if bool(job.get('native_lm_verify', False))
|
||||||
@@ -716,12 +728,13 @@ def execute_job(job, emit):
|
|||||||
pcb_started_ns = time.time_ns()
|
pcb_started_ns = time.time_ns()
|
||||||
if bool(job.get('native_lm_verify', False)):
|
if bool(job.get('native_lm_verify', False)):
|
||||||
from .library_manager_verify import launch_library_verify
|
from .library_manager_verify import launch_library_verify
|
||||||
|
dispatch_deadline = time.monotonic()+lm_dispatch_timeout_seconds(job['timeout'])
|
||||||
emit(stage='lm_launch', library=job['lmc_file'], block=job['block_name'])
|
emit(stage='lm_launch', library=job['lmc_file'], block=job['block_name'])
|
||||||
lm_session = launch_library_verify(
|
lm_session = launch_library_verify(
|
||||||
job['lmc_file'],
|
job['lmc_file'],
|
||||||
job['block_name'],
|
job['block_name'],
|
||||||
emit,
|
emit,
|
||||||
time.monotonic() + pcb_startup_timeout_seconds(job['timeout']),
|
dispatch_deadline,
|
||||||
mentor_bin=job.get('mentor_bin'),
|
mentor_bin=job.get('mentor_bin'),
|
||||||
interactive_input=bool(job.get('interactive_input', False)),
|
interactive_input=bool(job.get('interactive_input', False)),
|
||||||
)
|
)
|
||||||
@@ -737,8 +750,8 @@ def execute_job(job, emit):
|
|||||||
worker_parent_pid = int(launcher_process.pid)
|
worker_parent_pid = int(launcher_process.pid)
|
||||||
emit(stage='pcb_launcher_started', launcher_pid=worker_parent_pid,
|
emit(stage='pcb_launcher_started', launcher_pid=worker_parent_pid,
|
||||||
command=list(command), strategy='reusable_circuit_direct')
|
command=list(command), strategy='reusable_circuit_direct')
|
||||||
pcb_deadline = reset_verify_activity_deadline(
|
pcb_deadline = (dispatch_deadline if job.get('native_lm_verify') else
|
||||||
0.0, time.monotonic(), timeout_seconds=pcb_startup_timeout_seconds(job['timeout']))
|
time.monotonic()+pcb_startup_timeout_seconds(job['timeout']))
|
||||||
while time.monotonic() < pcb_deadline:
|
while time.monotonic() < pcb_deadline:
|
||||||
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
|
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
|
||||||
raise RuntimeError('VERIFY_CANCELLED: PCB 启动期间收到停止请求')
|
raise RuntimeError('VERIFY_CANCELLED: PCB 启动期间收到停止请求')
|
||||||
@@ -771,6 +784,8 @@ def execute_job(job, emit):
|
|||||||
break
|
break
|
||||||
time.sleep(.2)
|
time.sleep(.2)
|
||||||
if worker_pid is None:
|
if worker_pid is None:
|
||||||
|
if job.get('native_lm_verify'):
|
||||||
|
raise RuntimeError('VERIFY_DISPATCH_FAILED: LM 菜单返回但未观察到目标 PCB,未执行校验')
|
||||||
raise RuntimeError('ReusableCircuit common 启动后未观察到 wg PCB 子进程')
|
raise RuntimeError('ReusableCircuit common 启动后未观察到 wg PCB 子进程')
|
||||||
if job.get('diagnostic_only'):
|
if job.get('diagnostic_only'):
|
||||||
# Global PCB COM can wait on another design's modal window.
|
# Global PCB COM can wait on another design's modal window.
|
||||||
@@ -805,6 +820,10 @@ def execute_job(job, emit):
|
|||||||
# the old, working path acquires the token inside the SysWOW64
|
# the old, working path acquires the token inside the SysWOW64
|
||||||
# cscript save helper below. The PCB UI license dialog has already
|
# cscript save helper below. The PCB UI license dialog has already
|
||||||
# been handled by the private-desktop supervisor.
|
# been handled by the private-desktop supervisor.
|
||||||
|
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
|
||||||
|
raise RuntimeError('VERIFY_CANCELLED: 未开始工程集成')
|
||||||
|
write_admitted = True
|
||||||
|
if prewrite_eligible:emit(stage='startup_write_admitted',**startup_binding)
|
||||||
refresh_integration(
|
refresh_integration(
|
||||||
pi,
|
pi,
|
||||||
emit=emit,
|
emit=emit,
|
||||||
@@ -910,6 +929,10 @@ def execute_job(job, emit):
|
|||||||
elif not completed and worker_pid is not None:
|
elif not completed and worker_pid is not None:
|
||||||
try:
|
try:
|
||||||
from .failed_session import close_failed_startup
|
from .failed_session import close_failed_startup
|
||||||
|
if (prewrite_eligible and not write_admitted and not identity_verified
|
||||||
|
and job.get('cancel_signal') and Path(job['cancel_signal']).exists()):
|
||||||
|
emit(stage='startup_cancelled_prewrite',pcb_pid=worker_pid,
|
||||||
|
identity_verified=False,write_admitted=False,**startup_binding)
|
||||||
failed_close = close_failed_startup(job, worker_pid, baseline_pids=pcb_before, emit=emit,
|
failed_close = close_failed_startup(job, worker_pid, baseline_pids=pcb_before, emit=emit,
|
||||||
launcher_process=launcher_process)
|
launcher_process=launcher_process)
|
||||||
if failed_close.get('status') == 'CLOSED' and lm_session is not None:
|
if failed_close.get('status') == 'CLOSED' and lm_session is not None:
|
||||||
@@ -926,6 +949,8 @@ def execute_job(job, emit):
|
|||||||
)
|
)
|
||||||
if completed and lm_session is not None:
|
if completed and lm_session is not None:
|
||||||
lm_session.close()
|
lm_session.close()
|
||||||
|
elif worker_pid is None and lm_session is not None:
|
||||||
|
lm_session.close() # No PCB was dispatched; close only this owned LM.
|
||||||
|
|
||||||
|
|
||||||
def cleanup_verify_processes(lm_pid, worker_pid, worker_parent_pid=None, *,
|
def cleanup_verify_processes(lm_pid, worker_pid, worker_parent_pid=None, *,
|
||||||
|
|||||||
@@ -7,8 +7,15 @@ class CbbRecord:
|
|||||||
partition_name: str
|
partition_name: str
|
||||||
logical_type: str = "LP"
|
logical_type: str = "LP"
|
||||||
status: str = "UNKNOWN"
|
status: str = "UNKNOWN"
|
||||||
|
catalog_source: str = "provided"
|
||||||
|
status_source: str = "provided"
|
||||||
|
missing_reason: str = ""
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
class LibraryReadResult:
|
class LibraryReadResult:
|
||||||
records: tuple[CbbRecord, ...]
|
records: tuple[CbbRecord, ...]
|
||||||
error: str | None = None
|
error: str | None = None
|
||||||
|
directory_count: int | None = None
|
||||||
|
native_count: int | None = None
|
||||||
|
missing_project_count: int | None = None
|
||||||
|
catalog_verified: bool = False
|
||||||
@@ -1,7 +1,11 @@
|
|||||||
"""Open the official backup UI; version selection and writes stay native."""
|
"""Open the official backup UI; version selection and writes stay native."""
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
import json
|
import json
|
||||||
|
import hashlib
|
||||||
|
import os
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from pathlib import PureWindowsPath
|
||||||
|
import re
|
||||||
import stat
|
import stat
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
@@ -39,6 +43,36 @@ def native_backup_project(library, block):
|
|||||||
return project
|
return project
|
||||||
|
|
||||||
|
|
||||||
|
def native_backup_target(request, *, mode='versions', target_database=None):
|
||||||
|
"""Bind the official tool without requiring an openable/healthy PCB."""
|
||||||
|
from .backup_recovery import _project_text
|
||||||
|
from .maintenance_entry import maintenance_project_files
|
||||||
|
if mode not in ('versions', 'repair'):
|
||||||
|
raise ValueError('NATIVE_TARGET_MODE_INVALID')
|
||||||
|
project = native_backup_project(request.lmc_file, request.block_name)
|
||||||
|
candidates = (project,)
|
||||||
|
if target_database is not None:
|
||||||
|
pcbs = list((project.parent/'PCB').glob('*.pcb'))
|
||||||
|
if len(pcbs) != 1:
|
||||||
|
raise ValueError('NATIVE_TARGET_UNCONFIRMED: 无法唯一绑定 PCB 工程')
|
||||||
|
candidates = maintenance_project_files(project, pcbs[0])
|
||||||
|
matches = []
|
||||||
|
for config in candidates:
|
||||||
|
values = re.findall(r'^KEY iCDBDir "([^"\r\n]+)"\s*$', _project_text(config), re.M)
|
||||||
|
if len(values) != 1 or not values[0] or PureWindowsPath(values[0]).root or PureWindowsPath(values[0]).drive:
|
||||||
|
if config == project or target_database is None:
|
||||||
|
raise ValueError('NATIVE_TARGET_UNCONFIRMED: 主 PRJ 的 iCDBDir 必须唯一且为工程内相对路径,不支持绝对路径或多条记录')
|
||||||
|
continue
|
||||||
|
database = (config.parent/values[0]).resolve()
|
||||||
|
if not database.is_relative_to(project.parent.resolve()):
|
||||||
|
raise ValueError('NATIVE_TARGET_UNCONFIRMED: 数据库不在当前工程内')
|
||||||
|
if target_database is None or database == Path(target_database).resolve():
|
||||||
|
matches.append((config, database))
|
||||||
|
if len(matches) != 1:
|
||||||
|
raise ValueError('NATIVE_TARGET_UNCONFIRMED: 诊断数据库未绑定唯一工程 PRJ')
|
||||||
|
return matches[0]
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class NativeBackupSession:
|
class NativeBackupSession:
|
||||||
process: object
|
process: object
|
||||||
@@ -46,10 +80,18 @@ class NativeBackupSession:
|
|||||||
library: Path
|
library: Path
|
||||||
block: str
|
block: str
|
||||||
path_lease: object = None
|
path_lease: object = None
|
||||||
|
mode: str = 'versions'
|
||||||
|
project: Path | None = None
|
||||||
|
database: Path | None = None
|
||||||
|
session_record_path: Path | None = None
|
||||||
|
operation_id: str | None = None
|
||||||
|
|
||||||
|
|
||||||
def launch_native_backup(request):
|
def launch_native_backup(request, *, mode='versions', target_database=None):
|
||||||
project = native_backup_project(request.lmc_file, request.block_name)
|
from .library_lock import recheck_previous_release
|
||||||
|
from .session_record import register_worker_session
|
||||||
|
from .operation_queue import check_active, native_channel, task_stop, commit_worker_start
|
||||||
|
project, database = native_backup_target(request, mode=mode, target_database=target_database)
|
||||||
native_backup_executable(request.mentor_bin)
|
native_backup_executable(request.mentor_bin)
|
||||||
root = Path(request.evidence_dir).resolve()/('native-backup-'+uuid4().hex[:12])
|
root = Path(request.evidence_dir).resolve()/('native-backup-'+uuid4().hex[:12])
|
||||||
library_root = Path(request.lmc_file).resolve().parent
|
library_root = Path(request.lmc_file).resolve().parent
|
||||||
@@ -57,17 +99,55 @@ def launch_native_backup(request):
|
|||||||
raise ValueError('运行记录目录需位于中心库之外。')
|
raise ValueError('运行记录目录需位于中心库之外。')
|
||||||
root.mkdir(parents=True)
|
root.mkdir(parents=True)
|
||||||
job = root/'request.json'
|
job = root/'request.json'
|
||||||
job.write_text(json.dumps({'library': str(request.lmc_file), 'block': request.block_name,
|
recheck_previous_release(request.lmc_file, root/'previous-release',
|
||||||
'project': str(project), 'mentor_bin': request.mentor_bin}, ensure_ascii=False), 'utf-8')
|
block_name=request.block_name, stop=task_stop(None))
|
||||||
|
record = {'library': str(request.lmc_file), 'block': request.block_name,
|
||||||
|
'project': str(project), 'database': str(database), 'mode': mode,
|
||||||
|
'project_sha256': hashlib.sha256(project.read_bytes()).hexdigest(),
|
||||||
|
'target_database': str(target_database) if target_database is not None else None,
|
||||||
|
'mentor_bin': request.mentor_bin, 'automatic_repair': False,
|
||||||
|
'operation': 'native_backup', 'operation_id': root.name,
|
||||||
|
'session_record_path': str(root/'session.json'), 'start_gate': str(root/'start-worker.signal'),
|
||||||
|
'start_gate_protocol': 'event-v1',
|
||||||
|
'cancel_signal': str(root/'cancel-worker.signal'), 'supervisor_pid': os.getpid(), 'desktop': None}
|
||||||
|
job.write_text(json.dumps(record, ensure_ascii=False), 'utf-8')
|
||||||
command = ([sys.executable] if getattr(sys, 'frozen', False) else
|
command = ([sys.executable] if getattr(sys, 'frozen', False) else
|
||||||
[sys.executable, '-m', 'cbb_refresh_verify'])+['--native-backup-worker', str(job)]
|
[sys.executable, '-m', 'cbb_refresh_verify'])+['--native-backup-worker', str(job)]
|
||||||
|
try:
|
||||||
|
check_active()
|
||||||
process = subprocess.Popen(command, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
process = subprocess.Popen(command, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
||||||
return NativeBackupSession(process, job, Path(request.lmc_file), request.block_name)
|
register_worker_session(process, record)
|
||||||
|
with native_channel():
|
||||||
|
check_active()
|
||||||
|
commit_worker_start(process, record)
|
||||||
|
except BaseException:
|
||||||
|
Path(record['cancel_signal']).touch() # The unadmitted child exits without native launch.
|
||||||
|
raise
|
||||||
|
return NativeBackupSession(process, job, Path(request.lmc_file), request.block_name,
|
||||||
|
mode=mode, project=project, database=database, session_record_path=Path(record['session_record_path']),
|
||||||
|
operation_id=record['operation_id'])
|
||||||
|
|
||||||
|
|
||||||
|
class _BackupJobWriter:
|
||||||
|
"""Independent Job handle keeps future descendants inside the writer boundary."""
|
||||||
|
def __init__(self, job):
|
||||||
|
import win32api, win32con
|
||||||
|
current = win32api.GetCurrentProcess()
|
||||||
|
self.job = win32api.DuplicateHandle(current, job, current, 0, False, win32con.DUPLICATE_SAME_ACCESS)
|
||||||
|
|
||||||
|
def poll(self):
|
||||||
|
import win32job
|
||||||
|
if self.job is None:
|
||||||
|
return 0
|
||||||
|
if win32job.QueryInformationJobObject(self.job, win32job.JobObjectBasicProcessIdList):
|
||||||
|
return None
|
||||||
|
self.job.Close(); self.job = None
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
class _NativeBackupProcess:
|
class _NativeBackupProcess:
|
||||||
"""Track this visible tool and its descendants without killing on close."""
|
"""Track this visible tool and its descendants without killing on close."""
|
||||||
def __init__(self, command, cwd):
|
def __init__(self, command, cwd, *, before_resume=None):
|
||||||
import win32con, win32job, win32process
|
import win32con, win32job, win32process
|
||||||
self.job = win32job.CreateJobObject(None, '')
|
self.job = win32job.CreateJobObject(None, '')
|
||||||
startup = win32process.STARTUPINFO()
|
startup = win32process.STARTUPINFO()
|
||||||
@@ -80,6 +160,8 @@ class _NativeBackupProcess:
|
|||||||
raise
|
raise
|
||||||
try:
|
try:
|
||||||
win32job.AssignProcessToJobObject(self.job, self.handle)
|
win32job.AssignProcessToJobObject(self.job, self.handle)
|
||||||
|
if before_resume is not None:
|
||||||
|
before_resume(self)
|
||||||
win32process.ResumeThread(thread)
|
win32process.ResumeThread(thread)
|
||||||
except Exception:
|
except Exception:
|
||||||
# No native code has run while suspended; there can be no DB write.
|
# No native code has run while suspended; there can be no DB write.
|
||||||
@@ -102,11 +184,54 @@ class _NativeBackupProcess:
|
|||||||
self.handle.Close(); self.job.Close()
|
self.handle.Close(); self.job.Close()
|
||||||
|
|
||||||
|
|
||||||
|
def run_native_backup_worker(job, *, admission_state=None):
|
||||||
|
"""Publish admission refusal only when this exact worker never entered native work."""
|
||||||
|
from .desktop_worker import run_native_worker
|
||||||
|
from .management import _write_json
|
||||||
|
from .session_record import IDENTITY_KEYS, process_identity, read_session_record
|
||||||
|
job = Path(job)
|
||||||
|
entered = False
|
||||||
|
request = json.loads(job.read_text('utf-8'))
|
||||||
|
identity = process_identity(os.getpid())
|
||||||
|
def registered():
|
||||||
|
try:
|
||||||
|
path = Path(request['session_record_path'])
|
||||||
|
session = read_session_record(path, evidence_root=job.parent)
|
||||||
|
return (session['operation_id'] == request['operation_id']
|
||||||
|
and session.get('operation') == 'native_backup'
|
||||||
|
and session.get('library') == request['library'] and session.get('block') == request['block']
|
||||||
|
and request.get('project') in session.get('resource_scope', {}).get('projects', ())
|
||||||
|
and any(all(process.get(key) == identity[key] for key in IDENTITY_KEYS)
|
||||||
|
for process in session.get('processes', ()) if process.get('role') == 'worker'))
|
||||||
|
except (OSError, ValueError, KeyError, TypeError):
|
||||||
|
return False # Unknown registration never establishes a safe terminal result.
|
||||||
|
def execute(path):
|
||||||
|
nonlocal entered
|
||||||
|
if not registered():
|
||||||
|
raise ValueError('NATIVE_BACKUP_ADMISSION_UNCONFIRMED: 当前工程与工作进程未登记')
|
||||||
|
entered = True
|
||||||
|
return native_backup_worker_main(path)
|
||||||
|
try:
|
||||||
|
return run_native_worker(execute, job, admission_state=admission_state)
|
||||||
|
except Exception as error:
|
||||||
|
bound = registered()
|
||||||
|
_write_json(job.with_name('result.json'), {'status': 'FAILED', 'detail': str(error),
|
||||||
|
'operation_id': request.get('operation_id'), 'worker_identity': identity,
|
||||||
|
'library': request.get('library'), 'block': request.get('block'),
|
||||||
|
'mode': request.get('mode', 'versions'), 'project': request.get('project'),
|
||||||
|
'database': request.get('database'), 'worker_entered': entered,
|
||||||
|
'native_started': None if entered else False,
|
||||||
|
'safe_to_continue': bound and not entered, 'restore_confirmed': False,
|
||||||
|
'repair_confirmed': False, 'validation_passed': False, 'automatic_repair': False})
|
||||||
|
return 1
|
||||||
|
|
||||||
|
|
||||||
def native_backup_worker_main(job, *, process_factory=None):
|
def native_backup_worker_main(job, *, process_factory=None):
|
||||||
from .library_lock import LibraryLock
|
from .library_lock import LibraryLock
|
||||||
from .management import _write_json
|
from .management import _write_json
|
||||||
job = Path(job)
|
job = Path(job)
|
||||||
result = {'status': 'FAILED', 'safe_to_continue': True, 'restore_confirmed': False}
|
result = {'status': 'FAILED', 'safe_to_continue': True, 'restore_confirmed': False,
|
||||||
|
'repair_confirmed': False, 'validation_passed': False, 'automatic_repair': False}
|
||||||
native = None
|
native = None
|
||||||
def write_evidence(name, value):
|
def write_evidence(name, value):
|
||||||
try:
|
try:
|
||||||
@@ -117,14 +242,34 @@ def native_backup_worker_main(job, *, process_factory=None):
|
|||||||
try:
|
try:
|
||||||
record = json.loads(job.read_text('utf-8'))
|
record = json.loads(job.read_text('utf-8'))
|
||||||
library, block = Path(record['library']), record['block']
|
library, block = Path(record['library']), record['block']
|
||||||
result.update(library=str(library), block=block)
|
result.update(library=str(library), block=block, operation_id=record.get('operation_id'))
|
||||||
project = native_backup_project(library, block)
|
from types import SimpleNamespace
|
||||||
|
mode = record.get('mode', 'versions')
|
||||||
|
project, database = native_backup_target(SimpleNamespace(lmc_file=library, block_name=block),
|
||||||
|
mode=mode, target_database=record.get('target_database'))
|
||||||
if project != Path(record['project']):
|
if project != Path(record['project']):
|
||||||
raise ValueError('工程身份已变化,未打开原生工具。')
|
raise ValueError('工程身份已变化,未打开原生工具。')
|
||||||
|
if record.get('project_sha256') and hashlib.sha256(project.read_bytes()).hexdigest() != record['project_sha256']:
|
||||||
|
raise ValueError('工程内容身份已变化,未打开原生工具。')
|
||||||
|
if record.get('database') and database != Path(record['database']):
|
||||||
|
raise ValueError('数据库身份已变化,未打开原生工具。')
|
||||||
|
result.update(mode=mode, project=str(project), database=str(database),
|
||||||
|
session_record_path=record.get('session_record_path'))
|
||||||
executable = native_backup_executable(record.get('mentor_bin', ''))
|
executable = native_backup_executable(record.get('mentor_bin', ''))
|
||||||
released = True
|
released = True
|
||||||
with LibraryLock(library, checkpoint=False, safe_to_release=lambda: released):
|
with LibraryLock(library, checkpoint=bool(record.get('session_record_path')),
|
||||||
native = (process_factory or _NativeBackupProcess)([str(executable), '-p', str(project)], project.parent)
|
block_name=block, safe_to_release=lambda: released):
|
||||||
|
from .maintenance_entry import _assert_native_idle_for
|
||||||
|
_assert_native_idle_for(SimpleNamespace(project=project, database=database, library=library))
|
||||||
|
def admitted(process):
|
||||||
|
from .session_record import update_worker_state
|
||||||
|
from .desktop_worker import register_native_writer
|
||||||
|
if record.get('session_record_path'):
|
||||||
|
update_worker_state(record, 'NATIVE_CALL', identities=(('native', process.pid),), required=True)
|
||||||
|
register_native_writer(_BackupJobWriter(process.job))
|
||||||
|
command = [str(executable), '-p', str(project)] # User alone invokes Repair in the official UI.
|
||||||
|
native = (process_factory(command, project.parent) if process_factory else
|
||||||
|
_NativeBackupProcess(command, project.parent, before_resume=admitted))
|
||||||
released = False
|
released = False
|
||||||
result.update(status='OPEN', native_pid=native.pid, project=str(project), safe_to_continue=False)
|
result.update(status='OPEN', native_pid=native.pid, project=str(project), safe_to_continue=False)
|
||||||
write_evidence('state.json', result)
|
write_evidence('state.json', result)
|
||||||
@@ -145,6 +290,7 @@ def native_backup_worker_main(job, *, process_factory=None):
|
|||||||
time.sleep(.25)
|
time.sleep(.25)
|
||||||
released = True
|
released = True
|
||||||
result.update(status='CLOSED', native_exit_code=exit_code, safe_to_continue=True)
|
result.update(status='CLOSED', native_exit_code=exit_code, safe_to_continue=True)
|
||||||
|
result['release'] = {'native_exited': True, 'remaining_pids': [], 'safe_to_continue': True}
|
||||||
return 0 if result['native_exit_code'] == 0 else 1
|
return 0 if result['native_exit_code'] == 0 else 1
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
result.update(status='FAILED', detail=str(error), safe_to_continue=native is None)
|
result.update(status='FAILED', detail=str(error), safe_to_continue=native is None)
|
||||||
|
|||||||
@@ -191,17 +191,21 @@ def _normalized_project(path, expected_library):
|
|||||||
data = path.read_bytes(); encoding = _project_encoding(data)
|
data = path.read_bytes(); encoding = _project_encoding(data)
|
||||||
text = data.decode(encoding)
|
text = data.decode(encoding)
|
||||||
refs = re.findall(r'^KEY CentralLibrary "([^"\r\n]*)"', text, re.M)
|
refs = re.findall(r'^KEY CentralLibrary "([^"\r\n]*)"', text, re.M)
|
||||||
if not refs or any((path.parent/value).resolve() != expected_library.resolve() for value in refs):
|
if (not refs or any(not value.strip() for value in refs)
|
||||||
|
or expected_library is not None and any(
|
||||||
|
(path.parent/value).resolve() != expected_library.resolve() for value in refs)):
|
||||||
raise ValueError(f'CentralLibrary reference does not resolve to the approved library: {path}')
|
raise ValueError(f'CentralLibrary reference does not resolve to the approved library: {path}')
|
||||||
return re.sub(r'(?m)^(KEY CentralLibrary ")[^"\r\n]*(")',
|
return re.sub(r'(?m)^(KEY CentralLibrary ")[^"\r\n]*(")',
|
||||||
r'\1<CENTRAL_LIBRARY>\2', text).encode(encoding)
|
r'\1<CENTRAL_LIBRARY>\2', text).encode(encoding)
|
||||||
|
|
||||||
|
|
||||||
def asset_identity(source, expected_library):
|
def asset_identity(source, expected_library):
|
||||||
|
"""Normalize old library paths when None; imported projects require the exact target."""
|
||||||
from .backup_recovery import _project_text
|
from .backup_recovery import _project_text
|
||||||
source, pcb, top = source_project(source)
|
source, pcb, top = source_project(source)
|
||||||
expected_library = Path(expected_library)
|
expected_library = Path(expected_library) if expected_library is not None else None
|
||||||
if not expected_library.is_file(): raise ValueError('Approved CentralLibrary is missing.')
|
if expected_library is not None and not expected_library.is_file():
|
||||||
|
raise ValueError('Approved CentralLibrary is missing.')
|
||||||
root = source.parent
|
root = source.parent
|
||||||
from .maintenance_entry import maintenance_project_files
|
from .maintenance_entry import maintenance_project_files
|
||||||
projects = maintenance_project_files(source, pcb)
|
projects = maintenance_project_files(source, pcb)
|
||||||
@@ -236,6 +240,22 @@ def asset_identity(source, expected_library):
|
|||||||
'layout_sha256': hash_file(pcb.parent/'Layout/LayoutDB.lyt'), 'assets': assets}
|
'layout_sha256': hash_file(pcb.parent/'Layout/LayoutDB.lyt'), 'assets': assets}
|
||||||
|
|
||||||
|
|
||||||
|
def capture_registration_identity(source, evidence_root, *, expected_library):
|
||||||
|
"""File-only import evidence; native database normalization is not semantic proof."""
|
||||||
|
root = Path(evidence_root)
|
||||||
|
try:
|
||||||
|
root.mkdir(parents=True, exist_ok=False)
|
||||||
|
identity = {**asset_identity(source, expected_library),
|
||||||
|
'policy': 'mentor795-import-assets-v1',
|
||||||
|
'coverage': {'primary_assets_checked': True,
|
||||||
|
'schematic_semantics_checked': False}}
|
||||||
|
_write_json(root/'identity.json', {'identity': identity, 'safe_to_continue': True})
|
||||||
|
return IdentityOutcome(identity, True, 'Engineering files and project references checked; no native export.', root)
|
||||||
|
except Exception as error:
|
||||||
|
# No native session was acquired; the caller retains its own release proof.
|
||||||
|
return IdentityOutcome(None, True, str(error), root)
|
||||||
|
|
||||||
|
|
||||||
def check_exporters(mentor_home):
|
def check_exporters(mentor_home):
|
||||||
for name, expected in EXPORTER_PROOF.items():
|
for name, expected in EXPORTER_PROOF.items():
|
||||||
path = Path(mentor_home)/('wv/win32/bin' if name == 'edifExporter.exe' else 'iCDB/win32/bin')/name
|
path = Path(mentor_home)/('wv/win32/bin' if name == 'edifExporter.exe' else 'iCDB/win32/bin')/name
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ from uuid import uuid4
|
|||||||
from .management import _write_json
|
from .management import _write_json
|
||||||
|
|
||||||
|
|
||||||
def _preexisting_export_pids(record):
|
def _preexisting_export_pids(record, snapshot=None, *, project_root=None):
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from .native_engineering_identity import _process_birth
|
from .native_engineering_identity import _process_birth
|
||||||
identities = record.get('process_identities', [])
|
identities = record.get('process_identities', [])
|
||||||
@@ -16,9 +16,28 @@ def _preexisting_export_pids(record):
|
|||||||
birth = _process_birth(record.get('root_created') or root.get('created'))
|
birth = _process_birth(record.get('root_created') or root.get('created'))
|
||||||
if not isinstance(birth, datetime):
|
if not isinstance(birth, datetime):
|
||||||
return set()
|
return set()
|
||||||
return {p['pid'] for p in identities if p.get('pid') != record.get('pid')
|
earlier = [p for p in identities if p.get('pid') != record.get('pid')
|
||||||
and isinstance(_process_birth(p.get('created')), datetime)
|
and isinstance(_process_birth(p.get('created')), datetime)
|
||||||
and _process_birth(p['created']) < birth}
|
and _process_birth(p['created']) < birth]
|
||||||
|
if not earlier:return set()
|
||||||
|
from .native_engineering_identity import _process_snapshot,_OWNER_NAMES
|
||||||
|
from .backup_recovery import _native_scope_match
|
||||||
|
import ntpath
|
||||||
|
current={p['pid']:p for p in (_process_snapshot() if snapshot is None else snapshot)}
|
||||||
|
native_names=_OWNER_NAMES|{'viewdraw.exe','expeditionpcb.exe','librarymanager.exe',
|
||||||
|
'icdbprojectbackup.exe','reuseblockimporter.exe'}
|
||||||
|
excluded=set()
|
||||||
|
for recorded in earlier:
|
||||||
|
actual=current.get(recorded['pid'])
|
||||||
|
if (actual is None or _process_birth(actual.get('created'))!=_process_birth(recorded['created'])
|
||||||
|
or not recorded.get('executable') or not actual.get('executable')
|
||||||
|
or ntpath.normcase(actual['executable'])!=ntpath.normcase(recorded['executable'])):
|
||||||
|
continue
|
||||||
|
match=_native_scope_match(actual.get('command',''),roots=(project_root,)) if project_root is not None else None
|
||||||
|
if match is True or match is None and actual.get('name','').casefold() in native_names:
|
||||||
|
continue
|
||||||
|
excluded.add(recorded['pid'])
|
||||||
|
return excluded
|
||||||
|
|
||||||
|
|
||||||
def assert_retained_exports_idle(library=None):
|
def assert_retained_exports_idle(library=None):
|
||||||
@@ -44,7 +63,7 @@ def assert_retained_exports_idle(library=None):
|
|||||||
raise ValueError('Export process evidence must be a JSON object')
|
raise ValueError('Export process evidence must be a JSON object')
|
||||||
if record.get('pid') == process.pid:
|
if record.get('pid') == process.pid:
|
||||||
matched = True
|
matched = True
|
||||||
excluded.update(_preexisting_export_pids(record))
|
excluded.update(_preexisting_export_pids(record,project_root=Path(scope['analysis_root'])/'project'))
|
||||||
if not matched:
|
if not matched:
|
||||||
raise ValueError(f'No process evidence matches exporter PID {process.pid}')
|
raise ValueError(f'No process evidence matches exporter PID {process.pid}')
|
||||||
except (OSError, ValueError, KeyError, TypeError) as error:
|
except (OSError, ValueError, KeyError, TypeError) as error:
|
||||||
@@ -60,7 +79,7 @@ def assert_retained_exports_idle(library=None):
|
|||||||
|
|
||||||
|
|
||||||
def begin_export_analysis(library, root, project):
|
def begin_export_analysis(library, root, project):
|
||||||
from .library_lock import _guard, blocker_path, checkpoint_record, LibraryBusy
|
from .library_lock import LibraryLock, _library_guard, blocker_path, checkpoint_record, LibraryBusy
|
||||||
from .management_transaction import current_lease
|
from .management_transaction import current_lease
|
||||||
library, root, project = Path(library).resolve(), Path(root).resolve(), Path(project).resolve()
|
library, root, project = Path(library).resolve(), Path(root).resolve(), Path(project).resolve()
|
||||||
owner = current_lease(library)
|
owner = current_lease(library)
|
||||||
@@ -70,7 +89,7 @@ def begin_export_analysis(library, root, project):
|
|||||||
record = {'protocol': 'cbb-native-export-analysis', 'version': 1, 'token': uuid4().hex,
|
record = {'protocol': 'cbb-native-export-analysis', 'version': 1, 'token': uuid4().hex,
|
||||||
'library': str(library), 'lease_id': owner['lease_id'], 'supervisor_pid': owner['supervisor_pid'],
|
'library': str(library), 'lease_id': owner['lease_id'], 'supervisor_pid': owner['supervisor_pid'],
|
||||||
'analysis_root': str(root), 'project': str(project)}
|
'analysis_root': str(root), 'project': str(project)}
|
||||||
with _guard:
|
with _library_guard(LibraryLock(library).key):
|
||||||
marker = blocker_path(library)
|
marker = blocker_path(library)
|
||||||
checkpoint = checkpoint_record(marker)
|
checkpoint = checkpoint_record(marker)
|
||||||
if (checkpoint is None or checkpoint['lease_id'] != owner['lease_id']
|
if (checkpoint is None or checkpoint['lease_id'] != owner['lease_id']
|
||||||
@@ -81,6 +100,77 @@ def begin_export_analysis(library, root, project):
|
|||||||
return record['token']
|
return record['token']
|
||||||
|
|
||||||
|
|
||||||
|
def _external_export_library(process):
|
||||||
|
"""Recover a live copy's owner; an outside path alone proves no association."""
|
||||||
|
import ntpath
|
||||||
|
import re
|
||||||
|
import stat
|
||||||
|
import subprocess
|
||||||
|
from .failed_session import _command_args
|
||||||
|
from .backup_recovery import _native_scope_match
|
||||||
|
from .native_engineering_identity import _process_birth
|
||||||
|
def read(path):
|
||||||
|
info = path.lstat()
|
||||||
|
if info.st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT or info.st_size > 1024*1024:
|
||||||
|
raise ValueError('Untrusted export association')
|
||||||
|
value = json.loads(path.read_text('utf-8'))
|
||||||
|
if not isinstance(value, dict):
|
||||||
|
raise ValueError('Invalid export association')
|
||||||
|
return value
|
||||||
|
try:
|
||||||
|
birth = _process_birth(process.get('created'))
|
||||||
|
image = process.get('executable')
|
||||||
|
if birth is None or not image or ntpath.basename(image).casefold() != process['name'].casefold():
|
||||||
|
return None
|
||||||
|
candidates = []
|
||||||
|
for arg in _command_args(process.get('command', ''))[1:]:
|
||||||
|
path = Path(arg.split('=', 1)[-1])
|
||||||
|
if path.is_absolute() and (path.suffix.casefold() in ('.prj', '.pcb')
|
||||||
|
or path.name.casefold() in ('database', 'icdb.dat')):
|
||||||
|
candidates.append(path)
|
||||||
|
associations = set()
|
||||||
|
for path in candidates:
|
||||||
|
project_root = next((p for p in (path, *path.parents) if p.name.casefold() == 'project'), None)
|
||||||
|
if project_root is None or project_root.resolve() != project_root:
|
||||||
|
return None
|
||||||
|
root = project_root.parent
|
||||||
|
owner = read(root/'export-owner.json')
|
||||||
|
project, library = Path(owner['project']), Path(owner['library'])
|
||||||
|
if (owner.get('protocol') != 'cbb-native-export-analysis' or owner.get('version') != 1
|
||||||
|
or not re.fullmatch('[0-9a-f]{32}', str(owner.get('token', '')))
|
||||||
|
or not re.fullmatch('[0-9a-f]{32}', str(owner.get('lease_id', '')))
|
||||||
|
or type(owner.get('supervisor_pid')) is not int or owner['supervisor_pid'] <= 0
|
||||||
|
or Path(owner['analysis_root']) != root or project.parent != project_root
|
||||||
|
or project.suffix.casefold() != '.prj' or not project.is_file()
|
||||||
|
or not library.is_absolute() or library.suffix.casefold() != '.lmc' or not library.is_file()
|
||||||
|
or root.is_relative_to(library.parent) or library.parent.is_relative_to(root)
|
||||||
|
or _native_scope_match(process['command'], roots=(project_root,)) is not True):
|
||||||
|
return None
|
||||||
|
matched = False
|
||||||
|
for kind, executable in (('ascii', 'icdb2ascii.exe'), ('csv', 'icdb2csv.exe'), ('edif', 'edifexporter.exe')):
|
||||||
|
evidence = root/(kind+'-process.json')
|
||||||
|
if not evidence.exists():
|
||||||
|
continue
|
||||||
|
recorded = read(evidence)
|
||||||
|
command = recorded.get('command')
|
||||||
|
if (recorded.get('native_started') is not True or recorded.get('kind') != kind
|
||||||
|
or not isinstance(command, list) or not command or not all(isinstance(v, str) for v in command)
|
||||||
|
or ntpath.basename(command[0]).casefold() != executable
|
||||||
|
or _native_scope_match(subprocess.list2cmdline(command), roots=(project_root,)) is not True):
|
||||||
|
continue
|
||||||
|
for identity in recorded.get('process_identities', []):
|
||||||
|
if (identity.get('pid') == process['pid'] and _process_birth(identity.get('created')) == birth
|
||||||
|
and identity.get('executable')
|
||||||
|
and ntpath.normcase(identity['executable']) == ntpath.normcase(image)):
|
||||||
|
matched = True
|
||||||
|
if not matched:
|
||||||
|
return None
|
||||||
|
associations.add(library.resolve())
|
||||||
|
return next(iter(associations)) if len(associations) == 1 else None
|
||||||
|
except (OSError, ValueError, KeyError, TypeError, AttributeError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
@contextmanager
|
@contextmanager
|
||||||
def prove_export_copies_released(library, *, allow_unknown_checkpoint=False, unstarted_token=''):
|
def prove_export_copies_released(library, *, allow_unknown_checkpoint=False, unstarted_token=''):
|
||||||
"""Fresh process and exclusive-copy proof, including after interpreter exit."""
|
"""Fresh process and exclusive-copy proof, including after interpreter exit."""
|
||||||
@@ -97,8 +187,11 @@ def prove_export_copies_released(library, *, allow_unknown_checkpoint=False, uns
|
|||||||
raise LibraryBusy('Invalid library checkpoint cannot release export ownership.')
|
raise LibraryBusy('Invalid library checkpoint cannot release export ownership.')
|
||||||
# Only the explicit release path supplies full-library/native proof and
|
# Only the explicit release path supplies full-library/native proof and
|
||||||
# archives the unchanged metadata while its coordination handle is held.
|
# archives the unchanged metadata while its coordination handle is held.
|
||||||
assert_retained_exports_idle()
|
for process in _process_snapshot():
|
||||||
if any(p['name'].casefold() in _OWNER_NAMES for p in _process_snapshot()):
|
if process['name'].casefold() not in _OWNER_NAMES:
|
||||||
|
continue
|
||||||
|
associated_library = _external_export_library(process)
|
||||||
|
if associated_library is None or associated_library == library:
|
||||||
raise LibraryBusy('Unknown export checkpoint still has a possible native identity owner.')
|
raise LibraryBusy('Unknown export checkpoint still has a possible native identity owner.')
|
||||||
yield []
|
yield []
|
||||||
return
|
return
|
||||||
@@ -156,15 +249,18 @@ def prove_export_copies_released(library, *, allow_unknown_checkpoint=False, uns
|
|||||||
if any(not isinstance(pid, int) or pid <= 0 for pid in pids):
|
if any(not isinstance(pid, int) or pid <= 0 for pid in pids):
|
||||||
raise ValueError('Invalid export process identity.')
|
raise ValueError('Invalid export process identity.')
|
||||||
identities = {p['pid']: p for p in process.get('process_identities', [])}
|
identities = {p['pid']: p for p in process.get('process_identities', [])}
|
||||||
excluded = _preexisting_export_pids(process)
|
excluded = _preexisting_export_pids(process,snapshot,project_root=project.parent)
|
||||||
def original_alive(pid):
|
def original_alive(pid):
|
||||||
if pid in excluded:
|
if pid in excluded:
|
||||||
return False
|
return False
|
||||||
recorded = identities.get(pid, {})
|
recorded = identities.get(pid, {})
|
||||||
current = next((p for p in snapshot if p['pid'] == pid), None)
|
current = next((p for p in snapshot if p['pid'] == pid), None)
|
||||||
if recorded.get('created') and current and current.get('created'):
|
if recorded.get('created') and current and current.get('created'):
|
||||||
return (recorded['created'] == current['created']
|
from datetime import datetime
|
||||||
and recorded.get('executable') == current.get('executable'))
|
from .native_engineering_identity import _process_birth
|
||||||
|
before,now=_process_birth(recorded['created']),_process_birth(current['created'])
|
||||||
|
if isinstance(before,datetime) and isinstance(now,datetime):
|
||||||
|
return before==now
|
||||||
return any(p['pid'] == pid for p in snapshot) or _supervisor_alive(pid)
|
return any(p['pid'] == pid for p in snapshot) or _supervisor_alive(pid)
|
||||||
if any(original_alive(pid) for pid in pids):
|
if any(original_alive(pid) for pid in pids):
|
||||||
raise LibraryBusy('A recorded export process or descendant remains alive.')
|
raise LibraryBusy('A recorded export process or descendant remains alive.')
|
||||||
@@ -186,8 +282,8 @@ def prove_export_copies_released(library, *, allow_unknown_checkpoint=False, uns
|
|||||||
|
|
||||||
|
|
||||||
def finish_export_analysis(library, token, *, native_not_started=False):
|
def finish_export_analysis(library, token, *, native_not_started=False):
|
||||||
from .library_lock import _guard, blocker_path, checkpoint_record, LibraryBusy
|
from .library_lock import LibraryLock, _library_guard, blocker_path, checkpoint_record, LibraryBusy
|
||||||
with _guard, prove_export_copies_released(library,
|
with _library_guard(LibraryLock(library).key), prove_export_copies_released(library,
|
||||||
unstarted_token=token if native_not_started else ''):
|
unstarted_token=token if native_not_started else ''):
|
||||||
marker = blocker_path(library)
|
marker = blocker_path(library)
|
||||||
checkpoint = checkpoint_record(marker)
|
checkpoint = checkpoint_record(marker)
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"""Version-pinned native adapter, private desktop transport and strict catalog.
|
"""Version-pinned native import/removal, private desktop transport and catalog.
|
||||||
|
|
||||||
The installed Tcl CleanWGLib/F4 contract has isolated removal proof. Discovery
|
Normal import checks native registration and engineering files without invoking
|
||||||
of an Add dialog is deliberately insufficient to enable production Add/Update.
|
the independent schematic exporters. Optional Verify determines READY.
|
||||||
"""
|
"""
|
||||||
from dataclasses import asdict, replace
|
from dataclasses import asdict, replace
|
||||||
import ctypes
|
import ctypes
|
||||||
@@ -53,9 +53,10 @@ def removal_output_ok(code, output, name, partition):
|
|||||||
+ r"' from partition '" + re.escape(partition) + r"'\.", output) is not None)
|
+ r"' from partition '" + re.escape(partition) + r"'\.", output) is not None)
|
||||||
|
|
||||||
|
|
||||||
def catalog_dialog_action(title, text):
|
def catalog_dialog_action(title, text, *, read_only=False):
|
||||||
value = (title + '\n' + text).casefold()
|
value = (title + '\n' + text).casefold()
|
||||||
if ('this central library must be updated' in value or 'select flow type' in value):
|
if ('this central library must be updated' in value or 'select flow type' in value
|
||||||
|
or read_only and ('save' in value or 'upgrade' in value)):
|
||||||
return 'cancel'
|
return 'cancel'
|
||||||
return 'observe'
|
return 'observe'
|
||||||
|
|
||||||
@@ -71,10 +72,14 @@ class NativeManagementAdapter:
|
|||||||
self._pending_workers = {}
|
self._pending_workers = {}
|
||||||
self.stop = None
|
self.stop = None
|
||||||
self.session_progress = None
|
self.session_progress = None
|
||||||
|
self.write_admission = None
|
||||||
|
|
||||||
def bind_stop(self, stop):
|
def bind_stop(self, stop):
|
||||||
self.stop = stop
|
self.stop = stop
|
||||||
|
|
||||||
|
def bind_write_admission(self, admission):
|
||||||
|
self.write_admission=admission
|
||||||
|
|
||||||
def release_confirmed(self, library):
|
def release_confirmed(self, library):
|
||||||
"""Worker exit/result files do not replace independent resource proof."""
|
"""Worker exit/result files do not replace independent resource proof."""
|
||||||
key = str(Path(library).resolve()).casefold()
|
key = str(Path(library).resolve()).casefold()
|
||||||
@@ -131,17 +136,12 @@ class NativeManagementAdapter:
|
|||||||
|
|
||||||
def capabilities(self):
|
def capabilities(self):
|
||||||
reason = self._binary_capability()
|
reason = self._binary_capability()
|
||||||
add_reason = reason
|
|
||||||
if not add_reason:
|
|
||||||
from .native_engineering_identity import check_exporters
|
|
||||||
try: check_exporters(self.home)
|
|
||||||
except (ValueError, OSError, TypeError) as error: add_reason = str(error)
|
|
||||||
return {
|
return {
|
||||||
'remove': Capability(not reason, reason or '已验证 CleanWGLib/F4;仅 ASCII 名称、Logical-Physical 和 DxDesigner 库。'),
|
'remove': Capability(not reason, reason or '已验证 CleanWGLib/F4;仅 ASCII 名称、Logical-Physical 和 DxDesigner 库。'),
|
||||||
'add': Capability(not add_reason and _PRODUCTION_ADD_VALIDATED, add_reason or
|
'add': Capability(not reason and _PRODUCTION_ADD_VALIDATED, reason or
|
||||||
'已验证 EE7.9.5 原生导入及完整工程复读;仅 ASCII 名称、Logical-Physical 和 DxDesigner 库。'),
|
'EE7.9.5 原生导入及工程关联复读;仅 ASCII 名称、Logical-Physical 和 DxDesigner 库。'),
|
||||||
'update': Capability(not add_reason and _PRODUCTION_ADD_VALIDATED and _PRODUCTION_UPDATE_VALIDATED,
|
'update': Capability(not reason and _PRODUCTION_ADD_VALIDATED and _PRODUCTION_UPDATE_VALIDATED,
|
||||||
add_reason or '已验证同名原生替换:移除并重新导入;操作前请手动备份。'),
|
reason or '同名原生替换:移除并重新导入;操作前请手动备份。'),
|
||||||
}
|
}
|
||||||
|
|
||||||
def _worker(self, job, evidence):
|
def _worker(self, job, evidence):
|
||||||
@@ -223,6 +223,7 @@ class NativeManagementAdapter:
|
|||||||
from .session_record import process_identity
|
from .session_record import process_identity
|
||||||
job = {**job, 'cancel_signal': str(evidence/'cancel-management.signal'),
|
job = {**job, 'cancel_signal': str(evidence/'cancel-management.signal'),
|
||||||
'start_gate': str(evidence/'start-management.signal'),
|
'start_gate': str(evidence/'start-management.signal'),
|
||||||
|
'start_gate_protocol': 'event-v1',
|
||||||
'session_record_path': str(evidence/'session.json'), 'operation_id': uuid4().hex,
|
'session_record_path': str(evidence/'session.json'), 'operation_id': uuid4().hex,
|
||||||
'supervisor_pid': os.getpid(), 'supervisor_identity': process_identity(os.getpid()),
|
'supervisor_pid': os.getpid(), 'supervisor_identity': process_identity(os.getpid()),
|
||||||
'block': job.get('name')}
|
'block': job.get('name')}
|
||||||
@@ -243,7 +244,12 @@ class NativeManagementAdapter:
|
|||||||
worker.bind_cancellation(job['cancel_signal'])
|
worker.bind_cancellation(job['cancel_signal'])
|
||||||
if hasattr(worker, 'bind_session'):
|
if hasattr(worker, 'bind_session'):
|
||||||
worker.bind_session(job)
|
worker.bind_session(job)
|
||||||
Path(job['start_gate']).touch()
|
from contextlib import nullcontext
|
||||||
|
from .operation_queue import commit_worker_start, native_channel
|
||||||
|
# Only admitted native waiting outlives the UI's metadata deadline.
|
||||||
|
channel = native_channel(read_only=True) if job.get('worker_role') == 'catalog_readonly' else nullcontext()
|
||||||
|
with channel:
|
||||||
|
commit_worker_start(worker, job)
|
||||||
while worker.poll() is None and time.monotonic() < deadline:
|
while worker.poll() is None and time.monotonic() < deadline:
|
||||||
if self.stop is not None and self.stop.is_set():
|
if self.stop is not None and self.stop.is_set():
|
||||||
Path(job['cancel_signal']).touch()
|
Path(job['cancel_signal']).touch()
|
||||||
@@ -276,7 +282,8 @@ class NativeManagementAdapter:
|
|||||||
worker.close()
|
worker.close()
|
||||||
|
|
||||||
def catalog(self, library, evidence):
|
def catalog(self, library, evidence):
|
||||||
result = self._worker({'operation': 'catalog', 'library': str(absolute_preserving_drive(library))}, evidence)
|
result = self._worker({'operation': 'catalog', 'worker_role': 'catalog_readonly',
|
||||||
|
'library': str(absolute_preserving_drive(library))}, evidence)
|
||||||
if not result.get('success') or not result.get('safe_to_continue'):
|
if not result.get('success') or not result.get('safe_to_continue'):
|
||||||
raise NativeOperationError(result.get('detail', '原生目录复读未确认,禁止文件夹回退。'),
|
raise NativeOperationError(result.get('detail', '原生目录复读未确认,禁止文件夹回退。'),
|
||||||
safe_to_continue=result.get('safe_to_continue') is True)
|
safe_to_continue=result.get('safe_to_continue') is True)
|
||||||
@@ -301,26 +308,47 @@ class NativeManagementAdapter:
|
|||||||
removal_input(request.name, request.partition)
|
removal_input(request.name, request.partition)
|
||||||
if request.partition != 'Logical-Physical' or catalog.flow != 1:
|
if request.partition != 'Logical-Physical' or catalog.flow != 1:
|
||||||
raise ValueError('仅验证了 DxDesigner / Logical-Physical 管理操作。')
|
raise ValueError('仅验证了 DxDesigner / Logical-Physical 管理操作。')
|
||||||
|
self.validate_source(request)
|
||||||
|
|
||||||
|
def validate_source(self, request, *, probe_files=True):
|
||||||
|
if request.operation not in ('add', 'update'):
|
||||||
|
return
|
||||||
|
if request.source is None:
|
||||||
|
raise ValueError('请选择完整来源工程。')
|
||||||
|
source = Path(request.source)
|
||||||
|
if probe_files:
|
||||||
|
source = source.resolve(strict=True)
|
||||||
|
if source.suffix.casefold() != '.prj' or probe_files and not source.is_file():
|
||||||
|
raise ValueError('请选择完整来源工程的 PRJ 文件。')
|
||||||
|
if source.stem.casefold() != request.name.casefold():
|
||||||
|
raise ValueError(f'SOURCE_NAME_MISMATCH: 来源工程名 {source.stem} 与目标 {request.name} 不一致;'
|
||||||
|
'当前版本不支持改名,请重新选择同名 PRJ。')
|
||||||
|
|
||||||
def add(self, request, evidence):
|
def add(self, request, evidence):
|
||||||
# Route readiness never grants production mutation authority.
|
# Route readiness never grants production mutation authority.
|
||||||
capability = self.capabilities()['add']
|
capability = self.capabilities()['add']
|
||||||
if not capability.supported:
|
if not capability.supported:
|
||||||
return NativeOutcome(False, True, capability.reason, evidence_path=Path(evidence))
|
return NativeOutcome(False, True, capability.reason, evidence_path=Path(evidence))
|
||||||
|
try:
|
||||||
|
self.validate_source(request)
|
||||||
|
except (OSError, ValueError) as error:
|
||||||
|
return NativeOutcome(False, True, str(error), evidence_path=Path(evidence))
|
||||||
return self._add_transaction(request, Path(evidence))
|
return self._add_transaction(request, Path(evidence))
|
||||||
|
|
||||||
def prepare_add_transaction(self, request, root, *, original_source):
|
def prepare_add_transaction(self, request, root, *, original_source):
|
||||||
from .native_engineering_identity import project_library, asset_identity, capture_identity, IdentityOutcome
|
from .native_engineering_identity import asset_identity, capture_registration_identity, IdentityOutcome
|
||||||
from .native_add_failures import validate_native_copy_paths
|
from .native_add_failures import validate_native_copy_paths
|
||||||
from .management_transaction import current_lease, prepare_transaction
|
from .management_transaction import current_lease, prepare_transaction
|
||||||
from .management import source_project
|
from .management import source_project
|
||||||
from .backup_recovery import _align_library
|
from .backup_recovery import _align_library
|
||||||
try:
|
try:
|
||||||
|
self.validate_source(request)
|
||||||
if not self.capabilities()['add'].supported:
|
if not self.capabilities()['add'].supported:
|
||||||
raise ValueError(self.capabilities()['add'].reason)
|
raise ValueError(self.capabilities()['add'].reason)
|
||||||
validate_native_copy_paths(request.source, request.library, request.name)
|
validate_native_copy_paths(request.source, request.library, request.name)
|
||||||
current_lease(request.library)
|
current_lease(request.library)
|
||||||
original_assets = asset_identity(original_source, project_library(original_source))
|
# The selected destination replaces old library paths in the staged copy.
|
||||||
|
original_assets = asset_identity(original_source, None)
|
||||||
staged, pcb, _ = source_project(request.source, request.top_level_block)
|
staged, pcb, _ = source_project(request.source, request.top_level_block)
|
||||||
if staged.parent != Path(root).resolve()/'source':
|
if staged.parent != Path(root).resolve()/'source':
|
||||||
raise ValueError('Only the engine staged source can be aligned for native Add.')
|
raise ValueError('Only the engine staged source can be aligned for native Add.')
|
||||||
@@ -329,8 +357,7 @@ class NativeManagementAdapter:
|
|||||||
raise ValueError('Staged engineering assets differ from the original source.')
|
raise ValueError('Staged engineering assets differ from the original source.')
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
return request, IdentityOutcome(None, True, str(error), Path(root))
|
return request, IdentityOutcome(None, True, str(error), Path(root))
|
||||||
proof = capture_identity(staged, Path(root)/'source-identity', expected_library=request.library,
|
proof = capture_registration_identity(staged, Path(root)/'source-identity', expected_library=request.library)
|
||||||
owner_library=request.library, mentor_home=self.home, timeout_seconds=request.timeout_seconds)
|
|
||||||
if proof.identity is None or not proof.safe_to_continue:
|
if proof.identity is None or not proof.safe_to_continue:
|
||||||
return request, proof
|
return request, proof
|
||||||
try:
|
try:
|
||||||
@@ -344,7 +371,7 @@ class NativeManagementAdapter:
|
|||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from .management_transaction import validate_transaction
|
from .management_transaction import validate_transaction
|
||||||
from .library_lock import LibraryLock
|
from .library_lock import LibraryLock
|
||||||
from .native_engineering_identity import capture_identity, project_library
|
from .native_engineering_identity import capture_registration_identity, project_library
|
||||||
from .management import source_project
|
from .management import source_project
|
||||||
from .backup_recovery import _align_library, _idle_check
|
from .backup_recovery import _align_library, _idle_check
|
||||||
try:
|
try:
|
||||||
@@ -383,8 +410,12 @@ class NativeManagementAdapter:
|
|||||||
if len(projects) != 1:
|
if len(projects) != 1:
|
||||||
return NativeOutcome(True, owner_safe, 'Registered engineering project is not unique.',
|
return NativeOutcome(True, owner_safe, 'Registered engineering project is not unique.',
|
||||||
identity_matches=False, evidence_path=evidence)
|
identity_matches=False, evidence_path=evidence)
|
||||||
target, pcb, _ = source_project(projects[0], request.top_level_block)
|
target, pcb, _ = source_project(projects[0])
|
||||||
|
if self.write_admission is None:
|
||||||
_idle_check(request.library,target,pcb)
|
_idle_check(request.library,target,pcb)
|
||||||
|
else:
|
||||||
|
_idle_check(request.library,target,pcb,confirmation=self.write_admission,
|
||||||
|
evidence=evidence,block=request.name)
|
||||||
from .maintenance_entry import maintenance_project_files
|
from .maintenance_entry import maintenance_project_files
|
||||||
project_files = maintenance_project_files(target, pcb)
|
project_files = maintenance_project_files(target, pcb)
|
||||||
before_refs = {str(p): hash_file(p) for p in project_files}
|
before_refs = {str(p): hash_file(p) for p in project_files}
|
||||||
@@ -401,18 +432,31 @@ class NativeManagementAdapter:
|
|||||||
or catalog.flow != 1 or len(entries) != 1):
|
or catalog.flow != 1 or len(entries) != 1):
|
||||||
return NativeOutcome(True, owner_safe, 'Aligned target did not reopen with the exact catalog identity.',
|
return NativeOutcome(True, owner_safe, 'Aligned target did not reopen with the exact catalog identity.',
|
||||||
identity_matches=False, evidence_path=evidence)
|
identity_matches=False, evidence_path=evidence)
|
||||||
owner_safe = False
|
proof = capture_registration_identity(target, evidence/'registered-identity', expected_library=request.library)
|
||||||
proof = capture_identity(target, evidence/'registered-identity', expected_library=request.library,
|
# File-only content evidence cannot change the catalog owner's exit proof.
|
||||||
owner_library=request.library, mentor_home=self.home, timeout_seconds=request.timeout_seconds)
|
expected, registered = prepared['expected_identity'], proof.identity
|
||||||
owner_safe = proof.safe_to_continue
|
# Native Add rewrites PRJ metadata and runtime history. Registration
|
||||||
matched = proof.identity is not None and proof.identity == prepared['expected_identity']
|
# identity uses the top block and Layout; other file diffs are evidence.
|
||||||
|
allowed_tops = (expected['top_level_block'], request.name)
|
||||||
|
matched = (registered is not None and registered['top_level_block'] in allowed_tops
|
||||||
|
and registered['layout_sha256'] == expected['layout_sha256'])
|
||||||
|
before_assets, after_assets = expected['assets'], (registered or {}).get('assets', {})
|
||||||
|
differences = {'added': sorted(after_assets.keys()-before_assets.keys()),
|
||||||
|
'deleted': sorted(before_assets.keys()-after_assets.keys()),
|
||||||
|
'modified': sorted(key for key in before_assets.keys() & after_assets.keys()
|
||||||
|
if before_assets[key] != after_assets[key])}
|
||||||
|
assets_match = registered is not None and not any(differences.values())
|
||||||
_write_json(evidence/'identity-comparison.json', {'identity_matches': matched,
|
_write_json(evidence/'identity-comparison.json', {'identity_matches': matched,
|
||||||
'expected': prepared['expected_identity'], 'registered': proof.identity,
|
'assets_match': assets_match, 'asset_differences': differences,
|
||||||
|
'top_level_block_mapping': {'source': expected['top_level_block'],
|
||||||
|
'registered': (registered or {}).get('top_level_block'), 'allowed': list(allowed_tops)},
|
||||||
|
'expected': expected, 'registered': registered,
|
||||||
'safe_to_continue': owner_safe, 'detail': proof.detail})
|
'safe_to_continue': owner_safe, 'detail': proof.detail})
|
||||||
return NativeOutcome(True, owner_safe,
|
return NativeOutcome(True, owner_safe,
|
||||||
'Native ASCII/CSV/EDIF, physical assets and library references match.' if matched else
|
('原生注册、工程关联、顶层块和 Layout 已确认;未核验原理图语义。'
|
||||||
'Native registration succeeded but complete engineering identity proof did not match: '+proof.detail,
|
+ ('其他工程文件有差异,已记录供核对。' if not assets_match else '')) if matched else
|
||||||
identity_matches=matched, evidence_path=evidence, identity_proof=proof.identity)
|
'原生注册成功,但工程关联、顶层块或 Layout 未确认一致:'+proof.detail,
|
||||||
|
identity_matches=matched, evidence_path=evidence, identity_proof=registered)
|
||||||
|
|
||||||
def add_owned_fixture(self, request, evidence, *, probe_token):
|
def add_owned_fixture(self, request, evidence, *, probe_token):
|
||||||
"""Research only: stage and back up a token-bound, actively leased fixture."""
|
"""Research only: stage and back up a token-bound, actively leased fixture."""
|
||||||
@@ -426,6 +470,7 @@ class NativeManagementAdapter:
|
|||||||
return NativeOutcome(False, True, 'Native Add requires an existing staged PRJ source project.',
|
return NativeOutcome(False, True, 'Native Add requires an existing staged PRJ source project.',
|
||||||
evidence_path=evidence)
|
evidence_path=evidence)
|
||||||
try:
|
try:
|
||||||
|
self.validate_source(request)
|
||||||
source_identity = engineering_identity(source)
|
source_identity = engineering_identity(source)
|
||||||
except (ValueError, OSError) as error:
|
except (ValueError, OSError) as error:
|
||||||
return NativeOutcome(False, True, f'Unable to read source engineering identity: {error}',
|
return NativeOutcome(False, True, f'Unable to read source engineering identity: {error}',
|
||||||
@@ -463,13 +508,10 @@ class _OwnedFixtureManagementAdapter(NativeManagementAdapter):
|
|||||||
|
|
||||||
def capabilities(self):
|
def capabilities(self):
|
||||||
from .management_transaction import fixture_authority
|
from .management_transaction import fixture_authority
|
||||||
from .native_engineering_identity import check_exporters
|
|
||||||
fixture = self._fixture_authority
|
fixture = self._fixture_authority
|
||||||
fixture_authority(fixture['root'], Path(fixture['root'])/'native-add/fixture/mentor_lib.lmc', fixture['token'])
|
fixture_authority(fixture['root'], Path(fixture['root'])/'native-add/fixture/mentor_lib.lmc', fixture['token'])
|
||||||
caps = super().capabilities()
|
caps = super().capabilities()
|
||||||
reason = self._binary_capability()
|
reason = self._binary_capability()
|
||||||
try: check_exporters(self.home)
|
|
||||||
except (ValueError, OSError) as error: reason = str(error)
|
|
||||||
for operation in ('add', 'update'):
|
for operation in ('add', 'update'):
|
||||||
caps[operation] = Capability(not reason, reason or 'Owned fixture engine validation only; production capability unchanged.')
|
caps[operation] = Capability(not reason, reason or 'Owned fixture engine validation only; production capability unchanged.')
|
||||||
return caps
|
return caps
|
||||||
@@ -673,11 +715,11 @@ def _dispatch_diagnostics(root, stage, app, library, *, paths=None):
|
|||||||
stream.write(json.dumps(record, ensure_ascii=False, default=str) + '\n')
|
stream.write(json.dumps(record, ensure_ascii=False, default=str) + '\n')
|
||||||
|
|
||||||
|
|
||||||
def _set_probe_field(hwnd, control_id, expected, root):
|
def _set_probe_field(hwnd, control_id, expected, root, *, read_only=False):
|
||||||
"""Set/read a remote Edit with a one-second total message budget."""
|
"""Set/read or revalidate a remote Edit with a one-second total message budget."""
|
||||||
from ctypes import wintypes
|
from ctypes import wintypes
|
||||||
record = {'control_id': control_id, 'hwnd': int(hwnd), 'expected': expected,
|
record = {'control_id': control_id, 'hwnd': int(hwnd), 'expected': expected,
|
||||||
'actual': None, 'matched': False}
|
'actual': None, 'matched': False, 'read_only': read_only}
|
||||||
deadline = time.monotonic() + 1.0
|
deadline = time.monotonic() + 1.0
|
||||||
try:
|
try:
|
||||||
user32 = ctypes.WinDLL('user32', use_last_error=True)
|
user32 = ctypes.WinDLL('user32', use_last_error=True)
|
||||||
@@ -694,6 +736,7 @@ def _set_probe_field(hwnd, control_id, expected, root):
|
|||||||
remaining, ctypes.byref(returned)):
|
remaining, ctypes.byref(returned)):
|
||||||
raise TimeoutError(f'原生字段消息超时或失败:{control_id}, Windows={ctypes.get_last_error()}')
|
raise TimeoutError(f'原生字段消息超时或失败:{control_id}, Windows={ctypes.get_last_error()}')
|
||||||
return returned.value
|
return returned.value
|
||||||
|
if not read_only:
|
||||||
text = ctypes.create_unicode_buffer(expected)
|
text = ctypes.create_unicode_buffer(expected)
|
||||||
if not message(0x000C, 0, text): # WM_SETTEXT
|
if not message(0x000C, 0, text): # WM_SETTEXT
|
||||||
raise RuntimeError(f'原生字段拒绝写入:{control_id}')
|
raise RuntimeError(f'原生字段拒绝写入:{control_id}')
|
||||||
@@ -732,6 +775,9 @@ def _probe_add_dialog(app, job, desktop, owned_pids, root, *, library=None):
|
|||||||
import gc
|
import gc
|
||||||
gc.collect() # Release UIA wrappers before closing native child dialogs.
|
gc.collect() # Release UIA wrappers before closing native child dialogs.
|
||||||
if not job.get('_native_add_pending'):
|
if not job.get('_native_add_pending'):
|
||||||
|
writer = job.pop('_native_add_writer', None)
|
||||||
|
if writer is not None:
|
||||||
|
writer.complete()
|
||||||
_close_probe_dialogs(desktop, owned_pids)
|
_close_probe_dialogs(desktop, owned_pids)
|
||||||
|
|
||||||
|
|
||||||
@@ -827,6 +873,9 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
|
|||||||
if not hwnd or win32gui.GetClassName(hwnd) != 'Edit':
|
if not hwnd or win32gui.GetClassName(hwnd) != 'Edit':
|
||||||
raise RuntimeError(f'原生新增字段身份不匹配:{control}')
|
raise RuntimeError(f'原生新增字段身份不匹配:{control}')
|
||||||
_set_probe_field(hwnd, control, value, root)
|
_set_probe_field(hwnd, control, value, root)
|
||||||
|
# Changing source/top fields can make Mentor derive a different name.
|
||||||
|
for control, value in fields.items():
|
||||||
|
_set_probe_field(win32gui.GetDlgItem(dialog, control), control, value, root, read_only=True)
|
||||||
_write_json(root/'submitted-fields.json', fields)
|
_write_json(root/'submitted-fields.json', fields)
|
||||||
ok = win32gui.GetDlgItem(dialog, 1083)
|
ok = win32gui.GetDlgItem(dialog, 1083)
|
||||||
if not ok:
|
if not ok:
|
||||||
@@ -838,9 +887,18 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
|
|||||||
_require_add_supervisor(job, root)
|
_require_add_supervisor(job, root)
|
||||||
from .session_record import dispatch_native, update_worker_state
|
from .session_record import dispatch_native, update_worker_state
|
||||||
def submit_add():
|
def submit_add():
|
||||||
|
_require_add_supervisor(job, root) # Registration/journal I/O may have outlived cancellation.
|
||||||
job['_native_add_pending'] = True
|
job['_native_add_pending'] = True
|
||||||
win32gui.PostMessage(ok, win32con.BM_CLICK, 0, 0)
|
win32gui.PostMessage(ok, win32con.BM_CLICK, 0, 0)
|
||||||
|
from .desktop_worker import register_pending_native_operation
|
||||||
|
writer = register_pending_native_operation(job, owned_pids)
|
||||||
|
job['_native_add_writer'] = writer
|
||||||
|
try:
|
||||||
dispatch_native(job, submit_add, asynchronous=True, required=True)
|
dispatch_native(job, submit_add, asynchronous=True, required=True)
|
||||||
|
except Exception:
|
||||||
|
if not job.get('_native_add_pending'):
|
||||||
|
writer.complete()
|
||||||
|
raise
|
||||||
success = None
|
success = None
|
||||||
while time.monotonic() < deadline:
|
while time.monotonic() < deadline:
|
||||||
pythoncom.PumpWaitingMessages()
|
pythoncom.PumpWaitingMessages()
|
||||||
@@ -871,6 +929,7 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
|
|||||||
if not success:
|
if not success:
|
||||||
raise TimeoutError('未取得原生新增成功消息;保留副本与私有桌面证据。')
|
raise TimeoutError('未取得原生新增成功消息;保留副本与私有桌面证据。')
|
||||||
job['_native_add_pending'] = False
|
job['_native_add_pending'] = False
|
||||||
|
writer.complete()
|
||||||
update_worker_state(job, 'POSTCALL')
|
update_worker_state(job, 'POSTCALL')
|
||||||
|
|
||||||
|
|
||||||
@@ -1043,6 +1102,8 @@ def _catalog_native(job, root):
|
|||||||
|
|
||||||
|
|
||||||
def _catalog_com(job, root):
|
def _catalog_com(job, root):
|
||||||
|
if job.get('worker_role') == 'catalog_readonly' and job.get('operation') != 'catalog':
|
||||||
|
raise RuntimeError('WORKER_READONLY_ROLE_MISMATCH')
|
||||||
import pythoncom, win32com.client, win32con, win32gui, win32process
|
import pythoncom, win32com.client, win32con, win32gui, win32process
|
||||||
from .mentor_adapter import _process_details
|
from .mentor_adapter import _process_details
|
||||||
try:
|
try:
|
||||||
@@ -1076,7 +1137,7 @@ def _catalog_com(job, root):
|
|||||||
win32gui.EnumChildWindows(hwnd, lambda child, _: children.append(child), None)
|
win32gui.EnumChildWindows(hwnd, lambda child, _: children.append(child), None)
|
||||||
title = win32gui.GetWindowText(hwnd)
|
title = win32gui.GetWindowText(hwnd)
|
||||||
text = '\n'.join(win32gui.GetWindowText(child) for child in children)
|
text = '\n'.join(win32gui.GetWindowText(child) for child in children)
|
||||||
if catalog_dialog_action(title, text) == 'cancel':
|
if catalog_dialog_action(title, text, read_only=job.get('worker_role') == 'catalog_readonly') == 'cancel':
|
||||||
if hwnd not in observed:
|
if hwnd not in observed:
|
||||||
observed.append(hwnd)
|
observed.append(hwnd)
|
||||||
refused.append({'title': title, 'text': text})
|
refused.append({'title': title, 'text': text})
|
||||||
@@ -1210,11 +1271,23 @@ def _catalog_com(job, root):
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
def management_worker_main(request_path):
|
def catalog_worker_main(request_path):
|
||||||
|
"""A catalog-only entry: never allow this read role to select a write branch."""
|
||||||
|
job = json.loads(Path(request_path).read_text(encoding='utf-8'))
|
||||||
|
if job.get('operation') != 'catalog' or job.get('worker_role') != 'catalog_readonly':
|
||||||
|
raise RuntimeError('WORKER_READONLY_ROLE_MISMATCH')
|
||||||
|
return management_worker_main(request_path, catalog_readonly=True)
|
||||||
|
|
||||||
|
|
||||||
|
def management_worker_main(request_path, *, catalog_readonly=False):
|
||||||
"""Internal worker. Desktop identity and capability gates are rechecked here."""
|
"""Internal worker. Desktop identity and capability gates are rechecked here."""
|
||||||
request_path = Path(request_path)
|
request_path = Path(request_path)
|
||||||
root = request_path.parent
|
root = request_path.parent
|
||||||
job = json.loads(request_path.read_text(encoding='utf-8'))
|
job = json.loads(request_path.read_text(encoding='utf-8'))
|
||||||
|
if job.get('worker_role') == 'catalog_readonly' and not catalog_readonly:
|
||||||
|
raise RuntimeError('WORKER_READONLY_ROLE_MISMATCH')
|
||||||
|
if catalog_readonly and (job.get('operation') != 'catalog' or job.get('worker_role') != 'catalog_readonly'):
|
||||||
|
raise RuntimeError('WORKER_READONLY_ROLE_MISMATCH')
|
||||||
result = {'success': False, 'safe_to_continue': True}
|
result = {'success': False, 'safe_to_continue': True}
|
||||||
try:
|
try:
|
||||||
_, desktop = _current_desktop()
|
_, desktop = _current_desktop()
|
||||||
@@ -1272,6 +1345,8 @@ def management_worker_main(request_path):
|
|||||||
except (FileNotFoundError, PermissionError):
|
except (FileNotFoundError, PermissionError):
|
||||||
result['safe_to_continue'] = True
|
result['safe_to_continue'] = True
|
||||||
raise
|
raise
|
||||||
|
from .desktop_worker import register_native_writer
|
||||||
|
register_native_writer(process)
|
||||||
update_worker_state(job, 'NATIVE_CALL', identities=[('native', process.pid)], continuation=True)
|
update_worker_state(job, 'NATIVE_CALL', identities=[('native', process.pid)], continuation=True)
|
||||||
try:
|
try:
|
||||||
_write_json(root/'native-process.json', {'pid': process.pid, 'command': command})
|
_write_json(root/'native-process.json', {'pid': process.pid, 'command': command})
|
||||||
|
|||||||
@@ -264,21 +264,44 @@ def run_native_repair(target, root, *, mentor_bin='', timeout_seconds=300, progr
|
|||||||
job_path = root/'repair-request.json'
|
job_path = root/'repair-request.json'
|
||||||
cancel = root/'cancel-repair.signal'
|
cancel = root/'cancel-repair.signal'
|
||||||
desktop = 'CbbRepair_'+uuid4().hex[:12]
|
desktop = 'CbbRepair_'+uuid4().hex[:12]
|
||||||
job_path.write_text(json.dumps({'project': str(target.project), 'database': str(target.database),
|
from .operation_queue import current_context
|
||||||
|
context = current_context()
|
||||||
|
library = (maintenance_context or {}).get('library') or (context.library if context else str(target.project))
|
||||||
|
job = {'project': str(target.project), 'database': str(target.database),
|
||||||
'root': str(root), 'mentor_bin': str(mentor_bin or ''), 'timeout': timeout_seconds,
|
'root': str(root), 'mentor_bin': str(mentor_bin or ''), 'timeout': timeout_seconds,
|
||||||
'cancel_signal': str(cancel), 'supervisor_pid': os.getpid(), 'desktop': desktop,
|
'cancel_signal': str(cancel), 'supervisor_pid': os.getpid(), 'desktop': desktop,
|
||||||
'maintenance_context': maintenance_context, 'inspection_only': inspection_only},
|
'maintenance_context': maintenance_context, 'inspection_only': inspection_only,
|
||||||
ensure_ascii=False), encoding='utf-8')
|
'library': library, 'operation_id': root.name+'-'+uuid4().hex[:8],
|
||||||
|
'operation': 'inspect' if inspection_only else 'repair',
|
||||||
|
'block': (maintenance_context or {}).get('block'),
|
||||||
|
'session_record_path': str(root/'session.json'), 'start_gate': str(root/'start-repair.signal')}
|
||||||
|
job['start_gate_protocol'] = 'event-v1'
|
||||||
|
job_path.write_text(json.dumps(job, ensure_ascii=False), encoding='utf-8')
|
||||||
command = ([sys.executable] if getattr(sys, 'frozen', False) else
|
command = ([sys.executable] if getattr(sys, 'frozen', False) else
|
||||||
[sys.executable, '-m', 'cbb_refresh_verify']) + ['--repair-worker', str(job_path)]
|
[sys.executable, '-m', 'cbb_refresh_verify']) + ['--repair-worker', str(job_path)]
|
||||||
|
from .operation_queue import task_stop
|
||||||
|
return _supervise_repair(command, desktop, cancel, root, timeout_seconds, progress, task_stop(stop), job)
|
||||||
|
|
||||||
|
|
||||||
|
def _supervise_repair(command, desktop, cancel, root, timeout_seconds, progress, stop, job):
|
||||||
|
from .desktop_worker import DesktopWorker
|
||||||
worker = DesktopWorker(command, desktop)
|
worker = DesktopWorker(command, desktop)
|
||||||
worker.bind_cancellation(cancel)
|
worker.bind_cancellation(cancel)
|
||||||
|
from .operation_queue import check_active, native_channel, commit_worker_start
|
||||||
|
native = native_channel(inspection_only=job.get('inspection_only') is True)
|
||||||
|
entered = False
|
||||||
# Worker admission includes filesystem/ownership checks before the native
|
# Worker admission includes filesystem/ownership checks before the native
|
||||||
# timeout begins. Bound that preparation separately; never extend on polls.
|
# timeout begins. Bound that preparation separately; never extend on polls.
|
||||||
deadline = time.monotonic()+60+max(1, float(timeout_seconds))+5
|
deadline = time.monotonic()+60+max(1, float(timeout_seconds))+5
|
||||||
event_count = 0
|
event_count = 0
|
||||||
cancelled = False
|
cancelled = False
|
||||||
try:
|
try:
|
||||||
|
if hasattr(worker, 'bind_session'):
|
||||||
|
worker.bind_session(job)
|
||||||
|
check_active()
|
||||||
|
native.__enter__()
|
||||||
|
entered = True
|
||||||
|
commit_worker_start(worker, job)
|
||||||
while worker.poll() is None and time.monotonic()<deadline:
|
while worker.poll() is None and time.monotonic()<deadline:
|
||||||
if not cancelled and stop is not None and stop.is_set():
|
if not cancelled and stop is not None and stop.is_set():
|
||||||
worker.request_stop()
|
worker.request_stop()
|
||||||
@@ -294,6 +317,9 @@ def run_native_repair(target, root, *, mentor_bin='', timeout_seconds=300, progr
|
|||||||
break
|
break
|
||||||
event_count += 1
|
event_count += 1
|
||||||
time.sleep(.2)
|
time.sleep(.2)
|
||||||
|
if worker.poll() is not None:
|
||||||
|
native.__exit__(None, None, None)
|
||||||
|
entered = False
|
||||||
outcome = root/'repair-result.json'
|
outcome = root/'repair-result.json'
|
||||||
if worker.poll() is None or not outcome.is_file():
|
if worker.poll() is None or not outcome.is_file():
|
||||||
worker.request_stop()
|
worker.request_stop()
|
||||||
@@ -306,5 +332,17 @@ def run_native_repair(target, root, *, mentor_bin='', timeout_seconds=300, progr
|
|||||||
if worker.returncode != 0 and result.get('status') in ('REPAIRED', 'NOT_IN_USE', 'IN_USE'):
|
if worker.returncode != 0 and result.get('status') in ('REPAIRED', 'NOT_IN_USE', 'IN_USE'):
|
||||||
result['status'] = 'UNCONFIRMED'
|
result['status'] = 'UNCONFIRMED'
|
||||||
return {**result, 'evidence_path': str(root)}
|
return {**result, 'evidence_path': str(root)}
|
||||||
|
except BaseException:
|
||||||
|
worker.request_stop()
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
if entered:
|
||||||
|
native.__exit__(None, None, None)
|
||||||
|
if worker.poll() is None and getattr(worker, 'session_record_path', None):
|
||||||
|
from .session_record import handoff_session
|
||||||
|
from .operation_queue import hold_native_handoff
|
||||||
|
handoff_session(worker.session_record_path, evidence_root=root, process=worker)
|
||||||
|
hold_native_handoff(worker, worker.session_record_path)
|
||||||
finally:
|
finally:
|
||||||
worker.close()
|
worker.close()
|
||||||
@@ -192,6 +192,10 @@ def _inspect_project(job, process, emit):
|
|||||||
result = {'status': 'UNCONFIRMED', 'project': str(project), 'database': str(database),
|
result = {'status': 'UNCONFIRMED', 'project': str(project), 'database': str(database),
|
||||||
'native_pid': process.pid, 'inspection_only': True, 'repair_requested': False,
|
'native_pid': process.pid, 'inspection_only': True, 'repair_requested': False,
|
||||||
'repair_required': False, 'output': ''}
|
'repair_required': False, 'output': ''}
|
||||||
|
if getattr(process, '_handle', None) is not None:
|
||||||
|
from .residual_sessions import _handle_identity, _force_ownership
|
||||||
|
result['native_identity'] = dict(pid=process.pid,
|
||||||
|
**_handle_identity(process._handle), **_force_ownership(process._handle, process.pid))
|
||||||
deadline = time.monotonic() + max(1, float(job['timeout']))
|
deadline = time.monotonic() + max(1, float(job['timeout']))
|
||||||
closing = False
|
closing = False
|
||||||
last_state = None
|
last_state = None
|
||||||
@@ -335,6 +339,8 @@ def repair_worker_main(job_path):
|
|||||||
if Path(job['cancel_signal']).exists():
|
if Path(job['cancel_signal']).exists():
|
||||||
raise ValueError('REPAIR_CANCELLED_BEFORE_LAUNCH')
|
raise ValueError('REPAIR_CANCELLED_BEFORE_LAUNCH')
|
||||||
process = subprocess.Popen([str(executable), '-p', str(project)], cwd=str(project.parent))
|
process = subprocess.Popen([str(executable), '-p', str(project)], cwd=str(project.parent))
|
||||||
|
from .desktop_worker import register_native_writer
|
||||||
|
register_native_writer(process)
|
||||||
result['native_started'] = True
|
result['native_started'] = True
|
||||||
result['native_pid'] = process.pid
|
result['native_pid'] = process.pid
|
||||||
emit(stage='native_started', pid=process.pid, project=str(project))
|
emit(stage='native_started', pid=process.pid, project=str(project))
|
||||||
|
|||||||
@@ -2,10 +2,19 @@
|
|||||||
from collections.abc import Sequence
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
|
||||||
def recheck_failed_release(library, block, result):
|
def recheck_failed_release(library, block, result, *, stop=None, timeout_seconds=10):
|
||||||
"""Refresh resource facts after a late exit; keep the original business failure."""
|
"""Refresh resource facts after a late exit; keep the original business failure."""
|
||||||
if result.safe_to_continue or not result.evidence_path:
|
if result.safe_to_continue or not result.evidence_path:
|
||||||
return result
|
return result
|
||||||
|
from .operation_queue import BatchTaskContext, TaskHandoff, current_context, task_stop
|
||||||
|
if current_context() is None:
|
||||||
|
context = BatchTaskContext(library=str(library), targets=(block,))
|
||||||
|
try:
|
||||||
|
return context.run(lambda: recheck_failed_release(library, block, result, stop=stop),
|
||||||
|
stop=stop, timeout_seconds=timeout_seconds)
|
||||||
|
except TaskHandoff:
|
||||||
|
return result
|
||||||
|
stop = task_stop(stop)
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from dataclasses import replace
|
from dataclasses import replace
|
||||||
import json
|
import json
|
||||||
@@ -37,9 +46,16 @@ def recheck_failed_release(library, block, result):
|
|||||||
bound.append(candidate)
|
bound.append(candidate)
|
||||||
if not bound:
|
if not bound:
|
||||||
return result # A generic timeout without a bound owner is not an exit fact.
|
return result # A generic timeout without a bound owner is not an exit fact.
|
||||||
proof = release_retained_library(library, evidence.parent/'late-release', block_name=block)
|
from .operation_queue import check_active
|
||||||
if proof.get('status') != 'RELEASE_CONFIRMED' or Path(proof.get('library', '')).resolve() != Path(library).resolve():
|
check_active()
|
||||||
|
proof = release_retained_library(library, evidence.parent/'late-release', block_name=block, stop=stop)
|
||||||
|
scope = proof.get('resource_scope')
|
||||||
|
if (proof.get('status') != 'RELEASE_CONFIRMED' or proof.get('lease_state') != 'RELEASED'
|
||||||
|
or not isinstance(scope, dict) or scope.get('scope_state') != 'OBSERVED'
|
||||||
|
or proof.get('blocked_resources') != []
|
||||||
|
or Path(proof.get('library', '')).resolve() != Path(library).resolve()):
|
||||||
return result
|
return result
|
||||||
|
check_active()
|
||||||
evidence.with_name('late-release-result.json').write_text(json.dumps(dict(
|
evidence.with_name('late-release-result.json').write_text(json.dumps(dict(
|
||||||
business_status=result.status, safe_to_continue=True, release_proof=proof),
|
business_status=result.status, safe_to_continue=True, release_proof=proof),
|
||||||
ensure_ascii=False, default=str, indent=2), 'utf-8')
|
ensure_ascii=False, default=str, indent=2), 'utf-8')
|
||||||
|
|||||||
@@ -1,36 +1,448 @@
|
|||||||
"""Cooperative FIFO admission for this application's native operations."""
|
"""Cooperative FIFO admission for this application's native operations."""
|
||||||
from threading import Condition
|
from contextlib import contextmanager
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
import ntpath
|
||||||
|
from threading import Condition, Event, RLock, Thread, local
|
||||||
|
import time
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
|
||||||
class QueueCancelled(RuntimeError):
|
class QueueCancelled(RuntimeError):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class TaskHandoff(QueueCancelled):
|
||||||
|
"""The call is still observable; this is never a release receipt."""
|
||||||
|
def __init__(self, context, *, cancelled=False, result=None):
|
||||||
|
self.operation_id = context.operation_id
|
||||||
|
self.library = context.library
|
||||||
|
self.cancelled = cancelled
|
||||||
|
self.scope = context.scope
|
||||||
|
self.result = result
|
||||||
|
super().__init__('已交给后台观察;当前资源尚未确认释放。')
|
||||||
|
|
||||||
|
|
||||||
|
class _StopSignal:
|
||||||
|
def __init__(self):
|
||||||
|
self._event = Event()
|
||||||
|
|
||||||
|
def set(self):
|
||||||
|
with _tasks_guard:
|
||||||
|
self._event.set()
|
||||||
|
|
||||||
|
def is_set(self):
|
||||||
|
return self._event.is_set()
|
||||||
|
|
||||||
|
def wait(self, timeout=None):
|
||||||
|
return self._event.wait(timeout)
|
||||||
|
|
||||||
|
|
||||||
|
_local = local()
|
||||||
|
_tasks_guard = RLock()
|
||||||
|
_calls = {}
|
||||||
|
|
||||||
|
|
||||||
|
def _path_key(path):
|
||||||
|
# Identity was bound by the caller; queue predicates must never resolve a share.
|
||||||
|
return ntpath.normcase(ntpath.normpath(str(path)))
|
||||||
|
|
||||||
|
|
||||||
|
def request_library_keys(request, context=None):
|
||||||
|
library = str(getattr(request, 'lmc_file', getattr(request, 'library', '__injected_verifier_scope__')))
|
||||||
|
keys = {_path_key(library)}
|
||||||
|
drive, remote = getattr(request, 'mapped_drive', ''), getattr(request, 'mapped_remote_root', '')
|
||||||
|
if drive and remote and ntpath.splitdrive(library)[0].casefold() == drive.rstrip('\\/').casefold():
|
||||||
|
keys.add(_path_key(ntpath.join(remote, ntpath.splitdrive(library)[1].lstrip('\\/'))))
|
||||||
|
if context is not None:
|
||||||
|
aliases = {_path_key(v) for v in (context.library, *context.aliases)}
|
||||||
|
if keys.intersection(aliases):
|
||||||
|
keys.update(aliases)
|
||||||
|
return keys
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(eq=False)
|
||||||
|
class _Call:
|
||||||
|
context: object
|
||||||
|
external_stop: object = None
|
||||||
|
metadata_only: bool = False
|
||||||
|
done: Event = field(default_factory=Event)
|
||||||
|
abandoned: bool = False
|
||||||
|
native_depth: int = 0
|
||||||
|
commit_depth: int = 0
|
||||||
|
readonly_depth: int = 0
|
||||||
|
supervised_depth: int = 0
|
||||||
|
worker_sessions: list = field(default_factory=list)
|
||||||
|
shutdown_handoff: bool = False
|
||||||
|
native_handoff: str = ''
|
||||||
|
handoff_cancelled: bool = False
|
||||||
|
phase_started: float = field(default_factory=time.monotonic)
|
||||||
|
result: object = None
|
||||||
|
last_result: object = None
|
||||||
|
error: BaseException | None = None
|
||||||
|
|
||||||
|
def is_set(self):
|
||||||
|
return (self.abandoned or self.context.stop.is_set()
|
||||||
|
or self.external_stop is not None and self.external_stop.is_set())
|
||||||
|
|
||||||
|
|
||||||
|
def current_context():
|
||||||
|
call = getattr(_local, 'call', None)
|
||||||
|
return call.context if call is not None else None
|
||||||
|
|
||||||
|
|
||||||
|
def task_stop(fallback=None):
|
||||||
|
return getattr(_local, 'call', None) or fallback
|
||||||
|
|
||||||
|
|
||||||
|
def check_active():
|
||||||
|
call = getattr(_local, 'call', None)
|
||||||
|
if call is not None and call.is_set():
|
||||||
|
raise QueueCancelled('任务已取消,未提交新的原生操作。')
|
||||||
|
|
||||||
|
|
||||||
|
def note_metadata_progress():
|
||||||
|
"""Renew inactivity only after completed I/O; never revive an abandoned call."""
|
||||||
|
call = getattr(_local, 'call', None)
|
||||||
|
if call is not None:
|
||||||
|
with _tasks_guard:
|
||||||
|
if not call.native_depth:
|
||||||
|
check_active()
|
||||||
|
call.phase_started = time.monotonic()
|
||||||
|
|
||||||
|
|
||||||
|
def remember_result(result):
|
||||||
|
call = getattr(_local, 'call', None)
|
||||||
|
if call is not None:
|
||||||
|
with _tasks_guard:
|
||||||
|
call.last_result = result
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def bind_supervised_worker(path, record):
|
||||||
|
"""Called only after the common launcher has durably registered its worker."""
|
||||||
|
call = getattr(_local, 'call', None)
|
||||||
|
if call is not None:
|
||||||
|
with _tasks_guard:
|
||||||
|
call.worker_sessions.append(dict(path=str(path), operation_id=record['operation_id'],
|
||||||
|
processes=record['processes'], worker_lease_handle=record.get('worker_lease_handle'),
|
||||||
|
worker_protection=record.get('worker_protection'), resource_scope=record.get('resource_scope')))
|
||||||
|
|
||||||
|
|
||||||
|
def check_worker_admission(job):
|
||||||
|
check_active()
|
||||||
|
call = getattr(_local, 'call', None)
|
||||||
|
if (call is not None and call.readonly_depth and job.get('inspection_only') is not True
|
||||||
|
and not (job.get('operation') == 'catalog' and job.get('worker_role') == 'catalog_readonly')):
|
||||||
|
raise RuntimeError('NATIVE_ROLE_REQUIRED: 只读观察不能启动原生写入进程。')
|
||||||
|
|
||||||
|
|
||||||
|
def commit_worker_start(worker, job):
|
||||||
|
"""Prepare evidence outside the shutdown fence; only SetEvent grants admission."""
|
||||||
|
from pathlib import Path
|
||||||
|
import win32event
|
||||||
|
try:
|
||||||
|
check_worker_admission(job)
|
||||||
|
event = getattr(worker, '_start_event', None)
|
||||||
|
context = current_context()
|
||||||
|
if context is not None and context.native_policy == 'external' and event is None:
|
||||||
|
raise RuntimeError('WORKER_ADMISSION_UNCONFIRMED: 缺少已登记的启动事件。')
|
||||||
|
if event is not None and worker._start_binding != (
|
||||||
|
str(job['session_record_path']), job['operation_id'], job['start_gate']):
|
||||||
|
raise RuntimeError('WORKER_ADMISSION_IDENTITY_CHANGED')
|
||||||
|
Path(job['start_gate']).touch()
|
||||||
|
with _tasks_guard:
|
||||||
|
check_worker_admission(job)
|
||||||
|
if event is not None:
|
||||||
|
win32event.SetEvent(event)
|
||||||
|
except BaseException:
|
||||||
|
# A stalled evidence volume cannot delay shutdown or grant admission.
|
||||||
|
if job.get('cancel_signal'):
|
||||||
|
Path(job['cancel_signal']).touch()
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def hold_native_handoff(process, session_record_path):
|
||||||
|
"""Yield parent admission to controls; the gated worker retains write exclusion.
|
||||||
|
|
||||||
|
The caller registers the exact worker observer first. Its writer barrier and
|
||||||
|
inherited sidecar survive this supervisor, including while a user answers Save.
|
||||||
|
"""
|
||||||
|
call = getattr(_local, 'call', None)
|
||||||
|
if call is not None:
|
||||||
|
with _tasks_guard:
|
||||||
|
call.handoff_cancelled = call.is_set()
|
||||||
|
call.native_handoff = str(session_record_path)
|
||||||
|
call.abandoned = True
|
||||||
|
raise TaskHandoff(call.context, cancelled=call.handoff_cancelled, result=call.last_result)
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def local_commit():
|
||||||
|
"""Finish an admitted filesystem rename/rollback without native ownership claims."""
|
||||||
|
call = getattr(_local, 'call', None)
|
||||||
|
with _tasks_guard:
|
||||||
|
check_active()
|
||||||
|
if call is not None:
|
||||||
|
if call.metadata_only or call.readonly_depth:
|
||||||
|
raise RuntimeError('Read-only metadata cannot commit filesystem changes')
|
||||||
|
call.commit_depth += 1
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
if call is not None:
|
||||||
|
with _tasks_guard:
|
||||||
|
call.commit_depth -= 1
|
||||||
|
call.phase_started = time.monotonic()
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def native_phase(*, read_only=False, supervised=False):
|
||||||
|
"""Never abandon a transaction between native writes (including Remove/Add)."""
|
||||||
|
call = getattr(_local, 'call', None)
|
||||||
|
if call is not None and call.metadata_only:
|
||||||
|
raise RuntimeError('A metadata-only call cannot enter native work')
|
||||||
|
if call is not None:
|
||||||
|
if call.readonly_depth and not read_only:
|
||||||
|
raise RuntimeError('NATIVE_ROLE_REQUIRED: 只读观察不能提交原生写入。')
|
||||||
|
if not read_only and (call.context.native_policy == 'restricted'
|
||||||
|
or call.context.native_policy == 'external' and not supervised):
|
||||||
|
raise RuntimeError('NATIVE_ROLE_REQUIRED: 界面写入必须通过已登记的独立工作进程。')
|
||||||
|
with _tasks_guard:
|
||||||
|
check_active()
|
||||||
|
if call is not None:
|
||||||
|
call.native_depth += 1
|
||||||
|
call.readonly_depth += int(read_only)
|
||||||
|
call.supervised_depth += int(supervised)
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
if call is not None:
|
||||||
|
with _tasks_guard:
|
||||||
|
call.native_depth -= 1
|
||||||
|
call.readonly_depth -= int(read_only)
|
||||||
|
call.supervised_depth -= int(supervised)
|
||||||
|
call.phase_started = time.monotonic()
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def native_channel(*, inspection_only=False, read_only=False):
|
||||||
|
"""Shared by Verify, Repair and backup native clients; reentrant per thread."""
|
||||||
|
import win32con, win32event
|
||||||
|
with native_phase(read_only=read_only or inspection_only, supervised=True):
|
||||||
|
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||||
|
acquired = False
|
||||||
|
try:
|
||||||
|
check_active()
|
||||||
|
acquired = win32event.WaitForSingleObject(mutex, 0) in (
|
||||||
|
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
||||||
|
if not acquired:
|
||||||
|
raise RuntimeError('NATIVE_CHANNEL_BUSY: 另一个原生操作仍在运行。')
|
||||||
|
from .desktop_worker import assert_native_writer_idle
|
||||||
|
if inspection_only is not True:
|
||||||
|
assert_native_writer_idle()
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
if acquired:
|
||||||
|
win32event.ReleaseMutex(mutex)
|
||||||
|
mutex.Close()
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class BatchTaskContext:
|
||||||
|
library: str
|
||||||
|
aliases: tuple[str, ...] = ()
|
||||||
|
targets: tuple[str, ...] = ()
|
||||||
|
resources: tuple[str, ...] = ()
|
||||||
|
operation_id: str = field(default_factory=lambda: uuid4().hex)
|
||||||
|
stop: _StopSignal = field(default_factory=_StopSignal, repr=False, compare=False)
|
||||||
|
_closed: Event = field(default_factory=Event, repr=False, compare=False)
|
||||||
|
native_policy: str = field(default='legacy', kw_only=True)
|
||||||
|
# Only queue/batch boundaries consume this; the current item retains hard-stop semantics.
|
||||||
|
stop_after_current: _StopSignal = field(default_factory=_StopSignal, repr=False, compare=False, kw_only=True)
|
||||||
|
|
||||||
|
def __post_init__(self):
|
||||||
|
if self.native_policy not in ('legacy', 'restricted', 'external'):
|
||||||
|
raise ValueError('Unknown native task role')
|
||||||
|
object.__setattr__(self, 'library', str(self.library))
|
||||||
|
for name in ('aliases', 'targets', 'resources'):
|
||||||
|
object.__setattr__(self, name, tuple(str(v) for v in getattr(self, name)))
|
||||||
|
|
||||||
|
@property
|
||||||
|
def scope(self):
|
||||||
|
return dict(scope_state='DECLARED', library=self.library, aliases=list(self.aliases),
|
||||||
|
block_names=list(self.targets), resources=list(self.resources),
|
||||||
|
operation_ids=[self.operation_id])
|
||||||
|
|
||||||
|
@property
|
||||||
|
def state(self):
|
||||||
|
return self.snapshot()['state']
|
||||||
|
|
||||||
|
def snapshot(self):
|
||||||
|
with _tasks_guard:
|
||||||
|
calls = [call for call in _calls.values() if call.context is self]
|
||||||
|
pending = sum(not call.done.is_set() for call in calls)
|
||||||
|
return dict(operation_id=self.operation_id, resource_scope=self.scope,
|
||||||
|
state='CLOSED' if self._closed.is_set() else
|
||||||
|
'CANCELLED' if self.stop.is_set() else
|
||||||
|
'HANDED_OFF' if any(c.abandoned for c in calls) else
|
||||||
|
'RUNNING' if pending else 'IDLE', pending=pending,
|
||||||
|
pending_native=any(c.native_depth or c.commit_depth for c in calls))
|
||||||
|
|
||||||
|
def shutdown(self):
|
||||||
|
"""Yield UI supervision, never a native worker's write/lease ownership.
|
||||||
|
|
||||||
|
External workers commit their kernel start event under this same fence.
|
||||||
|
Registration and all filesystem preparation remain outside the fence.
|
||||||
|
Legacy in-process transactions cannot opt in.
|
||||||
|
"""
|
||||||
|
with _tasks_guard:
|
||||||
|
self._closed.set()
|
||||||
|
self.cancel()
|
||||||
|
calls = [c for c in _calls.values() if c.context is self and not c.done.is_set()]
|
||||||
|
for call in calls:
|
||||||
|
readonly = call.native_depth and call.readonly_depth == call.native_depth
|
||||||
|
external = (self.native_policy == 'external' and
|
||||||
|
call.supervised_depth == call.native_depth and
|
||||||
|
all(s.get('worker_protection') in ('duplicated_lease', 'worker_owned_lease', 'inspection_only', 'catalog_readonly')
|
||||||
|
for s in call.worker_sessions))
|
||||||
|
if not call.commit_depth and (not call.native_depth or readonly or external):
|
||||||
|
call.shutdown_handoff = call.abandoned = True
|
||||||
|
return {**self.snapshot(), 'safe_to_continue': False,
|
||||||
|
'shutdown_handoff': all(c.shutdown_handoff for c in calls),
|
||||||
|
'worker_sessions': [s for c in calls for s in c.worker_sessions]}
|
||||||
|
|
||||||
|
def cancel(self):
|
||||||
|
self.stop.set()
|
||||||
|
|
||||||
|
def check_active(self):
|
||||||
|
if self.stop.is_set() or self._closed.is_set():
|
||||||
|
raise QueueCancelled('任务已取消,未提交新的原生操作。')
|
||||||
|
check_active()
|
||||||
|
|
||||||
|
def guard_callback(self, callback, *, current=None):
|
||||||
|
call = getattr(_local, 'call', None)
|
||||||
|
def guarded(*args, **kwargs):
|
||||||
|
# Cancellation still gets its own terminal result; closing or an
|
||||||
|
# abandoned invocation cannot update a newer task/library.
|
||||||
|
if (not self._closed.is_set() and not (call and call.abandoned)
|
||||||
|
and (current is None or current() is self)):
|
||||||
|
return callback(*args, **kwargs)
|
||||||
|
return guarded
|
||||||
|
|
||||||
|
def close(self, *, timeout_seconds=30):
|
||||||
|
self._closed.set()
|
||||||
|
self.cancel()
|
||||||
|
deadline = time.monotonic() + min(30, max(0, timeout_seconds))
|
||||||
|
with _tasks_guard:
|
||||||
|
calls = [c for c in _calls.values() if c.context is self]
|
||||||
|
for call in calls:
|
||||||
|
call.done.wait(max(0, deadline-time.monotonic()))
|
||||||
|
with _tasks_guard:
|
||||||
|
for call in calls:
|
||||||
|
if not call.done.is_set() and not call.native_depth and not call.commit_depth:
|
||||||
|
call.abandoned = True
|
||||||
|
return self.snapshot()
|
||||||
|
|
||||||
|
def run(self, action, *, stop=None, timeout_seconds=10, metadata_only=False):
|
||||||
|
self.check_active()
|
||||||
|
if current_context() is self:
|
||||||
|
return action() # Preserve nested lease and mutex thread identity.
|
||||||
|
aliases = {_path_key(v) for v in (self.library, *self.aliases)}
|
||||||
|
call = _Call(self, stop, metadata_only=metadata_only)
|
||||||
|
with _tasks_guard:
|
||||||
|
if not metadata_only and self.native_policy != 'restricted' and any(c.abandoned and not c.metadata_only and aliases.intersection(
|
||||||
|
_path_key(v) for v in (c.context.library, *c.context.aliases))
|
||||||
|
for c in _calls.values()):
|
||||||
|
raise TaskHandoff(self)
|
||||||
|
_calls[id(call)] = call
|
||||||
|
def execute():
|
||||||
|
_local.call = call
|
||||||
|
try:
|
||||||
|
check_active()
|
||||||
|
call.result = action()
|
||||||
|
except BaseException as error:
|
||||||
|
call.error = error
|
||||||
|
finally:
|
||||||
|
with _tasks_guard:
|
||||||
|
call.done.set()
|
||||||
|
_calls.pop(id(call), None)
|
||||||
|
del _local.call
|
||||||
|
Thread(target=execute, name='cbb-task-'+self.operation_id[:12], daemon=True).start()
|
||||||
|
while not call.done.wait(.02):
|
||||||
|
with _tasks_guard:
|
||||||
|
if call.shutdown_handoff:
|
||||||
|
raise TaskHandoff(self, cancelled=True, result=call.last_result)
|
||||||
|
if call.native_handoff:
|
||||||
|
cancelled = call.handoff_cancelled
|
||||||
|
call.abandoned = True
|
||||||
|
raise TaskHandoff(self, cancelled=cancelled, result=call.last_result)
|
||||||
|
elapsed = time.monotonic()-call.phase_started
|
||||||
|
if not call.native_depth and not call.commit_depth and (call.abandoned or elapsed >= timeout_seconds):
|
||||||
|
cancelled = call.is_set()
|
||||||
|
call.abandoned = True
|
||||||
|
raise TaskHandoff(self, cancelled=cancelled, result=call.last_result)
|
||||||
|
if call.error is not None:
|
||||||
|
raise call.error
|
||||||
|
return call.result
|
||||||
|
|
||||||
|
|
||||||
class NativeQueue:
|
class NativeQueue:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.condition = Condition()
|
self.condition = Condition()
|
||||||
self.pending = []
|
self.pending = []
|
||||||
self.active = False
|
self.active = False
|
||||||
|
self.closed = False
|
||||||
|
self.contexts = {}
|
||||||
|
|
||||||
def wake(self):
|
def wake(self):
|
||||||
with self.condition: self.condition.notify_all()
|
with self.condition: self.condition.notify_all()
|
||||||
|
|
||||||
def run(self, action, *, stop=None, waiting=None, ready=lambda: True, wait_state=None):
|
def close(self, *, timeout_seconds=30):
|
||||||
ticket = object()
|
deadline = time.monotonic()+min(30, max(0, timeout_seconds))
|
||||||
|
with self.condition:
|
||||||
|
self.closed = True
|
||||||
|
contexts = tuple(self.contexts.values())
|
||||||
|
for context in contexts:
|
||||||
|
context.cancel()
|
||||||
|
self.condition.notify_all()
|
||||||
|
return tuple(context.close(timeout_seconds=max(0, deadline-time.monotonic()))
|
||||||
|
for context in contexts)
|
||||||
|
|
||||||
|
def run(self, action, *, stop=None, waiting=None, ready=lambda: True, wait_state=None,
|
||||||
|
context=None, timeout_seconds=10):
|
||||||
|
def available_now():
|
||||||
|
if not ready():
|
||||||
|
return False
|
||||||
|
if context is None:
|
||||||
|
return True # Explicit recovery controls must still reach their retained clients.
|
||||||
|
from .session_record import _live_library_available
|
||||||
|
return all(_live_library_available(path) for path in (context.library, *context.aliases))
|
||||||
|
ticket = [object(), False]
|
||||||
acquired, notified = False, False
|
acquired, notified = False, False
|
||||||
previous_state = None
|
previous_state = None
|
||||||
with self.condition: self.pending.append((ticket, ready))
|
with self.condition:
|
||||||
|
if self.closed:
|
||||||
|
raise QueueCancelled('队列已关闭,未启动新的操作。')
|
||||||
|
if context is not None:
|
||||||
|
self.contexts[id(context)] = context
|
||||||
|
self.pending.append(ticket)
|
||||||
try:
|
try:
|
||||||
while not acquired:
|
while not acquired:
|
||||||
|
available = available_now() # Cached predicates only, outside the queue lock.
|
||||||
with self.condition:
|
with self.condition:
|
||||||
if stop is not None and stop.is_set():
|
if (self.closed or stop is not None and stop.is_set()
|
||||||
|
or context is not None and (context.stop.is_set() or context.stop_after_current.is_set())):
|
||||||
raise QueueCancelled('已取消排队,未启动原生操作。')
|
raise QueueCancelled('已取消排队,未启动原生操作。')
|
||||||
first = next((token for token, available in self.pending if available()), None)
|
ticket[1] = bool(available)
|
||||||
|
first = next((entry for entry in self.pending if entry[1]), None)
|
||||||
if not self.active and first is ticket:
|
if not self.active and first is ticket:
|
||||||
self.pending = [entry for entry in self.pending if entry[0] is not ticket]
|
|
||||||
self.active = acquired = True
|
self.active = acquired = True
|
||||||
else:
|
else:
|
||||||
self.condition.wait(.1)
|
self.condition.wait(.1)
|
||||||
|
if acquired and not available_now():
|
||||||
|
with self.condition:
|
||||||
|
ticket[1] = self.active = acquired = False
|
||||||
|
self.condition.notify_all()
|
||||||
if not acquired and waiting is not None:
|
if not acquired and waiting is not None:
|
||||||
try:
|
try:
|
||||||
current_state = wait_state() if wait_state is not None else None
|
current_state = wait_state() if wait_state is not None else None
|
||||||
@@ -39,11 +451,12 @@ class NativeQueue:
|
|||||||
notified, previous_state = True, current_state
|
notified, previous_state = True, current_state
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
if stop is not None and stop.is_set():
|
if (stop is not None and stop.is_set()
|
||||||
|
or context is not None and context.stop_after_current.is_set()):
|
||||||
raise QueueCancelled('已取消排队,未启动原生操作。')
|
raise QueueCancelled('已取消排队,未启动原生操作。')
|
||||||
return action()
|
return context.run(action, stop=stop, timeout_seconds=timeout_seconds) if context else action()
|
||||||
finally:
|
finally:
|
||||||
with self.condition:
|
with self.condition:
|
||||||
self.pending = [entry for entry in self.pending if entry[0] is not ticket]
|
self.pending = [entry for entry in self.pending if entry is not ticket]
|
||||||
if acquired: self.active = False
|
if acquired: self.active = False
|
||||||
self.condition.notify_all()
|
self.condition.notify_all()
|
||||||
@@ -18,14 +18,16 @@ class OpenChoice:
|
|||||||
def __init__(self, block, library):
|
def __init__(self, block, library):
|
||||||
self.block, self.library = block, library
|
self.block, self.library = block, library
|
||||||
self.decision = None
|
self.decision = None
|
||||||
|
self.decision_origin = None
|
||||||
self._lock = Lock()
|
self._lock = Lock()
|
||||||
|
|
||||||
def choose(self, decision):
|
def choose(self, decision, *, origin='user'):
|
||||||
if decision not in ('continue', 'skip', 'cancel'):
|
if decision not in ('continue', 'skip', 'cancel'):
|
||||||
raise ValueError('无效的打开工程选择')
|
raise ValueError('无效的打开工程选择')
|
||||||
with self._lock:
|
with self._lock:
|
||||||
if self.decision is None:
|
if self.decision is None:
|
||||||
self.decision = decision
|
self.decision = decision
|
||||||
|
self.decision_origin = origin
|
||||||
|
|
||||||
|
|
||||||
def validate_owner(job, target_pid, launcher_pid, worker_pid):
|
def validate_owner(job, target_pid, launcher_pid, worker_pid):
|
||||||
@@ -46,8 +48,14 @@ def validate_owner(job, target_pid, launcher_pid, worker_pid):
|
|||||||
|
|
||||||
@contextmanager
|
@contextmanager
|
||||||
def resource_guard(job, allowed_pids):
|
def resource_guard(job, allowed_pids):
|
||||||
import win32con, win32file
|
import hashlib
|
||||||
from .icdb_ownership import database_directories, unreleased_addresses
|
from .file_probe import hold_release_files
|
||||||
|
from .maintenance_entry import maintenance_project_files
|
||||||
|
from .native_repair import RepairTarget, run_native_repair
|
||||||
|
from .native_occupancy import confirmed_inspection
|
||||||
|
from .session_record import IDENTITY_KEYS
|
||||||
|
from .operation_queue import task_stop
|
||||||
|
from .management import _write_json
|
||||||
from .owner_probe import query_process_snapshot
|
from .owner_probe import query_process_snapshot
|
||||||
from .library_lock import _owner_is_blocking
|
from .library_lock import _owner_is_blocking
|
||||||
from .verify_runner import preflight, VerifyRequest
|
from .verify_runner import preflight, VerifyRequest
|
||||||
@@ -56,21 +64,48 @@ def resource_guard(job, allowed_pids):
|
|||||||
if project.resolve() != Path(job['project']).resolve() or pcb.resolve() != Path(job['pcb']).resolve():
|
if project.resolve() != Path(job['project']).resolve() or pcb.resolve() != Path(job['pcb']).resolve():
|
||||||
raise ValueError('PCB_OPEN_PROJECT_CHANGED')
|
raise ValueError('PCB_OPEN_PROJECT_CHANGED')
|
||||||
roots = (project.parent, library.parent/'SymbolLibs')
|
roots = (project.parent, library.parent/'SymbolLibs')
|
||||||
|
configs = maintenance_project_files(project, pcb)
|
||||||
|
def binding():
|
||||||
|
return {str(path.resolve()): hashlib.sha256(path.read_bytes()).hexdigest() for path in (pcb, *configs)}
|
||||||
|
original_binding = binding()
|
||||||
def check():
|
def check():
|
||||||
if unreleased_addresses(library, project, pcb):
|
|
||||||
raise ValueError('目标仍有数据库地址记录,暂不能确认读写打开。')
|
|
||||||
for row in query_process_snapshot():
|
for row in query_process_snapshot():
|
||||||
if row['pid'] not in allowed_pids and _owner_is_blocking(row, library, roots):
|
if row['pid'] not in allowed_pids and _owner_is_blocking(row, library, roots):
|
||||||
raise ValueError(f'目标还有其他会话,PID={row["pid"]};未确认读写打开。')
|
raise ValueError(f'目标还有其他会话,PID={row["pid"]};未确认读写打开。')
|
||||||
check()
|
check()
|
||||||
paths = [library, pcb.parent/'Layout/LayoutDB.lyt',
|
stop = task_stop(None)
|
||||||
*(d/'icdb.dat' for d in database_directories(library, project, pcb) if (d/'icdb.dat').is_file())]
|
|
||||||
with ExitStack() as stack:
|
with ExitStack() as stack:
|
||||||
for path in dict.fromkeys(paths):
|
files = stack.enter_context(hold_release_files(library, roots, stop=stop))
|
||||||
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
|
inspections = []
|
||||||
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
if files['addresses']:
|
||||||
stack.callback(handle.Close)
|
targets = files['inspection_targets']
|
||||||
|
if any(Path(item['project']).resolve() not in {p.resolve() for p in configs} for item in targets):
|
||||||
|
raise ValueError('PCB_OPEN_DATABASE_UNCONFIRMED: 地址未绑定实际工程配置,需人工核对')
|
||||||
|
stack.close() # Native inspection must access the DB; repeat exact proof afterwards.
|
||||||
|
for index, item in enumerate(targets):
|
||||||
|
target = RepairTarget(Path(item['project']), Path(item['database']))
|
||||||
|
evidence = Path(job['root'])/('open-inspection-'+str(index))
|
||||||
|
result = run_native_repair(target, evidence, mentor_bin=job.get('mentor_bin'),
|
||||||
|
timeout_seconds=min(45, float(job.get('timeout', 45))), inspection_only=True, stop=stop)
|
||||||
|
identity = result.get('native_identity') or {}
|
||||||
|
if (not confirmed_inspection(target, result) or result['status'] != 'NOT_IN_USE'
|
||||||
|
or identity.get('pid') != result.get('native_pid')
|
||||||
|
or any(identity.get(key) is None for key in IDENTITY_KEYS)
|
||||||
|
or not identity.get('image') or not identity.get('owner_sid')):
|
||||||
|
raise ValueError('PCB_OPEN_DATABASE_UNCONFIRMED: 原生检查未确认当前数据库未占用')
|
||||||
|
inspections.append(result)
|
||||||
|
current = stack.enter_context(hold_release_files(library, roots, stop=stop))
|
||||||
|
if any(current[key] != files[key] for key in (
|
||||||
|
'exclusive_files', 'binding_files', 'addresses', 'signatures', 'inspection_targets', 'resource_scope')):
|
||||||
|
raise ValueError('PCB_OPEN_RESOURCE_CHANGED: 原生检查期间资源或地址身份变化')
|
||||||
|
if binding() != original_binding:
|
||||||
|
raise ValueError('PCB_OPEN_PROJECT_CHANGED: 原生检查期间工程引用变化')
|
||||||
check()
|
check()
|
||||||
|
_write_json(Path(job['root'])/'pcb-open-resource-proof.json', {
|
||||||
|
'operation_id': job.get('operation_id'), 'library': str(library),
|
||||||
|
'project': str(project), 'pcb': str(pcb), 'binding': original_binding,
|
||||||
|
'exclusive_files': files['exclusive_files'], 'addresses': files['addresses'],
|
||||||
|
'native_inspections': inspections, 'repair_confirmed': False})
|
||||||
yield
|
yield
|
||||||
|
|
||||||
|
|
||||||
@@ -106,15 +141,22 @@ class OpenController:
|
|||||||
action = {'action': 'user_confirmed_pcb_open', 'channels': ['win32_button_click'],
|
action = {'action': 'user_confirmed_pcb_open', 'channels': ['win32_button_click'],
|
||||||
'target': {'control_id': control}, 'desktop': self.job['desktop'],
|
'target': {'control_id': control}, 'desktop': self.job['desktop'],
|
||||||
'pid': target_pid, 'owner': owner, 'choice': self.choice.decision}
|
'pid': target_pid, 'owner': owner, 'choice': self.choice.decision}
|
||||||
|
action['decision_origin'] = self.choice.decision_origin
|
||||||
def send():
|
def send():
|
||||||
self.sent, self.sent_at = True, time.monotonic()
|
|
||||||
_write_json(Path(self.job['root'])/'pcb-open-user-choice.json', dict(
|
_write_json(Path(self.job['root'])/'pcb-open-user-choice.json', dict(
|
||||||
choice=self.choice.decision, project=self.job['project'], pcb=self.job['pcb'],
|
choice=self.choice.decision, decision_origin=self.choice.decision_origin,
|
||||||
|
project=self.job['project'], pcb=self.job['pcb'],
|
||||||
library=self.job['lmc_file'], owner=owner, snapshot=snapshot.to_record()))
|
library=self.job['lmc_file'], owner=owner, snapshot=snapshot.to_record()))
|
||||||
|
self.sent, self.sent_at = True, time.monotonic()
|
||||||
return perform(snapshot, action, snapshot.phase)
|
return perform(snapshot, action, snapshot.phase)
|
||||||
if control == 6:
|
if control == 6:
|
||||||
allowed = {target_pid, launcher_pid, worker_pid, self.job.get('supervisor_pid')}
|
allowed = {target_pid, launcher_pid, worker_pid, self.job.get('supervisor_pid')}
|
||||||
with resource_guard(self.job, allowed):
|
with resource_guard(self.job, allowed):
|
||||||
|
pass
|
||||||
|
# Deliberate TOCTOU tradeoff: release probes before Yes so Mentor
|
||||||
|
# can acquire the files without a sharing violation; recheck identity.
|
||||||
|
if validate_owner(self.job, target_pid, launcher_pid, worker_pid) != owner:
|
||||||
|
raise ValueError('PCB_OPEN_IDENTITY_CHANGED')
|
||||||
result = send()
|
result = send()
|
||||||
else:
|
else:
|
||||||
result = send()
|
result = send()
|
||||||
@@ -123,8 +165,10 @@ class OpenController:
|
|||||||
error = 'PCB_OPEN_ANSWER_FAILED'
|
error = 'PCB_OPEN_ANSWER_FAILED'
|
||||||
if not error and control == 7:
|
if not error and control == 7:
|
||||||
error = 'PCB_OPEN_SKIPPED' if self.choice.decision == 'skip' else 'USER_CANCELLED'
|
error = 'PCB_OPEN_SKIPPED' if self.choice.decision == 'skip' else 'USER_CANCELLED'
|
||||||
|
skipped_detail = ('超时默认跳过本项。' if self.choice.decision_origin == 'timeout_default'
|
||||||
|
else '用户跳过本项。')
|
||||||
return DialogPollResult(activity=True, action_sent=True, snapshot=snapshot,
|
return DialogPollResult(activity=True, action_sent=True, snapshot=snapshot,
|
||||||
error_code=error, detail=result.detail or ('用户跳过本项。' if control == 7 else ''),
|
error_code=error, detail=result.detail or (skipped_detail if control == 7 else ''),
|
||||||
accepted_controls=result.accepted_controls, channel=result.channel,
|
accepted_controls=result.accepted_controls, channel=result.channel,
|
||||||
action=action['action'], observed_snapshots=tuple(snapshots))
|
action=action['action'], observed_snapshots=tuple(snapshots))
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
|
|||||||
@@ -13,14 +13,16 @@ class RestoreChoice:
|
|||||||
self.block, self.library = block, library
|
self.block, self.library = block, library
|
||||||
self.candidates = tuple(dict(c) for c in candidates)
|
self.candidates = tuple(dict(c) for c in candidates)
|
||||||
self.decision = None
|
self.decision = None
|
||||||
|
self.decision_origin = None
|
||||||
self._lock = Lock()
|
self._lock = Lock()
|
||||||
|
|
||||||
def choose(self, kind):
|
def choose(self, kind, *, origin='user'):
|
||||||
if kind != 'cancel' and not any(c['kind'] == kind and c['enabled'] for c in self.candidates):
|
if kind != 'cancel' and not any(c['kind'] == kind and c['enabled'] for c in self.candidates):
|
||||||
raise ValueError('Unknown or disabled PCB restoration version')
|
raise ValueError('Unknown or disabled PCB restoration version')
|
||||||
with self._lock:
|
with self._lock:
|
||||||
if self.decision is None:
|
if self.decision is None:
|
||||||
self.decision = kind
|
self.decision = kind
|
||||||
|
self.decision_origin = origin
|
||||||
|
|
||||||
|
|
||||||
def _candidate_key(candidates):
|
def _candidate_key(candidates):
|
||||||
@@ -82,7 +84,11 @@ class RestoreController:
|
|||||||
if self.prompt.decision is None:
|
if self.prompt.decision is None:
|
||||||
return DialogPollResult(activity=True, observed_snapshots=tuple(snapshots))
|
return DialogPollResult(activity=True, observed_snapshots=tuple(snapshots))
|
||||||
if self.prompt.decision == 'cancel':
|
if self.prompt.decision == 'cancel':
|
||||||
raise ValueError('用户取消 PCB 版本选择;未确认恢复,保留原生现场。')
|
_write_json(Path(self.job['root'])/'pcb-version-user-choice.json', dict(
|
||||||
|
project=self.job['project'], pcb=self.job['pcb'], choice='cancel',
|
||||||
|
decision_origin=self.prompt.decision_origin, snapshot=snapshot.to_record()))
|
||||||
|
reason = '超时默认取消' if self.prompt.decision_origin == 'timeout_default' else '用户取消'
|
||||||
|
raise ValueError(reason+' PCB 版本选择;未确认恢复,保留原生现场。')
|
||||||
selected = next(c for c in choice['candidates'] if c['kind'] == self.prompt.decision)
|
selected = next(c for c in choice['candidates'] if c['kind'] == self.prompt.decision)
|
||||||
if not selected['enabled']:
|
if not selected['enabled']:
|
||||||
raise ValueError('PCB_VERSION_DISABLED')
|
raise ValueError('PCB_VERSION_DISABLED')
|
||||||
@@ -99,12 +105,14 @@ class RestoreController:
|
|||||||
action = {'action': 'user_selected_pcb_version', 'channels': ['win32_button_click'],
|
action = {'action': 'user_selected_pcb_version', 'channels': ['win32_button_click'],
|
||||||
'target': {'control_id': control}, 'desktop': self.job['desktop'], 'pid': target_pid,
|
'target': {'control_id': control}, 'desktop': self.job['desktop'], 'pid': target_pid,
|
||||||
'choice': selected['kind'], 'candidates': list(self.prompt.candidates)}
|
'choice': selected['kind'], 'candidates': list(self.prompt.candidates)}
|
||||||
|
action['decision_origin'] = self.prompt.decision_origin
|
||||||
if self.owner is not None:
|
if self.owner is not None:
|
||||||
action['owner'] = self.owner
|
action['owner'] = self.owner
|
||||||
self.selection_sent = True
|
self.selection_sent = True
|
||||||
self.confirm_sent = confirming
|
self.confirm_sent = confirming
|
||||||
self.sent_at = time.monotonic()
|
self.sent_at = time.monotonic()
|
||||||
record = {'project': self.job['project'], 'pcb': self.job['pcb'], 'choice': selected['kind'],
|
record = {'project': self.job['project'], 'pcb': self.job['pcb'], 'choice': selected['kind'],
|
||||||
|
'decision_origin': self.prompt.decision_origin,
|
||||||
'date': selected['date'], 'historical_restore': True, 'confirm_sent': confirming,
|
'date': selected['date'], 'historical_restore': True, 'confirm_sent': confirming,
|
||||||
'snapshot': snapshot.to_record()}
|
'snapshot': snapshot.to_record()}
|
||||||
_write_json(Path(self.job['root'])/'pcb-version-user-choice.json', record)
|
_write_json(Path(self.job['root'])/'pcb-version-user-choice.json', record)
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ def offers_reimport(result):
|
|||||||
|
|
||||||
|
|
||||||
def run_reimport_recovery(requests, *, previous_evidence, evidence_dir,
|
def run_reimport_recovery(requests, *, previous_evidence, evidence_dir,
|
||||||
adapter=None, stop=None, progress=None):
|
adapter=None, stop=None, progress=None,version_prompt=None):
|
||||||
from .management import ManagementResult, _write_json, source_project, run_management_batch
|
from .management import ManagementResult, _write_json, source_project, run_management_batch
|
||||||
from .library_lock import release_retained_library
|
from .library_lock import release_retained_library
|
||||||
requests = tuple(requests)
|
requests = tuple(requests)
|
||||||
@@ -62,7 +62,8 @@ def run_reimport_recovery(requests, *, previous_evidence, evidence_dir,
|
|||||||
if cancelled(): return []
|
if cancelled(): return []
|
||||||
stage = 'management'
|
stage = 'management'
|
||||||
save(stage, management_started=True)
|
save(stage, management_started=True)
|
||||||
results = run_management_batch(requests, adapter=adapter, stop=stop, progress=progress)
|
results = run_management_batch(requests, adapter=adapter, stop=stop, progress=progress,
|
||||||
|
version_prompt=version_prompt)
|
||||||
save('complete', results=[asdict(result) for result in results],
|
save('complete', results=[asdict(result) for result in results],
|
||||||
version_review_required=True)
|
version_review_required=True)
|
||||||
return results
|
return results
|
||||||
|
|||||||
@@ -252,7 +252,7 @@ def _post_window_message(window, hwnd, pid, message):
|
|||||||
win32gui.PostMessage(hwnd, message, 0, 0)
|
win32gui.PostMessage(hwnd, message, 0, 0)
|
||||||
|
|
||||||
|
|
||||||
def _process_windows(pids):
|
def _process_windows(pids, *, include_hidden_documents=False):
|
||||||
result = _WindowSnapshot(pids)
|
result = _WindowSnapshot(pids)
|
||||||
if not pids: return result
|
if not pids: return result
|
||||||
import win32api, win32con, win32gui, win32process
|
import win32api, win32con, win32gui, win32process
|
||||||
@@ -271,10 +271,13 @@ def _process_windows(pids):
|
|||||||
kind = win32gui.GetClassName(handle)
|
kind = win32gui.GetClassName(handle)
|
||||||
if kind == 'MDIClient' and win32gui.GetWindow(handle, win32con.GW_CHILD):
|
if kind == 'MDIClient' and win32gui.GetWindow(handle, win32con.GW_CHILD):
|
||||||
documents.append(handle)
|
documents.append(handle)
|
||||||
if win32gui.IsWindowVisible(handle):
|
visible = bool(win32gui.IsWindowVisible(handle))
|
||||||
|
if visible or (include_hidden_documents and kind.casefold().startswith('afx:')
|
||||||
|
and win32gui.GetClassName(win32gui.GetParent(handle)) == 'MDIClient'):
|
||||||
children.append({'hwnd': int(handle), 'class': kind,
|
children.append({'hwnd': int(handle), 'class': kind,
|
||||||
'id': win32gui.GetDlgCtrlID(handle) & 0xffff,
|
'id': win32gui.GetDlgCtrlID(handle) & 0xffff,
|
||||||
'text': win32gui.GetWindowText(handle), 'enabled': bool(win32gui.IsWindowEnabled(handle))})
|
'text': win32gui.GetWindowText(handle), 'enabled': bool(win32gui.IsWindowEnabled(handle)),
|
||||||
|
'visible': visible})
|
||||||
win32api.SetLastError(0)
|
win32api.SetLastError(0)
|
||||||
win32gui.EnumChildWindows(hwnd, child, None)
|
win32gui.EnumChildWindows(hwnd, child, None)
|
||||||
window = {'hwnd': int(hwnd), 'title': win32gui.GetWindowText(hwnd),
|
window = {'hwnd': int(hwnd), 'title': win32gui.GetWindowText(hwnd),
|
||||||
@@ -482,6 +485,339 @@ def inspect_residual_sessions(library, *, block_names=()):
|
|||||||
'previous_records': previous}
|
'previous_records': previous}
|
||||||
|
|
||||||
|
|
||||||
|
def _hidden_tip_owner(tip, pid):
|
||||||
|
"""Read only the Tip's direct hidden frame, never arbitrary hidden windows."""
|
||||||
|
import win32api, win32con, win32gui, win32process
|
||||||
|
with _window_desktop(tip['desktop']) as desktop:
|
||||||
|
hwnd = win32gui.GetWindow(tip['hwnd'], win32con.GW_OWNER)
|
||||||
|
if (not hwnd or hwnd not in _desktop_windows(desktop)
|
||||||
|
or win32process.GetWindowThreadProcessId(hwnd)[1] != pid
|
||||||
|
or win32gui.IsWindowVisible(hwnd) or win32gui.IsWindowEnabled(hwnd)):
|
||||||
|
return None
|
||||||
|
kind, title = win32gui.GetClassName(hwnd), win32gui.GetWindowText(hwnd)
|
||||||
|
if not kind.startswith('Afx:') or title.strip() not in (
|
||||||
|
'Expedition PCB', 'Expedition PCB - Reusable Block'):
|
||||||
|
return None
|
||||||
|
children, documents = [], []
|
||||||
|
def child(control, _):
|
||||||
|
control_class = win32gui.GetClassName(control)
|
||||||
|
if control_class.casefold() == 'msctls_progress32':
|
||||||
|
children.append({'class': control_class})
|
||||||
|
if control_class == 'MDIClient' and win32gui.GetWindow(control, win32con.GW_CHILD):
|
||||||
|
documents.append(control)
|
||||||
|
win32api.SetLastError(0)
|
||||||
|
win32gui.EnumChildWindows(hwnd, child, None)
|
||||||
|
return dict(hwnd=hwnd, title=title, **{'class': kind}, desktop=tip['desktop'],
|
||||||
|
enabled=False, children=children, documents=documents)
|
||||||
|
|
||||||
|
|
||||||
|
def _dismiss_startup_tip(row, handle, windows, *, incomplete=None, dismissed=(), deadline=None, stop=None):
|
||||||
|
"""A non-writing startup Tip may finish an already pending normal close."""
|
||||||
|
import win32con, win32event, win32gui
|
||||||
|
from .failed_session import _startup_snapshot, _tip_target
|
||||||
|
if (incomplete or row.get('scope_confirmed') is not True
|
||||||
|
or row.get('name', '').casefold() != 'expeditionpcb.exe'
|
||||||
|
or row.get('runtime_phase') in ('NATIVE_CALL', 'CLOSING', 'UNCONFIRMED')
|
||||||
|
or native_activity(row['name'], windows)['status'] != 'IDLE'):
|
||||||
|
return None
|
||||||
|
desktops = {w.get('desktop', '') for w in windows}
|
||||||
|
if len(desktops) != 1 or not next(iter(desktops), '').startswith('CbbVerify_'):
|
||||||
|
return None
|
||||||
|
tips = [w for w in windows if w['class'] == '#32770' and w['title'] == 'Tip of the Day']
|
||||||
|
if len(tips) != 1 or tips[0]['hwnd'] in dismissed:
|
||||||
|
return None
|
||||||
|
tip = tips[0]
|
||||||
|
hidden_owner = None
|
||||||
|
if not any(w['class'].startswith('Afx:') for w in windows):
|
||||||
|
hidden_owner = _hidden_tip_owner(tip, row['pid'])
|
||||||
|
# A disabled empty frame is expected behind a modal Tip. No document,
|
||||||
|
# progress, other dialog, or arbitrary disabled application is admitted.
|
||||||
|
rest = [dict(w, enabled=True) if w['class'].startswith('Afx:') else w
|
||||||
|
for w in windows if w is not tip]
|
||||||
|
if hidden_owner is not None:
|
||||||
|
rest.append(dict(hidden_owner, enabled=True))
|
||||||
|
main, _ = close_target(row['name'], rest)
|
||||||
|
if (main is None or main.get('documents')
|
||||||
|
or row.get('startup_frame', main['hwnd']) != main['hwnd']
|
||||||
|
or main['title'].strip() not in (
|
||||||
|
'Expedition PCB', 'Expedition PCB - Reusable Block')):
|
||||||
|
return None
|
||||||
|
buttons = [c for c in tip['children'] if c['class'] == 'Button' and c.get('id') == 1
|
||||||
|
and c.get('enabled')]
|
||||||
|
if len(buttons) != 1 or not tip['enabled']:
|
||||||
|
return None
|
||||||
|
if row.get('library'):
|
||||||
|
from .session_record import active_write_records
|
||||||
|
if active_write_records(row['library']):
|
||||||
|
return None
|
||||||
|
with _window_desktop(tip['desktop'], write=True):
|
||||||
|
if win32gui.GetWindow(tip['hwnd'], win32con.GW_OWNER) != main['hwnd']:
|
||||||
|
return None
|
||||||
|
current = _startup_snapshot(tip['hwnd'], row['pid'])
|
||||||
|
target = _tip_target(current)
|
||||||
|
if (target is None or target.handle != buttons[0]['hwnd']
|
||||||
|
or current.title != tip['title'] or current.window_class != tip['class']):
|
||||||
|
return None
|
||||||
|
fresh = _process_windows({row['pid']})
|
||||||
|
if (_window_error(fresh, row['pid']) or fresh.get(row['pid']) != windows
|
||||||
|
or win32event.WaitForSingleObject(handle, 0) != win32con.WAIT_TIMEOUT
|
||||||
|
or _handle_identity(handle) != {k: row.get(k) for k in ('created_handle', 'image')}
|
||||||
|
or win32gui.GetWindow(tip['hwnd'], win32con.GW_OWNER) != main['hwnd']
|
||||||
|
or hidden_owner is not None and _hidden_tip_owner(tip, row['pid']) != hidden_owner
|
||||||
|
or _startup_snapshot(tip['hwnd'], row['pid']) != current):
|
||||||
|
return None
|
||||||
|
if (deadline is not None and time.monotonic() >= deadline
|
||||||
|
or stop is not None and stop.is_set()):
|
||||||
|
return None
|
||||||
|
_post_window_message(tip, target.handle, row['pid'], win32con.BM_CLICK)
|
||||||
|
return tip['hwnd']
|
||||||
|
|
||||||
|
|
||||||
|
def _cancelled_diagnostic_record(row):
|
||||||
|
"""Existing complete registration can authorize cleanup, never validation."""
|
||||||
|
import stat
|
||||||
|
import pywintypes, win32con, win32event
|
||||||
|
from .session_record import _session, IDENTITY_KEYS, active_write_records
|
||||||
|
from .failed_session import _command_args
|
||||||
|
if row.get('scope_confirmed') is not True or row.get('name', '').casefold() != 'expeditionpcb.exe':
|
||||||
|
return None
|
||||||
|
def same(a, b):
|
||||||
|
return os.path.normcase(os.path.abspath(str(a))) == os.path.normcase(os.path.abspath(str(b)))
|
||||||
|
def read(path, *, lines=False):
|
||||||
|
if path.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
|
||||||
|
raise ValueError('STARTUP_RECORD_REPARSE_POINT')
|
||||||
|
with path.open('rb') as stream:
|
||||||
|
data = stream.read(1024*1024+1)
|
||||||
|
if len(data) > 1024*1024:
|
||||||
|
raise ValueError('STARTUP_RECORD_TOO_LARGE')
|
||||||
|
return [json.loads(line) for line in data.splitlines()] if lines else json.loads(data)
|
||||||
|
matches = []
|
||||||
|
for record in row.get('session_records', ()):
|
||||||
|
try:
|
||||||
|
path = Path(record['path']); root = path.parent
|
||||||
|
session, state, identities = _session(path, root)
|
||||||
|
job, result = read(root/'request.json'), read(root/'result.json')
|
||||||
|
operation = session['operation_id']
|
||||||
|
scope = session.get('resource_scope', {})
|
||||||
|
if (record.get('operation_id') != operation or job.get('operation_id') != operation
|
||||||
|
or job.get('diagnostic_only') not in (True,False) or job.get('interactive_input') is not False
|
||||||
|
or job.get('operation') != 'verify' or session.get('operation') != 'verify'
|
||||||
|
or not all(same(value, row['library']) for value in (job['library'], job['lmc_file'], session['library']))
|
||||||
|
or not same(job['root'], root) or not same(job['session_record_path'], path)
|
||||||
|
or job.get('desktop') != session.get('desktop') or not job['desktop'].startswith('CbbVerify_')
|
||||||
|
or scope.get('scope_state') != 'DECLARED' or scope.get('operation_id') != operation
|
||||||
|
or not same(scope.get('library', ''), row['library'])
|
||||||
|
or scope.get('projects') != [job['project']]
|
||||||
|
or not Path(job['pcb']).is_relative_to(Path(job['project']).parent)
|
||||||
|
or not same(job['cancel_signal'], session['cancel_signal'])
|
||||||
|
or Path(job['cancel_signal']).parent != root or not Path(job['cancel_signal']).is_file()
|
||||||
|
or result.get('status') != 'CANCELLED' or result.get('error_stage') != 'PCB_STARTING'
|
||||||
|
or result.get('write_outcome', {}).get('save_state') != 'UNKNOWN'
|
||||||
|
or state.get('phase') != 'UNCONFIRMED' or (root/'save.log').exists()):
|
||||||
|
continue
|
||||||
|
native = [p for p in identities if p.get('role') == 'native' and p['pid'] == row['pid']]
|
||||||
|
workers = [p for p in identities if p.get('role') in ('worker', 'helper')]
|
||||||
|
if (len(native) != 1 or not workers
|
||||||
|
or any(native[0][k] != row.get(k) for k in IDENTITY_KEYS)
|
||||||
|
or any(p.get('role') not in ('worker','helper','native','supervisor') for p in identities)):
|
||||||
|
continue
|
||||||
|
for worker in workers:
|
||||||
|
try:
|
||||||
|
with _process_handle(worker['pid']) as held:
|
||||||
|
if win32event.WaitForSingleObject(held, 0) != win32con.WAIT_OBJECT_0:
|
||||||
|
raise ValueError('STARTUP_WORKER_STILL_ACTIVE')
|
||||||
|
except (OSError, pywintypes.error) as error:
|
||||||
|
if getattr(error, 'winerror', None) != 87:
|
||||||
|
raise
|
||||||
|
args = _command_args(row['command'])
|
||||||
|
if ('-reusablecircuit' not in [a.casefold() for a in args]
|
||||||
|
or not any(same(a, job['pcb']) for a in args[1:])):
|
||||||
|
continue
|
||||||
|
events = read(root/'events.jsonl', lines=True)
|
||||||
|
if (not any(e.get('stage') == 'pcb_worker_started' and e.get('pcb_pid') == row['pid'] for e in events)
|
||||||
|
or not any(e.get('stage') == 'pcb_baseline' and row['pid'] not in e.get('pids', []) for e in events)
|
||||||
|
or any(str(e.get('stage', '')).startswith(('save', 'integration', 'validate', 'failure_close'))
|
||||||
|
or e.get('stage') == 'diagnostic_complete' for e in events)):
|
||||||
|
continue
|
||||||
|
closes = [e for e in events if e.get('stage') in ('startup_close_requested', 'diagnostic_wm_close')]
|
||||||
|
if len(closes) > 1 or any(e.get('pcb_pid') != row['pid'] or not e.get('hwnd') for e in closes):
|
||||||
|
continue
|
||||||
|
if any(r.get('operation_id') != operation for r in active_write_records(row['library'])):
|
||||||
|
continue
|
||||||
|
if job.get('diagnostic_only') is False:
|
||||||
|
from .failed_session import cancelled_prewrite_startup
|
||||||
|
from .diagnostic_open import _load_evidence
|
||||||
|
baseline=cancelled_prewrite_startup(job,row['pid'])
|
||||||
|
if baseline is None or _load_evidence(job,row['pid'],baseline,require_autosave=False) is None:
|
||||||
|
continue
|
||||||
|
matches.append(dict(job=job, record_path=str(path), operation_id=operation,
|
||||||
|
closed_frame=closes[0]['hwnd'] if closes else None,
|
||||||
|
declined_buttons=[e['hwnd'] for e in events if e.get('stage')=='startup_prompt_no'
|
||||||
|
and e.get('pcb_pid')==row['pid'] and e.get('control_id')==7 and e.get('hwnd')],
|
||||||
|
dismissed_tips=[e['hwnd'] for e in events if e.get('stage')=='startup_tip_dismissed'
|
||||||
|
and e.get('pcb_pid')==row['pid'] and e.get('hwnd')]))
|
||||||
|
except (OSError, pywintypes.error, ValueError, KeyError, TypeError):
|
||||||
|
continue
|
||||||
|
return matches[0] if len(matches) == 1 else None
|
||||||
|
|
||||||
|
|
||||||
|
def _legacy_diagnostic_windows(row):
|
||||||
|
"""Adapt the existing complete private-desktop snapshot for diagnostic policy."""
|
||||||
|
import win32con, win32gui
|
||||||
|
snapshot = _process_windows({row['pid']}, include_hidden_documents=True)
|
||||||
|
if _window_error(snapshot, row['pid']):
|
||||||
|
raise ValueError('STARTUP_WINDOW_UNCONFIRMED')
|
||||||
|
result = []
|
||||||
|
for window in snapshot.get(row['pid'], []):
|
||||||
|
if window.get('desktop') != row['cleanup_desktop']:
|
||||||
|
raise ValueError('STARTUP_DESKTOP_UNCONFIRMED')
|
||||||
|
benign = (not window['title'] and window['class'] in ('UAC_InputIndicatorOverlayWnd', 'UAC Input Indicator'))
|
||||||
|
benign = benign or (window['class'] == 'Internet Explorer_Hidden' and not window['title']
|
||||||
|
and not window['children'] and window.get('rect', [1,1,2,2])[:2] == window.get('rect', [1,1,2,2])[2:])
|
||||||
|
if benign:
|
||||||
|
continue
|
||||||
|
with _window_desktop(window['desktop']):
|
||||||
|
children = [dict(c, parent=win32gui.GetParent(c['hwnd'])) for c in window['children']]
|
||||||
|
result.append(dict(hwnd=window['hwnd'], pid=row['pid'], **{'class':window['class']},
|
||||||
|
text=window['title'], enabled=window['enabled'], children=children,
|
||||||
|
owner=int(win32gui.GetWindow(window['hwnd'], win32con.GW_OWNER) or 0)))
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _close_registered_startup(row, handle, proof, *, stop=None, deadline=None):
|
||||||
|
import pywintypes, win32con, win32event
|
||||||
|
from .diagnostic_open import cancelled_startup_step
|
||||||
|
from .operation_queue import check_active
|
||||||
|
job = proof['job']; bound = dict(row, cleanup_desktop=job['desktop'])
|
||||||
|
if deadline is None:deadline = time.monotonic()+30
|
||||||
|
def active_owner():
|
||||||
|
check_active()
|
||||||
|
if stop is not None and stop.is_set():
|
||||||
|
return False
|
||||||
|
owner = _force_ownership(handle,row['pid'])
|
||||||
|
return (owner.get('force_user_confirmed') is True
|
||||||
|
and win32event.WaitForSingleObject(handle,0) == win32con.WAIT_TIMEOUT
|
||||||
|
and _handle_identity(handle) == {k:row.get(k) for k in ('created_handle','image')}
|
||||||
|
and all(owner.get(k) == row.get(k) for k in ('owner_sid','session_id')))
|
||||||
|
def confirmed():
|
||||||
|
if not active_owner():return False
|
||||||
|
fresh = next((p for p in query_process_snapshot() if p['pid'] == row['pid']), None)
|
||||||
|
return (fresh is not None and all(fresh.get(k) == row.get(k) for k in ('created','command','executable','name'))
|
||||||
|
and _cancelled_diagnostic_record(row) == proof)
|
||||||
|
def post(hwnd, message):
|
||||||
|
if not active_owner() or time.monotonic() >= deadline:
|
||||||
|
raise ValueError('STARTUP_ACTION_UNCONFIRMED')
|
||||||
|
_post_window_message({'desktop':job['desktop']}, hwnd, row['pid'], message)
|
||||||
|
state = {'clicked':set()}; closed = proof['closed_frame']; dismissed_tips = set(proof.get('dismissed_tips',()))
|
||||||
|
def read_bound_windows():
|
||||||
|
windows=_legacy_diagnostic_windows(bound)
|
||||||
|
for window in windows:
|
||||||
|
if any(c['hwnd'] in proof.get('declined_buttons',()) for c in window['children']):
|
||||||
|
state['clicked'].add(window['hwnd'])
|
||||||
|
return windows
|
||||||
|
try:
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
if win32event.WaitForSingleObject(handle, 0) == win32con.WAIT_OBJECT_0:
|
||||||
|
return {'release_status':'RELEASED','detail':'已正常结束已取消的诊断启动'}
|
||||||
|
if not active_owner():
|
||||||
|
break
|
||||||
|
snapshot = _process_windows({row['pid']})
|
||||||
|
# Only this fully proved no-write operation may bypass its historical
|
||||||
|
# UNCONFIRMED label; other operations were vetoed by the proof above.
|
||||||
|
tip_row = {k:v for k,v in row.items() if k not in ('runtime_phase','library')}
|
||||||
|
if closed is not None:
|
||||||
|
tip_row['startup_frame'] = closed
|
||||||
|
has_tip = any(w['title'] == 'Tip of the Day' for w in snapshot.get(row['pid'],[]))
|
||||||
|
tip = (_dismiss_startup_tip(tip_row,handle,snapshot.get(row['pid'],[]),
|
||||||
|
incomplete=_window_error(snapshot,row['pid']),dismissed=dismissed_tips,deadline=deadline,stop=stop)
|
||||||
|
if has_tip and confirmed() else None)
|
||||||
|
if tip is not None:
|
||||||
|
dismissed_tips.add(tip)
|
||||||
|
if closed is None:
|
||||||
|
continue # Tip may precede loading; the same intent still owns its one Close.
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
if win32event.WaitForSingleObject(handle,100) == win32con.WAIT_OBJECT_0:
|
||||||
|
return {'release_status':'RELEASED','detail':'已关闭启动提示并正常退出'}
|
||||||
|
if stop is not None and stop.is_set():break
|
||||||
|
break # Never stack another Close after a legacy Tip acknowledgement.
|
||||||
|
try:
|
||||||
|
closed,_ = cancelled_startup_step(job,row['pid'],state,closed_frame=closed,deadline=deadline,
|
||||||
|
post=post,emit=lambda **event:None,read_windows=read_bound_windows,
|
||||||
|
identity_check=confirmed)
|
||||||
|
except RuntimeError as error:
|
||||||
|
if not str(error).startswith('STARTUP_WINDOW_CHANGED:'):
|
||||||
|
raise
|
||||||
|
# No may remove a modal and enable the target while the next
|
||||||
|
# snapshot is being read. Revalidate anew inside the same budget.
|
||||||
|
time.sleep(.1)
|
||||||
|
except (OSError, pywintypes.error, ValueError, RuntimeError) as error:
|
||||||
|
return {'release_status':'WAITING','detail':str(error)}
|
||||||
|
return {'release_status':'WAITING','detail':'已请求取消启动清理,等待原生退出后重新检查'}
|
||||||
|
|
||||||
|
|
||||||
|
def _ordinary_startup_close(row, handle, proof, *, stop=None):
|
||||||
|
"""One persisted retained phase, serialized with existing explicit release."""
|
||||||
|
import win32con, win32event
|
||||||
|
from .session_record import read_session_record, write_session_record
|
||||||
|
from .operation_queue import native_phase
|
||||||
|
waiting = {'release_status':'WAITING','detail':'取消启动清理已交接或原生执行通道忙,继续观察'}
|
||||||
|
mutex=win32event.CreateMutex(None,False,r'Local\CbbRefreshVerify795')
|
||||||
|
acquired=False
|
||||||
|
try:
|
||||||
|
acquired=win32event.WaitForSingleObject(mutex,0) in (win32con.WAIT_OBJECT_0,win32con.WAIT_ABANDONED)
|
||||||
|
if not acquired or stop is not None and stop.is_set():return waiting
|
||||||
|
path=Path(proof['record_path'])
|
||||||
|
record=read_session_record(path,evidence_root=path.parent)
|
||||||
|
if 'retained_startup_cleanup' in record or _cancelled_diagnostic_record(row)!=proof:return waiting
|
||||||
|
# Complete loaded identity and every prompt are checked before consuming
|
||||||
|
# the one-shot intent. Unknown/multiple documents remain observation-only.
|
||||||
|
from .diagnostic_open import _target_frame, _pending_prompt
|
||||||
|
windows=_legacy_diagnostic_windows(dict(row,cleanup_desktop=proof['job']['desktop']))
|
||||||
|
frame=_target_frame(windows,Path(proof['job']['pcb']).stem,require_ready=False)
|
||||||
|
if frame is None:return waiting
|
||||||
|
for window in windows:
|
||||||
|
_pending_prompt([window],closing=proof['closed_frame'] is not None,frame=frame,
|
||||||
|
pcb_name=Path(proof['job']['pcb']).name)
|
||||||
|
if _cancelled_diagnostic_record(row)!=proof or stop is not None and stop.is_set():return waiting
|
||||||
|
deadline=time.monotonic()+30
|
||||||
|
record['retained_startup_cleanup']=dict(operation_id=proof['operation_id'],
|
||||||
|
pcb_pid=row['pid'],owner_pid=os.getpid(),state='CLAIMED',closed_frame=proof['closed_frame'],
|
||||||
|
deadline_monotonic=deadline,identity={k:row[k] for k in ('created_handle','image','owner_sid','session_id')})
|
||||||
|
write_session_record(path,record) # Durable before No/Close; never removed or retried.
|
||||||
|
with native_phase(read_only=True):
|
||||||
|
return _close_registered_startup(row,handle,proof,stop=stop,deadline=deadline)
|
||||||
|
except (OSError,ValueError,RuntimeError):
|
||||||
|
return waiting
|
||||||
|
finally:
|
||||||
|
if acquired:win32event.ReleaseMutex(mutex)
|
||||||
|
mutex.Close()
|
||||||
|
|
||||||
|
|
||||||
|
def resume_cancelled_startup(path, *, stop=None):
|
||||||
|
"""Observer-only entry for one late loaded, positively proved ordinary cancel."""
|
||||||
|
from .session_record import _session
|
||||||
|
from .failed_session import cancelled_prewrite_startup
|
||||||
|
path=Path(path)
|
||||||
|
try:
|
||||||
|
session,state,identities=_session(path,path.parent)
|
||||||
|
if 'retained_startup_cleanup' in session or stop is not None and stop.is_set():return False
|
||||||
|
job=json.loads(path.with_name('request.json').read_text(encoding='utf-8'))
|
||||||
|
if job.get('diagnostic_only') is not False:return False
|
||||||
|
native=[p for p in identities if p.get('role')=='native'
|
||||||
|
and Path(p['image']).name.casefold()=='expeditionpcb.exe']
|
||||||
|
if len(native)!=1 or cancelled_prewrite_startup(job,native[0]['pid']) is None:return False
|
||||||
|
plan=inspect_residual_sessions(session['library'],block_names=(session['block'],))
|
||||||
|
rows=[r for r in plan['sessions'] if r['pid']==native[0]['pid']]
|
||||||
|
if len(rows)!=1:return False
|
||||||
|
row=dict(rows[0],session_records=[dict(path=str(path),operation_id=session['operation_id'])])
|
||||||
|
proof=_cancelled_diagnostic_record(row)
|
||||||
|
if proof is None:return False # Includes exact worker/helper exit and fresh loaded logs.
|
||||||
|
_request_close(row,stop=stop)
|
||||||
|
return True
|
||||||
|
except (OSError,ValueError,KeyError,TypeError,RuntimeError):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def _request_close(row, *, stop=None):
|
def _request_close(row, *, stop=None):
|
||||||
import win32con, win32event
|
import win32con, win32event
|
||||||
with _process_handle(row['pid']) as handle:
|
with _process_handle(row['pid']) as handle:
|
||||||
@@ -494,6 +830,35 @@ def _request_close(row, *, stop=None):
|
|||||||
windows, error = snapshot.get(row['pid'], []), _window_error(snapshot, row['pid'])
|
windows, error = snapshot.get(row['pid'], []), _window_error(snapshot, row['pid'])
|
||||||
if error:
|
if error:
|
||||||
return {'release_status': 'WAITING', 'detail': '该会话窗口读取不完整,请重新检查:'+error}
|
return {'release_status': 'WAITING', 'detail': '该会话窗口读取不完整,请重新检查:'+error}
|
||||||
|
if stop is not None and stop.is_set():
|
||||||
|
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
|
||||||
|
if proof := _cancelled_diagnostic_record(row):
|
||||||
|
owner = _force_ownership(handle,row['pid'])
|
||||||
|
if (owner.get('force_user_confirmed') is not True
|
||||||
|
or any(owner.get(k) != row.get(k) for k in ('owner_sid','session_id'))):
|
||||||
|
return {'release_status':'WAITING','detail':'取消启动会话的用户或 Windows 会话未确认'}
|
||||||
|
if stop is not None and stop.is_set():
|
||||||
|
return {'release_status':'CANCELLED','detail':'已停止释放'}
|
||||||
|
from .session_record import handoff_session
|
||||||
|
record_path = Path(proof['record_path'])
|
||||||
|
handoff_session(record_path, evidence_root=record_path.parent, observe_only=False)
|
||||||
|
if proof['job'].get('diagnostic_only') is False:
|
||||||
|
return _ordinary_startup_close(row,handle,proof,stop=stop)
|
||||||
|
from .operation_queue import native_phase
|
||||||
|
# This confirmed no-write native cleanup has its own single bounded
|
||||||
|
# budget; metadata inactivity must not abandon it between No and Close.
|
||||||
|
with native_phase(read_only=True):
|
||||||
|
return _close_registered_startup(row, handle, proof, stop=stop)
|
||||||
|
if _dismiss_startup_tip(row, handle, windows, stop=stop) is not None:
|
||||||
|
# Legacy startup cleanup may already have sent WM_CLOSE. Only wait
|
||||||
|
# for it here; never stack another close behind this acknowledgement.
|
||||||
|
deadline = time.monotonic()+3
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
if win32event.WaitForSingleObject(handle, 100) == win32con.WAIT_OBJECT_0:
|
||||||
|
return {'release_status': 'RELEASED', 'detail': '已关闭启动提示并正常退出'}
|
||||||
|
if stop is not None and stop.is_set():
|
||||||
|
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
|
||||||
|
return {'release_status': 'WAITING', 'detail': '已关闭启动提示,等待原生退出后重新检查'}
|
||||||
if row['name'].casefold() == 'expeditionpcb.exe':
|
if row['name'].casefold() == 'expeditionpcb.exe':
|
||||||
from .failed_session import _startup_snapshot, _cancel_target
|
from .failed_session import _startup_snapshot, _cancel_target
|
||||||
for window in windows:
|
for window in windows:
|
||||||
@@ -560,9 +925,11 @@ def _force_close(row, *, stop=None):
|
|||||||
'detail': '已强制结束客户端,工程待检查,未执行修复' if exited else '已请求结束客户端,等待退出'}
|
'detail': '已强制结束客户端,工程待检查,未执行修复' if exited else '已请求结束客户端,等待退出'}
|
||||||
|
|
||||||
|
|
||||||
def _finish_library_release(library, evidence):
|
def _finish_library_release(library, evidence, block_names=(), stop=None):
|
||||||
from .library_lock import release_retained_library
|
from .library_lock import release_retained_library
|
||||||
return release_retained_library(library, evidence)
|
return release_retained_library(library, evidence,
|
||||||
|
block_name=block_names[0] if len(block_names) == 1 else None,
|
||||||
|
block_names=block_names, stop=stop)
|
||||||
|
|
||||||
|
|
||||||
def _request_native_cancel(row, *, stop=None):
|
def _request_native_cancel(row, *, stop=None):
|
||||||
@@ -622,6 +989,7 @@ def release_targets_complete(rows):
|
|||||||
|
|
||||||
|
|
||||||
def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, cancel_native=False):
|
def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, cancel_native=False):
|
||||||
|
from .operation_queue import note_metadata_progress
|
||||||
library = Path(plan['library']).resolve()
|
library = Path(plan['library']).resolve()
|
||||||
root = Path(evidence_dir).resolve()/('sessions-'+uuid4().hex[:12])
|
root = Path(evidence_dir).resolve()/('sessions-'+uuid4().hex[:12])
|
||||||
if root.is_relative_to(library.parent) or library.parent.is_relative_to(root):
|
if root.is_relative_to(library.parent) or library.parent.is_relative_to(root):
|
||||||
@@ -661,6 +1029,7 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca
|
|||||||
result['consent_path'] = str(consent_path)
|
result['consent_path'] = str(consent_path)
|
||||||
try:
|
try:
|
||||||
fresh = {r['pid']: r for r in query_process_snapshot()}
|
fresh = {r['pid']: r for r in query_process_snapshot()}
|
||||||
|
note_metadata_progress()
|
||||||
blocks = plan.get('block_names', ())
|
blocks = plan.get('block_names', ())
|
||||||
roots = (tuple(library.parent/'ReusableBlocksLP'/b/'Work' for b in blocks)
|
roots = (tuple(library.parent/'ReusableBlocksLP'/b/'Work' for b in blocks)
|
||||||
+ (library.parent/'SymbolLibs',)) if blocks else (library.parent,)
|
+ (library.parent/'SymbolLibs',)) if blocks else (library.parent,)
|
||||||
@@ -691,6 +1060,9 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca
|
|||||||
if not save():
|
if not save():
|
||||||
return result
|
return result
|
||||||
try:
|
try:
|
||||||
|
if not force and not cancel_native:
|
||||||
|
row['session_records'] = [{k:r.get(k) for k in ('path','operation_id')}
|
||||||
|
for r in plan.get('runtime_sessions', []) if r.get('path')]
|
||||||
outcome = (_request_native_cancel(row, stop=stop) if cancel_native else
|
outcome = (_request_native_cancel(row, stop=stop) if cancel_native else
|
||||||
(_force_close if force else _request_close)(row, stop=stop))
|
(_force_close if force else _request_close)(row, stop=stop))
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
@@ -698,7 +1070,9 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca
|
|||||||
row.update(outcome)
|
row.update(outcome)
|
||||||
if not save():
|
if not save():
|
||||||
return result # Preserve completed facts; stop further actions on storage failure.
|
return result # Preserve completed facts; stop further actions on storage failure.
|
||||||
|
note_metadata_progress()
|
||||||
after = {r['pid']: r for r in query_process_snapshot()}
|
after = {r['pid']: r for r in query_process_snapshot()}
|
||||||
|
note_metadata_progress()
|
||||||
remaining_windows = _process_windows({r['pid'] for r in result['sessions']
|
remaining_windows = _process_windows({r['pid'] for r in result['sessions']
|
||||||
if r['release_status'] == 'WAITING' and r['pid'] in after})
|
if r['release_status'] == 'WAITING' and r['pid'] in after})
|
||||||
for row in result['sessions']:
|
for row in result['sessions']:
|
||||||
@@ -713,7 +1087,8 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca
|
|||||||
if row.get('force_user_confirmed') is True else None),
|
if row.get('force_user_confirmed') is True else None),
|
||||||
native_activity=native_activity(row['name'], windows, incomplete=error))
|
native_activity=native_activity(row['name'], windows, incomplete=error))
|
||||||
if release_targets_complete(result['sessions']) and not (stop and stop.is_set()):
|
if release_targets_complete(result['sessions']) and not (stop and stop.is_set()):
|
||||||
result['proof'] = _finish_library_release(library, root/'library-proof')
|
result['proof'] = _finish_library_release(library, root/'library-proof',
|
||||||
|
blocks, stop)
|
||||||
proof = result['proof']
|
proof = result['proof']
|
||||||
if (proof.get('status') != 'RELEASE_CONFIRMED'
|
if (proof.get('status') != 'RELEASE_CONFIRMED'
|
||||||
or Path(proof.get('library', '')).resolve() != library):
|
or Path(proof.get('library', '')).resolve() != library):
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ Unknown engineering files are primary. Only explicit runtime, history and
|
|||||||
generated categories are ignored by semantic comparisons; they are still copied
|
generated categories are ignored by semantic comparisons; they are still copied
|
||||||
and their membership/size/mtime must remain stable throughout the snapshot.
|
and their membership/size/mtime must remain stable throughout the snapshot.
|
||||||
"""
|
"""
|
||||||
from concurrent.futures import ThreadPoolExecutor
|
|
||||||
from contextlib import ExitStack
|
from contextlib import ExitStack
|
||||||
from dataclasses import asdict, dataclass
|
from dataclasses import asdict, dataclass
|
||||||
import hashlib
|
import hashlib
|
||||||
@@ -12,6 +11,7 @@ import os
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import shutil
|
import shutil
|
||||||
import stat
|
import stat
|
||||||
|
from .operation_queue import note_metadata_progress
|
||||||
|
|
||||||
|
|
||||||
MANIFEST_VERSION = 1
|
MANIFEST_VERSION = 1
|
||||||
@@ -207,6 +207,7 @@ def scan_tree(root, *, scope=None, exclude=None, check=None):
|
|||||||
if not (stat.S_ISDIR(metadata.st_mode) or stat.S_ISREG(metadata.st_mode)):
|
if not (stat.S_ISDIR(metadata.st_mode) or stat.S_ISREG(metadata.st_mode)):
|
||||||
raise ValueError(f'不支持的特殊文件:{entry.path}')
|
raise ValueError(f'不支持的特殊文件:{entry.path}')
|
||||||
entries[path] = metadata
|
entries[path] = metadata
|
||||||
|
note_metadata_progress()
|
||||||
if stat.S_ISDIR(metadata.st_mode):
|
if stat.S_ISDIR(metadata.st_mode):
|
||||||
folders.append(path)
|
folders.append(path)
|
||||||
return dict(sorted(entries.items()))
|
return dict(sorted(entries.items()))
|
||||||
@@ -250,8 +251,9 @@ def build_manifest(root, *, scope=None, exclude=None, progress=None, hash_functi
|
|||||||
files = {}
|
files = {}
|
||||||
hashed_bytes = 0
|
hashed_bytes = 0
|
||||||
_emit(progress, 'hash', 0, 0, total_files=len(selected))
|
_emit(progress, 'hash', 0, 0, total_files=len(selected))
|
||||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
# Stay on the bounded task thread: executor workers are joined at interpreter exit.
|
||||||
for count, (relative, item) in enumerate(pool.map(hashed, selected), 1):
|
for count, (relative, item) in enumerate(map(hashed, selected), 1):
|
||||||
|
note_metadata_progress()
|
||||||
files[relative] = item
|
files[relative] = item
|
||||||
hashed_bytes += item['size']
|
hashed_bytes += item['size']
|
||||||
if count % 256 == 0 or count == len(selected):
|
if count % 256 == 0 or count == len(selected):
|
||||||
@@ -285,6 +287,7 @@ def build_exclusive_library_manifest(root, *, scope, progress=None):
|
|||||||
raise OSError(f'LIBRARY_DATABASE_IN_USE: 无法独占读取 {path}:{error}') from error
|
raise OSError(f'LIBRARY_DATABASE_IN_USE: 无法独占读取 {path}:{error}') from error
|
||||||
handles[path] = handle
|
handles[path] = handle
|
||||||
stack.callback(handle.Close)
|
stack.callback(handle.Close)
|
||||||
|
note_metadata_progress()
|
||||||
|
|
||||||
def digest(path):
|
def digest(path):
|
||||||
if path not in handles:
|
if path not in handles:
|
||||||
@@ -328,7 +331,7 @@ def copy_verified(source, destination, *, scope=None, progress=None, hash_functi
|
|||||||
destination.mkdir(parents=True, exist_ok=False)
|
destination.mkdir(parents=True, exist_ok=False)
|
||||||
files = [path for path, info in entries.items() if stat.S_ISREG(info.st_mode)]
|
files = [path for path, info in entries.items() if stat.S_ISREG(info.st_mode)]
|
||||||
from .library_lock import owned_snapshot
|
from .library_lock import owned_snapshot
|
||||||
# Resolve ownership on the operation thread, before parallel copy workers.
|
# Resolve ownership on the operation thread before copying.
|
||||||
owned = {path: data for path in files
|
owned = {path: data for path in files
|
||||||
if path.name.endswith('.cbb-upload.lock')
|
if path.name.endswith('.cbb-upload.lock')
|
||||||
and (data := owned_snapshot(path)) is not None}
|
and (data := owned_snapshot(path)) is not None}
|
||||||
@@ -386,8 +389,8 @@ def copy_verified(source, destination, *, scope=None, progress=None, hash_functi
|
|||||||
raise OSError(f'复制期间文件变化:{path}')
|
raise OSError(f'复制期间文件变化:{path}')
|
||||||
return relative.as_posix(), digest, label
|
return relative.as_posix(), digest, label
|
||||||
|
|
||||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
for count, (relative, digest, label) in enumerate(map(copy_file, files), 1):
|
||||||
for count, (relative, digest, label) in enumerate(pool.map(copy_file, files), 1):
|
note_metadata_progress()
|
||||||
if label is not None:
|
if label is not None:
|
||||||
size = entries[source/relative].st_size
|
size = entries[source/relative].st_size
|
||||||
record[relative] = {'size': size, 'sha256': digest, 'scope': label}
|
record[relative] = {'size': size, 'sha256': digest, 'scope': label}
|
||||||
@@ -404,8 +407,9 @@ def copy_verified(source, destination, *, scope=None, progress=None, hash_functi
|
|||||||
raise OSError(f'复制期间主要文件内容变化:{path}')
|
raise OSError(f'复制期间主要文件内容变化:{path}')
|
||||||
if hash_function(destination/relative) != item['sha256']:
|
if hash_function(destination/relative) != item['sha256']:
|
||||||
raise OSError(f'复制内容校验失败:{path}')
|
raise OSError(f'复制内容校验失败:{path}')
|
||||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
for relative in record:
|
||||||
list(pool.map(validate_bytes, record))
|
validate_bytes(relative)
|
||||||
|
note_metadata_progress()
|
||||||
if _metadata_record(source, scan_tree(source)) != expected_metadata:
|
if _metadata_record(source, scan_tree(source)) != expected_metadata:
|
||||||
raise OSError(f'复制期间目录内容变化:{source}')
|
raise OSError(f'复制期间目录内容变化:{source}')
|
||||||
if _metadata_record(destination, scan_tree(destination)) != expected_metadata:
|
if _metadata_record(destination, scan_tree(destination)) != expected_metadata:
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
"""Bounded, observation-only journal for native calls that outlive a task."""
|
"""Bounded registration and observation for native calls that outlive a task."""
|
||||||
from contextlib import ExitStack
|
from contextlib import ExitStack
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
import json
|
import json
|
||||||
@@ -22,13 +22,30 @@ def _library_key(library):
|
|||||||
return os.path.normcase(os.path.normpath(str(library)))
|
return os.path.normcase(os.path.normpath(str(library)))
|
||||||
|
|
||||||
|
|
||||||
def library_available(library):
|
def library_available(library, *, live_only=False):
|
||||||
"""Cached queue predicate: no file, process or network queries."""
|
"""Cached queue predicate: no file, process or network queries."""
|
||||||
|
if live_only:
|
||||||
|
return _live_library_available(library)
|
||||||
key = _library_key(library)
|
key = _library_key(library)
|
||||||
with _observer_guard:
|
with _observer_guard:
|
||||||
return not any(key in aliases for aliases in _retained_libraries.values())
|
return not any(key in aliases for aliases in _retained_libraries.values())
|
||||||
|
|
||||||
|
|
||||||
|
def _live_library_available(library):
|
||||||
|
"""Ignore stale retention, but wait for an actual registered observer."""
|
||||||
|
key = _library_key(library)
|
||||||
|
with _observer_guard:
|
||||||
|
for path, aliases in _retained_libraries.items():
|
||||||
|
observer = _observers.get(path)
|
||||||
|
if key not in aliases or observer is None or not observer[0].is_alive():
|
||||||
|
continue
|
||||||
|
state = _retained_results.get(path, {})
|
||||||
|
if (state.get('observer_initializing') is True or state.get('status') == 'ACTIVE'
|
||||||
|
or state.get('owned_worker_alive') is True):
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
def retained_session_snapshot(library):
|
def retained_session_snapshot(library):
|
||||||
key = _library_key(library)
|
key = _library_key(library)
|
||||||
with _observer_guard:
|
with _observer_guard:
|
||||||
@@ -67,6 +84,25 @@ def acknowledge_library_release(proof, snapshot, *, block_name=None):
|
|||||||
_retained_results.pop(path, None)
|
_retained_results.pop(path, None)
|
||||||
|
|
||||||
|
|
||||||
|
def _proof_covers_session(proof, session):
|
||||||
|
"""A receipt may acknowledge only resources actually covered by its proof."""
|
||||||
|
scope = proof.get('resource_scope')
|
||||||
|
library = session.get('library')
|
||||||
|
if (proof.get('status') != 'RELEASE_CONFIRMED' or proof.get('lease_state') != 'RELEASED'
|
||||||
|
or not isinstance(scope, dict) or scope.get('scope_state') != 'OBSERVED'
|
||||||
|
or not library or _library_key(proof.get('library', '')) != _library_key(library)
|
||||||
|
or _library_key(scope.get('library', '')) != _library_key(library)):
|
||||||
|
return False
|
||||||
|
if proof.get('proof_scope') == 'LIBRARY':
|
||||||
|
return not scope.get('block_names') and not proof.get('proof_block_names')
|
||||||
|
blocks = proof.get('proof_block_names')
|
||||||
|
observed = scope.get('block_names')
|
||||||
|
if (proof.get('proof_scope') not in ('BLOCK', 'BLOCKS') or not isinstance(blocks, list)
|
||||||
|
or not blocks or not isinstance(observed, list) or blocks != observed):
|
||||||
|
return False
|
||||||
|
return bool(session.get('block') and session['block'] in blocks)
|
||||||
|
|
||||||
|
|
||||||
def record_session_release(proof, records):
|
def record_session_release(proof, records):
|
||||||
"""Persist a past proof only for the pre-proof operation, never replay it."""
|
"""Persist a past proof only for the pre-proof operation, never replay it."""
|
||||||
errors = []
|
errors = []
|
||||||
@@ -78,7 +114,8 @@ def record_session_release(proof, records):
|
|||||||
path = Path(record['path'])
|
path = Path(record['path'])
|
||||||
session = read_session_record(path, evidence_root=path.parent)
|
session = read_session_record(path, evidence_root=path.parent)
|
||||||
if (session['operation_id'] != record.get('operation_id')
|
if (session['operation_id'] != record.get('operation_id')
|
||||||
or Path(session['library']).resolve() != library):
|
or Path(session['library']).resolve() != library
|
||||||
|
or not _proof_covers_session(proof, session)):
|
||||||
continue
|
continue
|
||||||
write_session_record(path.with_name('observation-release-'+uuid4().hex+'.json'), {
|
write_session_record(path.with_name('observation-release-'+uuid4().hex+'.json'), {
|
||||||
'operation_id': session['operation_id'], 'library': str(library),
|
'operation_id': session['operation_id'], 'library': str(library),
|
||||||
@@ -108,14 +145,47 @@ def library_wait_reason(library):
|
|||||||
def register_worker_session(worker, job):
|
def register_worker_session(worker, job):
|
||||||
"""The launcher must persist identity before opening the worker's gate."""
|
"""The launcher must persist identity before opening the worker's gate."""
|
||||||
path = Path(job['session_record_path'])
|
path = Path(job['session_record_path'])
|
||||||
write_session_record(path, {k: job.get(k) for k in (
|
from .operation_queue import check_worker_admission, current_context, bind_supervised_worker
|
||||||
'operation_id', 'operation', 'library', 'block', 'desktop', 'cancel_signal')}
|
check_worker_admission(job)
|
||||||
| {'processes': [{'role': 'worker', **process_identity(worker.pid)}]})
|
context = current_context()
|
||||||
|
protection = ('duplicated_lease' if job.get('worker_lease_handle') else
|
||||||
|
'worker_owned_lease' if job.get('operation') == 'native_backup' else
|
||||||
|
'inspection_only' if job.get('inspection_only') is True else
|
||||||
|
'catalog_readonly' if job.get('worker_role') == 'catalog_readonly'
|
||||||
|
and job.get('operation') == 'catalog' else None)
|
||||||
|
if context is not None and context.native_policy == 'external':
|
||||||
|
if protection is None or worker.pid == os.getpid():
|
||||||
|
raise RuntimeError('WORKER_OWNERSHIP_REQUIRED: 原生写入未登记独立进程和租约。')
|
||||||
|
from .icdb_ownership import session_resource_scope
|
||||||
|
record = ({k: job.get(k) for k in (
|
||||||
|
'operation_id', 'operation', 'library', 'block', 'desktop', 'cancel_signal', 'worker_lease_handle',
|
||||||
|
'worker_role', 'start_gate_protocol', 'start_gate')}
|
||||||
|
| {'processes': [{'role': 'worker', **process_identity(worker.pid)}],
|
||||||
|
'lease_state': 'ACTIVE', 'resource_scope': session_resource_scope(job),
|
||||||
|
'worker_protection': protection, 'task_operation_id': context.operation_id if context else None,
|
||||||
|
'blocked_resources': [], 'data_recovery_required': None})
|
||||||
|
if job.get('start_gate_protocol') == 'event-v1':
|
||||||
|
import win32api, win32con, win32event
|
||||||
|
event = win32event.CreateEvent(None, True, False, None)
|
||||||
|
process = getattr(worker, 'handle', None) or getattr(worker, '_handle', None)
|
||||||
|
if process is None:
|
||||||
|
raise RuntimeError('WORKER_ADMISSION_UNCONFIRMED: 缺少工作进程句柄。')
|
||||||
|
# Use the launch handle, never a reopened PID. The child's event survives
|
||||||
|
# supervisor exit even before Python startup or journal reads finish.
|
||||||
|
remote = win32api.DuplicateHandle(win32api.GetCurrentProcess(), event,
|
||||||
|
process, 0, False, win32con.DUPLICATE_SAME_ACCESS)
|
||||||
|
record['worker_start_handle'] = remote.Detach()
|
||||||
|
worker._start_event = event
|
||||||
|
worker._start_binding = (str(path), job['operation_id'], job['start_gate'])
|
||||||
|
write_session_record(path, record)
|
||||||
|
bind_supervised_worker(path, record)
|
||||||
worker.session_record_path = path
|
worker.session_record_path = path
|
||||||
worker.cbb_library = job['library']
|
worker.cbb_library = job['library']
|
||||||
|
check_worker_admission(job) # A slow registration must not open a gate after UI shutdown.
|
||||||
|
|
||||||
|
|
||||||
def update_worker_state(job, phase, *, identities=(), write_outcome=None, required=False, continuation=False):
|
def update_worker_state(job, phase, *, identities=(), observed_identities=(), write_outcome=None,
|
||||||
|
required=False, continuation=False):
|
||||||
"""required controls I/O; only existing same-phase calls may continue recording after supervisor loss."""
|
"""required controls I/O; only existing same-phase calls may continue recording after supervisor loss."""
|
||||||
if not job.get('session_record_path'):
|
if not job.get('session_record_path'):
|
||||||
if required:
|
if required:
|
||||||
@@ -132,6 +202,12 @@ def update_worker_state(job, phase, *, identities=(), write_outcome=None, requir
|
|||||||
for role, pid in identities:
|
for role, pid in identities:
|
||||||
if pid and not any(p['pid'] == pid for p in state['processes']):
|
if pid and not any(p['pid'] == pid for p in state['processes']):
|
||||||
state['processes'].append({'role': role, **process_identity(pid)})
|
state['processes'].append({'role': role, **process_identity(pid)})
|
||||||
|
# Callers supply these only after validating an open handle's exact
|
||||||
|
# job membership; do not reopen a snapshot PID during publication.
|
||||||
|
for role, identity in observed_identities:
|
||||||
|
bound = {key: identity[key] for key in IDENTITY_KEYS}
|
||||||
|
if not any(all(p.get(key) == value for key, value in bound.items()) for p in state['processes']):
|
||||||
|
state['processes'].append({'role': role, **bound})
|
||||||
state['phase'] = phase
|
state['phase'] = phase
|
||||||
if write_outcome is not None:
|
if write_outcome is not None:
|
||||||
state['write_outcome'] = write_outcome
|
state['write_outcome'] = write_outcome
|
||||||
@@ -230,7 +306,13 @@ def _result(status, detail='', *, session=None, state=None, proof=None):
|
|||||||
return {'status': status, 'detail': detail, 'library': (session or {}).get('library'),
|
return {'status': status, 'detail': detail, 'library': (session or {}).get('library'),
|
||||||
'block': (session or {}).get('block'),
|
'block': (session or {}).get('block'),
|
||||||
'operation_id': (session or {}).get('operation_id'),
|
'operation_id': (session or {}).get('operation_id'),
|
||||||
'phase': (state or {}).get('phase', 'UNCONFIRMED'), 'release_proof': proof}
|
'phase': (state or {}).get('phase', 'UNCONFIRMED'), 'release_proof': proof,
|
||||||
|
'lease_state': (proof or {}).get('lease_state', 'ACTIVE' if status == 'ACTIVE' else 'UNCONFIRMED'),
|
||||||
|
'resource_scope': (proof or {}).get('resource_scope') or (session or {}).get('resource_scope')
|
||||||
|
or {'scope_state': 'RECHECK_REQUIRED'},
|
||||||
|
'blocked_resources': (proof or {}).get('blocked_resources', (session or {}).get('blocked_resources', [])),
|
||||||
|
'data_recovery_required': (proof or {}).get('data_recovery_required',
|
||||||
|
(session or {}).get('data_recovery_required'))}
|
||||||
|
|
||||||
|
|
||||||
def _reconcile(path, root, handles, stack, *, release=True):
|
def _reconcile(path, root, handles, stack, *, release=True):
|
||||||
@@ -305,15 +387,17 @@ def inspect_session_record(path, *, evidence_root):
|
|||||||
def observe_retained_session(path, *, evidence_root, stop=None, progress=None, process=None,
|
def observe_retained_session(path, *, evidence_root, stop=None, progress=None, process=None,
|
||||||
observe_only=False):
|
observe_only=False):
|
||||||
stop = stop if stop is not None else threading.Event()
|
stop = stop if stop is not None else threading.Event()
|
||||||
|
read_only = observe_only if callable(observe_only) else lambda: observe_only
|
||||||
observation = Path(path).with_name('observation-' + uuid4().hex + '.json')
|
observation = Path(path).with_name('observation-' + uuid4().hex + '.json')
|
||||||
with ExitStack() as stack:
|
with ExitStack() as stack:
|
||||||
handles = {}
|
handles = {}
|
||||||
while True:
|
while True:
|
||||||
|
observation_only = read_only()
|
||||||
try:
|
try:
|
||||||
result = _reconcile(Path(path), Path(evidence_root), handles, stack, release=not observe_only)
|
result = _reconcile(Path(path), Path(evidence_root), handles, stack, release=not observation_only)
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
result = _result('UNCONFIRMED', str(error))
|
result = _result('UNCONFIRMED', str(error))
|
||||||
if (not observe_only and process is not None and process.poll() is not None
|
if (not observation_only and process is not None and process.poll() is not None
|
||||||
and getattr(process, 'cbb_library', None)):
|
and getattr(process, 'cbb_library', None)):
|
||||||
try:
|
try:
|
||||||
from .library_lock import release_retained_library
|
from .library_lock import release_retained_library
|
||||||
@@ -323,7 +407,16 @@ def observe_retained_session(path, *, evidence_root, stop=None, progress=None, p
|
|||||||
session={'library': str(process.cbb_library)}, proof=proof)
|
session={'library': str(process.cbb_library)}, proof=proof)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
if result['status'] == 'IDENTITY_CHANGED' and not observe_only:
|
if result['status'] == 'ACTIVE' and not observation_only and not stop.is_set():
|
||||||
|
try:
|
||||||
|
from .residual_sessions import resume_cancelled_startup
|
||||||
|
if resume_cancelled_startup(path, stop=stop):
|
||||||
|
# Cleanup is not release proof. Re-read all held identities
|
||||||
|
# and independently prove the resource release as usual.
|
||||||
|
result = _reconcile(Path(path), Path(evidence_root), handles, stack)
|
||||||
|
except Exception:
|
||||||
|
logging.getLogger(__name__).warning('Retained startup cleanup unavailable', exc_info=True)
|
||||||
|
if result['status'] == 'IDENTITY_CHANGED' and not observation_only:
|
||||||
try:
|
try:
|
||||||
from .library_lock import release_retained_library
|
from .library_lock import release_retained_library
|
||||||
proof = release_retained_library(result['library'], Path(path).parent/'release-proof')
|
proof = release_retained_library(result['library'], Path(path).parent/'release-proof')
|
||||||
@@ -331,6 +424,10 @@ def observe_retained_session(path, *, evidence_root, stop=None, progress=None, p
|
|||||||
result = {**result, 'status': 'RELEASED', 'identity_changed': True, 'release_proof': proof}
|
result = {**result, 'status': 'RELEASED', 'identity_changed': True, 'release_proof': proof}
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
result['detail'] += f';资源释放待确认:{error}'
|
result['detail'] += f';资源释放待确认:{error}'
|
||||||
|
try:
|
||||||
|
result['owned_worker_alive'] = process is not None and process.poll() is None
|
||||||
|
except Exception:
|
||||||
|
result['owned_worker_alive'] = False
|
||||||
try:
|
try:
|
||||||
write_session_record(observation, {**result, 'operation_id': result['operation_id'] or 'unknown'})
|
write_session_record(observation, {**result, 'operation_id': result['operation_id'] or 'unknown'})
|
||||||
except (OSError, ValueError):
|
except (OSError, ValueError):
|
||||||
@@ -341,7 +438,7 @@ def observe_retained_session(path, *, evidence_root, stop=None, progress=None, p
|
|||||||
except Exception:
|
except Exception:
|
||||||
logging.getLogger(__name__).warning('Observation callback failed', exc_info=True)
|
logging.getLogger(__name__).warning('Observation callback failed', exc_info=True)
|
||||||
if (result['status'] == 'RELEASED' or stop.is_set()
|
if (result['status'] == 'RELEASED' or stop.is_set()
|
||||||
or observe_only and result['status'] != 'ACTIVE'):
|
or read_only() and result['status'] != 'ACTIVE'):
|
||||||
return result
|
return result
|
||||||
if not handles and process is not None and process.poll() is None:
|
if not handles and process is not None and process.poll() is None:
|
||||||
stop.wait(1)
|
stop.wait(1)
|
||||||
@@ -363,33 +460,49 @@ def handoff_session(path, *, evidence_root, process=None, progress=None, stop=No
|
|||||||
aliases = {_library_key(library), _library_key(Path(library).resolve())} if library else set()
|
aliases = {_library_key(library), _library_key(Path(library).resolve())} if library else set()
|
||||||
with _observer_guard:
|
with _observer_guard:
|
||||||
if key in _observers:
|
if key in _observers:
|
||||||
|
if (observe_only is False and session.get('operation_id')
|
||||||
|
and _retained_results.get(key, {}).get('operation_id') == session['operation_id']):
|
||||||
|
_retained_results[key]['release_operation_id'] = session['operation_id']
|
||||||
return
|
return
|
||||||
_retained_libraries[key] = aliases
|
_retained_libraries[key] = aliases
|
||||||
_retained_results[key] = {'status': 'UNCONFIRMED', 'phase': 'UNCONFIRMED',
|
_retained_results[key] = {'status': 'UNCONFIRMED', 'phase': 'UNCONFIRMED',
|
||||||
'library': str(library) if library else None, 'block': session.get('block'),
|
'library': str(library) if library else None, 'block': session.get('block'),
|
||||||
'detail': '正在核对残留会话', 'operation_id': session.get('operation_id')}
|
'detail': '正在核对残留会话', 'operation_id': session.get('operation_id'),
|
||||||
|
'observer_initializing': True}
|
||||||
def notify(value):
|
def notify(value):
|
||||||
with _observer_guard:
|
with _observer_guard:
|
||||||
if _retained_libraries.get(key) is aliases:
|
if _retained_libraries.get(key) is aliases:
|
||||||
previous = _retained_results[key]
|
previous = _retained_results[key]
|
||||||
_retained_results[key] = {**previous, **value,
|
_retained_results[key] = {**previous, **value,
|
||||||
|
'observer_initializing': False,
|
||||||
'library': value.get('library') or previous['library'],
|
'library': value.get('library') or previous['library'],
|
||||||
'operation_id': value.get('operation_id') or previous['operation_id'],
|
'operation_id': value.get('operation_id') or previous['operation_id'],
|
||||||
'block': value.get('block') or previous['block']}
|
'block': value.get('block') or previous['block']}
|
||||||
if progress is not None:
|
if progress is not None:
|
||||||
progress(value)
|
progress(value)
|
||||||
|
def observation_only():
|
||||||
|
if not observe_only:
|
||||||
|
return False
|
||||||
|
with _observer_guard:
|
||||||
|
value = _retained_results.get(key, {})
|
||||||
|
return not (session.get('operation_id') and _retained_libraries.get(key) is aliases
|
||||||
|
and value.get('operation_id') == session.get('operation_id')
|
||||||
|
and value.get('release_operation_id') == session.get('operation_id'))
|
||||||
def observe():
|
def observe():
|
||||||
result = None
|
result = None
|
||||||
try:
|
try:
|
||||||
result = observe_retained_session(path, evidence_root=evidence_root, progress=notify,
|
result = observe_retained_session(path, evidence_root=evidence_root, progress=notify,
|
||||||
stop=stop, process=process, observe_only=observe_only)
|
stop=stop, process=process, observe_only=observation_only)
|
||||||
if process is not None and process.poll() is not None:
|
if process is not None and process.poll() is not None:
|
||||||
process.close()
|
process.close()
|
||||||
return result
|
return result
|
||||||
finally:
|
finally:
|
||||||
with _observer_guard:
|
with _observer_guard:
|
||||||
|
if _observers.get(key, (None,))[0] is threading.current_thread():
|
||||||
_observers.pop(key, None)
|
_observers.pop(key, None)
|
||||||
if result and result['status'] == 'RELEASED':
|
if (result and result['status'] == 'RELEASED'
|
||||||
|
and _retained_libraries.get(key) is aliases
|
||||||
|
and _retained_results.get(key, {}).get('operation_id') == session.get('operation_id')):
|
||||||
_retained_libraries.pop(key, None)
|
_retained_libraries.pop(key, None)
|
||||||
_retained_results.pop(key, None)
|
_retained_results.pop(key, None)
|
||||||
thread = threading.Thread(target=observe, name='retained-native-session', daemon=True)
|
thread = threading.Thread(target=observe, name='retained-native-session', daemon=True)
|
||||||
@@ -420,9 +533,14 @@ def discover_sessions(evidence_root, *, library=None):
|
|||||||
if not (name.startswith('observation-') and name.endswith('.json')):
|
if not (name.startswith('observation-') and name.endswith('.json')):
|
||||||
continue
|
continue
|
||||||
observation = read_session_record(Path(folder)/name, evidence_root=root)
|
observation = read_session_record(Path(folder)/name, evidence_root=root)
|
||||||
|
proof = observation.get('release_proof') or {}
|
||||||
|
proof = proof if isinstance(proof, dict) else {}
|
||||||
|
session_scope = value.get('resource_scope')
|
||||||
if observation['operation_id'] == value['operation_id'] and (
|
if observation['operation_id'] == value['operation_id'] and (
|
||||||
observation.get('status') == 'RELEASED' and observation.get('release_proof')
|
observation.get('status') == 'RELEASED'
|
||||||
|
and _proof_covers_session(proof, value)
|
||||||
or observation.get('status') == 'FINISHED'
|
or observation.get('status') == 'FINISHED'
|
||||||
|
and isinstance(session_scope, dict) and session_scope.get('scope_state') == 'DECLARED'
|
||||||
and observation.get('native_release_confirmed') is True
|
and observation.get('native_release_confirmed') is True
|
||||||
and observation.get('worker_exited') is True):
|
and observation.get('worker_exited') is True):
|
||||||
completed = True
|
completed = True
|
||||||
|
|||||||
@@ -2,12 +2,14 @@
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from threading import Event
|
from threading import Event
|
||||||
|
|
||||||
from PySide6.QtCore import QObject, QThreadPool, Signal
|
from PySide6.QtCore import QObject, QThreadPool, Signal, Qt
|
||||||
from PySide6.QtWidgets import (QComboBox, QDialog, QFileDialog, QFormLayout,
|
from PySide6.QtWidgets import (QComboBox, QDialog, QFileDialog, QFormLayout,
|
||||||
QHBoxLayout, QLabel, QLineEdit, QPushButton, QMessageBox)
|
QHBoxLayout, QLabel, QLineEdit, QPushButton, QMessageBox)
|
||||||
|
|
||||||
from .workers import ServiceWorker
|
from .workers import ServiceWorker
|
||||||
from .backup_notice import MANUAL_BACKUP_NOTICE
|
from .backup_notice import MANUAL_BACKUP_NOTICE
|
||||||
|
from . import timed_prompt
|
||||||
|
from ..operation_queue import BatchTaskContext
|
||||||
|
|
||||||
|
|
||||||
class RecoverySignals(QObject):
|
class RecoverySignals(QObject):
|
||||||
@@ -27,13 +29,17 @@ class BackupRecoveryDialog(QDialog):
|
|||||||
self.recoverer = recoverer
|
self.recoverer = recoverer
|
||||||
self.native_queue = None
|
self.native_queue = None
|
||||||
self.stop = Event()
|
self.stop = Event()
|
||||||
|
self.context = None
|
||||||
|
self.ui_job = None
|
||||||
|
self.admit = None
|
||||||
|
self.setWindowModality(Qt.NonModal)
|
||||||
self.busy = False
|
self.busy = False
|
||||||
self.pool = QThreadPool(self)
|
self.pool = QThreadPool(self)
|
||||||
self.pool.setMaxThreadCount(1)
|
self.pool.setMaxThreadCount(1)
|
||||||
self.signals = RecoverySignals(self)
|
self.signals = RecoverySignals(self)
|
||||||
self.signals.progress.connect(self._progress)
|
self.signals.progress.connect(self._progress)
|
||||||
if parent is not None and hasattr(parent, '_show_version_choice'):
|
self._choice_handler = getattr(parent, '_show_version_choice', None)
|
||||||
self.signals.choice.connect(parent._show_version_choice)
|
self.signals.choice.connect(self._choice)
|
||||||
self.block_combo = QComboBox()
|
self.block_combo = QComboBox()
|
||||||
self.block_combo.addItems(list(names))
|
self.block_combo.addItems(list(names))
|
||||||
self.source_edit = QLineEdit()
|
self.source_edit = QLineEdit()
|
||||||
@@ -46,7 +52,7 @@ class BackupRecoveryDialog(QDialog):
|
|||||||
self.close_button.clicked.connect(self.reject)
|
self.close_button.clicked.connect(self.reject)
|
||||||
self.cancel_queue_button = QPushButton('取消排队')
|
self.cancel_queue_button = QPushButton('取消排队')
|
||||||
self.cancel_queue_button.setEnabled(False)
|
self.cancel_queue_button.setEnabled(False)
|
||||||
self.cancel_queue_button.clicked.connect(self.stop.set)
|
self.cancel_queue_button.clicked.connect(lambda:self.stop.set())
|
||||||
self.status_label = QLabel(MANUAL_BACKUP_NOTICE + ' 所选备份先在隔离库中验证;安装时旧 Work 仅改名保留。')
|
self.status_label = QLabel(MANUAL_BACKUP_NOTICE + ' 所选备份先在隔离库中验证;安装时旧 Work 仅改名保留。')
|
||||||
self.status_label.setWordWrap(True)
|
self.status_label.setWordWrap(True)
|
||||||
layout = QFormLayout(self)
|
layout = QFormLayout(self)
|
||||||
@@ -88,42 +94,69 @@ class BackupRecoveryDialog(QDialog):
|
|||||||
except Exception as error:
|
except Exception as error:
|
||||||
self.status_label.setText(str(error))
|
self.status_label.setText(str(error))
|
||||||
return
|
return
|
||||||
if QMessageBox.question(self, '确认从备份恢复',
|
if timed_prompt.question(self, '确认从备份恢复',
|
||||||
f'{MANUAL_BACKUP_NOTICE}\n\n目标库:{request.lmc_file}\nCBB:{name}\n来源:{source}'
|
f'{MANUAL_BACKUP_NOTICE}\n\n目标库:{request.lmc_file}\nCBB:{name}\n来源:{source}'
|
||||||
'\n\n将创建用于校验的隔离库副本,校验通过后替换目标工程。确认继续?',
|
'\n\n将创建用于校验的隔离库副本,校验通过后替换目标工程。确认继续?',
|
||||||
QMessageBox.Yes | QMessageBox.No, QMessageBox.No) != QMessageBox.Yes:
|
QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) != QMessageBox.Yes:
|
||||||
|
return
|
||||||
|
if self.admit is not None and not self.admit((request, source)):
|
||||||
|
self.status_label.setText('相同任务已提交,未重复执行。')
|
||||||
return
|
return
|
||||||
self.busy = True
|
self.busy = True
|
||||||
self.stop.clear()
|
self.context = BatchTaskContext(str(request.lmc_file), targets=(name,), native_policy='external')
|
||||||
|
context = self.context
|
||||||
|
self.stop = context.stop
|
||||||
self._set_enabled(False)
|
self._set_enabled(False)
|
||||||
self.status_label.setText('正在准备恢复…')
|
self.status_label.setText('正在准备恢复…')
|
||||||
self.started.emit(name)
|
self.started.emit(name)
|
||||||
def execute():
|
def execute():
|
||||||
options = {'version_prompt': self.signals.choice.emit} if self.recoverer is None else {}
|
options = {'version_prompt': lambda choice:self._emit(context, 'choice',choice),'stop':context.stop} if self.recoverer is None else {}
|
||||||
action = lambda: recoverer(request, source, progress=self.signals.progress.emit, **options)
|
action = lambda: recoverer(request, source, progress=lambda event:self._emit(context, 'progress',event), **options)
|
||||||
if self.native_queue is None: return action()
|
if self.native_queue is None: return context.run(action)
|
||||||
from ..operation_queue import QueueCancelled
|
from ..operation_queue import QueueCancelled
|
||||||
def restore():
|
def restore():
|
||||||
self.signals.progress.emit({'stage': 'queue_acquired'})
|
self._emit(context, 'progress',{'stage': 'queue_acquired'})
|
||||||
return action()
|
return action()
|
||||||
try:
|
try:
|
||||||
return self.native_queue.run(restore, stop=self.stop, waiting=lambda: self.signals.progress.emit(
|
return self.native_queue.run(restore, stop=context.stop, context=context, waiting=lambda: self._emit(context, 'progress',
|
||||||
{'stage': 'waiting_native_slot', 'detail': '已排队,等待当前检查结束'}))
|
{'stage': 'waiting_native_slot', 'detail': '已排队,等待当前检查结束'}))
|
||||||
except QueueCancelled as error:
|
except QueueCancelled as error:
|
||||||
from ..verify_runner import VerifyResult
|
from ..operation_queue import TaskHandoff
|
||||||
|
from ..verify_runner import VerifyResult, _handoff_verify_result
|
||||||
|
if isinstance(error, TaskHandoff): return _handoff_verify_result(error)
|
||||||
return VerifyResult('CANCELLED', stderr=str(error))
|
return VerifyResult('CANCELLED', stderr=str(error))
|
||||||
self.worker = ServiceWorker(execute)
|
self.worker = ServiceWorker(execute)
|
||||||
self.worker.signals.succeeded.connect(lambda result: self._result(name, result))
|
self.worker.signals.succeeded.connect(context.guard_callback(lambda result: self._result(name, result), current=lambda:self.context))
|
||||||
self.worker.signals.failed.connect(lambda error: self._failed(name, error))
|
self.worker.signals.failed.connect(context.guard_callback(lambda error: self._failed(name, error), current=lambda:self.context))
|
||||||
self.worker.signals.finished.connect(self._finished)
|
self.worker.signals.finished.connect(lambda:self._finished() if self.context is context else None)
|
||||||
self.pool.start(self.worker)
|
self.pool.start(self.worker)
|
||||||
|
|
||||||
|
def _emit(self, context, signal, value):
|
||||||
|
if context is not self.context or not self.busy or signal == 'choice' and context.stop.is_set():
|
||||||
|
if signal == 'choice': value.choose('cancel')
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
delivered = context.guard_callback(lambda:getattr(self.signals, signal).emit((context,value)) or True)()
|
||||||
|
if not delivered and signal == 'choice': value.choose('cancel')
|
||||||
|
except RuntimeError:
|
||||||
|
if signal == 'choice': value.choose('cancel')
|
||||||
|
|
||||||
|
def _choice(self, payload):
|
||||||
|
context, choice = payload
|
||||||
|
if context is not self.context or not self.busy or context.stop.is_set() or self._choice_handler is None:
|
||||||
|
choice.choose('cancel')
|
||||||
|
return
|
||||||
|
self._choice_handler((self.ui_job,choice) if self.ui_job else choice)
|
||||||
|
|
||||||
def _set_enabled(self, enabled):
|
def _set_enabled(self, enabled):
|
||||||
for widget in (self.block_combo, self.source_edit, self.browse_button,
|
for widget in (self.block_combo, self.source_edit, self.browse_button,
|
||||||
self.restore_button, self.close_button):
|
self.restore_button, self.close_button):
|
||||||
widget.setEnabled(enabled)
|
widget.setEnabled(enabled)
|
||||||
|
|
||||||
def _progress(self, event):
|
def _progress(self, event):
|
||||||
|
if isinstance(event, tuple):
|
||||||
|
context, event = event
|
||||||
|
if context is not self.context or not self.busy: return
|
||||||
if isinstance(event, dict):
|
if isinstance(event, dict):
|
||||||
if event.get('stage') in ('waiting_native_slot', 'queue_acquired'):
|
if event.get('stage') in ('waiting_native_slot', 'queue_acquired'):
|
||||||
self.cancel_queue_button.setEnabled(event['stage'] == 'waiting_native_slot')
|
self.cancel_queue_button.setEnabled(event['stage'] == 'waiting_native_slot')
|
||||||
@@ -134,6 +167,9 @@ class BackupRecoveryDialog(QDialog):
|
|||||||
def _result(self, name, result):
|
def _result(self, name, result):
|
||||||
if result.status == 'PASS':
|
if result.status == 'PASS':
|
||||||
message = '恢复完成,工程打开与校验通过。'
|
message = '恢复完成,工程打开与校验通过。'
|
||||||
|
elif result.status in ('SKIPPED', 'CANCELLED'):
|
||||||
|
label = '恢复已跳过' if result.status == 'SKIPPED' else '恢复已取消'
|
||||||
|
message = f'{label}:{result.stderr or result.stdout or result.status}'
|
||||||
else:
|
else:
|
||||||
message = f'恢复未通过:{result.stderr or result.stdout or result.status}'
|
message = f'恢复未通过:{result.stderr or result.stdout or result.status}'
|
||||||
if result.evidence_path:
|
if result.evidence_path:
|
||||||
@@ -156,6 +192,7 @@ class BackupRecoveryDialog(QDialog):
|
|||||||
|
|
||||||
def closeEvent(self, event):
|
def closeEvent(self, event):
|
||||||
if self.busy:
|
if self.busy:
|
||||||
|
self.stop.set()
|
||||||
event.ignore()
|
event.ignore()
|
||||||
else:
|
else:
|
||||||
super().closeEvent(event)
|
super().closeEvent(event)
|
||||||
@@ -1,8 +1,7 @@
|
|||||||
"""A check batch owns its snapshot and yields the native queue after each CBB."""
|
"""A check batch owns its snapshot and yields the native queue after each CBB."""
|
||||||
from threading import Event
|
|
||||||
from PySide6.QtCore import QObject, QThreadPool, Signal
|
from PySide6.QtCore import QObject, QThreadPool, Signal
|
||||||
from .workers import ServiceWorker
|
from .workers import ServiceWorker
|
||||||
from ..operation_queue import QueueCancelled
|
from ..operation_queue import QueueCancelled, BatchTaskContext
|
||||||
from ..verify_runner import VerifyResult, run_verify, write_batch_report
|
from ..verify_runner import VerifyResult, run_verify, write_batch_report
|
||||||
from ..icdb_maintenance import write_maintenance_report
|
from ..icdb_maintenance import write_maintenance_report
|
||||||
|
|
||||||
@@ -12,14 +11,18 @@ class IcdbCheckTask(QObject):
|
|||||||
item_done = Signal(str, object)
|
item_done = Signal(str, object)
|
||||||
finished = Signal(object)
|
finished = Signal(object)
|
||||||
|
|
||||||
def __init__(self, requests, queue, report_root, *, verifier=None, path_lease=None, parent=None):
|
def __init__(self, requests, queue, report_root, *, verifier=None, path_lease=None, parent=None, status_reader=None, choice_prompt=None):
|
||||||
super().__init__(parent)
|
super().__init__(parent)
|
||||||
self.requests = tuple(requests)
|
self.requests = tuple(requests)
|
||||||
self.queue, self.report_root = queue, report_root
|
self.queue, self.report_root = queue, report_root
|
||||||
self.path_lease = path_lease
|
self.path_lease = path_lease
|
||||||
self.verifier = verifier or (lambda req: run_verify(req, progress=self.event.emit, stop=self.stop))
|
self.context = BatchTaskContext(str(self.requests[0].lmc_file),
|
||||||
|
targets=tuple(r.block_name for r in self.requests), native_policy='external')
|
||||||
|
self.status_reader = status_reader
|
||||||
|
self.verifier = verifier or (lambda req: run_verify(req, progress=self._emit_event,
|
||||||
|
stop=self.stop, version_prompt=choice_prompt))
|
||||||
self.results = []
|
self.results = []
|
||||||
self.stop = Event()
|
self.stop = self.context.stop
|
||||||
self.active = False
|
self.active = False
|
||||||
self.paused = False
|
self.paused = False
|
||||||
self.invalidated = set()
|
self.invalidated = set()
|
||||||
@@ -30,6 +33,12 @@ class IcdbCheckTask(QObject):
|
|||||||
self.retained_libraries = set()
|
self.retained_libraries = set()
|
||||||
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1)
|
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1)
|
||||||
|
|
||||||
|
def _emit_event(self, event):
|
||||||
|
try:
|
||||||
|
self.context.guard_callback(self.event.emit)(event)
|
||||||
|
except RuntimeError:
|
||||||
|
pass
|
||||||
|
|
||||||
def start(self):
|
def start(self):
|
||||||
self.active = True
|
self.active = True
|
||||||
self._next()
|
self._next()
|
||||||
@@ -68,23 +77,31 @@ class IcdbCheckTask(QObject):
|
|||||||
from ..session_record import library_available, library_wait_reason
|
from ..session_record import library_available, library_wait_reason
|
||||||
try:
|
try:
|
||||||
def execute():
|
def execute():
|
||||||
|
if self.status_reader is not None:
|
||||||
|
statuses = self.status_reader((request.block_name,), request.lmc_file)
|
||||||
|
self.update_statuses(statuses)
|
||||||
|
if statuses.get(request.block_name) == 'NOT_REGISTERED':
|
||||||
|
return VerifyResult('SKIPPED', stderr='仅发现目录,原生目录未登记此 CBB。')
|
||||||
if request.block_name in self.ready_names:
|
if request.block_name in self.ready_names:
|
||||||
return VerifyResult('SKIPPED', stderr='工程已为 READY,跳过 ICDB 检查。')
|
return VerifyResult('SKIPPED', stderr='工程已为 READY,跳过 ICDB 检查。')
|
||||||
if request.block_name in self.invalidated:
|
if request.block_name in self.invalidated:
|
||||||
return VerifyResult('SKIPPED', stderr='目标已有后续管理操作,请重新检查。')
|
return VerifyResult('SKIPPED', stderr='目标已有后续管理操作,请重新检查。')
|
||||||
self.event.emit({'stage': 'icdb_check_start', 'block': request.block_name})
|
self._emit_event({'stage': 'icdb_check_start', 'block': request.block_name})
|
||||||
result = self.verifier(request)
|
result = self.verifier(request)
|
||||||
if not result.safe_to_continue:
|
if not result.safe_to_continue:
|
||||||
from ..operation_lifecycle import recheck_failed_release
|
from ..operation_lifecycle import recheck_failed_release
|
||||||
result = recheck_failed_release(request.lmc_file, request.block_name, result)
|
result = recheck_failed_release(request.lmc_file, request.block_name, result)
|
||||||
return result
|
return result
|
||||||
return self.queue.run(execute, stop=self.stop,
|
return self.queue.run(execute, stop=self.stop, context=self.context,
|
||||||
wait_state=lambda: (self.paused, library_wait_reason(request.lmc_file)),
|
wait_state=lambda: (self.paused, library_wait_reason(request.lmc_file)),
|
||||||
ready=lambda: not self.paused and library_available(request.lmc_file),
|
ready=lambda: not self.paused,
|
||||||
waiting=lambda: self.event.emit({'stage': 'waiting_native_slot', 'block': request.block_name,
|
waiting=lambda: self._emit_event({'stage': 'waiting_native_slot', 'block': request.block_name,
|
||||||
'library': str(request.lmc_file), 'retained': not library_available(request.lmc_file),
|
'library': str(request.lmc_file), 'retained': not library_available(request.lmc_file),
|
||||||
'detail': library_wait_reason(request.lmc_file) or '已排队,等待当前原生操作结束'}))
|
'detail': library_wait_reason(request.lmc_file) or '已排队,等待当前原生操作结束'}))
|
||||||
except QueueCancelled as error:
|
except QueueCancelled as error:
|
||||||
|
from ..operation_queue import TaskHandoff
|
||||||
|
from ..verify_runner import _handoff_verify_result
|
||||||
|
if isinstance(error, TaskHandoff): return _handoff_verify_result(error)
|
||||||
return VerifyResult('CANCELLED', stderr=str(error))
|
return VerifyResult('CANCELLED', stderr=str(error))
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
return VerifyResult('FAIL', stderr=str(error), safe_to_continue=False,
|
return VerifyResult('FAIL', stderr=str(error), safe_to_continue=False,
|
||||||
@@ -117,7 +134,12 @@ class IcdbCheckTask(QObject):
|
|||||||
return report, ''
|
return report, ''
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
return None, str(error)
|
return None, str(error)
|
||||||
self.worker = ServiceWorker(write)
|
def bounded_write():
|
||||||
|
try:
|
||||||
|
return BatchTaskContext(str(self.requests[0].lmc_file)).run(write, metadata_only=True)
|
||||||
|
except Exception as error:
|
||||||
|
return None, str(error)
|
||||||
|
self.worker = ServiceWorker(bounded_write)
|
||||||
self.worker.signals.succeeded.connect(self._report_ready)
|
self.worker.signals.succeeded.connect(self._report_ready)
|
||||||
self.worker.signals.finished.connect(self._complete)
|
self.worker.signals.finished.connect(self._complete)
|
||||||
self.pool.start(self.worker)
|
self.pool.start(self.worker)
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -1,24 +1,27 @@
|
|||||||
"""Explicit preview and asynchronous, checkpointed CBB management batch."""
|
"""Explicit preview and asynchronous, checkpointed CBB management batch."""
|
||||||
from dataclasses import replace
|
from dataclasses import replace
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from threading import Event
|
|
||||||
|
|
||||||
from PySide6.QtCore import QObject, QThreadPool, Signal, Qt
|
from PySide6.QtCore import QObject, QThreadPool, Signal, Qt
|
||||||
from PySide6.QtWidgets import (QCheckBox, QDialog, QFileDialog, QHBoxLayout, QLabel,
|
from PySide6.QtWidgets import (QCheckBox, QDialog, QFileDialog, QHBoxLayout, QLabel,
|
||||||
QMessageBox, QPushButton, QTableWidget, QTableWidgetItem, QTextEdit, QVBoxLayout)
|
QMessageBox, QPushButton, QTableWidget, QTableWidgetItem, QTextEdit, QVBoxLayout)
|
||||||
|
from shiboken6 import isValid
|
||||||
|
|
||||||
from .workers import ServiceWorker
|
from .workers import ServiceWorker
|
||||||
from .backup_notice import MANUAL_BACKUP_NOTICE
|
from .backup_notice import MANUAL_BACKUP_NOTICE
|
||||||
from ..management import run_management_batch, validate_name
|
from . import timed_prompt
|
||||||
|
from ..management import run_management_batch
|
||||||
|
from ..operation_queue import BatchTaskContext
|
||||||
|
|
||||||
RESULT_LABELS = {
|
RESULT_LABELS = {
|
||||||
'REMOVED': '已移除', 'UPLOADED': '已上传 / 未自动校验',
|
'REMOVED': '已移除', 'UPLOADED': '已上传 / 未自动校验',
|
||||||
'UPLOADED_VERIFIED': '已上传且校验通过', 'UPLOADED_VERIFY_FAILED': '已上传但校验未通过',
|
'UPLOADED_VERIFIED': '已上传且校验通过', 'UPLOADED_VERIFY_FAILED': '已上传但校验未通过',
|
||||||
'UPLOAD_FAILED': '上传失败', 'RECOVERY_REQUIRED': '需要人工恢复',
|
'UPLOAD_FAILED': '上传失败', 'RECOVERY_REQUIRED': '需要人工恢复',
|
||||||
'BLOCKED': '操作被阻止', 'UNSUPPORTED': '当前环境不支持',
|
'BLOCKED': '操作被阻止', 'UNSUPPORTED': '当前环境不支持',
|
||||||
|
'SKIPPED': '已跳过 / 未执行', 'CANCELLED': '已取消',
|
||||||
}
|
}
|
||||||
STAGE_LABELS = {
|
STAGE_LABELS = {
|
||||||
'prepare_identity': '正在核对来源工程内容',
|
'prepare_identity': '正在检查来源工程文件',
|
||||||
'catalog_before': '正在核对原生目录', 'baseline': '正在记录中心库内容基线',
|
'catalog_before': '正在核对原生目录', 'baseline': '正在记录中心库内容基线',
|
||||||
'stage_source': '正在复制并检查来源工程', 'native_remove': '正在移除',
|
'stage_source': '正在复制并检查来源工程', 'native_remove': '正在移除',
|
||||||
'removed': '原条目已移除', 'native_add': '正在上传', 'uploaded': '上传已确认',
|
'removed': '原条目已移除', 'native_add': '正在上传', 'uploaded': '上传已确认',
|
||||||
@@ -57,12 +60,16 @@ class ManagementDialog(QDialog):
|
|||||||
evidence_dir=self.template.evidence_dir.parent/'reimport-recovery', **kwargs)
|
evidence_dir=self.template.evidence_dir.parent/'reimport-recovery', **kwargs)
|
||||||
self.busy = False
|
self.busy = False
|
||||||
self.executed = False
|
self.executed = False
|
||||||
self.stop = Event()
|
self.context = BatchTaskContext(str(self.template.library), native_policy='external')
|
||||||
|
self.stop = self.context.stop
|
||||||
|
self.ui_job = None
|
||||||
|
self.admit = None
|
||||||
|
self.setWindowModality(Qt.NonModal)
|
||||||
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1)
|
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1)
|
||||||
self.signals = ManagementSignals(self)
|
self.signals = ManagementSignals(self)
|
||||||
self.signals.progress.connect(self._progress)
|
self.signals.progress.connect(self._progress)
|
||||||
if parent is not None and hasattr(parent, '_show_version_choice'):
|
self._choice_handler = getattr(parent, '_show_version_choice', None)
|
||||||
self.signals.choice.connect(parent._show_version_choice)
|
self.signals.choice.connect(self._choice)
|
||||||
self.setWindowTitle({'add': '新增 CBB', 'update': '同名更新 CBB', 'remove': '移除 CBB'}[self.operation])
|
self.setWindowTitle({'add': '新增 CBB', 'update': '同名更新 CBB', 'remove': '移除 CBB'}[self.operation])
|
||||||
self.resize(850, 450)
|
self.resize(850, 450)
|
||||||
self.table = QTableWidget(0, 4)
|
self.table = QTableWidget(0, 4)
|
||||||
@@ -94,7 +101,7 @@ class ManagementDialog(QDialog):
|
|||||||
self.execute_button = QPushButton('预览并确认执行…')
|
self.execute_button = QPushButton('预览并确认执行…')
|
||||||
self.execute_button.clicked.connect(self._execute)
|
self.execute_button.clicked.connect(self._execute)
|
||||||
self.stop_button = QPushButton('当前项结束后停止'); self.stop_button.setEnabled(False)
|
self.stop_button = QPushButton('当前项结束后停止'); self.stop_button.setEnabled(False)
|
||||||
self.stop_button.clicked.connect(self.stop.set)
|
self.stop_button.clicked.connect(lambda:self.context.stop_after_current.set())
|
||||||
self.close_button = QPushButton('关闭'); self.close_button.clicked.connect(self.reject)
|
self.close_button = QPushButton('关闭'); self.close_button.clicked.connect(self.reject)
|
||||||
layout = QVBoxLayout(self)
|
layout = QVBoxLayout(self)
|
||||||
layout.addWidget(QLabel(f'目标库:{self.template.library}'))
|
layout.addWidget(QLabel(f'目标库:{self.template.library}'))
|
||||||
@@ -150,13 +157,13 @@ class ManagementDialog(QDialog):
|
|||||||
try:
|
try:
|
||||||
if not requests:
|
if not requests:
|
||||||
raise ValueError('请先选择来源工程。')
|
raise ValueError('请先选择来源工程。')
|
||||||
|
if hasattr(self.adapter, 'validate_source'):
|
||||||
for request in requests:
|
for request in requests:
|
||||||
validate_name(request.name)
|
self.adapter.validate_source(request, probe_files=False)
|
||||||
if request.operation != 'remove' and (request.source is None or not request.source.is_file()):
|
# Per-item input errors belong in batch results, so valid rows still run.
|
||||||
raise ValueError(f'{request.name}:请选择完整来源 PRJ。')
|
|
||||||
if len({(r.partition.casefold(), r.name.casefold()) for r in requests}) != len(requests):
|
if len({(r.partition.casefold(), r.name.casefold()) for r in requests}) != len(requests):
|
||||||
raise ValueError('批次包含重复目标名称。')
|
raise ValueError('批次包含重复目标名称。')
|
||||||
except ValueError as error:
|
except (OSError, ValueError) as error:
|
||||||
self.status_label.setText(str(error)); return
|
self.status_label.setText(str(error)); return
|
||||||
preview = '\n'.join(f'{r.partition} / {r.name}' + (f' ← {r.source}' if r.source else '') for r in requests)
|
preview = '\n'.join(f'{r.partition} / {r.name}' + (f' ← {r.source}' if r.source else '') for r in requests)
|
||||||
description = ('同名更新会原生移除并重新导入;导入失败需要使用手动备份恢复。' if self.operation == 'update'
|
description = ('同名更新会原生移除并重新导入;导入失败需要使用手动备份恢复。' if self.operation == 'update'
|
||||||
@@ -165,49 +172,75 @@ class ManagementDialog(QDialog):
|
|||||||
if self.recovery_from:
|
if self.recovery_from:
|
||||||
description = ('将用所选副本替换这些 CBB。操作会先移除原条目,再导入副本;'
|
description = ('将用所选副本替换这些 CBB。操作会先移除原条目,再导入副本;'
|
||||||
'导入失败时需要用备份恢复。请确认副本版本。')
|
'导入失败时需要用备份恢复。请确认副本版本。')
|
||||||
answer = QMessageBox.question(self, '确认管理操作',
|
answer = timed_prompt.question(self, '确认管理操作',
|
||||||
f'{MANUAL_BACKUP_NOTICE}\n{description}\n\n目标库:{self.template.library}\n{preview}\n\n'
|
f'{MANUAL_BACKUP_NOTICE}\n{description}\n\n目标库:{self.template.library}\n{preview}\n\n'
|
||||||
'确认继续执行?', QMessageBox.Yes | QMessageBox.No,
|
'确认继续执行?', QMessageBox.Yes | QMessageBox.No,
|
||||||
QMessageBox.No)
|
QMessageBox.Yes)
|
||||||
if answer != QMessageBox.Yes:
|
if answer != QMessageBox.Yes:
|
||||||
return
|
return
|
||||||
|
requests = [replace(request, check_previous_release=True) for request in requests]
|
||||||
|
if self.admit is not None and not self.admit(tuple(requests)):
|
||||||
|
self.status_label.setText('相同任务已提交,未重复执行。')
|
||||||
|
return
|
||||||
|
self.context = BatchTaskContext(str(self.template.library), targets=tuple(r.name for r in requests), native_policy='external')
|
||||||
|
context = self.context
|
||||||
|
self.stop = context.stop
|
||||||
self.busy = True; self.executed = True
|
self.busy = True; self.executed = True
|
||||||
self._enabled(False)
|
self._enabled(False)
|
||||||
self.before_execute.emit([r.name for r in requests])
|
self.before_execute.emit([r.name for r in requests])
|
||||||
def execute():
|
def execute():
|
||||||
action = lambda: self.runner(requests, adapter=self.adapter, stop=self.stop,
|
choices={'version_prompt':lambda choice:self._emit(context, 'choice',choice)} if self.runner is run_management_batch or self.recovery_from else {}
|
||||||
progress=self.signals.progress.emit)
|
action = lambda: self.runner(requests, adapter=self.adapter, stop=context.stop,
|
||||||
if self.native_queue is None: return action()
|
progress=lambda event:self._emit(context, 'progress',event),**choices)
|
||||||
|
if self.native_queue is None: return context.run(action)
|
||||||
from ..operation_queue import QueueCancelled
|
from ..operation_queue import QueueCancelled
|
||||||
from ..session_record import library_available, library_wait_reason
|
from ..session_record import library_available, library_wait_reason
|
||||||
try:
|
try:
|
||||||
if self.runner is run_management_batch:
|
if self.runner is run_management_batch:
|
||||||
def item(request, action):
|
def item(request, action):
|
||||||
return self.native_queue.run(action, stop=self.stop,
|
return self.native_queue.run(action, stop=context.stop, context=context,
|
||||||
ready=lambda: library_available(request.library),
|
|
||||||
wait_state=lambda: library_wait_reason(request.library),
|
wait_state=lambda: library_wait_reason(request.library),
|
||||||
waiting=lambda: self.signals.progress.emit({'stage': 'waiting_native_slot',
|
waiting=lambda: self._emit(context, 'progress',{'stage': 'waiting_native_slot',
|
||||||
'retained': not library_available(request.library),
|
'retained': not library_available(request.library),
|
||||||
'detail': library_wait_reason(request.library) or '已排队,等待当前原生操作结束'}))
|
'detail': library_wait_reason(request.library) or '已排队,等待当前原生操作结束'}))
|
||||||
return self.runner(requests, adapter=self.adapter, stop=self.stop,
|
return self.runner(requests, adapter=self.adapter, stop=context.stop,
|
||||||
progress=self.signals.progress.emit, item_executor=item,
|
progress=lambda event:self._emit(context, 'progress',event), item_executor=item,
|
||||||
version_prompt=self.signals.choice.emit)
|
version_prompt=lambda choice:self._emit(context, 'choice',choice), context=context)
|
||||||
return self.native_queue.run(action, stop=self.stop, waiting=lambda: self.signals.progress.emit(
|
return self.native_queue.run(action, stop=context.stop, context=context, waiting=lambda: self._emit(context, 'progress',
|
||||||
{'stage': 'waiting_native_slot',
|
{'stage': 'waiting_native_slot',
|
||||||
'retained': not library_available(self.template.library),
|
'retained': not library_available(self.template.library),
|
||||||
'detail': library_wait_reason(self.template.library) or '已排队,等待当前检查结束'}),
|
'detail': library_wait_reason(self.template.library) or '已排队,等待当前检查结束'}),
|
||||||
ready=lambda: library_available(self.template.library),
|
|
||||||
wait_state=lambda: library_wait_reason(self.template.library))
|
wait_state=lambda: library_wait_reason(self.template.library))
|
||||||
except QueueCancelled as error:
|
except QueueCancelled as error:
|
||||||
|
from ..operation_queue import TaskHandoff
|
||||||
from ..management import ManagementResult
|
from ..management import ManagementResult
|
||||||
return [ManagementResult(r.operation, r.library, r.name, r.partition, r.source, r.auto_verify,
|
return [ManagementResult(r.operation, r.library, r.name, r.partition, r.source, r.auto_verify,
|
||||||
'complete', 'BLOCKED', True, str(error)) for r in requests]
|
'complete', 'RECOVERY_REQUIRED' if isinstance(error,TaskHandoff) else 'CANCELLED',
|
||||||
|
not isinstance(error,TaskHandoff), str(error)) for r in requests]
|
||||||
self.worker = ServiceWorker(execute)
|
self.worker = ServiceWorker(execute)
|
||||||
self.worker.signals.succeeded.connect(self._result)
|
current = lambda: self.context if isValid(self) else None
|
||||||
self.worker.signals.failed.connect(self._failed)
|
self.worker.signals.succeeded.connect(context.guard_callback(self._result, current=current))
|
||||||
self.worker.signals.finished.connect(self._finished)
|
self.worker.signals.failed.connect(context.guard_callback(self._failed, current=current))
|
||||||
|
self.worker.signals.finished.connect(lambda:self._finished() if current() is context else None)
|
||||||
self.pool.start(self.worker)
|
self.pool.start(self.worker)
|
||||||
|
|
||||||
|
def _emit(self, context, signal, value):
|
||||||
|
if context is not self.context or not self.busy or signal == 'choice' and context.stop.is_set():
|
||||||
|
if signal == 'choice': value.choose('cancel')
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
delivered = context.guard_callback(lambda:getattr(self.signals, signal).emit((context,value)) or True)()
|
||||||
|
if not delivered and signal == 'choice': value.choose('cancel')
|
||||||
|
except RuntimeError:
|
||||||
|
if signal == 'choice': value.choose('cancel')
|
||||||
|
|
||||||
|
def _choice(self, payload):
|
||||||
|
context, choice = payload
|
||||||
|
if context is not self.context or not self.busy or context.stop.is_set() or self._choice_handler is None:
|
||||||
|
choice.choose('cancel')
|
||||||
|
return
|
||||||
|
self._choice_handler((self.ui_job,choice) if self.ui_job else choice)
|
||||||
|
|
||||||
def _enabled(self, enabled):
|
def _enabled(self, enabled):
|
||||||
for widget in (self.table, self.sources_button, self.auto_verify, self.close_button):
|
for widget in (self.table, self.sources_button, self.auto_verify, self.close_button):
|
||||||
widget.setEnabled(enabled)
|
widget.setEnabled(enabled)
|
||||||
@@ -215,6 +248,9 @@ class ManagementDialog(QDialog):
|
|||||||
self.stop_button.setEnabled(not enabled)
|
self.stop_button.setEnabled(not enabled)
|
||||||
|
|
||||||
def _progress(self, event):
|
def _progress(self, event):
|
||||||
|
if isinstance(event, tuple):
|
||||||
|
context, event = event
|
||||||
|
if context is not self.context or not self.busy: return
|
||||||
stage = str(event.get('stage', ''))
|
stage = str(event.get('stage', ''))
|
||||||
self.release_wait_button.setVisible(stage == 'waiting_native_slot' and bool(event.get('retained')))
|
self.release_wait_button.setVisible(stage == 'waiting_native_slot' and bool(event.get('retained')))
|
||||||
text = f'{event.get("block", "")} {STAGE_LABELS.get(stage, RESULT_LABELS.get(stage, "正在处理"))}'
|
text = f'{event.get("block", "")} {STAGE_LABELS.get(stage, RESULT_LABELS.get(stage, "正在处理"))}'
|
||||||
@@ -271,6 +307,6 @@ class ManagementDialog(QDialog):
|
|||||||
|
|
||||||
def closeEvent(self, event):
|
def closeEvent(self, event):
|
||||||
if self.busy:
|
if self.busy:
|
||||||
self.stop.set(); event.ignore()
|
self.context.stop_after_current.set(); event.ignore()
|
||||||
else:
|
else:
|
||||||
super().closeEvent(event)
|
super().closeEvent(event)
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
from PySide6.QtWidgets import QMessageBox
|
from PySide6.QtWidgets import QMessageBox
|
||||||
|
from .timed_prompt import arm_default
|
||||||
|
|
||||||
|
|
||||||
class PcbOpenDialog(QMessageBox):
|
class PcbOpenDialog(QMessageBox):
|
||||||
@@ -13,9 +14,11 @@ class PcbOpenDialog(QMessageBox):
|
|||||||
self.continue_button = self.addButton('确认无人使用,继续打开', QMessageBox.ActionRole)
|
self.continue_button = self.addButton('确认无人使用,继续打开', QMessageBox.ActionRole)
|
||||||
self.skip_button = self.addButton('跳过本项', QMessageBox.ActionRole)
|
self.skip_button = self.addButton('跳过本项', QMessageBox.ActionRole)
|
||||||
self.cancel_button = self.addButton('取消本批次', QMessageBox.RejectRole)
|
self.cancel_button = self.addButton('取消本批次', QMessageBox.RejectRole)
|
||||||
self.setDefaultButton(self.cancel_button)
|
self.setDefaultButton(self.skip_button)
|
||||||
self.setEscapeButton(self.cancel_button)
|
self.setEscapeButton(self.cancel_button)
|
||||||
self.setModal(True)
|
self.setModal(True)
|
||||||
self.buttonClicked.connect(lambda b: choice.choose('continue' if b is self.continue_button else
|
self.buttonClicked.connect(lambda b: choice.choose('continue' if b is self.continue_button else
|
||||||
'skip' if b is self.skip_button else 'cancel'))
|
'skip' if b is self.skip_button else 'cancel',
|
||||||
|
origin=self.property('selectionOrigin') or 'user'))
|
||||||
self.finished.connect(lambda _: choice.choose('cancel'))
|
self.finished.connect(lambda _: choice.choose('cancel'))
|
||||||
|
arm_default(self, self.skip_button)
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
"""Show the native version dates without preselecting a recovery version."""
|
"""Prefer the authorized last manually saved version after a visible countdown."""
|
||||||
from PySide6.QtWidgets import QMessageBox
|
from PySide6.QtWidgets import QMessageBox
|
||||||
|
from .timed_prompt import arm_default
|
||||||
|
|
||||||
|
|
||||||
class PcbRestoreDialog(QMessageBox):
|
class PcbRestoreDialog(QMessageBox):
|
||||||
@@ -14,7 +15,7 @@ class PcbRestoreDialog(QMessageBox):
|
|||||||
'原生程序检测到上次异常退出,需要选择 PCB 恢复版本。\n'
|
'原生程序检测到上次异常退出,需要选择 PCB 恢复版本。\n'
|
||||||
f'最后手动保存:{manual["date"]}\n自动保存:{auto["date"]}\n\n'
|
f'最后手动保存:{manual["date"]}\n自动保存:{auto["date"]}\n\n'
|
||||||
'选择历史版本可能丢失此版本之后的修改。选择后继续校验、保存和状态确认;恢复版本仍需核对。'
|
'选择历史版本可能丢失此版本之后的修改。选择后继续校验、保存和状态确认;恢复版本仍需核对。'
|
||||||
'\n取消将停止本项并保留原生现场,不自动选取版本。')
|
'\n默认选择最后手动保存;该版本不可用时取消本项。')
|
||||||
self.manual_button = self.addButton(f'最后手动保存({manual["date"]})', QMessageBox.ActionRole)
|
self.manual_button = self.addButton(f'最后手动保存({manual["date"]})', QMessageBox.ActionRole)
|
||||||
self.auto_button = self.addButton(f'自动保存({auto["date"]})', QMessageBox.ActionRole)
|
self.auto_button = self.addButton(f'自动保存({auto["date"]})', QMessageBox.ActionRole)
|
||||||
self.manual_button.setEnabled(manual['enabled'])
|
self.manual_button.setEnabled(manual['enabled'])
|
||||||
@@ -25,7 +26,9 @@ class PcbRestoreDialog(QMessageBox):
|
|||||||
self.buttonClicked.connect(self._chosen)
|
self.buttonClicked.connect(self._chosen)
|
||||||
self.finished.connect(lambda _: choice.choose('cancel'))
|
self.finished.connect(lambda _: choice.choose('cancel'))
|
||||||
self.setModal(True)
|
self.setModal(True)
|
||||||
|
arm_default(self, self.manual_button if manual['enabled'] else self.cancel_button)
|
||||||
|
|
||||||
def _chosen(self, button):
|
def _chosen(self, button):
|
||||||
self.choice.choose('last_user_saved' if button is self.manual_button else
|
self.choice.choose('last_user_saved' if button is self.manual_button else
|
||||||
'autosave' if button is self.auto_button else 'cancel')
|
'autosave' if button is self.auto_button else 'cancel',
|
||||||
|
origin=self.property('selectionOrigin') or 'user')
|
||||||
@@ -2,11 +2,14 @@
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from threading import Event
|
from threading import Event
|
||||||
|
|
||||||
from PySide6.QtCore import QThreadPool, Signal
|
from PySide6.QtCore import QThreadPool, Signal, Qt
|
||||||
from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
|
from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
|
||||||
QTableWidget, QTableWidgetItem, QHeaderView, QMessageBox)
|
QTableWidget, QTableWidgetItem, QHeaderView, QMessageBox)
|
||||||
|
|
||||||
from .workers import ServiceWorker
|
from .workers import ServiceWorker
|
||||||
|
from .timed_prompt import arm_default
|
||||||
|
from . import timed_prompt
|
||||||
|
from ..operation_queue import BatchTaskContext
|
||||||
from ..residual_sessions import force_block_reason, release_targets_complete
|
from ..residual_sessions import force_block_reason, release_targets_complete
|
||||||
|
|
||||||
|
|
||||||
@@ -22,10 +25,12 @@ class ResidualReleaseDialog(QDialog):
|
|||||||
self.release_finalizer = None
|
self.release_finalizer = None
|
||||||
self.busy = False
|
self.busy = False
|
||||||
self.stop = Event()
|
self.stop = Event()
|
||||||
|
self.context = None
|
||||||
|
self._workers = set()
|
||||||
self._refresh_after = False
|
self._refresh_after = False
|
||||||
self.pool = QThreadPool(self)
|
self.pool = QThreadPool(self)
|
||||||
self.setWindowTitle('释放残留会话')
|
self.setWindowTitle('释放残留会话')
|
||||||
self.setModal(True)
|
self.setWindowModality(Qt.NonModal)
|
||||||
self.resize(1040, 400)
|
self.resize(1040, 400)
|
||||||
layout = QVBoxLayout(self)
|
layout = QVBoxLayout(self)
|
||||||
self.message = QLabel('正在检查当前库关联的会话…')
|
self.message = QLabel('正在检查当前库关联的会话…')
|
||||||
@@ -63,7 +68,9 @@ class ResidualReleaseDialog(QDialog):
|
|||||||
self.table.itemSelectionChanged.connect(self._update_prompt)
|
self.table.itemSelectionChanged.connect(self._update_prompt)
|
||||||
self.refresh()
|
self.refresh()
|
||||||
|
|
||||||
def _start(self, action, completed):
|
def _start(self, action, completed, *, metadata_only=False):
|
||||||
|
context = BatchTaskContext(str(self.library))
|
||||||
|
self.context, self.stop = context, context.stop
|
||||||
self.busy = True
|
self.busy = True
|
||||||
self.confirm_button.setEnabled(False)
|
self.confirm_button.setEnabled(False)
|
||||||
self.refresh_button.setEnabled(False)
|
self.refresh_button.setEnabled(False)
|
||||||
@@ -71,10 +78,12 @@ class ResidualReleaseDialog(QDialog):
|
|||||||
self.force_button.setEnabled(False)
|
self.force_button.setEnabled(False)
|
||||||
self.cancel_native_button.setEnabled(False)
|
self.cancel_native_button.setEnabled(False)
|
||||||
self.close_button.setText('停止释放')
|
self.close_button.setText('停止释放')
|
||||||
self.worker = ServiceWorker(action)
|
self.worker = ServiceWorker(lambda:context.run(action, metadata_only=metadata_only))
|
||||||
self.worker.signals.succeeded.connect(completed)
|
worker = self.worker
|
||||||
self.worker.signals.failed.connect(lambda error: self.message.setText(str(error)))
|
self._workers.add(worker)
|
||||||
self.worker.signals.finished.connect(self._finished)
|
self.worker.signals.succeeded.connect(context.guard_callback(completed, current=lambda:self.context))
|
||||||
|
self.worker.signals.failed.connect(context.guard_callback(lambda error: self.message.setText(str(error)), current=lambda:self.context))
|
||||||
|
self.worker.signals.finished.connect(lambda:(self._workers.discard(worker), self._finished() if self.context is context else None))
|
||||||
self.pool.start(self.worker)
|
self.pool.start(self.worker)
|
||||||
|
|
||||||
def _finished(self):
|
def _finished(self):
|
||||||
@@ -128,6 +137,9 @@ class ResidualReleaseDialog(QDialog):
|
|||||||
details.extend(c.get('text', '') for c in window.get('children', [])
|
details.extend(c.get('text', '') for c in window.get('children', [])
|
||||||
if c.get('class') == 'Static')
|
if c.get('class') == 'Static')
|
||||||
box.setDetailedText('\n'.join(details))
|
box.setDetailedText('\n'.join(details))
|
||||||
|
box.setWindowModality(Qt.NonModal)
|
||||||
|
box.setStandardButtons(QMessageBox.Close)
|
||||||
|
arm_default(box, box.button(QMessageBox.Close))
|
||||||
box.show()
|
box.show()
|
||||||
|
|
||||||
def cancel_native(self):
|
def cancel_native(self):
|
||||||
@@ -136,13 +148,13 @@ class ResidualReleaseDialog(QDialog):
|
|||||||
if row < 0: return
|
if row < 0: return
|
||||||
session = self.plan['sessions'][row]
|
session = self.plan['sessions'][row]
|
||||||
if not session.get('cancel_prompt'): return
|
if not session.get('cancel_prompt'): return
|
||||||
answer = QMessageBox.question(self, '请求原生取消',
|
answer = timed_prompt.question(self, '请求原生取消',
|
||||||
f'请求 {session["name"]} (PID {session["pid"]}) 当前显示的取消按钮?\n'
|
f'请求 {session["name"]} (PID {session["pid"]}) 当前显示的取消按钮?\n'
|
||||||
'取消后的工程状态仍需核对;不会强制结束进程。',
|
'取消后的工程状态仍需核对;不会强制结束进程。',
|
||||||
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
|
QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
|
||||||
if answer != QMessageBox.Yes: return
|
if answer != QMessageBox.Yes: return
|
||||||
from cbb_refresh_verify.residual_sessions import request_native_cancel
|
from cbb_refresh_verify.residual_sessions import request_native_cancel
|
||||||
self.before_release.emit(); self.stop.clear()
|
self.before_release.emit(); self.stop = Event()
|
||||||
def execute():
|
def execute():
|
||||||
action = lambda: self._finalize_release_result(
|
action = lambda: self._finalize_release_result(
|
||||||
request_native_cancel(session, self.library, self.evidence_dir, stop=self.stop))
|
request_native_cancel(session, self.library, self.evidence_dir, stop=self.stop))
|
||||||
@@ -187,9 +199,9 @@ class ResidualReleaseDialog(QDialog):
|
|||||||
session = self.plan['sessions'][row]
|
session = self.plan['sessions'][row]
|
||||||
prompt = session.get('prompt')
|
prompt = session.get('prompt')
|
||||||
if not prompt: return
|
if not prompt: return
|
||||||
choice = QMessageBox.question(self, '关闭工程前保存', prompt['text']+
|
choice = timed_prompt.question(self, '关闭工程前保存', prompt['text']+
|
||||||
'\n\n是:保存后关闭;否:放弃未保存更改;取消:保留会话。',
|
'\n\n是:保存后关闭;否:放弃未保存更改;取消:保留会话。',
|
||||||
QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel, QMessageBox.Cancel)
|
QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel, QMessageBox.Yes)
|
||||||
code = {QMessageBox.Yes: 6, QMessageBox.No: 7, QMessageBox.Cancel: 2}[choice]
|
code = {QMessageBox.Yes: 6, QMessageBox.No: 7, QMessageBox.Cancel: 2}[choice]
|
||||||
from cbb_refresh_verify.residual_sessions import answer_save_question
|
from cbb_refresh_verify.residual_sessions import answer_save_question
|
||||||
self._start(lambda: answer_save_question(session, code),
|
self._start(lambda: answer_save_question(session, code),
|
||||||
@@ -226,14 +238,14 @@ class ResidualReleaseDialog(QDialog):
|
|||||||
states.update({str(Path(row['path']).absolute()).casefold(): row for row in
|
states.update({str(Path(row['path']).absolute()).casefold(): row for row in
|
||||||
discover_sessions(self.evidence_dir.parent, library=library)})
|
discover_sessions(self.evidence_dir.parent, library=library)})
|
||||||
return {**plan, 'runtime_sessions': list(states.values())}
|
return {**plan, 'runtime_sessions': list(states.values())}
|
||||||
self._start(inspect, ready)
|
self._start(inspect, ready, metadata_only=True)
|
||||||
|
|
||||||
def force_release(self):
|
def force_release(self):
|
||||||
if self.busy or not self.plan or not self.plan['sessions']: return
|
if self.busy or not self.plan or not self.plan['sessions']: return
|
||||||
targets = [r for r in self.plan['sessions'] if not force_block_reason(r)]
|
targets = [r for r in self.plan['sessions'] if not force_block_reason(r)]
|
||||||
if not targets: return
|
if not targets: return
|
||||||
names = '\n'.join(f'{r.get("project", "")} — {r["name"]} (PID {r["pid"]})' for r in targets)
|
names = '\n'.join(f'{r.get("project", "")} — {r["name"]} (PID {r["pid"]})' for r in targets)
|
||||||
answer = QMessageBox.warning(self, '强制结束客户端',
|
answer = timed_prompt.warning(self, '强制结束客户端',
|
||||||
'仅强制结束以下客户端。客户端中其他已打开工程也会退出;未保存的更改会丢失,正在写入的工程可能需要恢复。'
|
'仅强制结束以下客户端。客户端中其他已打开工程也会退出;未保存的更改会丢失,正在写入的工程可能需要恢复。'
|
||||||
'\n数据库服务器和归属未知的进程不会被强制结束。\n\n'+names+
|
'\n数据库服务器和归属未知的进程不会被强制结束。\n\n'+names+
|
||||||
'\n\n仍要结束这些进程吗?', QMessageBox.Yes | QMessageBox.Cancel, QMessageBox.Cancel)
|
'\n\n仍要结束这些进程吗?', QMessageBox.Yes | QMessageBox.Cancel, QMessageBox.Cancel)
|
||||||
@@ -242,7 +254,7 @@ class ResidualReleaseDialog(QDialog):
|
|||||||
def confirm_release(self, checked=False, *, force=False):
|
def confirm_release(self, checked=False, *, force=False):
|
||||||
if self.busy or self.plan is None: return
|
if self.busy or self.plan is None: return
|
||||||
from cbb_refresh_verify.library_lock import release_residual_sessions
|
from cbb_refresh_verify.library_lock import release_residual_sessions
|
||||||
self.stop.clear()
|
self.stop = Event()
|
||||||
plan = self.plan
|
plan = self.plan
|
||||||
self.before_release.emit()
|
self.before_release.emit()
|
||||||
self.message.setText('正在逐项释放,请稍候…')
|
self.message.setText('正在逐项释放,请稍候…')
|
||||||
|
|||||||
@@ -0,0 +1,98 @@
|
|||||||
|
"""Visible, one-shot defaults for confirmation prompts in unattended batches."""
|
||||||
|
from math import ceil
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from PySide6.QtCore import QElapsedTimer, QEvent, QObject, QTimer, Slot
|
||||||
|
from PySide6.QtWidgets import QMessageBox
|
||||||
|
|
||||||
|
DEFAULT_TIMEOUT_MS = 3000
|
||||||
|
|
||||||
|
|
||||||
|
class _Countdown(QObject):
|
||||||
|
def __init__(self, box, button):
|
||||||
|
super().__init__(box)
|
||||||
|
self.box, self.button = box, button
|
||||||
|
self.label = button.text()
|
||||||
|
self.duration = DEFAULT_TIMEOUT_MS
|
||||||
|
self.elapsed = QElapsedTimer()
|
||||||
|
self.timer = QTimer(self)
|
||||||
|
self.timer.setInterval(50)
|
||||||
|
self.timer.timeout.connect(self.tick)
|
||||||
|
self.done = False
|
||||||
|
box.setDefaultButton(button)
|
||||||
|
box.buttonClicked.connect(self.stop)
|
||||||
|
box.finished.connect(self.stop)
|
||||||
|
box.installEventFilter(self)
|
||||||
|
if box.isVisible():
|
||||||
|
self.start()
|
||||||
|
|
||||||
|
@Slot()
|
||||||
|
def start(self):
|
||||||
|
if self.done:
|
||||||
|
return
|
||||||
|
self.elapsed.start()
|
||||||
|
self.timer.start()
|
||||||
|
self.button.setText(f'{self.label}({ceil(self.duration / 1000)} 秒)')
|
||||||
|
|
||||||
|
def eventFilter(self, watched, event):
|
||||||
|
if event.type() == QEvent.Show:
|
||||||
|
self.start()
|
||||||
|
elif event.type() in (QEvent.Hide, QEvent.Close):
|
||||||
|
self.timer.stop()
|
||||||
|
return False
|
||||||
|
|
||||||
|
@Slot()
|
||||||
|
def stop(self):
|
||||||
|
self.done = True
|
||||||
|
self.timer.stop()
|
||||||
|
from shiboken6 import isValid
|
||||||
|
if isValid(self.button): self.button.setText(self.label)
|
||||||
|
|
||||||
|
@Slot()
|
||||||
|
def tick(self):
|
||||||
|
if self.done or not self.box.isVisible():
|
||||||
|
self.timer.stop()
|
||||||
|
return
|
||||||
|
remaining = self.duration - self.elapsed.elapsed()
|
||||||
|
if remaining > 0:
|
||||||
|
self.button.setText(f'{self.label}({ceil(remaining / 1000)} 秒)')
|
||||||
|
return
|
||||||
|
self.timer.stop()
|
||||||
|
self.done = True
|
||||||
|
if not self.button.isEnabled():
|
||||||
|
self.box.setProperty('selectionOrigin', 'timeout_default')
|
||||||
|
self.box.reject()
|
||||||
|
return
|
||||||
|
self.box.setProperty('selectionOrigin', 'timeout_default')
|
||||||
|
self.button.click()
|
||||||
|
|
||||||
|
|
||||||
|
def arm_default(box, button):
|
||||||
|
countdown = _Countdown(box, button)
|
||||||
|
box._default_countdown = countdown
|
||||||
|
return countdown
|
||||||
|
|
||||||
|
|
||||||
|
def _ask(icon, parent, title, text, buttons, default):
|
||||||
|
box = QMessageBox(icon, title, text, buttons, parent)
|
||||||
|
arm_default(box, box.button(default))
|
||||||
|
try:
|
||||||
|
result = QMessageBox.StandardButton(box.exec())
|
||||||
|
owner = parent
|
||||||
|
while owner is not None and getattr(owner, 'logging_context', None) is None:
|
||||||
|
owner = owner.parentWidget()
|
||||||
|
context = getattr(owner, 'logging_context', None)
|
||||||
|
logger = context.logger if context is not None else logging.getLogger('cbb_refresh_verify')
|
||||||
|
logger.info('prompt_decision title=%s result=%s origin=%s', title, result.name,
|
||||||
|
box.property('selectionOrigin') or 'user')
|
||||||
|
return result
|
||||||
|
finally:
|
||||||
|
box.deleteLater()
|
||||||
|
|
||||||
|
|
||||||
|
def question(parent, title, text, buttons, default):
|
||||||
|
return _ask(QMessageBox.Question, parent, title, text, buttons, default)
|
||||||
|
|
||||||
|
|
||||||
|
def warning(parent, title, text, buttons, default):
|
||||||
|
return _ask(QMessageBox.Warning, parent, title, text, buttons, default)
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
from PySide6.QtWidgets import QMessageBox
|
||||||
|
from .timed_prompt import arm_default
|
||||||
|
|
||||||
|
|
||||||
|
class WriteOwnerDialog(QMessageBox):
|
||||||
|
def __init__(self, choice, parent=None):
|
||||||
|
super().__init__(parent)
|
||||||
|
self.choice = choice
|
||||||
|
self.setWindowTitle('确认中心库未被占用')
|
||||||
|
self.setIcon(QMessageBox.Question)
|
||||||
|
owners = '\n'.join(f'{row["name"]} · PID {row["pid"]}' for row in choice.owners)
|
||||||
|
self.setText(f'中心库:{choice.library}\n当前 CBB:{choice.block}\n\n'
|
||||||
|
f'无法确认下列程序是否打开了此库:\n{owners}\n\n'
|
||||||
|
'请确认这些程序在本批次完成前都不使用此库,再继续。')
|
||||||
|
self.setDetailedText('\n'.join(f'PID {row["pid"]}:{row["image"]}' for row in choice.owners))
|
||||||
|
self.continue_button = self.addButton('已确认未使用此库,继续', QMessageBox.ActionRole)
|
||||||
|
self.skip_button = self.addButton('跳过本项', QMessageBox.ActionRole)
|
||||||
|
self.cancel_button = self.addButton('取消本批次', QMessageBox.RejectRole)
|
||||||
|
self.setDefaultButton(self.skip_button)
|
||||||
|
self.setEscapeButton(self.cancel_button)
|
||||||
|
self.setModal(True)
|
||||||
|
self.buttonClicked.connect(lambda b: choice.choose('continue' if b is self.continue_button else
|
||||||
|
'skip' if b is self.skip_button else 'cancel',
|
||||||
|
origin=self.property('selectionOrigin') or 'user'))
|
||||||
|
self.finished.connect(lambda _: choice.choose('cancel'))
|
||||||
|
arm_default(self, self.skip_button)
|
||||||
@@ -230,7 +230,7 @@ def _run_process(command, timeout_seconds, cwd, *, evidence_root=None):
|
|||||||
return run_content_check(command, timeout_seconds, cwd, evidence_root=evidence_root)
|
return run_content_check(command, timeout_seconds, cwd, evidence_root=evidence_root)
|
||||||
|
|
||||||
|
|
||||||
def _stop_worker(process, *, timeout=5):
|
def _stop_worker(process, *, timeout=5, wait_for_native_write=True):
|
||||||
"""Request stop without interrupting a possibly unreturned native call."""
|
"""Request stop without interrupting a possibly unreturned native call."""
|
||||||
try:
|
try:
|
||||||
if hasattr(process, 'request_stop'):
|
if hasattr(process, 'request_stop'):
|
||||||
@@ -243,7 +243,8 @@ def _stop_worker(process, *, timeout=5):
|
|||||||
process.wait(timeout=timeout)
|
process.wait(timeout=timeout)
|
||||||
except Exception:
|
except Exception:
|
||||||
pending = getattr(process, 'native_write_pending', lambda: False)()
|
pending = getattr(process, 'native_write_pending', lambda: False)()
|
||||||
if pending is not False and not getattr(process, '_stop_wait_complete', False):
|
wait_required = wait_for_native_write() if callable(wait_for_native_write) else wait_for_native_write
|
||||||
|
if wait_required and pending is not False and not getattr(process, '_stop_wait_complete', False):
|
||||||
from .defaults import NATIVE_WRITE_STOP_WAIT_SECONDS
|
from .defaults import NATIVE_WRITE_STOP_WAIT_SECONDS
|
||||||
try:
|
try:
|
||||||
process.wait(timeout=max(0, NATIVE_WRITE_STOP_WAIT_SECONDS - timeout))
|
process.wait(timeout=max(0, NATIVE_WRITE_STOP_WAIT_SECONDS - timeout))
|
||||||
@@ -412,6 +413,42 @@ def phase_for_event(event, current=None):
|
|||||||
return mapping.get(stage, current or DialogPhase.PCB_STARTING)
|
return mapping.get(stage, current or DialogPhase.PCB_STARTING)
|
||||||
|
|
||||||
|
|
||||||
|
def _diagnostic_close_event(job, event, target_pid):
|
||||||
|
close_id = event.get('close_id')
|
||||||
|
return (job.get('diagnostic_only') is True and event.get('stage') == 'diagnostic_close_requested'
|
||||||
|
and target_pid is not None and event.get('pcb_pid') == target_pid
|
||||||
|
and type(event.get('hwnd')) is int and event['hwnd'] > 0
|
||||||
|
and isinstance(close_id, str) and len(close_id) == 32 and all(c in '0123456789abcdef' for c in close_id)
|
||||||
|
and bool(job.get('operation_id')) and event.get('operation_id') == job['operation_id']
|
||||||
|
and all(job.get(key) and event.get(key) == job[key] for key in ('project', 'pcb', 'desktop')))
|
||||||
|
|
||||||
|
|
||||||
|
def _acknowledge_diagnostic_close(job, event, stop):
|
||||||
|
from .operation_queue import check_active
|
||||||
|
check_active()
|
||||||
|
if stop is not None and stop.is_set() or Path(job['cancel_signal']).exists():
|
||||||
|
raise InterruptedError('VERIFY_CANCELLED: diagnostic handoff cancelled')
|
||||||
|
ack = Path(job['root'])/'diagnostic-close-ack.json'
|
||||||
|
pending = ack.with_suffix('.pending')
|
||||||
|
pending.write_text(json.dumps({key: event[key] for key in
|
||||||
|
('pcb_pid', 'hwnd', 'operation_id', 'desktop', 'project', 'pcb', 'close_id')}), encoding='utf-8')
|
||||||
|
check_active()
|
||||||
|
if stop is not None and stop.is_set() or Path(job['cancel_signal']).exists():
|
||||||
|
raise InterruptedError('VERIFY_CANCELLED: diagnostic handoff cancelled')
|
||||||
|
pending.replace(ack)
|
||||||
|
|
||||||
|
|
||||||
|
def _close_intent_after_poll(job, events, offset, target_pid):
|
||||||
|
if not job.get('diagnostic_only') or not events.exists(): return None
|
||||||
|
with events.open(encoding='utf-8') as stream:
|
||||||
|
stream.seek(offset)
|
||||||
|
for line in stream:
|
||||||
|
try: event = json.loads(line)
|
||||||
|
except json.JSONDecodeError: break
|
||||||
|
if _diagnostic_close_event(job, event, target_pid): return event
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def classify_verify_dispatch(*, verify_invoked, invoke_returned, target_pid, observation):
|
def classify_verify_dispatch(*, verify_invoked, invoke_returned, target_pid, observation):
|
||||||
"""Classify a returned Verify command that never started its PCB.
|
"""Classify a returned Verify command that never started its PCB.
|
||||||
|
|
||||||
@@ -545,14 +582,59 @@ def _cleanup_session_processes(root, *, lm_pid, target_pid, pcb, pcb_baseline, l
|
|||||||
|
|
||||||
|
|
||||||
def run_verify(request, *, progress=None, flag_reader=None, process_runner=None, port_check=None,
|
def run_verify(request, *, progress=None, flag_reader=None, process_runner=None, port_check=None,
|
||||||
|
dialog_supervisor_factory=None, version_prompt=None, stop=None, context=None,
|
||||||
|
admission_timeout_seconds=10):
|
||||||
|
from .operation_queue import BatchTaskContext, TaskHandoff, current_context, task_stop
|
||||||
|
if stop is not None and stop.is_set() or context is not None and context.stop.is_set():
|
||||||
|
return VerifyResult('CANCELLED', stderr='已取消,未启动原生操作。', safe_to_continue=True)
|
||||||
|
options = dict(progress=progress, flag_reader=flag_reader, process_runner=process_runner,
|
||||||
|
port_check=port_check, dialog_supervisor_factory=dialog_supervisor_factory,
|
||||||
|
version_prompt=version_prompt)
|
||||||
|
bound = current_context()
|
||||||
|
if bound is None:
|
||||||
|
# Management may call Verify while holding a same-thread lease. Do not
|
||||||
|
# transfer that transaction to a different thread.
|
||||||
|
import threading
|
||||||
|
from .library_lock import _guard, _owners
|
||||||
|
with _guard:
|
||||||
|
nested = any(v['thread'] == threading.get_ident() and v['depth'] > 0
|
||||||
|
for v in _owners.values())
|
||||||
|
if not nested:
|
||||||
|
from .operation_queue import request_library_keys
|
||||||
|
bound = context or BatchTaskContext(library=str(request.lmc_file),
|
||||||
|
aliases=tuple(sorted(request_library_keys(request))), targets=(request.block_name,))
|
||||||
|
try:
|
||||||
|
return bound.run(lambda: run_verify(request, stop=stop, **options),
|
||||||
|
stop=stop, timeout_seconds=admission_timeout_seconds)
|
||||||
|
except TaskHandoff as error:
|
||||||
|
result = _handoff_verify_result(error)
|
||||||
|
_notify_progress(bound.guard_callback(progress) if progress else None,
|
||||||
|
dict(stage='task_handoff', operation_id=bound.operation_id,
|
||||||
|
library=bound.library, status=result.status, resource_scope=error.scope))
|
||||||
|
return result
|
||||||
|
if bound is not None and progress is not None:
|
||||||
|
options['progress'] = bound.guard_callback(progress)
|
||||||
|
return _run_verify_task(request, stop=task_stop(stop), **options)
|
||||||
|
|
||||||
|
|
||||||
|
def _handoff_verify_result(error):
|
||||||
|
known = error.result if isinstance(error.result, VerifyResult) else None
|
||||||
|
result = known or VerifyResult('CANCELLED' if error.cancelled else 'TIMEOUT')
|
||||||
|
return replace(result, status='FAIL' if result.status == 'PASS' else result.status,
|
||||||
|
stderr=result.stderr or str(error), safe_to_continue=False,
|
||||||
|
error_stage=result.error_stage or 'admission_or_finalization',
|
||||||
|
error_category=result.error_category or 'TASK_HANDOFF',
|
||||||
|
release_proof=dict(lease_state='PENDING', resource_scope=error.scope,
|
||||||
|
blocked_resources=error.scope.get('resources', [])))
|
||||||
|
|
||||||
|
|
||||||
|
def _run_verify_task(request, *, progress=None, flag_reader=None, process_runner=None, port_check=None,
|
||||||
dialog_supervisor_factory=None, version_prompt=None, stop=None):
|
dialog_supervisor_factory=None, version_prompt=None, stop=None):
|
||||||
# Cover contents checking, native work and final state reads with one
|
# Admission/finalization keep only the library lease. Native launch paths
|
||||||
# session-wide mutex. The worker-stage lock below is reentrant on Windows.
|
# acquire the host channel after slow metadata has returned.
|
||||||
import win32event, win32con
|
from .operation_queue import check_active
|
||||||
from .com_runtime import initialize_com, uninitialize_com
|
from .com_runtime import initialize_com, uninitialize_com
|
||||||
initialized = initialize_com()
|
initialized = initialize_com()
|
||||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
|
||||||
acquired = False
|
|
||||||
library_lock = None
|
library_lock = None
|
||||||
previous_release = None
|
previous_release = None
|
||||||
release_confirmed = True
|
release_confirmed = True
|
||||||
@@ -563,11 +645,7 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
|
|||||||
from .library_lock import _supervisor_alive
|
from .library_lock import _supervisor_alive
|
||||||
return bool(remaining_clients) and not any(_supervisor_alive(pid) for pid in remaining_clients)
|
return bool(remaining_clients) and not any(_supervisor_alive(pid) for pid in remaining_clients)
|
||||||
try:
|
try:
|
||||||
acquired = win32event.WaitForSingleObject(mutex, 0) in (
|
check_active()
|
||||||
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
|
||||||
if not acquired:
|
|
||||||
return VerifyResult('BLOCKED', stderr='已有 CBB 校验任务运行,请等待结束。',
|
|
||||||
safe_to_continue=True, error_category='NATIVE_CHANNEL_BUSY')
|
|
||||||
if request.maintenance:
|
if request.maintenance:
|
||||||
from .maintenance_entry import run_icdb_check
|
from .maintenance_entry import run_icdb_check
|
||||||
return run_icdb_check(request, progress=progress, stop=stop)
|
return run_icdb_check(request, progress=progress, stop=stop)
|
||||||
@@ -576,10 +654,13 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
|
|||||||
if Path(request.lmc_file).is_file():
|
if Path(request.lmc_file).is_file():
|
||||||
try:
|
try:
|
||||||
previous_release = recheck_previous_release(request.lmc_file,
|
previous_release = recheck_previous_release(request.lmc_file,
|
||||||
Path(request.evidence_dir)/'previous-release', block_name=request.block_name, progress=progress)
|
Path(request.evidence_dir)/'previous-release', block_name=request.block_name,
|
||||||
|
progress=progress, stop=stop)
|
||||||
|
check_active()
|
||||||
library_lock = LibraryLock(request.lmc_file, checkpoint=False,
|
library_lock = LibraryLock(request.lmc_file, checkpoint=False,
|
||||||
safe_to_release=clients_released)
|
safe_to_release=clients_released)
|
||||||
library_lock.__enter__()
|
library_lock.__enter__()
|
||||||
|
check_active()
|
||||||
except LibraryBusy as error:
|
except LibraryBusy as error:
|
||||||
return VerifyResult('FAIL', stderr=str(error), error_category='LIBRARY_IN_USE')
|
return VerifyResult('FAIL', stderr=str(error), error_category='LIBRARY_IN_USE')
|
||||||
except (OSError, ValueError, RuntimeError, pywintypes.error) as error:
|
except (OSError, ValueError, RuntimeError, pywintypes.error) as error:
|
||||||
@@ -691,14 +772,12 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
|
|||||||
if library_lock is not None:
|
if library_lock is not None:
|
||||||
library_lock.__exit__(None, None, None)
|
library_lock.__exit__(None, None, None)
|
||||||
finally:
|
finally:
|
||||||
if acquired:
|
|
||||||
win32event.ReleaseMutex(mutex)
|
|
||||||
mutex.Close()
|
|
||||||
uninitialize_com(initialized)
|
uninitialize_com(initialized)
|
||||||
|
|
||||||
|
|
||||||
def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_runner=None,
|
def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_runner=None,
|
||||||
port_check=None, dialog_supervisor_factory=None, version_prompt=None, stop=None):
|
port_check=None, dialog_supervisor_factory=None, version_prompt=None, stop=None):
|
||||||
|
from .operation_queue import remember_result
|
||||||
timing = RunTimings()
|
timing = RunTimings()
|
||||||
result = _run_verify(request, timing=timing, progress=progress, flag_reader=flag_reader,
|
result = _run_verify(request, timing=timing, progress=progress, flag_reader=flag_reader,
|
||||||
process_runner=process_runner, port_check=port_check,
|
process_runner=process_runner, port_check=port_check,
|
||||||
@@ -722,6 +801,7 @@ def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_
|
|||||||
result = replace(result, status='FAIL', stderr='原生会话或自动化客户端尚未退出。')
|
result = replace(result, status='FAIL', stderr='原生会话或自动化客户端尚未退出。')
|
||||||
except (OSError, ValueError, KeyError):
|
except (OSError, ValueError, KeyError):
|
||||||
pass
|
pass
|
||||||
|
remember_result(result)
|
||||||
if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP', 'CANCELLED'} and result.evidence_path:
|
if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP', 'CANCELLED'} and result.evidence_path:
|
||||||
job_path = result.evidence_path.with_name('request.json')
|
job_path = result.evidence_path.with_name('request.json')
|
||||||
if job_path.is_file():
|
if job_path.is_file():
|
||||||
@@ -735,13 +815,13 @@ def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_
|
|||||||
finally:
|
finally:
|
||||||
timing.end('failure_diagnostics')
|
timing.end('failure_diagnostics')
|
||||||
if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP'}:
|
if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP'}:
|
||||||
from .icdb_recovery import ERROR_CODE, RECOVERY_ACTION, parse_session_loss, recovery_detail
|
from .icdb_recovery import ERROR_CODE, RECOVERY_ACTION, parse_recovery_request, recovery_detail
|
||||||
recovery = parse_session_loss(result.stderr)
|
recovery = parse_recovery_request(result.stderr)
|
||||||
if recovery is None and result.evidence_path:
|
if recovery is None and result.evidence_path:
|
||||||
try:
|
try:
|
||||||
saved = json.loads(result.evidence_path.with_name('diagnostics').joinpath(
|
saved = json.loads(result.evidence_path.with_name('diagnostics').joinpath(
|
||||||
'icdb-recovery.json').read_text('utf-8'))
|
'icdb-recovery.json').read_text('utf-8'))
|
||||||
recovery = parse_session_loss(saved.get('native_message', ''))
|
recovery = parse_recovery_request(saved.get('native_message', ''))
|
||||||
except (OSError, ValueError, AttributeError):
|
except (OSError, ValueError, AttributeError):
|
||||||
pass
|
pass
|
||||||
if recovery or ERROR_CODE.casefold() in result.stderr.casefold():
|
if recovery or ERROR_CODE.casefold() in result.stderr.casefold():
|
||||||
@@ -764,6 +844,7 @@ def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_
|
|||||||
if result.status not in {"PASS", "SKIPPED"} else ""),
|
if result.status not in {"PASS", "SKIPPED"} else ""),
|
||||||
error_stage=(result.error_stage or (unfinished[-1] if unfinished else 'execution')
|
error_stage=(result.error_stage or (unfinished[-1] if unfinished else 'execution')
|
||||||
if result.status not in {"PASS", "SKIPPED"} else ""))
|
if result.status not in {"PASS", "SKIPPED"} else ""))
|
||||||
|
remember_result(result)
|
||||||
if result.evidence_path:
|
if result.evidence_path:
|
||||||
_write_optional_evidence(result.evidence_path, {'block_name': request.block_name, **asdict(result)})
|
_write_optional_evidence(result.evidence_path, {'block_name': request.block_name, **asdict(result)})
|
||||||
_write_optional_evidence(result.evidence_path.with_name('performance.json'), {
|
_write_optional_evidence(result.evidence_path.with_name('performance.json'), {
|
||||||
@@ -819,7 +900,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
|||||||
except Exception:
|
except Exception:
|
||||||
# Cleanup must never hide or change the verification result.
|
# Cleanup must never hide or change the verification result.
|
||||||
pass
|
pass
|
||||||
return replace(result, evidence_path=result_path)
|
from .operation_queue import remember_result
|
||||||
|
return remember_result(replace(result, evidence_path=result_path))
|
||||||
|
|
||||||
if stop is not None and stop.is_set():
|
if stop is not None and stop.is_set():
|
||||||
return finish(VerifyResult('CANCELLED', stderr='已取消,未启动校验。'))
|
return finish(VerifyResult('CANCELLED', stderr='已取消,未启动校验。'))
|
||||||
@@ -843,6 +925,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
|||||||
'detail': ' '.join(command)})
|
'detail': ' '.join(command)})
|
||||||
timing.begin('content_check')
|
timing.begin('content_check')
|
||||||
try:
|
try:
|
||||||
|
from .operation_queue import native_channel
|
||||||
|
with native_channel(read_only=True):
|
||||||
exit_code, stdout, stderr, timed_out = runner(command, request.timeout_seconds, Path(request.lmc_file).parent)
|
exit_code, stdout, stderr, timed_out = runner(command, request.timeout_seconds, Path(request.lmc_file).parent)
|
||||||
finally:
|
finally:
|
||||||
timing.end('content_check')
|
timing.end('content_check')
|
||||||
@@ -886,7 +970,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
|||||||
'cancel_signal': str(root/'cancel-worker.signal'),
|
'cancel_signal': str(root/'cancel-worker.signal'),
|
||||||
'start_gate': str(root/'start-worker.signal')}
|
'start_gate': str(root/'start-worker.signal')}
|
||||||
job.update(operation_id=root.name, operation='verify', library=str(request.lmc_file),
|
job.update(operation_id=root.name, operation='verify', library=str(request.lmc_file),
|
||||||
block=request.block_name, session_record_path=str(root/'session.json'))
|
block=request.block_name, session_record_path=str(root/'session.json'), start_gate_protocol='event-v1')
|
||||||
from .session_record import process_identity
|
from .session_record import process_identity
|
||||||
job['supervisor_identity'] = process_identity(os.getpid())
|
job['supervisor_identity'] = process_identity(os.getpid())
|
||||||
consent = None
|
consent = None
|
||||||
@@ -902,11 +986,22 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
|||||||
except Exception as error:
|
except Exception as error:
|
||||||
return finish(VerifyResult('FAIL', stderr=str(error)))
|
return finish(VerifyResult('FAIL', stderr=str(error)))
|
||||||
events = root/'events.jsonl'
|
events = root/'events.jsonl'
|
||||||
|
prewrite_eligible = not (request.diagnostic_only or request.interactive_input or request.native_lm_verify or consent)
|
||||||
|
def startup_phase(stage,**facts):
|
||||||
|
record={k:job[k] for k in ('operation_id','project','pcb','desktop')}
|
||||||
|
with events.open('a',encoding='utf-8') as stream:
|
||||||
|
stream.write(json.dumps(dict(stage=stage,**record,**facts))+'\n')
|
||||||
|
def before_dialog_action(snapshot,action):
|
||||||
|
name=action.get('action') if isinstance(action,dict) else action
|
||||||
|
if name not in ('dismiss_tip','accept_license','decline_database_log'):
|
||||||
|
startup_phase('startup_supervisor_write_possible',action=name,pid=snapshot.pid,hwnd=snapshot.hwnd)
|
||||||
offset = 0
|
offset = 0
|
||||||
target_pid = None
|
target_pid = None
|
||||||
|
diagnostic_closing = False
|
||||||
launcher_pid = None
|
launcher_pid = None
|
||||||
lm_pid = None
|
lm_pid = None
|
||||||
verify_invoked = False
|
verify_invoked = False
|
||||||
|
lm_dispatch_deadline = None
|
||||||
invoke_returned = False
|
invoke_returned = False
|
||||||
pcb_baseline = set()
|
pcb_baseline = set()
|
||||||
last_observation = 0.0
|
last_observation = 0.0
|
||||||
@@ -915,17 +1010,21 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
|||||||
from .desktop_worker import DesktopWorker
|
from .desktop_worker import DesktopWorker
|
||||||
from .dialog_supervisor import AgentDialogBackend, DialogSupervisor, Win32DialogBackend
|
from .dialog_supervisor import AgentDialogBackend, DialogSupervisor, Win32DialogBackend
|
||||||
from .dialog_models import DialogPhase
|
from .dialog_models import DialogPhase
|
||||||
import win32event, win32con
|
from .operation_queue import TaskHandoff, check_active, native_channel
|
||||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
check_active()
|
||||||
lock_status = win32event.WaitForSingleObject(mutex, 0)
|
|
||||||
if lock_status not in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED):
|
|
||||||
mutex.Close()
|
|
||||||
return finish(VerifyResult('BLOCKED', stderr='已有 CBB 校验任务运行;本次未启动。',
|
|
||||||
safe_to_continue=True, error_category='NATIVE_CHANNEL_BUSY'))
|
|
||||||
worker_launch_attempted = False
|
worker_launch_attempted = False
|
||||||
|
native = native_channel()
|
||||||
|
phase_entered = False
|
||||||
|
def end_native_phase():
|
||||||
|
nonlocal phase_entered
|
||||||
|
if phase_entered:
|
||||||
|
native.__exit__(None, None, None)
|
||||||
|
phase_entered = False
|
||||||
try:
|
try:
|
||||||
|
if prewrite_eligible:startup_phase('startup_supervisor_no_write')
|
||||||
timing.begin('worker_setup')
|
timing.begin('worker_setup')
|
||||||
with (root/'worker.log').open('w', encoding='utf-8') as log:
|
with (root/'worker.log').open('w', encoding='utf-8') as log:
|
||||||
|
check_active()
|
||||||
worker_launch_attempted = True
|
worker_launch_attempted = True
|
||||||
if request.interactive_input:
|
if request.interactive_input:
|
||||||
process = DesktopWorker(
|
process = DesktopWorker(
|
||||||
@@ -949,14 +1048,14 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
|||||||
from .dialog_rules import default_rules_path, load_rules
|
from .dialog_rules import default_rules_path, load_rules
|
||||||
dialog_agent = DialogAgentClient.start(process, root/'dialog-agent', stop=stop)
|
dialog_agent = DialogAgentClient.start(process, root/'dialog-agent', stop=stop)
|
||||||
dialog_supervisor = DialogSupervisor(
|
dialog_supervisor = DialogSupervisor(
|
||||||
AgentDialogBackend(dialog_agent, pids=lambda: {
|
AgentDialogBackend(dialog_agent, before_action=before_dialog_action if prewrite_eligible else None, pids=lambda: {
|
||||||
int(pid) for pid in (target_pid, lm_pid, launcher_pid) if pid}),
|
int(pid) for pid in (target_pid, lm_pid, launcher_pid) if pid}),
|
||||||
rules=load_rules(default_rules_path()),
|
rules=load_rules(default_rules_path(), diagnostic_only=request.diagnostic_only),
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
dialog_supervisor = DialogSupervisor(Win32DialogBackend(
|
dialog_supervisor = DialogSupervisor(Win32DialogBackend(
|
||||||
lambda: ({value for value in (target_pid, lm_pid) if value is not None}),
|
lambda: ({value for value in (target_pid, lm_pid) if value is not None}),
|
||||||
desktop=process.desktop,
|
desktop=process.desktop,before_action=before_dialog_action if prewrite_eligible else None,
|
||||||
))
|
))
|
||||||
else:
|
else:
|
||||||
dialog_supervisor = dialog_supervisor_factory(
|
dialog_supervisor = dialog_supervisor_factory(
|
||||||
@@ -965,7 +1064,15 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
|||||||
)
|
)
|
||||||
if stop is not None and stop.is_set():
|
if stop is not None and stop.is_set():
|
||||||
raise InterruptedError('VERIFY_CANCELLED: 启动已取消,未启动 PCB')
|
raise InterruptedError('VERIFY_CANCELLED: 启动已取消,未启动 PCB')
|
||||||
Path(job['start_gate']).touch()
|
check_active()
|
||||||
|
try:
|
||||||
|
native.__enter__()
|
||||||
|
phase_entered = True
|
||||||
|
except RuntimeError as error:
|
||||||
|
return finish(VerifyResult('BLOCKED', stderr=str(error), safe_to_continue=False,
|
||||||
|
error_category='NATIVE_CHANNEL_BUSY'))
|
||||||
|
from .operation_queue import commit_worker_start
|
||||||
|
commit_worker_start(process, job)
|
||||||
while process.poll() is None:
|
while process.poll() is None:
|
||||||
if stop is not None and stop.is_set():
|
if stop is not None and stop.is_set():
|
||||||
save_markers = timing._save_markers
|
save_markers = timing._save_markers
|
||||||
@@ -974,7 +1081,9 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
|||||||
'已请求停止,等待当前原生操作返回')
|
'已请求停止,等待当前原生操作返回')
|
||||||
_notify_progress(progress, {'stage': 'save_stop_requested', 'block': request.block_name,
|
_notify_progress(progress, {'stage': 'save_stop_requested', 'block': request.block_name,
|
||||||
'detail': detail})
|
'detail': detail})
|
||||||
_stop_worker(process)
|
from .failed_session import cancelled_prewrite_startup
|
||||||
|
_stop_worker(process, wait_for_native_write=False if request.diagnostic_only else
|
||||||
|
lambda:cancelled_prewrite_startup(job,target_pid) is None)
|
||||||
return finish(VerifyResult('CANCELLED', stderr='已取消当前校验。',
|
return finish(VerifyResult('CANCELLED', stderr='已取消当前校验。',
|
||||||
safe_to_continue=False, error_stage=phase.value))
|
safe_to_continue=False, error_stage=phase.value))
|
||||||
if events.exists():
|
if events.exists():
|
||||||
@@ -986,10 +1095,16 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
|||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
break
|
break
|
||||||
timing.record(event)
|
timing.record(event)
|
||||||
|
if _diagnostic_close_event(job, event, target_pid):
|
||||||
|
_acknowledge_diagnostic_close(job, event, stop)
|
||||||
|
diagnostic_closing = True
|
||||||
if event.get('pcb_pid'): target_pid = event['pcb_pid']
|
if event.get('pcb_pid'): target_pid = event['pcb_pid']
|
||||||
if event.get('launcher_pid'): launcher_pid = event['launcher_pid']
|
if event.get('launcher_pid'): launcher_pid = event['launcher_pid']
|
||||||
if event.get('lm_pid'): lm_pid = event['lm_pid']
|
if event.get('lm_pid'): lm_pid = event['lm_pid']
|
||||||
stage = event.get('stage')
|
stage = event.get('stage')
|
||||||
|
if stage == 'lm_launch' and lm_dispatch_deadline is None:
|
||||||
|
from .mentor_adapter import lm_dispatch_timeout_seconds
|
||||||
|
lm_dispatch_deadline = (event.get('monotonic_seconds') or time.monotonic()) + lm_dispatch_timeout_seconds(request.timeout_seconds)
|
||||||
if stage == 'verify_invoke': verify_invoked = True
|
if stage == 'verify_invoke': verify_invoked = True
|
||||||
if stage == 'verify_invoke_returned': invoke_returned = True
|
if stage == 'verify_invoke_returned': invoke_returned = True
|
||||||
if stage == 'pcb_baseline': pcb_baseline = set(event.get('pids', ()))
|
if stage == 'pcb_baseline': pcb_baseline = set(event.get('pids', ()))
|
||||||
@@ -1021,7 +1136,11 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
|||||||
except Exception as error:
|
except Exception as error:
|
||||||
observation = {'error': str(error)}
|
observation = {'error': str(error)}
|
||||||
last_post_verify_observation = observation
|
last_post_verify_observation = observation
|
||||||
if dialog_agent is not None and target_pid is None:
|
if diagnostic_closing:
|
||||||
|
# The exact diagnostic worker owns its bounded close/No sequence.
|
||||||
|
from .dialog_supervisor import DialogPollResult
|
||||||
|
dialog_result = DialogPollResult(activity=False)
|
||||||
|
elif dialog_agent is not None and target_pid is None:
|
||||||
# The Library Manager Verify route starts its own window
|
# The Library Manager Verify route starts its own window
|
||||||
# before it launches Expedition PCB. Do not feed that
|
# before it launches Expedition PCB. Do not feed that
|
||||||
# large MFC main window to the PCB dialog probe; it can
|
# large MFC main window to the PCB dialog probe; it can
|
||||||
@@ -1039,6 +1158,13 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
|||||||
dialog_result = dialog_supervisor.poll()
|
dialog_result = dialog_supervisor.poll()
|
||||||
else:
|
else:
|
||||||
dialog_result = dialog_supervisor.poll()
|
dialog_result = dialog_supervisor.poll()
|
||||||
|
if not diagnostic_closing:
|
||||||
|
intent = _close_intent_after_poll(job, events, offset, target_pid)
|
||||||
|
if intent is not None:
|
||||||
|
_acknowledge_diagnostic_close(job, intent, stop)
|
||||||
|
diagnostic_closing = True
|
||||||
|
from .dialog_supervisor import DialogPollResult
|
||||||
|
dialog_result = DialogPollResult(activity=False)
|
||||||
if (version_prompt is not None and consent is None and dialog_agent is not None
|
if (version_prompt is not None and consent is None and dialog_agent is not None
|
||||||
and not request.diagnostic_only and not request.native_lm_verify
|
and not request.diagnostic_only and not request.native_lm_verify
|
||||||
and dialog_result.error_code == 'DATABASE_RECOVERY_REQUIRED'
|
and dialog_result.error_code == 'DATABASE_RECOVERY_REQUIRED'
|
||||||
@@ -1107,7 +1233,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
|||||||
error_stage=phase.value,
|
error_stage=phase.value,
|
||||||
safe_to_continue=False,
|
safe_to_continue=False,
|
||||||
))
|
))
|
||||||
if deadline.expired():
|
if deadline.expired() or (lm_dispatch_deadline is not None and target_pid is None
|
||||||
|
and time.monotonic() >= lm_dispatch_deadline):
|
||||||
_write_failure_windows(root, latest_snapshots)
|
_write_failure_windows(root, latest_snapshots)
|
||||||
# Stop automation without killing PCB/iCDB during a write.
|
# Stop automation without killing PCB/iCDB during a write.
|
||||||
_write_process_tree(root, process, target_pid)
|
_write_process_tree(root, process, target_pid)
|
||||||
@@ -1123,7 +1250,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
|||||||
target_pid=target_pid,
|
target_pid=target_pid,
|
||||||
observation=last_post_verify_observation,
|
observation=last_post_verify_observation,
|
||||||
)
|
)
|
||||||
_stop_worker(process)
|
_stop_worker(process, wait_for_native_write=not request.diagnostic_only)
|
||||||
if dispatch_failure is not None:
|
if dispatch_failure is not None:
|
||||||
status, detail = dispatch_failure
|
status, detail = dispatch_failure
|
||||||
if progress:
|
if progress:
|
||||||
@@ -1136,6 +1263,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
|||||||
return finish(VerifyResult(status, stderr=detail, safe_to_continue=False))
|
return finish(VerifyResult(status, stderr=detail, safe_to_continue=False))
|
||||||
return finish(VerifyResult('TIMEOUT', stderr='操作超时,当前项未完成。', error_stage=phase.value, safe_to_continue=False))
|
return finish(VerifyResult('TIMEOUT', stderr='操作超时,当前项未完成。', error_stage=phase.value, safe_to_continue=False))
|
||||||
time.sleep(.2)
|
time.sleep(.2)
|
||||||
|
end_native_phase() # Exact worker exit precedes all optional outcome/evidence I/O.
|
||||||
worker_result = root/'outcome.json'
|
worker_result = root/'outcome.json'
|
||||||
if not worker_result.exists():
|
if not worker_result.exists():
|
||||||
return finish(VerifyResult('FAIL', stderr=f'执行器异常退出 ({process.returncode}),见 worker.log', safe_to_continue=False))
|
return finish(VerifyResult('FAIL', stderr=f'执行器异常退出 ({process.returncode}),见 worker.log', safe_to_continue=False))
|
||||||
@@ -1145,7 +1273,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
|||||||
result = VerifyResult(**outcome)
|
result = VerifyResult(**outcome)
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
if 'process' in locals() and process.poll() is None:
|
if 'process' in locals() and process.poll() is None:
|
||||||
_stop_worker(process)
|
_stop_worker(process, wait_for_native_write=not request.diagnostic_only)
|
||||||
launch_release = getattr(error, 'worker_launch_release', None) if 'process' not in locals() else None
|
launch_release = getattr(error, 'worker_launch_release', None) if 'process' not in locals() else None
|
||||||
if not worker_launch_attempted:
|
if not worker_launch_attempted:
|
||||||
launch_release = {'process_created': False, 'worker_exited': True,
|
launch_release = {'process_created': False, 'worker_exited': True,
|
||||||
@@ -1164,7 +1292,12 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
|||||||
finally:
|
finally:
|
||||||
close_errors = []
|
close_errors = []
|
||||||
worker_exited = False
|
worker_exited = False
|
||||||
|
observer_started = False
|
||||||
automation_release = {'safe_to_continue': False}
|
automation_release = {'safe_to_continue': False}
|
||||||
|
if 'process' not in locals() or process.poll() is not None or getattr(process, 'session_record_path', None):
|
||||||
|
# A gated worker owns its writer barrier and inherited sidecar.
|
||||||
|
# Parent admission must not block controls needed for its exit.
|
||||||
|
end_native_phase()
|
||||||
if 'dialog_agent' in locals() and dialog_agent is not None:
|
if 'dialog_agent' in locals() and dialog_agent is not None:
|
||||||
try:
|
try:
|
||||||
dialog_agent.close()
|
dialog_agent.close()
|
||||||
@@ -1174,20 +1307,27 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
|||||||
try:
|
try:
|
||||||
worker_exited = process.poll() is not None
|
worker_exited = process.poll() is not None
|
||||||
if not worker_exited:
|
if not worker_exited:
|
||||||
worker_exited = _stop_worker(process)
|
worker_exited = _stop_worker(process, wait_for_native_write=not request.diagnostic_only)
|
||||||
if hasattr(process, 'automation_release_state'):
|
if hasattr(process, 'automation_release_state'):
|
||||||
automation_release = process.automation_release_state()
|
automation_release = process.automation_release_state()
|
||||||
else:
|
else:
|
||||||
automation_release = {'safe_to_continue': worker_exited, 'remaining_pids': []}
|
automation_release = {'safe_to_continue': worker_exited, 'remaining_pids': []}
|
||||||
if worker_exited:
|
if not worker_exited and getattr(process, 'session_record_path', None):
|
||||||
process.close()
|
|
||||||
elif getattr(process, 'session_record_path', None):
|
|
||||||
from .session_record import handoff_session
|
from .session_record import handoff_session
|
||||||
handoff_session(process.session_record_path, evidence_root=root,
|
handoff_session(process.session_record_path, evidence_root=root,
|
||||||
process=process, progress=lambda state: _notify_progress(progress,
|
process=process, progress=lambda state: _notify_progress(progress,
|
||||||
{'stage': 'session_observation', 'block': request.block_name, **state}))
|
{'stage': 'session_observation', 'block': request.block_name, **state}))
|
||||||
|
observer_started = True
|
||||||
_notify_progress(progress, {'stage': 'session_handoff', 'block': request.block_name,
|
_notify_progress(progress, {'stage': 'session_handoff', 'block': request.block_name,
|
||||||
'detail': '已转后台观察,可查看状态'})
|
'detail': '已转后台观察,可查看状态'})
|
||||||
|
from .operation_queue import hold_native_handoff
|
||||||
|
hold_native_handoff(process, process.session_record_path)
|
||||||
|
except TaskHandoff as error:
|
||||||
|
handoff_result = _handoff_verify_result(error)
|
||||||
|
if handoff_result.evidence_path:
|
||||||
|
_write_optional_evidence(handoff_result.evidence_path,
|
||||||
|
{'block_name': request.block_name, **asdict(handoff_result)})
|
||||||
|
raise
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
close_errors.append(str(error))
|
close_errors.append(str(error))
|
||||||
if 'process' in locals():
|
if 'process' in locals():
|
||||||
@@ -1232,6 +1372,25 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
|||||||
'automation_release': automation_release, 'worker_exited': worker_exited}
|
'automation_release': automation_release, 'worker_exited': worker_exited}
|
||||||
release_result['remaining_pids'] = sorted(set(release_result.get('remaining_pids', []))
|
release_result['remaining_pids'] = sorted(set(release_result.get('remaining_pids', []))
|
||||||
| set(automation_release.get('remaining_pids', [])))
|
| set(automation_release.get('remaining_pids', [])))
|
||||||
|
if worker_exited:
|
||||||
|
try:
|
||||||
|
if (release_result.get('safe_to_continue') is not True
|
||||||
|
and getattr(process, 'session_record_path', None)):
|
||||||
|
if not observer_started:
|
||||||
|
from .session_record import handoff_session
|
||||||
|
# Retain the exact worker handle until registered
|
||||||
|
# native clients exit and the observer obtains proof.
|
||||||
|
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}))
|
||||||
|
observer_started = True
|
||||||
|
_notify_progress(progress, {'stage': 'session_handoff', 'block': request.block_name,
|
||||||
|
'detail': '工作进程已退出,原生会话继续后台观察'})
|
||||||
|
else:
|
||||||
|
process.close()
|
||||||
|
except Exception as error:
|
||||||
|
release_result = {**release_result, 'safe_to_continue': False,
|
||||||
|
'close_errors': [*close_errors, str(error)]}
|
||||||
try:
|
try:
|
||||||
from .operation_lifecycle import classify_save_state
|
from .operation_lifecycle import classify_save_state
|
||||||
save_lines = ((root/'save.log').read_text('utf-8', errors='replace').splitlines()
|
save_lines = ((root/'save.log').read_text('utf-8', errors='replace').splitlines()
|
||||||
@@ -1279,8 +1438,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
|||||||
except OSError:
|
except OSError:
|
||||||
pass
|
pass
|
||||||
finally:
|
finally:
|
||||||
win32event.ReleaseMutex(mutex)
|
end_native_phase()
|
||||||
mutex.Close()
|
|
||||||
|
|
||||||
if result.status == 'PASS' and not request.diagnostic_only:
|
if result.status == 'PASS' and not request.diagnostic_only:
|
||||||
timing.begin('library_flag')
|
timing.begin('library_flag')
|
||||||
@@ -1290,6 +1448,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
|||||||
if progress:
|
if progress:
|
||||||
_notify_progress(progress, {'stage': 'library_flag_probe', 'block': request.block_name, **record})
|
_notify_progress(progress, {'stage': 'library_flag_probe', 'block': request.block_name, **record})
|
||||||
try:
|
try:
|
||||||
|
with native_channel(read_only=True):
|
||||||
probe = read_library_flag_with_retry(
|
probe = read_library_flag_with_retry(
|
||||||
flag_reader or read_library_flag_if_available, Path(request.lmc_file),
|
flag_reader or read_library_flag_if_available, Path(request.lmc_file),
|
||||||
request.block_name, on_attempt=record_attempt)
|
request.block_name, on_attempt=record_attempt)
|
||||||
@@ -1304,20 +1463,27 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
|||||||
return finish(result)
|
return finish(result)
|
||||||
|
|
||||||
|
|
||||||
def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=None, item_executor=None):
|
def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=None, item_executor=None,
|
||||||
|
context=None):
|
||||||
"""Run serially and stop when database/session safety is unconfirmed."""
|
"""Run serially and stop when database/session safety is unconfirmed."""
|
||||||
if max_workers != 1:
|
if max_workers != 1:
|
||||||
raise ValueError('Only serial Verify is supported for the shared Library Manager session')
|
raise ValueError('Only serial Verify is supported for the shared Library Manager session')
|
||||||
|
if context is not None:
|
||||||
|
stop = stop if stop is not None else context.stop
|
||||||
|
progress = context.guard_callback(progress) if progress is not None else None
|
||||||
if verifier is None:
|
if verifier is None:
|
||||||
verifier = lambda request: run_verify(request, flag_reader=read_library_flag_if_available, stop=stop) # noqa: E731
|
verifier = lambda request: run_verify(request, flag_reader=read_library_flag_if_available,
|
||||||
|
stop=stop, context=context) # noqa: E731
|
||||||
results = []
|
results = []
|
||||||
queue_stop = False
|
queue_stop = False
|
||||||
retained_libraries = set()
|
retained_libraries = set()
|
||||||
for request in requests:
|
for request in requests:
|
||||||
library_key = str(getattr(request, 'lmc_file', '__injected_verifier_scope__')).casefold()
|
from .operation_queue import request_library_keys
|
||||||
if queue_stop or (stop is not None and stop.is_set()):
|
library_keys = request_library_keys(request, context)
|
||||||
|
if (queue_stop or stop is not None and stop.is_set()
|
||||||
|
or context is not None and context.stop.is_set()):
|
||||||
result = VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB')
|
result = VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB')
|
||||||
elif library_key in retained_libraries:
|
elif library_keys.intersection(retained_libraries):
|
||||||
result = VerifyResult('SKIPPED', stderr='同库原生会话尚未释放,未启动新的写入')
|
result = VerifyResult('SKIPPED', stderr='同库原生会话尚未释放,未启动新的写入')
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
@@ -1325,18 +1491,19 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
|
|||||||
result = verifier(request)
|
result = verifier(request)
|
||||||
if not result.safe_to_continue:
|
if not result.safe_to_continue:
|
||||||
from .operation_lifecycle import recheck_failed_release
|
from .operation_lifecycle import recheck_failed_release
|
||||||
result = recheck_failed_release(request.lmc_file, request.block_name, result)
|
result = recheck_failed_release(request.lmc_file, request.block_name, result, stop=stop)
|
||||||
return result
|
return result
|
||||||
result = item_executor(request, execute) if item_executor is not None else execute()
|
result = item_executor(request, execute) if item_executor is not None else execute()
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
from .operation_queue import QueueCancelled
|
from .operation_queue import QueueCancelled, TaskHandoff
|
||||||
# An unexpected exception cannot establish database safety.
|
# An unexpected exception cannot establish database safety.
|
||||||
result = VerifyResult('CANCELLED' if isinstance(error, QueueCancelled) else 'FAIL',
|
result = (_handoff_verify_result(error) if isinstance(error, TaskHandoff) else
|
||||||
stderr=str(error), safe_to_continue=isinstance(error, QueueCancelled))
|
VerifyResult('CANCELLED' if isinstance(error, QueueCancelled) else 'FAIL',
|
||||||
|
stderr=str(error), safe_to_continue=isinstance(error, QueueCancelled)))
|
||||||
results.append(result)
|
results.append(result)
|
||||||
# Never start another writer after an unconfirmed native shutdown.
|
# Never start another writer after an unconfirmed native shutdown.
|
||||||
if not result.safe_to_continue:
|
if not result.safe_to_continue:
|
||||||
retained_libraries.add(library_key)
|
retained_libraries.update(library_keys)
|
||||||
queue_stop = queue_stop or result.status in {'QUEUE_STOP', 'CANCELLED'}
|
queue_stop = queue_stop or result.status in {'QUEUE_STOP', 'CANCELLED'}
|
||||||
if queue_stop and stop is not None:
|
if queue_stop and stop is not None:
|
||||||
stop.set()
|
stop.set()
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
"""Batch-local user confirmation for native clients with unknown target paths."""
|
||||||
|
from pathlib import Path
|
||||||
|
import time
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from .pcb_open_consent import OpenChoice
|
||||||
|
from .session_record import process_identity
|
||||||
|
|
||||||
|
|
||||||
|
class WriteOwnerChoice(OpenChoice):
|
||||||
|
def __init__(self, block, library, owners):
|
||||||
|
super().__init__(block, library)
|
||||||
|
self.owners = tuple(dict(row) for row in owners)
|
||||||
|
|
||||||
|
|
||||||
|
class WriteAdmissionDeclined(ValueError):
|
||||||
|
def __init__(self, decision, detail=None):
|
||||||
|
self.decision = decision
|
||||||
|
super().__init__(detail or ('已取消本批次,未提交后续写入。' if decision == 'cancel' else
|
||||||
|
'用户跳过本项,未确认未知程序与目标库无关。'))
|
||||||
|
|
||||||
|
|
||||||
|
class WriteAdmission:
|
||||||
|
def __init__(self, *, prompt=None, stop=None):
|
||||||
|
self.prompt, self.stop = prompt, stop
|
||||||
|
self._grants = {}
|
||||||
|
|
||||||
|
def _identities(self, owners):
|
||||||
|
rows = []
|
||||||
|
for row in owners:
|
||||||
|
try:
|
||||||
|
identity = process_identity(row['pid'])
|
||||||
|
except Exception as error:
|
||||||
|
if getattr(error, 'winerror', None) == 87:
|
||||||
|
continue
|
||||||
|
raise
|
||||||
|
if Path(identity['image']).name.casefold() != row['name'].casefold():
|
||||||
|
raise ValueError('TARGET_NATIVE_OWNER_UNCONFIRMED: PID 已被其他程序复用,请重新检查。')
|
||||||
|
if row.get('executable') and Path(row['executable']).resolve() != Path(identity['image']).resolve():
|
||||||
|
raise ValueError('TARGET_NATIVE_OWNER_UNCONFIRMED: 原生程序身份已变化,请重新检查。')
|
||||||
|
rows.append({**identity, 'name': row['name']})
|
||||||
|
return tuple(sorted((row['pid'], row['created_handle'], row['image'], row['owner_sid'], row['session_id'])
|
||||||
|
for row in rows)), rows
|
||||||
|
|
||||||
|
def confirmed(self, library, owners):
|
||||||
|
key = str(Path(library).resolve()).casefold()
|
||||||
|
identities, _ = self._identities(owners)
|
||||||
|
return set(identities).issubset(self._grants.get(key, set()))
|
||||||
|
|
||||||
|
def confirm(self, library, owners, *, evidence, block):
|
||||||
|
key = str(Path(library).resolve()).casefold()
|
||||||
|
identities, rows = self._identities(owners)
|
||||||
|
if set(identities).issubset(self._grants.get(key, set())):
|
||||||
|
return
|
||||||
|
if self.prompt is None:
|
||||||
|
raise WriteAdmissionDeclined('skip',
|
||||||
|
'TARGET_NATIVE_OWNER_UNCONFIRMED: 无法确认原生程序是否使用目标库,未执行;请通过界面核对后选择。')
|
||||||
|
choice = WriteOwnerChoice(block, str(Path(library)), rows)
|
||||||
|
self.prompt(choice)
|
||||||
|
while choice.decision is None and not (self.stop is not None and self.stop.is_set()):
|
||||||
|
time.sleep(.05)
|
||||||
|
decision = choice.decision or 'cancel'
|
||||||
|
if decision != 'continue':
|
||||||
|
if decision == 'cancel' and self.stop is not None:
|
||||||
|
self.stop.set()
|
||||||
|
detail = ('确认等待超时默认跳过本项,未授予未知进程写入许可。'
|
||||||
|
if decision == 'skip' and choice.decision_origin == 'timeout_default' else None)
|
||||||
|
raise WriteAdmissionDeclined(decision, detail)
|
||||||
|
current, _ = self._identities(owners)
|
||||||
|
if not set(current).issubset(identities):
|
||||||
|
raise ValueError('TARGET_NATIVE_OWNER_UNCONFIRMED: 确认期间进程身份已变化,请重新检查。')
|
||||||
|
from .management import _write_json
|
||||||
|
root = Path(evidence)
|
||||||
|
root.mkdir(parents=True, exist_ok=True)
|
||||||
|
_write_json(root/('write-owner-consent-'+uuid4().hex+'.json'), dict(
|
||||||
|
intent='user_confirmed_unknown_clients_do_not_use_target_library', library=str(Path(library).resolve()),
|
||||||
|
block=block, scope='current_batch_library', owners=rows, choice='continue',
|
||||||
|
decision_origin=choice.decision_origin,
|
||||||
|
proves_native_ownership=False, requires_fresh_resource_checks=True))
|
||||||
|
self._grants.setdefault(key, set()).update(current)
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
"""Keep subprocess imports on the worktree being tested."""
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def pytest_configure():
|
||||||
|
source = str(Path(__file__).resolve().parents[1] / 'src')
|
||||||
|
existing = os.environ.get('PYTHONPATH', '').split(os.pathsep)
|
||||||
|
os.environ['PYTHONPATH'] = os.pathsep.join(
|
||||||
|
[source, *(entry for entry in existing if entry and entry != source)])
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
"""Run the real Add dispatch with harmless process and Win32/UIA boundaries."""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
from pytest import MonkeyPatch
|
||||||
|
|
||||||
|
from cbb_refresh_verify import desktop_worker, native_management as native
|
||||||
|
from cbb_refresh_verify.session_record import update_worker_state
|
||||||
|
|
||||||
|
|
||||||
|
def run(job_path):
|
||||||
|
job = json.loads(Path(job_path).read_text(encoding='utf-8'))
|
||||||
|
root = Path(job['root'])
|
||||||
|
signals = root.parent
|
||||||
|
mode = job['test_mode']
|
||||||
|
lm_script = '''import subprocess,sys,time
|
||||||
|
from pathlib import Path
|
||||||
|
root=Path(sys.argv[1])
|
||||||
|
input()
|
||||||
|
if sys.argv[2] == 'pending':
|
||||||
|
code='import sys,time; from pathlib import Path; p=Path(sys.argv[1]); '+\
|
||||||
|
'\\nwhile not p.exists(): time.sleep(.02)'
|
||||||
|
child=subprocess.Popen([sys.executable,'-c',code,str(root/'native-done')])
|
||||||
|
(root/'descendant-pid').write_text(str(child.pid))
|
||||||
|
while not (root/'lm-exit').exists(): time.sleep(.02)
|
||||||
|
'''
|
||||||
|
lm = subprocess.Popen([sys.executable, '-c', lm_script, str(signals), mode], stdin=subprocess.PIPE, text=True)
|
||||||
|
(signals/'lm-pid').write_text(str(lm.pid))
|
||||||
|
update_worker_state(job, 'POSTCALL', identities=[('native', lm.pid)], required=True)
|
||||||
|
desktop_worker.start_supervisor_watchdog(job['supervisor_pid'], cancel_path=job['cancel_signal'],
|
||||||
|
session_record_path=job['session_record_path'], operation_id=job['operation_id'],
|
||||||
|
supervisor_identity=job['supervisor_identity'])
|
||||||
|
state = {'new': False, 'posted': False, 'closed': False}
|
||||||
|
patch = MonkeyPatch()
|
||||||
|
import win32gui, win32process
|
||||||
|
if mode == 'assignment-failed':
|
||||||
|
def deny_job(*args):
|
||||||
|
raise OSError('exact native job admission denied')
|
||||||
|
patch.setattr(desktop_worker.win32job, 'AssignProcessToJobObject', deny_job)
|
||||||
|
if mode == 'cancel-after-registration':
|
||||||
|
assign = desktop_worker.win32job.AssignProcessToJobObject
|
||||||
|
def cancel_after_assign(*args):
|
||||||
|
result = assign(*args)
|
||||||
|
(root/'cancel-native-add.signal').touch()
|
||||||
|
return result
|
||||||
|
patch.setattr(desktop_worker.win32job, 'AssignProcessToJobObject', cancel_after_assign)
|
||||||
|
tab = SimpleNamespace(window_text=lambda: 'Logical - Physical', is_selected=lambda: True)
|
||||||
|
patch.setitem(sys.modules, 'pywinauto', SimpleNamespace(Desktop=lambda **kw: SimpleNamespace(
|
||||||
|
window=lambda **kw: SimpleNamespace(descendants=lambda **kw: [tab]))))
|
||||||
|
patch.setattr(win32process, 'GetWindowThreadProcessId', lambda _: (1, lm.pid))
|
||||||
|
patch.setattr(win32gui, 'IsWindowVisible', lambda _: True)
|
||||||
|
patch.setattr(win32gui, 'IsWindowEnabled', lambda _: True)
|
||||||
|
patch.setattr(win32gui, 'GetWindowText', lambda h: {
|
||||||
|
100: 'Reusable Blocks', 200: 'New Reusable Block', 300: 'Native result',
|
||||||
|
301: 'New Logical-Physical Reuse Block was successfully added.'}.get(int(h), ''))
|
||||||
|
patch.setattr(win32gui, 'GetDlgItem', lambda h, c:
|
||||||
|
110 if h == 100 and c == 1066 else 112 if h == 100 else 210 if c == 1083 else 302 if h == 300 else c+1000)
|
||||||
|
patch.setattr(win32gui, 'GetClassName', lambda _: 'Edit')
|
||||||
|
patch.setattr(win32gui, 'IsWindow', lambda _: not state['closed'])
|
||||||
|
patch.setattr(win32gui, 'EnumChildWindows', lambda h, fn, arg:
|
||||||
|
fn(301, arg) if h == 300 and mode == 'acknowledged' else None)
|
||||||
|
# Only the external native text-control setter is substituted.
|
||||||
|
patch.setattr(native, '_set_probe_field', lambda hwnd, control, value, root, *, read_only=False: None)
|
||||||
|
def post(hwnd, *args):
|
||||||
|
if hwnd == 110: state['new'] = True
|
||||||
|
if hwnd == 210:
|
||||||
|
state['posted'] = True
|
||||||
|
lm.stdin.write('Add\n')
|
||||||
|
lm.stdin.flush()
|
||||||
|
(signals/'add-dispatched').touch()
|
||||||
|
if hwnd == 112: state['closed'] = True
|
||||||
|
patch.setattr(win32gui, 'PostMessage', post)
|
||||||
|
def windows():
|
||||||
|
if state['closed']: return []
|
||||||
|
return ([100, 200, 300] if state['posted'] and mode == 'acknowledged' else
|
||||||
|
[100, 200] if state['new'] else [100])
|
||||||
|
desktop = SimpleNamespace(EnumDesktopWindows=windows)
|
||||||
|
try:
|
||||||
|
native._probe_add_dialog(SimpleNamespace(OnReusableBlocksEditor=lambda: None),
|
||||||
|
job, desktop, {lm.pid}, root)
|
||||||
|
result = {'success': True, 'safe_to_continue': False}
|
||||||
|
except (TimeoutError, OSError, RuntimeError) as error:
|
||||||
|
result = {'success': False, 'safe_to_continue': False, 'detail': str(error)}
|
||||||
|
finally:
|
||||||
|
patch.undo()
|
||||||
|
(root/'result.json').write_text(json.dumps(result))
|
||||||
|
update_worker_state(job, 'UNCONFIRMED')
|
||||||
|
(signals/'add-unwound').touch()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
desktop_worker.run_native_worker(run, Path(sys.argv[1]))
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
"""Real application close while one disposable metadata boundary is held."""
|
||||||
|
from pathlib import Path
|
||||||
|
import sys,time
|
||||||
|
|
||||||
|
from PySide6.QtCore import QTimer
|
||||||
|
from PySide6.QtWidgets import QApplication
|
||||||
|
from cbb_refresh_verify import scoped_manifest as manifest
|
||||||
|
from cbb_refresh_verify.operation_queue import check_active
|
||||||
|
from cbb_refresh_verify.ui.main_window import MainWindow
|
||||||
|
|
||||||
|
root=Path(sys.argv[1]);mode=sys.argv[2]
|
||||||
|
source=root/'source';source.mkdir()
|
||||||
|
(source/('one.log' if mode=='copy' else 'one.dat')).write_bytes(b'isolated fixture')
|
||||||
|
def held():
|
||||||
|
(root/'entered').touch()
|
||||||
|
while not (root/'release').exists():time.sleep(.02)
|
||||||
|
def hash_file(path):
|
||||||
|
held()
|
||||||
|
return manifest.hash_file(path)
|
||||||
|
if mode=='copy':
|
||||||
|
original=manifest.shutil.copy2
|
||||||
|
def copy_file(*args,**kwargs):
|
||||||
|
held()
|
||||||
|
return original(*args,**kwargs)
|
||||||
|
manifest.shutil.copy2=copy_file
|
||||||
|
def action():
|
||||||
|
if mode=='hash':manifest.build_manifest(source,hash_function=hash_file)
|
||||||
|
else:manifest.copy_verified(source,root/'partial-copy',hash_function=hash_file)
|
||||||
|
check_active()
|
||||||
|
(root/'late-dispatch').touch()
|
||||||
|
app=QApplication([])
|
||||||
|
window=MainWindow(reader=lambda _:None,data_root=root/'data');window.show()
|
||||||
|
job=window._new_job('management',library=root/'library.lmc')
|
||||||
|
window._start(action,lambda _:None,queued=False,job=job)
|
||||||
|
def close_when_entered():
|
||||||
|
if (root/'entered').exists():window.close()
|
||||||
|
else:QTimer.singleShot(20,close_when_entered)
|
||||||
|
QTimer.singleShot(20,close_when_entered)
|
||||||
|
code=app.exec()
|
||||||
|
(root/'main-returning').touch()
|
||||||
|
raise SystemExit(code)
|
||||||
@@ -9,6 +9,7 @@ from uuid import uuid4
|
|||||||
workspace = Path(sys.argv[1]).resolve()
|
workspace = Path(sys.argv[1]).resolve()
|
||||||
bundle_root = Path(sys.argv[2]).resolve()
|
bundle_root = Path(sys.argv[2]).resolve()
|
||||||
sys.path.insert(0, str(workspace/'src'))
|
sys.path.insert(0, str(workspace/'src'))
|
||||||
|
from cbb_refresh_verify import __version__
|
||||||
exe = bundle_root/'dist/CbbRefreshVerify-Background/CbbRefreshVerify.exe'
|
exe = bundle_root/'dist/CbbRefreshVerify-Background/CbbRefreshVerify.exe'
|
||||||
root = bundle_root/('smoke-' + uuid4().hex[:8])
|
root = bundle_root/('smoke-' + uuid4().hex[:8])
|
||||||
root.mkdir()
|
root.mkdir()
|
||||||
@@ -64,7 +65,7 @@ finally:
|
|||||||
from PyInstaller.archive.readers import ZlibArchiveReader
|
from PyInstaller.archive.readers import ZlibArchiveReader
|
||||||
pyz = bundle_root/'build/CbbRefreshVerify/PYZ-00.pyz'
|
pyz = bundle_root/'build/CbbRefreshVerify/PYZ-00.pyz'
|
||||||
code = ZlibArchiveReader(str(pyz)).extract('cbb_refresh_verify')
|
code = ZlibArchiveReader(str(pyz)).extract('cbb_refresh_verify')
|
||||||
assert '0.2.4b2' in code.co_consts
|
assert __version__ in code.co_consts
|
||||||
toc = ast.literal_eval((bundle_root/'build/CbbRefreshVerify/Analysis-00.toc').read_text('utf-8'))
|
toc = ast.literal_eval((bundle_root/'build/CbbRefreshVerify/Analysis-00.toc').read_text('utf-8'))
|
||||||
stack, rows = [toc], []
|
stack, rows = [toc], []
|
||||||
while stack:
|
while stack:
|
||||||
@@ -77,6 +78,6 @@ while stack:
|
|||||||
stack.extend(value)
|
stack.extend(value)
|
||||||
assert rows and all(Path(row[1]).is_relative_to(workspace/'src') for row in rows)
|
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['module_origins'] = {'status': 'passed', 'module_count': len(rows), 'source_root': str(workspace/'src')}
|
||||||
results['version'] = '0.2.4b2'
|
results['version'] = __version__
|
||||||
(root/'result.json').write_text(json.dumps(results, ensure_ascii=False, indent=2), 'utf-8')
|
(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)
|
print(json.dumps({'evidence': str(root/'result.json'), **results}, ensure_ascii=False), flush=True)
|
||||||
@@ -130,7 +130,7 @@ def test_main_logs_and_evidence_buttons_open_the_correct_paths(controls, qtbot):
|
|||||||
w.recovery_path = evidence
|
w.recovery_path = evidence
|
||||||
w.recovery_button.setEnabled(True)
|
w.recovery_button.setEnabled(True)
|
||||||
press(qtbot, w.recovery_button)
|
press(qtbot, w.recovery_button)
|
||||||
assert controls.opened == [w.data_root, evidence]
|
assert controls.opened == [w.data_root/'logs', evidence]
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize('attribute', ['selected_batch_button', 'batch_button', 'icdb_repair_button'])
|
@pytest.mark.parametrize('attribute', ['selected_batch_button', 'batch_button', 'icdb_repair_button'])
|
||||||
@@ -152,7 +152,7 @@ def test_main_check_buttons_have_real_confirm_and_cancel_paths(controls, qtbot,
|
|||||||
assert details is not None
|
assert details is not None
|
||||||
press(qtbot, details)
|
press(qtbot, details)
|
||||||
assert summary.findChild(QTextEdit).isVisible()
|
assert summary.findChild(QTextEdit).isVisible()
|
||||||
press(qtbot, summary.button(QMessageBox.Ok))
|
press(qtbot, summary.button(QMessageBox.Close))
|
||||||
assert not isValid(summary) or not summary.isVisible()
|
assert not isValid(summary) or not summary.isVisible()
|
||||||
|
|
||||||
|
|
||||||
@@ -280,7 +280,7 @@ def test_management_confirm_cancel_execute_stop_and_repeated_click(controls, qtb
|
|||||||
qtbot.mouseClick(dialog.close_button, Qt.LeftButton)
|
qtbot.mouseClick(dialog.close_button, Qt.LeftButton)
|
||||||
assert len(calls) == 1 and dialog.isVisible()
|
assert len(calls) == 1 and dialog.isVisible()
|
||||||
press(qtbot, dialog.stop_button)
|
press(qtbot, dialog.stop_button)
|
||||||
assert dialog.stop.is_set()
|
assert dialog.context.stop_after_current.is_set() and not dialog.stop.is_set()
|
||||||
finally:
|
finally:
|
||||||
finish.set()
|
finish.set()
|
||||||
qtbot.waitUntil(lambda: not dialog.busy)
|
qtbot.waitUntil(lambda: not dialog.busy)
|
||||||
@@ -411,7 +411,7 @@ def test_residual_refresh_details_confirm_and_close(residual, qtbot):
|
|||||||
expand = next(b for b in details.findChildren(QPushButton) if 'Details' in b.text())
|
expand = next(b for b in details.findChildren(QPushButton) if 'Details' in b.text())
|
||||||
press(qtbot, expand)
|
press(qtbot, expand)
|
||||||
assert details.findChild(QTextEdit).isVisible()
|
assert details.findChild(QTextEdit).isVisible()
|
||||||
press(qtbot, details.button(QMessageBox.Ok))
|
press(qtbot, details.button(QMessageBox.Close))
|
||||||
press(qtbot, d.confirm_button)
|
press(qtbot, d.confirm_button)
|
||||||
qtbot.waitUntil(lambda: not d.busy)
|
qtbot.waitUntil(lambda: not d.busy)
|
||||||
assert len(residual.releases) == 1 and residual.releases[0]['force'] is False
|
assert len(residual.releases) == 1 and residual.releases[0]['force'] is False
|
||||||
|
|||||||
@@ -69,9 +69,10 @@ def test_completed_old_library_result_does_not_release_new_library(qtbot, tmp_pa
|
|||||||
qtbot.waitUntil(lambda: not window._icdb_active())
|
qtbot.waitUntil(lambda: not window._icdb_active())
|
||||||
summary = window.icdb_summary
|
summary = window.icdb_summary
|
||||||
window.lmc_edit.setText('other.lmc')
|
window.lmc_edit.setText('other.lmc')
|
||||||
|
message = window.status_label.text()
|
||||||
next(button for button in summary.buttons() if '释放' in button.text()).click()
|
next(button for button in summary.buttons() if '释放' in button.text()).click()
|
||||||
assert getattr(window, 'release_dialog', None) is None
|
assert getattr(window, 'release_dialog', None) is None
|
||||||
assert '切' in window.status_label.text()
|
assert window.status_label.text() == message
|
||||||
|
|
||||||
|
|
||||||
def test_later_management_invalidates_old_recovery_offer(qtbot, tmp_path, monkeypatch):
|
def test_later_management_invalidates_old_recovery_offer(qtbot, tmp_path, monkeypatch):
|
||||||
@@ -109,4 +110,4 @@ def test_check_release_action_tracks_busy_and_retained_queue(qtbot, tmp_path, mo
|
|||||||
assert opened == [{'queued': True}]
|
assert opened == [{'queued': True}]
|
||||||
window.busy = False
|
window.busy = False
|
||||||
window._update()
|
window._update()
|
||||||
assert action.isEnabled()
|
assert not action.isEnabled(), 'A dismissed one-shot result cannot be reactivated'
|
||||||
@@ -83,7 +83,8 @@ def test_worker_refresh_excludes_ready_before_any_gui_result_callback(qtbot,tmp_
|
|||||||
status_refresher=lambda names,path:{name:'READY' for name in names})
|
status_refresher=lambda names,path:{name:'READY' for name in names})
|
||||||
release,calls=background(window,qtbot)
|
release,calls=background(window,qtbot)
|
||||||
try:
|
try:
|
||||||
window._start(lambda:window._read_affected_records(('Gamma',)),lambda payload:None)
|
library=window.mentor_lmc_path or window.loaded_path
|
||||||
|
window._start(lambda:window._read_affected_records(('Gamma',),library=library),lambda payload:None)
|
||||||
qtbot.waitUntil(lambda:bool(window.native_queue.pending))
|
qtbot.waitUntil(lambda:bool(window.native_queue.pending))
|
||||||
release.set()
|
release.set()
|
||||||
qtbot.waitUntil(lambda:not window._icdb_active() and not window.busy)
|
qtbot.waitUntil(lambda:not window._icdb_active() and not window.busy)
|
||||||
|
|||||||
@@ -183,9 +183,9 @@ def test_idle_guard_ignores_unrelated_project_and_prefix_sibling(recovery_files,
|
|||||||
request, original, _ = recovery_files
|
request, original, _ = recovery_files
|
||||||
unrelated = original.parent.with_name(original.parent.name+'Old')/'PCB/A.pcb'
|
unrelated = original.parent.with_name(original.parent.name+'Old')/'PCB/A.pcb'
|
||||||
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: [(123, '', str(unrelated))])
|
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: [(123, '', str(unrelated))])
|
||||||
monkeypatch.setattr(mentor_adapter, '_process_details', lambda name:
|
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda names:[
|
||||||
[(123, 'ExpeditionPCB.exe', f'ExpeditionPCB.exe "{unrelated}" -ReusableCircuit', 0)]
|
dict(pid=123,name='ExpeditionPCB.exe',executable='ExpeditionPCB.exe',
|
||||||
if name == 'ExpeditionPCB.exe' else [])
|
command=f'ExpeditionPCB.exe "{unrelated}" -ReusableCircuit',parent=0)])
|
||||||
_idle_check(request.lmc_file, original, original.parent/'PCB/A.pcb')
|
_idle_check(request.lmc_file, original, original.parent/'PCB/A.pcb')
|
||||||
|
|
||||||
|
|
||||||
@@ -195,23 +195,23 @@ def test_idle_guard_rejects_exact_target_process(recovery_files, monkeypatch):
|
|||||||
request, original, _ = recovery_files
|
request, original, _ = recovery_files
|
||||||
target = original.parent/'PCB/A.pcb'
|
target = original.parent/'PCB/A.pcb'
|
||||||
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: [])
|
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: [])
|
||||||
monkeypatch.setattr(mentor_adapter, '_process_details', lambda name:
|
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda names:[
|
||||||
[(123, 'ExpeditionPCB.exe', f'ExpeditionPCB.exe "{target}" -ReusableCircuit', 0)]
|
dict(pid=123,name='ExpeditionPCB.exe',executable='ExpeditionPCB.exe',
|
||||||
if name == 'ExpeditionPCB.exe' else [])
|
command=f'ExpeditionPCB.exe "{target}" -ReusableCircuit',parent=0)])
|
||||||
with pytest.raises(ValueError, match='TARGET_NATIVE_OWNER_ACTIVE'):
|
with pytest.raises(ValueError, match='TARGET_NATIVE_OWNER_ACTIVE'):
|
||||||
_idle_check(request.lmc_file, original, target)
|
_idle_check(request.lmc_file, original, target)
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize('target_state', ['idle', 'open_file', 'address'])
|
@pytest.mark.parametrize('target_state', ['idle', 'open_file', 'address'])
|
||||||
def test_pathless_external_client_uses_target_resource_proof(recovery_files, monkeypatch, target_state):
|
def test_pathless_external_client_requires_resource_proof_and_confirmation(recovery_files, monkeypatch, target_state):
|
||||||
import pywintypes
|
import pywintypes
|
||||||
import win32con
|
import win32con
|
||||||
import win32file
|
import win32file
|
||||||
from cbb_refresh_verify import mentor_adapter
|
from cbb_refresh_verify import mentor_adapter
|
||||||
from cbb_refresh_verify.backup_recovery import _idle_check
|
from cbb_refresh_verify.backup_recovery import _idle_check
|
||||||
request, original, _ = recovery_files
|
request, original, _ = recovery_files
|
||||||
monkeypatch.setattr(mentor_adapter, '_process_details', lambda name:
|
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda names:[
|
||||||
[(123, 'viewdraw.exe', 'viewdraw.exe', 0)] if name == 'viewdraw.exe' else [])
|
dict(pid=123,name='viewdraw.exe',executable='viewdraw.exe',command='viewdraw.exe',parent=0)])
|
||||||
address = original.parent/'database/cdbsvr/sAddress.adr'
|
address = original.parent/'database/cdbsvr/sAddress.adr'
|
||||||
handle = None
|
handle = None
|
||||||
try:
|
try:
|
||||||
@@ -228,6 +228,7 @@ def test_pathless_external_client_uses_target_resource_proof(recovery_files, mon
|
|||||||
_idle_check(request.lmc_file, original, original.parent/'PCB/A.pcb')
|
_idle_check(request.lmc_file, original, original.parent/'PCB/A.pcb')
|
||||||
assert address.read_bytes() == b'live or unconfirmed native address'
|
assert address.read_bytes() == b'live or unconfirmed native address'
|
||||||
else:
|
else:
|
||||||
|
with pytest.raises(ValueError,match='TARGET_NATIVE_OWNER_UNCONFIRMED'):
|
||||||
_idle_check(request.lmc_file, original, original.parent/'PCB/A.pcb')
|
_idle_check(request.lmc_file, original, original.parent/'PCB/A.pcb')
|
||||||
finally:
|
finally:
|
||||||
if handle is not None: handle.Close()
|
if handle is not None: handle.Close()
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
from cbb_refresh_verify.ui import timed_prompt
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from threading import Event
|
from threading import Event
|
||||||
|
|
||||||
@@ -8,7 +9,7 @@ import pytest
|
|||||||
@pytest.fixture(autouse=True)
|
@pytest.fixture(autouse=True)
|
||||||
def accept_manual_backup_reminder(monkeypatch):
|
def accept_manual_backup_reminder(monkeypatch):
|
||||||
from PySide6.QtWidgets import QMessageBox
|
from PySide6.QtWidgets import QMessageBox
|
||||||
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
|
monkeypatch.setattr(timed_prompt, 'question', lambda *a, **k: QMessageBox.Yes)
|
||||||
|
|
||||||
|
|
||||||
def test_backup_dialog_requires_a_project_and_passes_selected_target(qtbot, tmp_path):
|
def test_backup_dialog_requires_a_project_and_passes_selected_target(qtbot, tmp_path):
|
||||||
|
|||||||
@@ -71,7 +71,7 @@ def test_verify_failure_recheck_finishes_before_yielding_native_queue(qtbot,tmp_
|
|||||||
try:return action()
|
try:return action()
|
||||||
finally:active.pop()
|
finally:active.pop()
|
||||||
return run
|
return run
|
||||||
def recheck(library,block,result):
|
def recheck(library,block,result,**kwargs):
|
||||||
seen.append(bool(active))
|
seen.append(bool(active))
|
||||||
return replace(result,safe_to_continue=True)
|
return replace(result,safe_to_continue=True)
|
||||||
monkeypatch.setattr(window,'_queued_action',queued)
|
monkeypatch.setattr(window,'_queued_action',queued)
|
||||||
@@ -92,7 +92,7 @@ def test_management_failure_recheck_finishes_before_yielding_native_queue(tmp_pa
|
|||||||
active.append(True)
|
active.append(True)
|
||||||
try:return action()
|
try:return action()
|
||||||
finally:active.pop()
|
finally:active.pop()
|
||||||
def recheck(library,block,result):
|
def recheck(library,block,result,**kwargs):
|
||||||
seen.append(bool(active))
|
seen.append(bool(active))
|
||||||
return replace(result,safe_to_continue=True)
|
return replace(result,safe_to_continue=True)
|
||||||
monkeypatch.setattr(operation_lifecycle,'recheck_failed_release',recheck)
|
monkeypatch.setattr(operation_lifecycle,'recheck_failed_release',recheck)
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
from threading import Event
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from cbb_refresh_verify.operation_queue import BatchTaskContext, NativeQueue, TaskHandoff, hold_native_handoff
|
||||||
|
from cbb_refresh_verify.ui.icdb_check_task import IcdbCheckTask
|
||||||
|
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||||
|
from test_verify_runner import fixture, request
|
||||||
|
|
||||||
|
|
||||||
|
def test_cancelled_diagnostic_report_survives_ongoing_handoff_finalization(qtbot,tmp_path):
|
||||||
|
fixture(tmp_path)
|
||||||
|
req=request(tmp_path,diagnostic_only=True)
|
||||||
|
context=BatchTaskContext(str(req.lmc_file),native_policy='external')
|
||||||
|
entered,finish=Event(),Event()
|
||||||
|
def finalize():
|
||||||
|
try:
|
||||||
|
hold_native_handoff(None,tmp_path/'session.json')
|
||||||
|
except TaskHandoff:
|
||||||
|
entered.set()
|
||||||
|
assert finish.wait(5)
|
||||||
|
try:
|
||||||
|
with pytest.raises(TaskHandoff):context.run(finalize)
|
||||||
|
assert entered.is_set()
|
||||||
|
task=IcdbCheckTask([req],NativeQueue(),tmp_path/'reports')
|
||||||
|
task.active=True
|
||||||
|
task.results=[VerifyResult('CANCELLED',safe_to_continue=False,stderr='已转后台观察')]
|
||||||
|
task._report()
|
||||||
|
qtbot.waitUntil(lambda:not task.active,timeout=3000)
|
||||||
|
assert task.report is not None and task.report.exists(),task.report_error
|
||||||
|
assert not task.report_error and task.results[0].status=='CANCELLED'
|
||||||
|
finally:
|
||||||
|
finish.set()
|
||||||
|
context.close(timeout_seconds=2)
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
"""Cancellation may race native loading after COM/document admission stopped."""
|
||||||
|
from copy import deepcopy
|
||||||
|
from pathlib import Path
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from cbb_refresh_verify import diagnostic_open, failed_session, residual_sessions
|
||||||
|
from cbb_refresh_verify.dialog_models import ControlSnapshot, DialogPhase, WindowSnapshot
|
||||||
|
from test_failed_startup import startup_fixture
|
||||||
|
from test_diagnostic_open import write_logs
|
||||||
|
|
||||||
|
|
||||||
|
def loaded_fixture(tmp_path, monkeypatch, *, empty_close_first=False, obstacle=''):
|
||||||
|
import win32con, win32gui
|
||||||
|
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||||
|
job.update(project=str(tmp_path/'IP101GR/IP101GR.prj'), pcb=str(tmp_path/'IP101GR/PCB/IP101GR.pcb'),
|
||||||
|
diagnostic_only=True, cancel_signal=str(tmp_path/'cancel.signal'))
|
||||||
|
Path(job['pcb']).parent.mkdir(parents=True)
|
||||||
|
Path(job['pcb']).touch(); Path(job['cancel_signal']).touch()
|
||||||
|
records[0] = (12, records[0][1], f'ExpeditionPCB.exe "{job["pcb"]}" -ReusableCircuit', 11)
|
||||||
|
job['diagnostic_log_baseline'] = diagnostic_open.snapshot_diagnostic_logs(job)
|
||||||
|
write_logs(job, pid=99 if obstacle == 'foreign_log_pid' else 12, foreign=obstacle == 'foreign_log_path')
|
||||||
|
if obstacle == 'stale_logs': job['diagnostic_log_baseline'] = diagnostic_open.snapshot_diagnostic_logs(job)
|
||||||
|
if obstacle == 'write': (tmp_path/'save.log').write_text('save entered')
|
||||||
|
if obstacle == 'ordinary': job['diagnostic_only'] = False
|
||||||
|
if obstacle == 'not_cancelled': Path(job['cancel_signal']).unlink()
|
||||||
|
state = dict(ticks=0., tip=not empty_close_first, declined=False, closing=False)
|
||||||
|
clock = SimpleNamespace(monotonic=lambda:state['ticks'],
|
||||||
|
sleep=lambda seconds:state.__setitem__('ticks', state['ticks']+seconds))
|
||||||
|
monkeypatch.setattr(failed_session, 'time', clock)
|
||||||
|
monkeypatch.setattr(diagnostic_open, 'time', clock)
|
||||||
|
target = dict(hwnd=100, pid=12, **{'class':'Afx:main'},
|
||||||
|
text='Expedition PCB - Reusable Block - [IP101GR]', enabled=False,
|
||||||
|
children=[dict(hwnd=101, **{'class':'MDIClient'}, text='', parent=100),
|
||||||
|
dict(hwnd=102, **{'class':'Afx:document'}, text='IP101GR', parent=101)])
|
||||||
|
if obstacle == 'foreign_mdi': target['children'][1]['text'] = 'Other'
|
||||||
|
forward = dict(hwnd=200, pid=12, **{'class':'#32770'}, text='Expedition PCB', owner=100,
|
||||||
|
children=[dict(hwnd=30, **{'class':'Static'}, id=6172,
|
||||||
|
text='New changes are ready for Forward Annotation. Do you want to Forward Annotate now?'),
|
||||||
|
dict(hwnd=31, **{'class':'Button'}, id=7, text='&No', enabled=True),
|
||||||
|
dict(hwnd=32, **{'class':'Button'}, id=6, text='&Yes', enabled=True)])
|
||||||
|
if obstacle == 'foreign_prompt': forward['owner'] = 999
|
||||||
|
if obstacle == 'unknown': forward['text'] = 'Unknown action'
|
||||||
|
def windows(pid):
|
||||||
|
if state['tip'] or empty_close_first and not state['closing']: return []
|
||||||
|
frame = deepcopy(target)
|
||||||
|
frame['enabled'] = state['declined']
|
||||||
|
if not state['declined'] or obstacle == 'progress':
|
||||||
|
frame['children'].append(dict(hwnd=103, **{'class':'msctls_progress32'}, text='', visible=True))
|
||||||
|
return [frame] + ([] if state['declined'] else [deepcopy(forward)])
|
||||||
|
monkeypatch.setattr(diagnostic_open, '_windows', windows)
|
||||||
|
monkeypatch.setattr(diagnostic_open, '_request_close_handoff', lambda *a, **kw:
|
||||||
|
pytest.fail('cancelled supervisor must not be asked for a normal admission ack'))
|
||||||
|
monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn,arg:
|
||||||
|
[fn(h,arg) for h in ((200,) if state['tip'] else (100,200))])
|
||||||
|
monkeypatch.setattr(win32gui, 'GetClassName', lambda h:'#32770' if h == 200 else 'Afx:main')
|
||||||
|
monkeypatch.setattr(win32gui, 'GetWindowText', lambda h:
|
||||||
|
'Expedition PCB' if empty_close_first and not state['closing'] else target['text'])
|
||||||
|
monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda h: h != 200 or state['tip'] or not empty_close_first)
|
||||||
|
tip = WindowSnapshot(200,12,'ExpeditionPCB.exe','pcb','#32770','Tip of the Day',
|
||||||
|
DialogPhase.PCB_STARTING,(ControlSnapshot(201,1,'Button','OK',enabled=True),))
|
||||||
|
unknown = WindowSnapshot(200,12,'ExpeditionPCB.exe','pcb','#32770','Expedition PCB',
|
||||||
|
DialogPhase.PCB_STARTING,())
|
||||||
|
monkeypatch.setattr(failed_session, '_startup_snapshot', lambda *a:tip if state['tip'] else unknown)
|
||||||
|
def post(hwnd, message, *_):
|
||||||
|
messages.append((hwnd,message))
|
||||||
|
if hwnd == 201: state['tip'] = False
|
||||||
|
elif hwnd == 31:
|
||||||
|
state['declined'] = True
|
||||||
|
if state['closing']: records.clear()
|
||||||
|
elif hwnd == 100 and message == win32con.WM_CLOSE:
|
||||||
|
state['closing'] = True
|
||||||
|
if state['declined']: records.clear()
|
||||||
|
monkeypatch.setattr(win32gui, 'PostMessage', post)
|
||||||
|
return job, records, messages, state
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('empty_close_first', [False, True])
|
||||||
|
def test_cancelled_diagnostic_tip_to_loaded_forward_no_closes_once_without_ack(tmp_path, monkeypatch, empty_close_first):
|
||||||
|
job, records, messages, state = loaded_fixture(tmp_path, monkeypatch, empty_close_first=empty_close_first)
|
||||||
|
events = []
|
||||||
|
result = failed_session.close_failed_startup(job,12,timeout_seconds=1,
|
||||||
|
emit=lambda **event:events.append(event))
|
||||||
|
assert result['status'] == 'CLOSED' and result['release']['safe_to_continue']
|
||||||
|
assert messages == ([(100,16),(31,245)] if empty_close_first else [(201,245),(31,245),(100,16)])
|
||||||
|
assert not records and Path(job['cancel_signal']).exists()
|
||||||
|
assert not any(e.get('stage') in ('diagnostic_complete','diagnostic_native_open_confirmed','save_start') for e in events)
|
||||||
|
assert sum(e['stage']=='startup_close_requested' for e in events)==1
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('obstacle', ['foreign_log_pid','foreign_log_path','stale_logs','foreign_mdi',
|
||||||
|
'foreign_prompt','unknown','progress','write','ordinary','not_cancelled'])
|
||||||
|
def test_cancelled_loaded_cleanup_cannot_override_identity_write_or_unknown_guards(tmp_path, monkeypatch, obstacle):
|
||||||
|
job, records, messages, state = loaded_fixture(tmp_path, monkeypatch, obstacle=obstacle)
|
||||||
|
result = failed_session.close_failed_startup(job,12,timeout_seconds=.5)
|
||||||
|
assert result['status']=='RETAINED' and records
|
||||||
|
assert messages == ([(201,245),(31,245)] if obstacle=='progress' else [(201,245)])
|
||||||
|
|
||||||
|
|
||||||
|
def test_cancelled_diagnostic_keeps_one_thirty_second_cleanup_budget(tmp_path, monkeypatch):
|
||||||
|
job, records, messages, state = loaded_fixture(tmp_path,monkeypatch,obstacle='progress')
|
||||||
|
result = failed_session.close_failed_startup(job,12)
|
||||||
|
assert result['status']=='RETAINED' and records
|
||||||
|
assert 30 <= state['ticks'] <= 30.2
|
||||||
|
assert messages==[(201,245),(31,245)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_sibling_vetoes_known_forward_no(tmp_path,monkeypatch):
|
||||||
|
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch)
|
||||||
|
original=diagnostic_open._windows
|
||||||
|
def windows(pid):
|
||||||
|
values=original(pid)
|
||||||
|
return values+[dict(hwnd=999,pid=12,**{'class':'#32770'},text='Unknown action',children=[])] if values else values
|
||||||
|
monkeypatch.setattr(diagnostic_open,'_windows',windows)
|
||||||
|
result=failed_session.close_failed_startup(job,12,timeout_seconds=.5)
|
||||||
|
assert result['status']=='RETAINED' and records
|
||||||
|
assert messages==[(201,245)]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('filename',['IP101GR.pcb','Foreign.pcb'])
|
||||||
|
def test_cancelled_loaded_close_only_declines_exact_owned_save_question(tmp_path,monkeypatch,filename):
|
||||||
|
import win32gui
|
||||||
|
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch)
|
||||||
|
original_windows=diagnostic_open._windows
|
||||||
|
def windows(pid):
|
||||||
|
if not state['closing']:return original_windows(pid)
|
||||||
|
return [dict(hwnd=400,pid=12,**{'class':'#32770'},text='Expedition PCB',owner=100,
|
||||||
|
children=[dict(hwnd=40,**{'class':'Static'},text=f'Save changes to {filename}?'),
|
||||||
|
dict(hwnd=41,**{'class':'Button'},id=7,text='No',enabled=True),
|
||||||
|
dict(hwnd=42,**{'class':'Button'},id=6,text='Yes',enabled=True),
|
||||||
|
dict(hwnd=43,**{'class':'Button'},id=2,text='Cancel',enabled=True)])]
|
||||||
|
monkeypatch.setattr(diagnostic_open,'_windows',windows)
|
||||||
|
original_post=win32gui.PostMessage
|
||||||
|
def post(hwnd,message,*args):
|
||||||
|
if hwnd==100:
|
||||||
|
messages.append((hwnd,message));state['closing']=True
|
||||||
|
elif hwnd==41:
|
||||||
|
messages.append((hwnd,message));records.clear()
|
||||||
|
else:original_post(hwnd,message,*args)
|
||||||
|
monkeypatch.setattr(win32gui,'PostMessage',post)
|
||||||
|
result=failed_session.close_failed_startup(job,12,timeout_seconds=1)
|
||||||
|
assert result['status']==('CLOSED' if filename=='IP101GR.pcb' else 'RETAINED')
|
||||||
|
assert messages==[(201,245),(31,245),(100,16)]+([(41,245)] if filename=='IP101GR.pcb' else [])
|
||||||
|
|
||||||
|
|
||||||
|
def test_supervisor_finishes_inflight_poll_before_signalling_cleanup_and_never_polls_again(tmp_path,monkeypatch):
|
||||||
|
import json
|
||||||
|
from threading import Event
|
||||||
|
from cbb_refresh_verify import desktop_worker
|
||||||
|
from cbb_refresh_verify.verify_runner import run_verify
|
||||||
|
from cbb_refresh_verify.dialog_supervisor import DialogPollResult
|
||||||
|
from test_verify_runner import fixture, request, PORTS_OK
|
||||||
|
fixture(tmp_path); stop=Event(); state={'polling':False,'polls':0,'cleanup':False}
|
||||||
|
class Worker:
|
||||||
|
desktop=None;pid=700;companion_pids=[];returncode=None
|
||||||
|
def __init__(self,command,name):
|
||||||
|
self.name=name
|
||||||
|
state['path']=Path(command[-1]);state['job']=json.loads(state['path'].read_text())
|
||||||
|
state['path'].with_name('events.jsonl').write_text(json.dumps(dict(stage='pcb_worker_started',pcb_pid=901))+'\n')
|
||||||
|
def poll(self):return self.returncode
|
||||||
|
def request_stop(self):
|
||||||
|
assert not state['polling'] and state['polls']==1
|
||||||
|
Path(state['job']['cancel_signal']).touch()
|
||||||
|
def wait(self,timeout=5):
|
||||||
|
assert Path(state['job']['cancel_signal']).exists() and not state['polling']
|
||||||
|
state['cleanup']=True;self.returncode=1;return 1
|
||||||
|
def close(self):pass
|
||||||
|
class Supervisor:
|
||||||
|
def poll(self,*args):
|
||||||
|
assert not state['cleanup'] and not Path(state['job']['cancel_signal']).exists()
|
||||||
|
state['polling']=True;state['polls']+=1;stop.set();state['polling']=False
|
||||||
|
return DialogPollResult()
|
||||||
|
monkeypatch.setattr(desktop_worker,'DesktopWorker',Worker)
|
||||||
|
result=run_verify(request(tmp_path,diagnostic_only=True),port_check=PORTS_OK,stop=stop,
|
||||||
|
dialog_supervisor_factory=lambda **kw:Supervisor())
|
||||||
|
assert result.status=='CANCELLED' and state['cleanup'] and state['polls']==1
|
||||||
|
assert not state['path'].with_name('diagnostic-close-ack.json').exists()
|
||||||
@@ -0,0 +1,198 @@
|
|||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from cbb_refresh_verify import failed_session,session_record,diagnostic_open
|
||||||
|
from test_cancelled_loaded_startup import loaded_fixture
|
||||||
|
|
||||||
|
|
||||||
|
def ordinary_proof(job,root,baseline,*,worker=None,pid=12):
|
||||||
|
worker=worker or dict(pid=11,created_handle='worker-created',image='C:/App/python.exe',owner_sid='current',session_id=1)
|
||||||
|
job.update(diagnostic_only=False,operation='verify',operation_id=job.get('operation_id','verify-ordinary'),
|
||||||
|
library=job['lmc_file'],session_record_path=str(root/'session.json'),interactive_input=False)
|
||||||
|
job.pop('diagnostic_log_baseline',None)
|
||||||
|
session_record.write_session_record(root/'session.json',dict(operation_id=job['operation_id'],operation='verify',
|
||||||
|
library=job['library'],block=job.get('block',job.get('block_name')),desktop=job['desktop'],cancel_signal=job['cancel_signal'],processes=[dict(role='worker',**worker)],
|
||||||
|
resource_scope=dict(scope_state='DECLARED',library=job['library'],operation_id=job['operation_id'],projects=[job['project']])))
|
||||||
|
binding={k:job[k] for k in ('operation_id','project','pcb','desktop')}
|
||||||
|
events=[dict(stage='startup_supervisor_no_write',**binding),
|
||||||
|
dict(stage='startup_prewrite_ready',worker_identity=worker,baseline=baseline,**binding),
|
||||||
|
dict(stage='pcb_baseline',pids=[]),dict(stage='pcb_worker_started',pcb_pid=pid),
|
||||||
|
dict(stage='startup_cancelled_prewrite',pcb_pid=pid,identity_verified=False,write_admitted=False,**binding)]
|
||||||
|
(root/'events.jsonl').write_text(''.join(json.dumps(e)+'\n' for e in events))
|
||||||
|
return events
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('prior_close',[False,True])
|
||||||
|
def test_proved_ordinary_cancel_finishes_tip_to_loaded_without_annotation_or_second_close(tmp_path,monkeypatch,prior_close):
|
||||||
|
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch,empty_close_first=prior_close)
|
||||||
|
ordinary_proof(job,tmp_path,job['diagnostic_log_baseline'])
|
||||||
|
result=failed_session.close_failed_startup(job,12,timeout_seconds=1)
|
||||||
|
assert result['status']=='CLOSED' and not records
|
||||||
|
assert messages==([(100,16),(31,245)] if prior_close else [(201,245),(31,245),(100,16)])
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('obstacle',['missing_ready','missing_cancel_phase','supervisor_write','worker_write',
|
||||||
|
'missing_supervisor','missing_baseline','foreign_worker','foreign_target','save','missing_cancel','interactive','native_lm'])
|
||||||
|
def test_ordinary_cleanup_requires_positive_bound_no_write_evidence(tmp_path,monkeypatch,obstacle):
|
||||||
|
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch)
|
||||||
|
events=ordinary_proof(job,tmp_path,job['diagnostic_log_baseline'])
|
||||||
|
if obstacle=='missing_ready':events=[e for e in events if e['stage']!='startup_prewrite_ready']
|
||||||
|
if obstacle=='missing_cancel_phase':events=[e for e in events if e['stage']!='startup_cancelled_prewrite']
|
||||||
|
if obstacle=='missing_supervisor':events=events[1:]
|
||||||
|
if obstacle=='supervisor_write':events.append(dict(stage='startup_supervisor_write_possible'))
|
||||||
|
if obstacle=='worker_write':events.append(dict(stage='startup_write_admitted'))
|
||||||
|
if obstacle=='missing_baseline':events[1].pop('baseline')
|
||||||
|
if obstacle=='foreign_worker':events[1]['worker_identity']['created_handle']='other'
|
||||||
|
if obstacle=='foreign_target':events[-1]['pcb']='C:/foreign.pcb'
|
||||||
|
if obstacle=='save':(tmp_path/'save.log').write_text('SAVE_ENTERED')
|
||||||
|
if obstacle=='missing_cancel':Path(job['cancel_signal']).unlink()
|
||||||
|
if obstacle=='interactive':job['interactive_input']=True
|
||||||
|
if obstacle=='native_lm':job['native_lm_verify']=True
|
||||||
|
(tmp_path/'events.jsonl').write_text(''.join(json.dumps(e)+'\n' for e in events))
|
||||||
|
result=failed_session.close_failed_startup(job,12,timeout_seconds=.3)
|
||||||
|
assert result['status']=='RETAINED' and records
|
||||||
|
assert not any(h==31 or m==16 for h,m in messages)
|
||||||
|
|
||||||
|
|
||||||
|
def test_worker_publishes_bound_baseline_before_launch_and_revokes_before_integration(tmp_path,monkeypatch):
|
||||||
|
from test_verify_worker_stability import exercise_worker
|
||||||
|
from cbb_refresh_verify import mentor_adapter,integration
|
||||||
|
job,events,execute=exercise_worker(tmp_path,monkeypatch)
|
||||||
|
job.update(operation_id='op',operation='verify',library=job['lmc_file'],desktop='CbbVerify_test',
|
||||||
|
session_record_path=str(Path(job['root'])/'session.json'),diagnostic_only=False)
|
||||||
|
launch=mentor_adapter.launch_pcb_process
|
||||||
|
def start(*args):
|
||||||
|
assert any(e['stage']=='startup_prewrite_ready' and 'baseline' in e for e in events)
|
||||||
|
return launch(*args)
|
||||||
|
def write(*args,**kwargs):
|
||||||
|
assert any(e['stage']=='startup_write_admitted' for e in events)
|
||||||
|
monkeypatch.setattr(mentor_adapter,'launch_pcb_process',start)
|
||||||
|
monkeypatch.setattr(integration,'refresh_integration',write)
|
||||||
|
assert execute()['status']=='PASS'
|
||||||
|
|
||||||
|
|
||||||
|
def test_cancelled_worker_records_positive_prewrite_phase_before_startup_cleanup(tmp_path,monkeypatch):
|
||||||
|
from test_verify_worker_stability import exercise_worker
|
||||||
|
from cbb_refresh_verify import pcb_bridge
|
||||||
|
job,events,execute=exercise_worker(tmp_path,monkeypatch)
|
||||||
|
job.update(operation_id='op',operation='verify',library=job['lmc_file'],desktop='CbbVerify_test',
|
||||||
|
session_record_path=str(Path(job['root'])/'session.json'),diagnostic_only=False,
|
||||||
|
cancel_signal=str(tmp_path/'cancel.signal'))
|
||||||
|
def cancel(*args,**kwargs):
|
||||||
|
Path(job['cancel_signal']).touch();raise RuntimeError('VERIFY_CANCELLED')
|
||||||
|
monkeypatch.setattr(pcb_bridge,'wait_for_target_document',cancel)
|
||||||
|
observed=[]
|
||||||
|
def cleanup(*args,**kwargs):observed.extend(events);return {'status':'RETAINED'}
|
||||||
|
monkeypatch.setattr(failed_session,'close_failed_startup',cleanup)
|
||||||
|
with pytest.raises(RuntimeError,match='VERIFY_CANCELLED'):execute()
|
||||||
|
assert any(e['stage']=='startup_cancelled_prewrite' and e['write_admitted'] is False
|
||||||
|
and e['identity_verified'] is False for e in observed)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('journal_fails',[False,True])
|
||||||
|
def test_dialog_backend_records_write_revocation_before_action(journal_fails):
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from cbb_refresh_verify.dialog_supervisor import Win32DialogBackend,DialogSnapshot,DialogControl
|
||||||
|
calls=[]
|
||||||
|
gui=SimpleNamespace(PostMessage=lambda *args:calls.append('native'))
|
||||||
|
backend=Win32DialogBackend((),win32gui=gui,win32process=object(),win32con=SimpleNamespace(BM_CLICK=245))
|
||||||
|
def before(snapshot,action):
|
||||||
|
calls.append('journal')
|
||||||
|
if journal_fails:raise OSError('cannot record phase')
|
||||||
|
backend.before_action=before
|
||||||
|
snapshot=DialogSnapshot(100,12,'Expedition PCB',(DialogControl(101,6,'Button','Yes',True),))
|
||||||
|
if journal_fails:
|
||||||
|
with pytest.raises(OSError):backend.perform(snapshot,'confirm_forward_annotation')
|
||||||
|
assert calls==['journal']
|
||||||
|
else:
|
||||||
|
backend.perform(snapshot,'confirm_forward_annotation');assert calls==['journal','native']
|
||||||
|
|
||||||
|
|
||||||
|
def test_positive_ordinary_cancel_phase_yields_after_initial_wait(tmp_path,monkeypatch):
|
||||||
|
from test_cancelled_session_handoff import worker_fixture
|
||||||
|
state,stop,run=worker_fixture(tmp_path,monkeypatch)
|
||||||
|
# The real worker publishes its cancellation fact during the first wait.
|
||||||
|
from cbb_refresh_verify import desktop_worker
|
||||||
|
Worker=desktop_worker.DesktopWorker;wait=Worker.wait
|
||||||
|
def complete_proof(worker,timeout=5):
|
||||||
|
job=state['job']
|
||||||
|
baseline={'started_ns':1,'files':{}}
|
||||||
|
ordinary_proof(job,state['path'].parent,baseline,pid=901,
|
||||||
|
worker=dict(pid=700,created_handle='worker',image='C:/App/python.exe',owner_sid='current',session_id=1))
|
||||||
|
return wait(worker,timeout)
|
||||||
|
monkeypatch.setattr(Worker,'wait',complete_proof)
|
||||||
|
assert run(False).status=='CANCELLED'
|
||||||
|
assert state['waits']==[5]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('proof_present',[True,False])
|
||||||
|
def test_normal_release_of_ordinary_retained_startup_requires_new_complete_prewrite_proof(tmp_path,monkeypatch,proof_present):
|
||||||
|
from test_registered_startup_release import registered_fixture
|
||||||
|
from cbb_refresh_verify import residual_sessions
|
||||||
|
load=diagnostic_open._load_evidence
|
||||||
|
job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch)
|
||||||
|
monkeypatch.setattr(diagnostic_open,'_load_evidence',load)
|
||||||
|
job['diagnostic_only']=False
|
||||||
|
if proof_present:ordinary_proof(job,tmp_path,state['prelaunch_baseline'])
|
||||||
|
(tmp_path/'request.json').write_text(json.dumps(job))
|
||||||
|
result=residual_sessions._request_close(row)
|
||||||
|
assert result['release_status']==('RELEASED' if proof_present else 'WAITING'),result
|
||||||
|
assert messages==([(31,245),(100,16)] if proof_present else [])
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('obstacle',['unknown','hidden_document','progress','foreign_log_pid','foreign_log_path','revoked'])
|
||||||
|
def test_ordinary_cleanup_keeps_native_window_write_and_identity_vetoes(tmp_path,monkeypatch,obstacle):
|
||||||
|
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch,
|
||||||
|
obstacle=obstacle if obstacle in ('unknown','progress','foreign_log_pid','foreign_log_path') else '')
|
||||||
|
ordinary_proof(job,tmp_path,job['diagnostic_log_baseline'])
|
||||||
|
read=diagnostic_open._windows
|
||||||
|
def windows(pid):
|
||||||
|
values=read(pid)
|
||||||
|
if values and obstacle=='hidden_document':
|
||||||
|
values[0]['children'].append(dict(hwnd=888,**{'class':'Afx:document'},text='Other',parent=101,visible=False))
|
||||||
|
if state['declined'] and obstacle=='revoked':
|
||||||
|
with (tmp_path/'events.jsonl').open('a') as stream:stream.write(json.dumps(dict(stage='startup_write_admitted'))+'\n')
|
||||||
|
return values
|
||||||
|
monkeypatch.setattr(diagnostic_open,'_windows',windows)
|
||||||
|
result=failed_session.close_failed_startup(job,12,timeout_seconds=.5)
|
||||||
|
assert result['status']=='RETAINED' and records
|
||||||
|
assert not any(message==16 for _,message in messages)
|
||||||
|
assert messages==[(201,245)]+([(31,245)] if obstacle in ('progress','revoked') else [])
|
||||||
|
|
||||||
|
|
||||||
|
def test_proved_cancelled_startup_cannot_ack_tip_after_absolute_deadline(tmp_path,monkeypatch):
|
||||||
|
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch)
|
||||||
|
ordinary_proof(job,tmp_path,job['diagnostic_log_baseline'])
|
||||||
|
assert failed_session.close_failed_startup(job,12,timeout_seconds=0)['status']=='RETAINED'
|
||||||
|
assert not messages and records
|
||||||
|
|
||||||
|
|
||||||
|
def test_agent_backend_cannot_dispatch_before_phase_journal():
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from cbb_refresh_verify.dialog_supervisor import AgentDialogBackend
|
||||||
|
from cbb_refresh_verify.dialog_models import WindowSnapshot,DialogPhase
|
||||||
|
calls=[]
|
||||||
|
backend=AgentDialogBackend(SimpleNamespace(perform=lambda **kwargs:calls.append('native')),
|
||||||
|
before_action=lambda *args:calls.append('journal'))
|
||||||
|
snapshot=WindowSnapshot(100,12,'ExpeditionPCB.exe','pcb','#32770','Expedition PCB',DialogPhase.PCB_STARTING,())
|
||||||
|
backend.perform(snapshot,{'action':'confirm_forward_annotation'},DialogPhase.PCB_STARTING)
|
||||||
|
assert calls==['journal','native']
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('action',['tip','empty_close'])
|
||||||
|
def test_startup_deadline_is_rechecked_after_window_read_before_post(tmp_path,monkeypatch,action):
|
||||||
|
import win32gui
|
||||||
|
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch,empty_close_first=action=='empty_close')
|
||||||
|
ordinary_proof(job,tmp_path,job['diagnostic_log_baseline'])
|
||||||
|
if action=='tip':
|
||||||
|
snapshot=failed_session._startup_snapshot
|
||||||
|
def read(*args):
|
||||||
|
value=snapshot(*args);state['ticks']=2;return value
|
||||||
|
monkeypatch.setattr(failed_session,'_startup_snapshot',read)
|
||||||
|
else:
|
||||||
|
def children(*args):state['ticks']=2
|
||||||
|
monkeypatch.setattr(win32gui,'EnumChildWindows',children)
|
||||||
|
assert failed_session.close_failed_startup(job,12,timeout_seconds=1)['status']=='RETAINED'
|
||||||
|
assert not messages
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
from threading import Event
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from cbb_refresh_verify import desktop_worker, session_record, verify_runner as runner
|
||||||
|
from cbb_refresh_verify.dialog_supervisor import DialogPollResult
|
||||||
|
from test_verify_runner import fixture, request, PORTS_OK
|
||||||
|
|
||||||
|
|
||||||
|
def worker_fixture(tmp_path, monkeypatch, *, exited=False):
|
||||||
|
fixture(tmp_path)
|
||||||
|
state = dict(waits=[], closed=False, observers=[], polling=False, polls=0)
|
||||||
|
stop = Event()
|
||||||
|
class Worker:
|
||||||
|
desktop=None; pid=700; companion_pids=[]; returncode=1 if exited else None
|
||||||
|
def __init__(self, command, name):
|
||||||
|
self.name=name
|
||||||
|
path=Path(command[-1]); state.update(path=path,job=json.loads(path.read_text()),worker=self)
|
||||||
|
self.session_record_path=path.with_name('session.json')
|
||||||
|
session_record.write_session_record(self.session_record_path, dict(
|
||||||
|
operation_id=state['job']['operation_id'],library=state['job']['library'],
|
||||||
|
block=state['job']['block']))
|
||||||
|
path.with_name('events.jsonl').write_text(json.dumps(dict(stage='pcb_worker_started',pcb_pid=901))+'\n')
|
||||||
|
path.with_name('outcome.json').write_text(json.dumps(dict(status='CANCELLED',safe_to_continue=False)))
|
||||||
|
def poll(self):return self.returncode
|
||||||
|
def request_stop(self):
|
||||||
|
assert not state['polling']
|
||||||
|
Path(state['job']['cancel_signal']).touch()
|
||||||
|
def native_write_pending(self):return True
|
||||||
|
def wait(self,timeout=5):
|
||||||
|
state['waits'].append(timeout)
|
||||||
|
if timeout <= 5:raise TimeoutError('native startup still closing')
|
||||||
|
self.returncode=1;return 1
|
||||||
|
def automation_release_state(self):return {'safe_to_continue':self.poll() is not None,'remaining_pids':[]}
|
||||||
|
def close(self):state['closed']=True
|
||||||
|
class Supervisor:
|
||||||
|
def poll(self,*args):
|
||||||
|
assert not state['observers']
|
||||||
|
state['polling']=True;state['polls']+=1;stop.set();state['polling']=False
|
||||||
|
return DialogPollResult()
|
||||||
|
monkeypatch.setattr(desktop_worker,'DesktopWorker',Worker)
|
||||||
|
monkeypatch.setattr(runner,'_cleanup_session_processes',lambda *a,**kw:
|
||||||
|
{'safe_to_continue':False,'remaining_pids':[901]})
|
||||||
|
monkeypatch.setattr(session_record,'handoff_session',lambda path,**kw:
|
||||||
|
state['observers'].append((path,kw,state['closed'])))
|
||||||
|
# Keep the task runner deterministic while exercising real supervisor ownership decisions.
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.operation_queue.hold_native_handoff',lambda *a:None)
|
||||||
|
return state,stop,lambda diagnostic:runner.run_verify(request(tmp_path,diagnostic_only=diagnostic),
|
||||||
|
port_check=PORTS_OK,stop=stop,dialog_supervisor_factory=lambda **kw:Supervisor())
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('diagnostic',[True,False])
|
||||||
|
def test_diagnostic_cancel_yields_after_five_seconds_but_write_wait_is_unchanged(tmp_path,monkeypatch,diagnostic):
|
||||||
|
state,stop,run=worker_fixture(tmp_path,monkeypatch)
|
||||||
|
assert run(diagnostic).status=='CANCELLED'
|
||||||
|
assert state['waits']==([5] if diagnostic else [5,115])
|
||||||
|
assert state['observers'] and state['observers'][0][1]['process'] is state['worker']
|
||||||
|
assert not state['observers'][0][2] and not state['closed']
|
||||||
|
assert state['polls']==1
|
||||||
|
|
||||||
|
|
||||||
|
def test_exited_worker_with_live_native_clients_keeps_ownership_for_observer(tmp_path,monkeypatch):
|
||||||
|
state,stop,run=worker_fixture(tmp_path,monkeypatch,exited=True)
|
||||||
|
result=run(True)
|
||||||
|
assert result.status=='CANCELLED' and not result.safe_to_continue
|
||||||
|
assert len(state['observers'])==1, 'worker exit must not orphan the still-live registered native client'
|
||||||
|
path,options,already_closed=state['observers'][0]
|
||||||
|
assert path==state['worker'].session_record_path
|
||||||
|
assert options['process'] is state['worker'] and not already_closed and not state['closed']
|
||||||
|
original=json.loads(state['path'].with_name('result.json').read_text())
|
||||||
|
assert original['status']=='CANCELLED' and not original['safe_to_continue']
|
||||||
|
|
||||||
|
|
||||||
|
def test_failed_observer_registration_preserves_original_cancelled_result_and_handle(tmp_path,monkeypatch):
|
||||||
|
state,stop,run=worker_fixture(tmp_path,monkeypatch,exited=True)
|
||||||
|
def fail(*args,**kwargs):raise OSError('observation journal unavailable')
|
||||||
|
monkeypatch.setattr(session_record,'handoff_session',fail)
|
||||||
|
result=run(True)
|
||||||
|
assert result.status=='CANCELLED' and not result.safe_to_continue
|
||||||
|
assert not state['closed']
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_operation_identity_cannot_promote_cold_observation(tmp_path,monkeypatch):
|
||||||
|
from types import SimpleNamespace
|
||||||
|
path=tmp_path/'session.json';path.write_text('{invalid')
|
||||||
|
entered,finish=Event(),Event();modes=[]
|
||||||
|
def observe(*args,**kwargs):
|
||||||
|
mode=kwargs['observe_only'];modes.append(mode() if callable(mode) else mode)
|
||||||
|
entered.set();assert finish.wait(3)
|
||||||
|
return dict(status='UNCONFIRMED',operation_id=None)
|
||||||
|
monkeypatch.setattr(session_record,'observe_retained_session',observe)
|
||||||
|
owner=SimpleNamespace(cbb_library=str(tmp_path/'lib.lmc'),poll=lambda:0,close=lambda:None)
|
||||||
|
thread=None
|
||||||
|
try:
|
||||||
|
session_record.handoff_session(path,evidence_root=tmp_path,process=owner,observe_only=True)
|
||||||
|
assert entered.wait(2)
|
||||||
|
thread=session_record._observers[str(path.absolute()).casefold()][0]
|
||||||
|
assert modes==[True]
|
||||||
|
finally:
|
||||||
|
finish.set()
|
||||||
|
if thread:thread.join(3)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('cold_observer',[False,True])
|
||||||
|
def test_natural_native_exit_gets_fresh_release_and_admits_waiting_scope_without_click(tmp_path,monkeypatch,cold_observer):
|
||||||
|
import subprocess,sys,time
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from cbb_refresh_verify import library_lock
|
||||||
|
from cbb_refresh_verify.operation_queue import NativeQueue,BatchTaskContext
|
||||||
|
from test_issue15_resource_release import library_file,cleanup
|
||||||
|
library=library_file(tmp_path)
|
||||||
|
gate=tmp_path/'native-exit'
|
||||||
|
native=subprocess.Popen([sys.executable,'-c',
|
||||||
|
'from pathlib import Path; import time,sys\nwhile not Path(sys.argv[1]).exists(): time.sleep(.02)',str(gate)])
|
||||||
|
evidence=tmp_path/'evidence';evidence.mkdir();path=evidence/'session.json'
|
||||||
|
session_record.write_session_record(path,dict(operation_id='cancelled-owned',operation='verify',
|
||||||
|
library=str(library),block='A',processes=[dict(role='native',**session_record.process_identity(native.pid))]))
|
||||||
|
original=evidence/'result.json';original.write_text('{"status":"CANCELLED","safe_to_continue":false}')
|
||||||
|
before=original.read_bytes()
|
||||||
|
with library_lock.LibraryLock(library,block_name='A',safe_to_release=lambda:False) as lease:pass
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners',lambda *a,**kw:[])
|
||||||
|
active=Event();stop=Event();closed=[]
|
||||||
|
owner=SimpleNamespace(pid=700,poll=lambda:0,close=lambda:closed.append(native.poll()))
|
||||||
|
thread=None
|
||||||
|
try:
|
||||||
|
session_record.handoff_session(path,evidence_root=evidence,process=owner,stop=stop,observe_only=cold_observer,
|
||||||
|
progress=lambda state:active.set() if state['status']=='ACTIVE' else None)
|
||||||
|
assert active.wait(3) and not closed
|
||||||
|
key=str(path.absolute()).casefold()
|
||||||
|
thread=session_record._observers[key][0]
|
||||||
|
if cold_observer:
|
||||||
|
session_record.handoff_session(path,evidence_root=evidence,observe_only=False)
|
||||||
|
assert session_record._observers[key][0] is thread
|
||||||
|
assert not session_record.library_available(library)
|
||||||
|
queue=NativeQueue()
|
||||||
|
def admitted():
|
||||||
|
with library_lock.LibraryLock(library,checkpoint=False):return 'fresh admission'
|
||||||
|
with ThreadPoolExecutor(1) as pool:
|
||||||
|
future=pool.submit(queue.run,admitted,context=BatchTaskContext(str(library)),stop=stop)
|
||||||
|
time.sleep(.15);assert not future.done()
|
||||||
|
gate.touch();native.wait(5)
|
||||||
|
assert future.result(8)=='fresh admission'
|
||||||
|
thread.join(3)
|
||||||
|
assert not thread.is_alive() and closed==[0]
|
||||||
|
observations=[json.loads(p.read_text()) for p in evidence.glob('observation-*.json')]
|
||||||
|
assert any(o.get('status')=='RELEASED' and o['release_proof']['proof_block_name']=='A' for o in observations)
|
||||||
|
assert original.read_bytes()==before
|
||||||
|
finally:
|
||||||
|
gate.touch();native.wait(5);stop.set()
|
||||||
|
if thread:thread.join(3)
|
||||||
|
cleanup(lease)
|
||||||
@@ -115,6 +115,27 @@ def test_reader_never_creates_a_desktop_or_process(monkeypatch, tmp_path, reader
|
|||||||
import win32service
|
import win32service
|
||||||
import win32process
|
import win32process
|
||||||
import cbb_refresh_verify.mentor_adapter as module
|
import cbb_refresh_verify.mentor_adapter as module
|
||||||
|
import sys
|
||||||
|
import pythoncom
|
||||||
|
if 'pywinauto' not in sys.modules:
|
||||||
|
# Match the real worker's STA apartment. pywinauto's first import probes
|
||||||
|
# MTA and may report its fallback; validate that exact diagnostic only.
|
||||||
|
import warnings
|
||||||
|
pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED)
|
||||||
|
try:
|
||||||
|
with warnings.catch_warnings(record=True) as diagnostics:
|
||||||
|
warnings.simplefilter('always')
|
||||||
|
from pywinauto import Desktop
|
||||||
|
for diagnostic in diagnostics:
|
||||||
|
if diagnostic.category is UserWarning and str(diagnostic.message) in (
|
||||||
|
'Revert to STA COM threading mode', 'Apply externally defined coinit_flags: 2'):
|
||||||
|
assert sys.coinit_flags == pythoncom.COINIT_APARTMENTTHREADED
|
||||||
|
else:
|
||||||
|
warnings.warn_explicit(diagnostic.message, diagnostic.category,
|
||||||
|
diagnostic.filename, diagnostic.lineno)
|
||||||
|
finally:
|
||||||
|
pythoncom.CoUninitialize()
|
||||||
|
else:
|
||||||
from pywinauto import Desktop
|
from pywinauto import Desktop
|
||||||
monkeypatch.setattr(Desktop, 'windows', lambda *_: [])
|
monkeypatch.setattr(Desktop, 'windows', lambda *_: [])
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from test_verify_runner import fixture, request, PORTS_OK
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('fault', ['', 'no_event', 'wrong_pid', 'wrong_operation', 'wrong_project', 'wrong_desktop', 'ordinary'])
|
||||||
|
def test_only_current_diagnostic_close_leaves_prompt_actions_to_checker(tmp_path, monkeypatch, fault):
|
||||||
|
from cbb_refresh_verify import desktop_worker
|
||||||
|
from cbb_refresh_verify.verify_runner import run_verify
|
||||||
|
from cbb_refresh_verify.dialog_supervisor import DialogPollResult
|
||||||
|
fixture(tmp_path); polls = []
|
||||||
|
class Worker:
|
||||||
|
desktop = None
|
||||||
|
pid = 700
|
||||||
|
companion_pids = []
|
||||||
|
returncode = None
|
||||||
|
count = 0
|
||||||
|
def __init__(self, command, name):
|
||||||
|
self.name = name
|
||||||
|
path = Path(command[-1]); job = json.loads(path.read_text())
|
||||||
|
event = dict(stage='diagnostic_close_requested', close_id='b'*32, pcb_pid=901, hwnd=900,
|
||||||
|
operation_id=job['operation_id'], desktop=job['desktop'], project=job['project'], pcb=job['pcb'])
|
||||||
|
for condition, key, value in [('wrong_pid','pcb_pid',999),('wrong_operation','operation_id','foreign'),
|
||||||
|
('wrong_project','project','foreign.prj'),('wrong_desktop','desktop','Default')]:
|
||||||
|
if fault == condition: event[key] = value
|
||||||
|
events = [dict(stage='pcb_worker_started', pcb_pid=901)]
|
||||||
|
if fault != 'no_event': events.append(event)
|
||||||
|
path.with_name('events.jsonl').write_text(''.join(json.dumps(e)+'\n' for e in events))
|
||||||
|
path.with_name('outcome.json').write_text(json.dumps({'status':'FAIL','safe_to_continue':False,
|
||||||
|
'stderr':'DIAGNOSTIC_CLOSE_UNCONFIRMED: unknown prompt retained'}))
|
||||||
|
def poll(self):
|
||||||
|
self.count += 1
|
||||||
|
if self.count > 2: self.returncode = 1
|
||||||
|
return self.returncode
|
||||||
|
def close(self): pass
|
||||||
|
def wait(self, timeout=5): self.returncode = 1; return 1
|
||||||
|
class Supervisor:
|
||||||
|
def poll(self, *args):
|
||||||
|
polls.append(True)
|
||||||
|
return DialogPollResult(error_code='UNKNOWN_DIALOG', detail='competing save prompt')
|
||||||
|
monkeypatch.setattr(desktop_worker, 'DesktopWorker', Worker)
|
||||||
|
result = run_verify(request(tmp_path, diagnostic_only=fault!='ordinary'), port_check=PORTS_OK,
|
||||||
|
dialog_supervisor_factory=lambda **kwargs:Supervisor())
|
||||||
|
assert result.status == 'FAIL'
|
||||||
|
assert json.loads(result.evidence_path.with_name('outcome.json').read_text())['safe_to_continue'] is False
|
||||||
|
if not fault:
|
||||||
|
assert polls == []
|
||||||
|
assert 'DIAGNOSTIC_CLOSE_UNCONFIRMED' in result.stderr
|
||||||
|
else:
|
||||||
|
assert polls and 'UNKNOWN_DIALOG' in result.stderr
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import time
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from test_verify_runner import fixture, request, PORTS_OK
|
||||||
|
from test_diagnostic_open import job, write_logs, frame, Session
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('fault', ['', 'foreign_operation', 'ordinary', 'missing_nonce'])
|
||||||
|
def test_close_handoff_arriving_during_poll_prevents_competing_abort(tmp_path, monkeypatch, fault):
|
||||||
|
from cbb_refresh_verify import desktop_worker
|
||||||
|
from cbb_refresh_verify.verify_runner import run_verify
|
||||||
|
from cbb_refresh_verify.dialog_supervisor import DialogPollResult
|
||||||
|
fixture(tmp_path); state = {}
|
||||||
|
class Worker:
|
||||||
|
desktop = None; pid = 700; companion_pids = []; returncode = None; count = 0
|
||||||
|
def __init__(self, command, name):
|
||||||
|
self.name = name
|
||||||
|
path = Path(command[-1]); state.update(path=path, job=json.loads(path.read_text()))
|
||||||
|
path.with_name('events.jsonl').write_text(json.dumps(dict(stage='pcb_worker_started', pcb_pid=901))+'\n')
|
||||||
|
path.with_name('outcome.json').write_text(json.dumps(dict(status='FAIL', safe_to_continue=False,
|
||||||
|
stderr='DIAGNOSTIC_CLOSE_UNCONFIRMED: checker retained unknown prompt')))
|
||||||
|
def poll(self):
|
||||||
|
self.count += 1
|
||||||
|
if self.count > 2: self.returncode = 1
|
||||||
|
return self.returncode
|
||||||
|
def close(self): pass
|
||||||
|
def wait(self, timeout=5): self.returncode = 1; return 1
|
||||||
|
class Supervisor:
|
||||||
|
def poll(self, *args):
|
||||||
|
j = state['job']
|
||||||
|
event = dict(stage='diagnostic_close_requested', close_id='a'*32, pcb_pid=901, hwnd=900,
|
||||||
|
operation_id=j['operation_id'], desktop=j['desktop'], project=j['project'], pcb=j['pcb'])
|
||||||
|
if fault == 'foreign_operation': event['operation_id'] = 'foreign'
|
||||||
|
if fault == 'missing_nonce': event.pop('close_id')
|
||||||
|
with state['path'].with_name('events.jsonl').open('a') as stream:
|
||||||
|
stream.write(json.dumps(event)+'\n')
|
||||||
|
return DialogPollResult(error_code='UNKNOWN_DIALOG', detail='in-flight competing save prompt')
|
||||||
|
monkeypatch.setattr(desktop_worker, 'DesktopWorker', Worker)
|
||||||
|
result = run_verify(request(tmp_path, diagnostic_only=fault!='ordinary'), port_check=PORTS_OK,
|
||||||
|
dialog_supervisor_factory=lambda **kw: Supervisor())
|
||||||
|
assert result.status == 'FAIL'
|
||||||
|
ack = state['path'].with_name('diagnostic-close-ack.json')
|
||||||
|
if fault:
|
||||||
|
assert 'UNKNOWN_DIALOG' in result.stderr and not ack.exists()
|
||||||
|
else:
|
||||||
|
assert 'DIAGNOSTIC_CLOSE_UNCONFIRMED' in result.stderr
|
||||||
|
assert 'UNKNOWN_DIALOG' not in result.stderr
|
||||||
|
assert json.loads(ack.read_text())['close_id'] == 'a'*32
|
||||||
|
|
||||||
|
|
||||||
|
def test_checker_never_posts_close_before_bound_supervisor_ack(job, monkeypatch):
|
||||||
|
from cbb_refresh_verify import diagnostic_open as diagnostic
|
||||||
|
job['operation_id'] = 'verify-protocol'
|
||||||
|
Path(job['root']).mkdir(exist_ok=True)
|
||||||
|
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||||
|
write_logs(job); events = []
|
||||||
|
ack = Path(job['root'])/'diagnostic-close-ack.json'
|
||||||
|
class AcknowledgedSession(Session):
|
||||||
|
def post(self, hwnd, message):
|
||||||
|
assert ack.exists(), 'WM_CLOSE raced ahead of supervisor ownership acknowledgement'
|
||||||
|
assert events[-1]['stage'] == 'diagnostic_close_requested'
|
||||||
|
super().post(hwnd, message)
|
||||||
|
def emit(**event):
|
||||||
|
events.append(event)
|
||||||
|
if event['stage'] == 'diagnostic_close_requested':
|
||||||
|
ack.write_text(json.dumps({k:v for k,v in event.items() if k != 'stage'}))
|
||||||
|
monkeypatch.setattr(diagnostic, '_NativeSession', AcknowledgedSession)
|
||||||
|
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [frame(job)] if Session.instances[-1].alive else [])
|
||||||
|
assert diagnostic.check_target_window(job, 42, emit=emit, error_reader=lambda: None)['status'] == 'PASS'
|
||||||
|
assert Session.instances[-1].posted == [(10, 0x10)]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('fault', ['missing', 'stale_nonce', 'foreign_pid', 'foreign_project',
|
||||||
|
'foreign_desktop', 'cancel_wait', 'cancel_ack', 'late_ack'])
|
||||||
|
def test_missing_stale_cancelled_or_late_ack_preserves_native(job, monkeypatch, fault):
|
||||||
|
from cbb_refresh_verify import diagnostic_open as diagnostic
|
||||||
|
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||||
|
write_logs(job)
|
||||||
|
offset = [0]; clock = time.monotonic
|
||||||
|
cancel = Path(job['root'])/'cancel.signal'; job['cancel_signal'] = str(cancel)
|
||||||
|
def wait(_):
|
||||||
|
if fault == 'cancel_wait': cancel.touch()
|
||||||
|
else: offset[0] += 31
|
||||||
|
monkeypatch.setattr(diagnostic, 'time', SimpleNamespace(monotonic=lambda:clock()+offset[0], sleep=wait))
|
||||||
|
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
|
||||||
|
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [frame(job)])
|
||||||
|
def emit(**event):
|
||||||
|
if event['stage'] != 'diagnostic_close_requested': return
|
||||||
|
if fault in ('missing', 'cancel_wait'): return
|
||||||
|
ack = {k:v for k,v in event.items() if k != 'stage'}
|
||||||
|
for condition,key,value in [('stale_nonce','close_id','0'*32),('foreign_pid','pcb_pid',99),
|
||||||
|
('foreign_project','project','foreign'),('foreign_desktop','desktop','Default')]:
|
||||||
|
if fault == condition: ack[key] = value
|
||||||
|
(Path(job['root'])/'diagnostic-close-ack.json').write_text(json.dumps(ack))
|
||||||
|
if fault == 'cancel_ack': cancel.touch()
|
||||||
|
if fault == 'late_ack': offset[0] += 31
|
||||||
|
with pytest.raises(RuntimeError, match='VERIFY_CANCELLED' if fault.startswith('cancel') else 'DIAGNOSTIC_CLOSE_UNCONFIRMED'):
|
||||||
|
diagnostic.check_target_window(job,42,emit=emit,error_reader=lambda:None)
|
||||||
|
assert Session.instances[-1].alive and Session.instances[-1].posted == []
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('change', ['progress', 'disabled', 'hwnd', 'pid', 'unknown', 'forward', 'native_error', 'cancel_recheck'])
|
||||||
|
def test_ready_frame_and_prompt_are_revalidated_after_ack(job, monkeypatch, change):
|
||||||
|
from cbb_refresh_verify import diagnostic_open as diagnostic
|
||||||
|
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||||
|
write_logs(job); acknowledged = []
|
||||||
|
job['cancel_signal'] = str(Path(job['root'])/'cancel.signal')
|
||||||
|
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
|
||||||
|
def windows(pid):
|
||||||
|
target = frame(job); rows = [target]
|
||||||
|
if not acknowledged: return rows
|
||||||
|
if change == 'progress': target['children'].append({'class':'msctls_progress32','visible':True})
|
||||||
|
if change == 'disabled': target['enabled'] = False
|
||||||
|
if change == 'hwnd': target['hwnd'] = 99
|
||||||
|
if change == 'pid': target['pid'] = 99
|
||||||
|
if change == 'cancel_recheck': Path(job['cancel_signal']).touch()
|
||||||
|
if change == 'unknown': rows.append({'hwnd':20,'pid':42,'class':'#32770','text':'Unknown','children':[]})
|
||||||
|
if change == 'forward': rows.append({'hwnd':20,'pid':42,'class':'#32770','text':'Expedition PCB','owner':10,
|
||||||
|
'children':[{'class':'Static','id':6172,'text':'New changes are ready for Forward Annotation. Do you want to Forward Annotate now?'},
|
||||||
|
{'hwnd':21,'class':'Button','id':7,'text':'No'}, {'hwnd':22,'class':'Button','id':6,'text':'Yes'}]})
|
||||||
|
return rows
|
||||||
|
monkeypatch.setattr(diagnostic, '_windows', windows)
|
||||||
|
def emit(**event):
|
||||||
|
if event['stage'] == 'diagnostic_close_requested':
|
||||||
|
(Path(job['root'])/'diagnostic-close-ack.json').write_text(json.dumps({k:v for k,v in event.items() if k!='stage'}))
|
||||||
|
acknowledged.append(True)
|
||||||
|
def error():
|
||||||
|
return 'ICDB_INCONSISTENT: fresh error after handoff' if change == 'native_error' and acknowledged else None
|
||||||
|
expected = {'native_error':'ICDB_INCONSISTENT', 'cancel_recheck':'VERIFY_CANCELLED'}.get(change, 'DIAGNOSTIC_CLOSE_UNCONFIRMED')
|
||||||
|
with pytest.raises(RuntimeError, match=expected):
|
||||||
|
diagnostic.check_target_window(job,42,emit=emit,error_reader=error)
|
||||||
|
assert acknowledged and Session.instances[-1].posted == []
|
||||||
@@ -1,14 +1,25 @@
|
|||||||
import importlib
|
import importlib
|
||||||
import importlib.util
|
import importlib.util
|
||||||
|
import json
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def diagnostic():
|
def diagnostic(monkeypatch):
|
||||||
assert importlib.util.find_spec('cbb_refresh_verify.diagnostic_open') is not None, 'diagnostic open module is missing'
|
assert importlib.util.find_spec('cbb_refresh_verify.diagnostic_open') is not None, 'diagnostic open module is missing'
|
||||||
return importlib.import_module('cbb_refresh_verify.diagnostic_open')
|
module = importlib.import_module('cbb_refresh_verify.diagnostic_open')
|
||||||
|
check = module.check_target_window
|
||||||
|
def acknowledged(job, pid, *, emit, **kwargs):
|
||||||
|
def parent(**event):
|
||||||
|
emit(**event)
|
||||||
|
if event['stage'] == 'diagnostic_close_requested':
|
||||||
|
(Path(job['root'])/'diagnostic-close-ack.json').write_text(json.dumps(
|
||||||
|
{key:value for key,value in event.items() if key != 'stage'}))
|
||||||
|
return check(job, pid, emit=parent, **kwargs)
|
||||||
|
monkeypatch.setattr(module, 'check_target_window', acknowledged)
|
||||||
|
return module
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
@@ -17,8 +28,9 @@ def job(tmp_path):
|
|||||||
pcb = project / 'PCB/IP101GR.pcb'
|
pcb = project / 'PCB/IP101GR.pcb'
|
||||||
pcb.parent.mkdir(parents=True)
|
pcb.parent.mkdir(parents=True)
|
||||||
pcb.write_bytes(b'pcb')
|
pcb.write_bytes(b'pcb')
|
||||||
|
(tmp_path/'evidence').mkdir()
|
||||||
return {'project': str(project / 'IP101GR.prj'), 'pcb': str(pcb), 'root': str(tmp_path / 'evidence'),
|
return {'project': str(project / 'IP101GR.prj'), 'pcb': str(pcb), 'root': str(tmp_path / 'evidence'),
|
||||||
'desktop': 'CbbDiagnosticTest', 'timeout': .03}
|
'desktop': 'CbbDiagnosticTest', 'operation_id': 'verify-fixture', 'timeout': .03}
|
||||||
|
|
||||||
|
|
||||||
def write_logs(job, *, pid=42, foreign=False, success=True):
|
def write_logs(job, *, pid=42, foreign=False, success=True):
|
||||||
@@ -83,6 +95,58 @@ def test_target_title_without_target_mdi_does_not_pass(diagnostic, job):
|
|||||||
assert diagnostic._target_frame([window], Path(job['pcb']).stem) is None
|
assert diagnostic._target_frame([window], Path(job['pcb']).stem) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_visible_loading_progress_is_not_ready_for_diagnostic_close(diagnostic, job):
|
||||||
|
window = frame(job)
|
||||||
|
progress = {'hwnd': 13, 'class': 'msctls_progress32', 'text': '', 'visible': True}
|
||||||
|
window['children'].append(progress)
|
||||||
|
assert diagnostic._target_frame([window], 'IP101GR') is None
|
||||||
|
progress['visible'] = False
|
||||||
|
assert diagnostic._target_frame([window], 'IP101GR') == window
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('cancel', [False, True])
|
||||||
|
def test_persistent_loading_progress_keeps_deadline_and_never_closes(diagnostic, job, monkeypatch, cancel):
|
||||||
|
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||||
|
write_logs(job)
|
||||||
|
signal = Path(job['root']).parent/'cancel-progress'
|
||||||
|
job['cancel_signal'] = str(signal)
|
||||||
|
target = frame(job)
|
||||||
|
target['children'].append({'hwnd':13,'class':'msctls_progress32','text':'','visible':True})
|
||||||
|
def windows(pid):
|
||||||
|
if cancel: signal.touch()
|
||||||
|
return [target]
|
||||||
|
monkeypatch.setattr(diagnostic,'_NativeSession',Session)
|
||||||
|
monkeypatch.setattr(diagnostic,'_windows',windows)
|
||||||
|
with pytest.raises(RuntimeError, match='VERIFY_CANCELLED' if cancel else 'DIAGNOSTIC_OPEN_UNCONFIRMED'):
|
||||||
|
diagnostic.check_target_window(job,42,emit=lambda **event:None,error_reader=lambda:None)
|
||||||
|
assert Session.instances[-1].posted == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_diagnostic_waits_for_startup_forward_no_before_close(diagnostic, job, monkeypatch):
|
||||||
|
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||||
|
write_logs(job); job['timeout'] = 1
|
||||||
|
class ForwardSession(Session):
|
||||||
|
declined = False
|
||||||
|
def post(self, hwnd, message):
|
||||||
|
self.posted.append((hwnd,message))
|
||||||
|
if hwnd == 31: self.declined = True
|
||||||
|
else: self.alive = False
|
||||||
|
def windows(pid):
|
||||||
|
state = Session.instances[-1]
|
||||||
|
target = frame(job)
|
||||||
|
if state.declined: return [target] if state.alive else []
|
||||||
|
target['enabled'] = False
|
||||||
|
target['children'].append({'hwnd':13,'class':'msctls_progress32','text':'','visible':True})
|
||||||
|
return [target, {'hwnd':20,'pid':42,'class':'#32770','text':'Expedition PCB','owner':10,
|
||||||
|
'children':[{'hwnd':30,'class':'Static','id':6172,'text':'New changes are ready for Forward Annotation. Do you want to Forward Annotate now?'},
|
||||||
|
{'hwnd':31,'class':'Button','id':7,'text':'&No','enabled':True},
|
||||||
|
{'hwnd':32,'class':'Button','id':6,'text':'&Yes','enabled':True}]}]
|
||||||
|
monkeypatch.setattr(diagnostic,'_NativeSession',ForwardSession)
|
||||||
|
monkeypatch.setattr(diagnostic,'_windows',windows)
|
||||||
|
assert diagnostic.check_target_window(job,42,emit=lambda **event:None,error_reader=lambda:None)['status']=='PASS'
|
||||||
|
assert Session.instances[-1].posted == [(31,0xF5),(10,0x10)]
|
||||||
|
|
||||||
|
|
||||||
class Session:
|
class Session:
|
||||||
instances = []
|
instances = []
|
||||||
def __init__(self, job, pid, launcher):
|
def __init__(self, job, pid, launcher):
|
||||||
@@ -127,6 +191,87 @@ def test_success_posts_one_exact_close_and_reports_only_open_check(diagnostic, j
|
|||||||
assert Session.instances[-1].closed
|
assert Session.instances[-1].closed
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('incomplete_scan', [1, 2, 3])
|
||||||
|
def test_transient_incomplete_scan_is_retried_without_acting_on_partial_windows(diagnostic, job, monkeypatch, incomplete_scan):
|
||||||
|
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||||
|
job['timeout'] = 1
|
||||||
|
write_logs(job)
|
||||||
|
class ClosingSession(Session):
|
||||||
|
closing = False
|
||||||
|
def post(self, hwnd, message):
|
||||||
|
self.posted.append((hwnd, message))
|
||||||
|
self.closing = True
|
||||||
|
monkeypatch.setattr(diagnostic, '_NativeSession', ClosingSession)
|
||||||
|
scans = []
|
||||||
|
def windows(pid):
|
||||||
|
scans.append(True)
|
||||||
|
if len(scans) == incomplete_scan:
|
||||||
|
raise RuntimeError('DIAGNOSTIC_WINDOW_LIMIT: window scan exceeded 0.2s')
|
||||||
|
if Session.instances[-1].closing:
|
||||||
|
Session.instances[-1].alive = False
|
||||||
|
return []
|
||||||
|
return [frame(job)]
|
||||||
|
monkeypatch.setattr(diagnostic, '_windows', windows)
|
||||||
|
events = []
|
||||||
|
result = diagnostic.check_target_window(job, 42, emit=lambda **event:events.append(event), error_reader=lambda:None)
|
||||||
|
assert result['status'] == 'PASS'
|
||||||
|
assert Session.instances[-1].posted == [(10, 0x10)]
|
||||||
|
assert any(e['stage'] == 'diagnostic_window_retry' for e in events)
|
||||||
|
|
||||||
|
|
||||||
|
def test_incomplete_scans_keep_original_open_deadline_and_never_close(diagnostic, job, monkeypatch):
|
||||||
|
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||||
|
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
|
||||||
|
calls = []
|
||||||
|
def windows(pid):
|
||||||
|
calls.append(True)
|
||||||
|
raise RuntimeError('DIAGNOSTIC_WINDOW_LIMIT: window scan exceeded 0.2s')
|
||||||
|
monkeypatch.setattr(diagnostic, '_windows', windows)
|
||||||
|
with pytest.raises(RuntimeError, match='DIAGNOSTIC_WINDOW_LIMIT'):
|
||||||
|
diagnostic.check_target_window(job, 42, emit=lambda **event:None, error_reader=lambda:None)
|
||||||
|
assert len(calls) <= 3
|
||||||
|
assert Session.instances[-1].posted == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_cancel_during_incomplete_scan_stops_retry_without_close(diagnostic, job, monkeypatch):
|
||||||
|
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||||
|
job['timeout'] = 10
|
||||||
|
cancel = Path(job['root']).parent/'cancel-scan'
|
||||||
|
job['cancel_signal'] = str(cancel)
|
||||||
|
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
|
||||||
|
calls = []
|
||||||
|
def windows(pid):
|
||||||
|
calls.append(True)
|
||||||
|
cancel.touch()
|
||||||
|
raise RuntimeError('DIAGNOSTIC_WINDOW_LIMIT: window scan exceeded 0.2s')
|
||||||
|
monkeypatch.setattr(diagnostic, '_windows', windows)
|
||||||
|
with pytest.raises(RuntimeError, match='VERIFY_CANCELLED'):
|
||||||
|
diagnostic.check_target_window(job, 42, emit=lambda **event:None, error_reader=lambda:None)
|
||||||
|
assert len(calls) == 1 and Session.instances[-1].posted == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_incomplete_close_scan_cannot_extend_thirty_second_deadline(diagnostic, job, monkeypatch):
|
||||||
|
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||||
|
write_logs(job)
|
||||||
|
clock, offset = diagnostic.time.monotonic, [0]
|
||||||
|
monkeypatch.setattr(diagnostic.time, 'monotonic', lambda:clock()+offset[0])
|
||||||
|
class ClosingSession(Session):
|
||||||
|
closing = False
|
||||||
|
def post(self, hwnd, message):
|
||||||
|
self.posted.append((hwnd, message))
|
||||||
|
self.closing = True
|
||||||
|
monkeypatch.setattr(diagnostic, '_NativeSession', ClosingSession)
|
||||||
|
def windows(pid):
|
||||||
|
if Session.instances[-1].closing:
|
||||||
|
offset[0] = 31
|
||||||
|
raise RuntimeError('DIAGNOSTIC_WINDOW_LIMIT: window scan exceeded 0.2s')
|
||||||
|
return [frame(job)]
|
||||||
|
monkeypatch.setattr(diagnostic, '_windows', windows)
|
||||||
|
with pytest.raises(RuntimeError, match='DIAGNOSTIC_WINDOW_LIMIT'):
|
||||||
|
diagnostic.check_target_window(job, 42, emit=lambda **event:None, error_reader=lambda:None)
|
||||||
|
assert Session.instances[-1].posted == [(10, 0x10)]
|
||||||
|
|
||||||
|
|
||||||
def test_transient_startup_window_cannot_abort_before_target_is_loaded(diagnostic, job, monkeypatch):
|
def test_transient_startup_window_cannot_abort_before_target_is_loaded(diagnostic, job, monkeypatch):
|
||||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||||
write_logs(job)
|
write_logs(job)
|
||||||
@@ -336,3 +481,37 @@ def test_recycled_window_from_another_pid_never_receives_close(diagnostic, monke
|
|||||||
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda hwnd: (1, 99))
|
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda hwnd: (1, 99))
|
||||||
with pytest.raises(RuntimeError, match='DIAGNOSTIC_STALE_WINDOW'):
|
with pytest.raises(RuntimeError, match='DIAGNOSTIC_STALE_WINDOW'):
|
||||||
session.post(10, 0x10)
|
session.post(10, 0x10)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('fault', ['', 'foreign_pid', 'cycle', 'other_frame', 'visible', 'enabled', 'class', 'title', 'desktop', 'incomplete', 'filename'])
|
||||||
|
def test_diagnostic_save_accepts_only_complete_hidden_owner_chain(diagnostic, job, fault):
|
||||||
|
target = frame(job)
|
||||||
|
owner = {'hwnd': 15, 'pid': 42, 'class': '#32770', 'text': 'Expedition PCB',
|
||||||
|
'owner': 10, 'visible': False, 'enabled': False, 'same_desktop': True}
|
||||||
|
end = {**target, 'same_desktop': True}
|
||||||
|
window = {'hwnd': 20, 'pid': 42, 'class': '#32770', 'text': 'Expedition PCB',
|
||||||
|
'owner': 15, 'owner_chain': [owner, end], 'children': [
|
||||||
|
{'hwnd': 30, 'class': 'Static', 'text': 'Save changes to IP101GR.pcb?', 'id': -1},
|
||||||
|
{'hwnd': 31, 'class': 'Button', 'text': '否(&N)', 'id': 7},
|
||||||
|
{'hwnd': 32, 'class': 'Button', 'text': '是(&Y)', 'id': 6},
|
||||||
|
{'hwnd': 33, 'class': 'Button', 'text': '取消', 'id': 2}]}
|
||||||
|
if fault == 'foreign_pid': owner['pid'] = 99
|
||||||
|
if fault == 'cycle': owner['owner'] = 15
|
||||||
|
if fault == 'other_frame': end['hwnd'] = 99
|
||||||
|
if fault == 'visible': owner['visible'] = True
|
||||||
|
if fault == 'enabled': owner['enabled'] = True
|
||||||
|
if fault == 'class': owner['class'] = 'VendorDialog'
|
||||||
|
if fault == 'title': owner['text'] = 'Unknown recovery'
|
||||||
|
if fault == 'desktop': owner['same_desktop'] = False
|
||||||
|
if fault == 'incomplete': window['owner_chain'] = [owner]
|
||||||
|
if fault == 'filename': window['children'][0]['text'] = 'Save changes to Foreign.pcb?'
|
||||||
|
session = Session(job, 42, None)
|
||||||
|
action = lambda:diagnostic._pending_prompt([window], closing=True, frame=target,
|
||||||
|
session=session, clicked=set(), pcb_name='IP101GR.pcb')
|
||||||
|
if not fault:
|
||||||
|
assert action() is False
|
||||||
|
assert session.posted == [(31, 0xF5)]
|
||||||
|
else:
|
||||||
|
with pytest.raises(RuntimeError, match='DIAGNOSTIC_CLOSE_UNCONFIRMED'):
|
||||||
|
action()
|
||||||
|
assert session.posted == []
|
||||||
@@ -179,3 +179,13 @@ def test_probe_skips_project_integration_panel_during_com_phase():
|
|||||||
snapshots = make_probe(gui, (10,)).capture(DialogPhase.PROJECT_INTEGRATION)
|
snapshots = make_probe(gui, (10,)).capture(DialogPhase.PROJECT_INTEGRATION)
|
||||||
|
|
||||||
assert snapshots == ()
|
assert snapshots == ()
|
||||||
|
|
||||||
|
|
||||||
|
def test_save_integration_panel_uses_complete_win32_controls_without_huge_uia_tree():
|
||||||
|
gui=FakeGui({10:{'class_name':'#32770','text':'Project Integration','owner':99},
|
||||||
|
11:{'class_name':'Button','text':'&Close','control_id':2}},children={10:(11,)})
|
||||||
|
probe=make_probe(gui,(10,),FakeUia(error=AssertionError('unnecessary large UIA panel scan')))
|
||||||
|
probe.process_name_reader=lambda _: 'ExpeditionPCB.exe'
|
||||||
|
snapshot=probe.capture(DialogPhase.SAVE,pids={1010})[0]
|
||||||
|
assert snapshot.controls[0].control_id==2
|
||||||
|
assert snapshot.diagnostics==()
|
||||||
@@ -15,6 +15,15 @@ from cbb_refresh_verify.dialog_rules import (
|
|||||||
ASSETS = Path(__file__).resolve().parents[1] / "src" / "cbb_refresh_verify" / "assets"
|
ASSETS = Path(__file__).resolve().parents[1] / "src" / "cbb_refresh_verify" / "assets"
|
||||||
|
|
||||||
|
|
||||||
|
def test_diagnostic_forward_prompt_is_observed_while_ordinary_verify_still_confirms():
|
||||||
|
text = 'New changes are ready for Forward Annotation. Do you want to Forward Annotate now?'
|
||||||
|
snapshot = prompt(text)
|
||||||
|
ordinary = decide(snapshot, load_rules(ASSETS/'dialog_rules.v1.json'))
|
||||||
|
diagnostic = decide(snapshot, load_rules(ASSETS/'dialog_rules.v1.json', diagnostic_only=True))
|
||||||
|
assert ordinary.action == 'confirm_forward_annotation'
|
||||||
|
assert diagnostic.category == 'OBSERVE_PROGRESS' and not diagnostic.action
|
||||||
|
|
||||||
|
|
||||||
def prompt(text, *, phase=DialogPhase.PCB_STARTING, window_class="#32770",
|
def prompt(text, *, phase=DialogPhase.PCB_STARTING, window_class="#32770",
|
||||||
control_types=("Text", "Button")):
|
control_types=("Text", "Button")):
|
||||||
controls = tuple(
|
controls = tuple(
|
||||||
@@ -244,3 +253,41 @@ def test_database_open_failure_is_classified_and_declines_log_view():
|
|||||||
assert decision.category == 'FATAL_ACK'
|
assert decision.category == 'FATAL_ACK'
|
||||||
assert decision.error_code == 'MENTOR_DATABASE_LOAD_FAILED'
|
assert decision.error_code == 'MENTOR_DATABASE_LOAD_FAILED'
|
||||||
assert dict(decision.target)['control_id'] == 7 # IDNO, never launch another log viewer
|
assert dict(decision.target)['control_id'] == 7 # IDNO, never launch another log viewer
|
||||||
|
|
||||||
|
|
||||||
|
def completed_integration_panel():
|
||||||
|
texts={1033:'No connectivity changes to be forward annotated',
|
||||||
|
1032:'No pending schematic CES changes to load into PCB',
|
||||||
|
1035:'No pending PCB changes to be back annotated',
|
||||||
|
1034:'No pending CES changes to load into PCB'}
|
||||||
|
return WindowSnapshot(hwnd=10,pid=20,process_name='ExpeditionPCB.exe',process_role='pcb',
|
||||||
|
window_class='#32770',title='Project Integration',phase=DialogPhase.SAVE,owner_hwnd=99,
|
||||||
|
controls=(ControlSnapshot(handle=12,control_id=2,class_name='Button',name='&Close'),
|
||||||
|
*(ControlSnapshot(handle=i,control_id=i,class_name='Static',name=text) for i,text in texts.items())))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('phase',[DialogPhase.SAVE,DialogPhase.CLOSE])
|
||||||
|
def test_completed_integration_panel_only_closes_its_exact_close_control(phase):
|
||||||
|
from dataclasses import replace
|
||||||
|
decision=decide(replace(completed_integration_panel(),phase=phase),load_rules(ASSETS/'dialog_rules.v1.json'))
|
||||||
|
assert decision.action=='close_completed_integration'
|
||||||
|
assert decision.channels==('win32_button_click',)
|
||||||
|
assert dict(decision.target)=={'control_id':2}
|
||||||
|
assert decision.postcondition=='window_gone' and not decision.error_code
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('fault',['pending','missing','duplicate','partial','foreign','unowned','disabled','early','error'])
|
||||||
|
def test_integration_panel_without_complete_owned_idle_proof_never_closes(fault):
|
||||||
|
from dataclasses import replace
|
||||||
|
panel=completed_integration_panel()
|
||||||
|
if fault=='pending': panel=replace(panel,controls=(*panel.controls[:-1],replace(panel.controls[-1],name='CES changes are pending')))
|
||||||
|
elif fault=='missing': panel=replace(panel,controls=panel.controls[:-1])
|
||||||
|
elif fault=='duplicate': panel=replace(panel,controls=(*panel.controls,panel.controls[-1]))
|
||||||
|
elif fault=='partial': panel=replace(panel,diagnostics=('WINDOW_ENUM_INCOMPLETE',))
|
||||||
|
elif fault=='foreign': panel=replace(panel,process_name='Unrelated.exe',process_role='unknown')
|
||||||
|
elif fault=='unowned': panel=replace(panel,owner_hwnd=0)
|
||||||
|
elif fault=='disabled': panel=replace(panel,controls=(replace(panel.controls[0],enabled=False),*panel.controls[1:]))
|
||||||
|
elif fault=='early': panel=replace(panel,phase=DialogPhase.DOCUMENT_ATTACH)
|
||||||
|
elif fault=='error': panel=replace(panel,controls=(*panel.controls,
|
||||||
|
ControlSnapshot(handle=500,control_id=500,class_name='Static',name='There were errors during Project Integration.')))
|
||||||
|
assert decide(panel,load_rules(ASSETS/'dialog_rules.v1.json')).action!='close_completed_integration'
|
||||||
@@ -54,7 +54,7 @@ def test_preflight_rejects_pcb_junction_outside_current_block(tmp_path):
|
|||||||
preflight(VerifyRequest(library, 'CBB', tmp_path/'evidence'))
|
preflight(VerifyRequest(library, 'CBB', tmp_path/'evidence'))
|
||||||
|
|
||||||
|
|
||||||
def test_serial_guard_covers_preflight_and_content_check(tmp_path, monkeypatch):
|
def test_nonnative_preparation_leaves_real_host_channel_available(tmp_path, monkeypatch):
|
||||||
from cbb_refresh_verify import verify_runner as runner
|
from cbb_refresh_verify import verify_runner as runner
|
||||||
entered, release = Event(), Event()
|
entered, release = Event(), Event()
|
||||||
calls, results = [], []
|
calls, results = [], []
|
||||||
@@ -70,14 +70,14 @@ def test_serial_guard_covers_preflight_and_content_check(tmp_path, monkeypatch):
|
|||||||
thread.start()
|
thread.start()
|
||||||
assert entered.wait(3)
|
assert entered.wait(3)
|
||||||
try:
|
try:
|
||||||
second = runner.run_verify(VerifyRequest(tmp_path/'lib.lmc', 'second', tmp_path/'evidence'))
|
from cbb_refresh_verify.operation_queue import native_channel
|
||||||
assert second.status == 'BLOCKED'
|
with native_channel():
|
||||||
assert second.safe_to_continue
|
pass
|
||||||
assert second.error_category == 'NATIVE_CHANNEL_BUSY'
|
|
||||||
assert calls == ['first']
|
assert calls == ['first']
|
||||||
finally:
|
finally:
|
||||||
release.set()
|
release.set()
|
||||||
thread.join(6)
|
thread.join(6)
|
||||||
|
assert results[0].status == 'PASS'
|
||||||
|
|
||||||
|
|
||||||
def test_recovery_retains_temporary_network_mapping():
|
def test_recovery_retains_temporary_network_mapping():
|
||||||
|
|||||||
@@ -7,8 +7,9 @@ from cbb_refresh_verify import failed_session, mentor_adapter
|
|||||||
|
|
||||||
|
|
||||||
def startup_fixture(tmp_path, monkeypatch):
|
def startup_fixture(tmp_path, monkeypatch):
|
||||||
import win32gui, win32process
|
from contextlib import nullcontext
|
||||||
from cbb_refresh_verify import native_repair_ui
|
import win32gui, win32process, win32event, win32con
|
||||||
|
from cbb_refresh_verify import native_repair_ui, residual_sessions
|
||||||
job = {'root': str(tmp_path), 'pcb': str(tmp_path/'PCB/CBB.pcb'),
|
job = {'root': str(tmp_path), 'pcb': str(tmp_path/'PCB/CBB.pcb'),
|
||||||
'project': str(tmp_path/'CBB.prj'), 'lmc_file': str(tmp_path/'lib.lmc'),
|
'project': str(tmp_path/'CBB.prj'), 'lmc_file': str(tmp_path/'lib.lmc'),
|
||||||
'desktop': 'CbbVerify_test'}
|
'desktop': 'CbbVerify_test'}
|
||||||
@@ -20,6 +21,12 @@ def startup_fixture(tmp_path, monkeypatch):
|
|||||||
records = [(12, r'C:\Mentor\wg\ExpeditionPCB.exe',
|
records = [(12, r'C:\Mentor\wg\ExpeditionPCB.exe',
|
||||||
f'ExpeditionPCB.exe "{job["pcb"]}" -ReusableCircuit', 11)]
|
f'ExpeditionPCB.exe "{job["pcb"]}" -ReusableCircuit', 11)]
|
||||||
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: list(records))
|
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: list(records))
|
||||||
|
monkeypatch.setattr(residual_sessions, '_process_handle', lambda *a, **kw: nullcontext(123))
|
||||||
|
monkeypatch.setattr(residual_sessions, '_handle_identity', lambda h:
|
||||||
|
{'created_handle': 'original', 'image': r'C:\Mentor\wg\ExpeditionPCB.exe'})
|
||||||
|
monkeypatch.setattr(residual_sessions, '_process_windows', lambda pids: {12: []})
|
||||||
|
monkeypatch.setattr(win32event, 'WaitForSingleObject', lambda *a:
|
||||||
|
win32con.WAIT_TIMEOUT if records else win32con.WAIT_OBJECT_0)
|
||||||
monkeypatch.setattr(native_repair_ui, '_current_desktop_name', lambda: 'CbbVerify_test')
|
monkeypatch.setattr(native_repair_ui, '_current_desktop_name', lambda: 'CbbVerify_test')
|
||||||
monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg: fn(100, arg))
|
monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg: fn(100, arg))
|
||||||
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda *args: None)
|
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda *args: None)
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
from threading import Event,Thread
|
||||||
|
|
||||||
|
from cbb_refresh_verify.operation_queue import QueueCancelled
|
||||||
|
from test_issue15_ui_integration import window_for
|
||||||
|
|
||||||
|
|
||||||
|
def test_actual_global_stop_button_cancels_running_and_same_app_queued_jobs(qtbot,tmp_path,monkeypatch):
|
||||||
|
window=window_for(qtbot,tmp_path,monkeypatch)
|
||||||
|
first=window._new_job('verify',library=tmp_path/'lib.lmc')
|
||||||
|
second=window._new_job('native_session',library=tmp_path/'lib.lmc')
|
||||||
|
entered,release,waiting,done=Event(),Event(),Event(),Event();calls=[];errors=[]
|
||||||
|
def current():
|
||||||
|
calls.append('first');entered.set();release.wait(3)
|
||||||
|
def run_first():
|
||||||
|
try:window.native_queue.run(current,context=first.context,stop=first.context.stop)
|
||||||
|
except QueueCancelled:pass
|
||||||
|
def queued():
|
||||||
|
try:window.native_queue.run(lambda:calls.append('second'),context=second.context,
|
||||||
|
stop=second.context.stop,waiting=waiting.set)
|
||||||
|
except QueueCancelled as error:errors.append(error)
|
||||||
|
finally:done.set()
|
||||||
|
a=Thread(target=run_first);b=Thread(target=queued)
|
||||||
|
a.start();assert entered.wait(2);b.start()
|
||||||
|
try:
|
||||||
|
qtbot.waitUntil(waiting.is_set);window._update()
|
||||||
|
assert window.stop_button.isEnabled()
|
||||||
|
window.stop_button.click()
|
||||||
|
qtbot.waitUntil(done.is_set)
|
||||||
|
assert first.context.stop.is_set() and second.context.stop.is_set()
|
||||||
|
assert calls==['first'] and len(errors)==1
|
||||||
|
finally:
|
||||||
|
release.set();a.join(3);b.join(3)
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
"""Batch ICDB checks open diagnostically without dispatching Repair."""
|
"""Batch ICDB checks open diagnostically without dispatching Repair."""
|
||||||
|
from cbb_refresh_verify.ui import timed_prompt
|
||||||
from dataclasses import replace
|
from dataclasses import replace
|
||||||
import json
|
import json
|
||||||
|
|
||||||
@@ -93,7 +94,7 @@ def test_ui_check_summary_reports_findings_and_never_claims_repair(qtbot, tmp_pa
|
|||||||
verifier=lambda req: (requests.append(req) or VerifyResult('FAIL',
|
verifier=lambda req: (requests.append(req) or VerifyResult('FAIL',
|
||||||
error_category='ICDB_REPAIR_REQUIRED', stderr='发现 ICDB 问题,未执行修复。')),
|
error_category='ICDB_REPAIR_REQUIRED', stderr='发现 ICDB 问题,未执行修复。')),
|
||||||
status_refresher=lambda names, _: {name: 'PENDING' for name in names})
|
status_refresher=lambda names, _: {name: 'PENDING' for name in names})
|
||||||
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: (prompts.append(a[2]) or QMessageBox.Yes))
|
monkeypatch.setattr(timed_prompt, 'question', lambda *a, **k: (prompts.append(a[2]) or QMessageBox.Yes))
|
||||||
window.search_edit.setText('Beta')
|
window.search_edit.setText('Beta')
|
||||||
window.icdb_repair_button.click(); qtbot.waitUntil(lambda: not window._icdb_active())
|
window.icdb_repair_button.click(); qtbot.waitUntil(lambda: not window._icdb_active())
|
||||||
assert requests[0].maintenance and not requests[0].auto_repair
|
assert requests[0].maintenance and not requests[0].auto_repair
|
||||||
|
|||||||
@@ -277,7 +277,8 @@ def test_contents_session_loss_records_each_item_without_launching_pcb_or_repair
|
|||||||
assert results[1].error_category == 'ICDB_REPAIR_REQUIRED'
|
assert results[1].error_category == 'ICDB_REPAIR_REQUIRED'
|
||||||
|
|
||||||
|
|
||||||
def test_supervisor_enriches_generic_failure_from_fresh_native_log(tmp_path, monkeypatch):
|
@pytest.mark.parametrize('fault', ['session_loss', 'inconsistent'])
|
||||||
|
def test_supervisor_enriches_generic_failure_from_fresh_native_log(tmp_path, monkeypatch, fault):
|
||||||
from test_verify_runner import fixture, request
|
from test_verify_runner import fixture, request
|
||||||
from cbb_refresh_verify.icdb_recovery import snapshot_log
|
from cbb_refresh_verify.icdb_recovery import snapshot_log
|
||||||
from cbb_refresh_verify.verify_diagnostics import failure_logs_main
|
from cbb_refresh_verify.verify_diagnostics import failure_logs_main
|
||||||
@@ -292,7 +293,8 @@ def test_supervisor_enriches_generic_failure_from_fresh_native_log(tmp_path, mon
|
|||||||
(root/'diagnostics').mkdir()
|
(root/'diagnostics').mkdir()
|
||||||
(root/'diagnostics/startup-log-baseline.json').write_text(json.dumps({
|
(root/'diagnostics/startup-log-baseline.json').write_text(json.dumps({
|
||||||
'source': str(log), 'baseline': snapshot_log(log)}), encoding='utf-8')
|
'source': str(log), 'baseline': snapshot_log(log)}), encoding='utf-8')
|
||||||
log.write_text(ERROR, encoding='utf-8')
|
from test_issue15_native_entry import inconsistency
|
||||||
|
log.write_text(ERROR if fault == 'session_loss' else inconsistency(work/'database'), encoding='utf-8')
|
||||||
(root/'outcome.json').write_text(json.dumps({
|
(root/'outcome.json').write_text(json.dumps({
|
||||||
'status': 'FAIL', 'stderr': 'MENTOR_DATABASE_LOAD_FAILED: opening failed',
|
'status': 'FAIL', 'stderr': 'MENTOR_DATABASE_LOAD_FAILED: opening failed',
|
||||||
'safe_to_continue': False}), encoding='utf-8')
|
'safe_to_continue': False}), encoding='utf-8')
|
||||||
@@ -305,7 +307,11 @@ def test_supervisor_enriches_generic_failure_from_fresh_native_log(tmp_path, mon
|
|||||||
assert result.error_category == 'ICDB_REPAIR_REQUIRED'
|
assert result.error_category == 'ICDB_REPAIR_REQUIRED'
|
||||||
assert result.safe_to_continue is True
|
assert result.safe_to_continue is True
|
||||||
assert 'opening failed' in result.stderr
|
assert 'opening failed' in result.stderr
|
||||||
|
if fault == 'session_loss':
|
||||||
assert '200091-CBB' in result.stderr
|
assert '200091-CBB' in result.stderr
|
||||||
assert '__ReusableBlocksSymb' in result.stderr
|
assert '__ReusableBlocksSymb' in result.stderr
|
||||||
assert '2026-10-24 08.22.29-10308' in result.stderr
|
assert '2026-10-24 08.22.29-10308' in result.stderr
|
||||||
|
else:
|
||||||
|
assert str(work/'database') in result.stderr
|
||||||
|
assert '未修复' in result.stderr
|
||||||
assert json.loads(result.evidence_path.read_text('utf-8'))['error_category'] == 'ICDB_REPAIR_REQUIRED'
|
assert json.loads(result.evidence_path.read_text('utf-8'))['error_category'] == 'ICDB_REPAIR_REQUIRED'
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
"""Normal imports must not depend on optional schematic export tools."""
|
||||||
|
from cbb_refresh_verify.ui import timed_prompt
|
||||||
|
from dataclasses import replace
|
||||||
|
import json
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from test_management_native_transaction import transaction, execute
|
||||||
|
from test_management import setup
|
||||||
|
|
||||||
|
|
||||||
|
def test_import_capability_does_not_require_exporters(tmp_path, monkeypatch):
|
||||||
|
import cbb_refresh_verify.native_management as native
|
||||||
|
import cbb_refresh_verify.native_engineering_identity as identity
|
||||||
|
monkeypatch.setattr(native.NativeManagementAdapter, '_binary_capability', lambda _: '')
|
||||||
|
def missing(*_):
|
||||||
|
raise ValueError('edifExporter.exe is not installed')
|
||||||
|
monkeypatch.setattr(identity, 'check_exporters', missing)
|
||||||
|
caps = native.NativeManagementAdapter(mentor_home=tmp_path).capabilities()
|
||||||
|
assert caps['add'].supported and caps['update'].supported
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('auto_verify', [False, True])
|
||||||
|
def test_real_engine_imports_without_any_native_export(transaction, monkeypatch, auto_verify):
|
||||||
|
import cbb_refresh_verify.native_engineering_identity as identity
|
||||||
|
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||||
|
root, request, state = transaction
|
||||||
|
def forbidden(*_a, **_kw):
|
||||||
|
raise AssertionError('An optional native exporter was called by import')
|
||||||
|
monkeypatch.setattr(identity, 'capture_identity', forbidden)
|
||||||
|
monkeypatch.setattr(identity, 'check_exporters', forbidden)
|
||||||
|
verified = []
|
||||||
|
def verify(request, **_):
|
||||||
|
verified.append(request.block_name)
|
||||||
|
return VerifyResult('PASS', library_flag='GREEN', library_flag_detail='READY')
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.verify_runner.run_verify', verify)
|
||||||
|
result = execute(root, replace(request, auto_verify=auto_verify))
|
||||||
|
assert result.status == ('UPLOADED_VERIFIED' if auto_verify else 'UPLOADED'), result.detail
|
||||||
|
assert result.safe_to_continue
|
||||||
|
assert verified == (['Block'] if auto_verify else [])
|
||||||
|
proof = json.loads((result.evidence_path.parent/'source-identity/identity.json').read_text())
|
||||||
|
assert proof['identity']['coverage']['schematic_semantics_checked'] is False
|
||||||
|
assert 'edif_sha256' not in proof['identity']
|
||||||
|
assert 'add' in state['calls']
|
||||||
|
|
||||||
|
|
||||||
|
def test_bad_source_row_does_not_prevent_valid_rows_from_starting(qtbot, tmp_path, monkeypatch):
|
||||||
|
from PySide6.QtWidgets import QMessageBox
|
||||||
|
from cbb_refresh_verify.management import ManagementRequest, ManagementResult
|
||||||
|
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
|
||||||
|
good = tmp_path/'good.prj'; good.write_text('fixture')
|
||||||
|
rows = [ManagementRequest('add', tmp_path/'lib.lmc', 'Missing', source=tmp_path/'missing.prj'),
|
||||||
|
ManagementRequest('add', tmp_path/'lib.lmc', 'Good', source=good)]
|
||||||
|
seen = []
|
||||||
|
def runner(requests, **_):
|
||||||
|
seen.extend(requests)
|
||||||
|
return [ManagementResult(r.operation, r.library, r.name, r.partition, r.source,
|
||||||
|
r.auto_verify, 'complete', 'UPLOAD_FAILED' if r.name == 'Missing' else 'UPLOADED',
|
||||||
|
True, 'per-item result') for r in requests]
|
||||||
|
dialog = ManagementDialog(rows, runner=runner); qtbot.addWidget(dialog)
|
||||||
|
monkeypatch.setattr(timed_prompt, 'question', lambda *_a, **_kw: QMessageBox.Yes)
|
||||||
|
dialog.execute_button.click()
|
||||||
|
qtbot.waitUntil(lambda: bool(seen) and not dialog.busy)
|
||||||
|
assert [r.name for r in seen] == ['Missing', 'Good']
|
||||||
|
|
||||||
|
|
||||||
|
def test_import_retargets_old_library_reference_without_requiring_old_library(transaction):
|
||||||
|
root, request, state = transaction
|
||||||
|
for path in (request.source, request.source.parent/'PCB/pcb.prj'):
|
||||||
|
text = path.read_text()
|
||||||
|
path.write_text(text.replace(str(request.library), str(root/'unavailable-old-library.lmc')))
|
||||||
|
before = request.source.read_bytes()
|
||||||
|
result = execute(root, request)
|
||||||
|
assert result.status == 'UPLOADED' and result.safe_to_continue, result.detail
|
||||||
|
assert request.source.read_bytes() == before
|
||||||
|
|
||||||
|
|
||||||
|
def test_input_and_optional_verify_failures_do_not_skip_later_imports(setup, tmp_path):
|
||||||
|
from cbb_refresh_verify.management import run_management_batch
|
||||||
|
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||||
|
request, adapter, source = setup
|
||||||
|
results = run_management_batch([
|
||||||
|
replace(request, operation='add', name='Bad', source=tmp_path/'absent.prj'),
|
||||||
|
replace(request, operation='add', name='First', source=source, auto_verify=True),
|
||||||
|
replace(request, operation='add', name='Second', source=source, auto_verify=False)],
|
||||||
|
adapter=adapter, idle_check=lambda *_: None,
|
||||||
|
verifier=lambda *_a, **_kw: VerifyResult('FAIL', stderr='Optional Verify did not pass'))
|
||||||
|
assert [r.status for r in results] == ['UPLOAD_FAILED', 'UPLOADED_VERIFY_FAILED', 'UPLOADED']
|
||||||
|
assert all(r.safe_to_continue for r in results)
|
||||||
|
assert len(adapter.calls) == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_native_project_normalization_is_a_recorded_difference_not_import_failure(transaction, monkeypatch):
|
||||||
|
import cbb_refresh_verify.native_management as native
|
||||||
|
root, request, state = transaction
|
||||||
|
original_worker = native.NativeManagementAdapter._worker
|
||||||
|
def worker(adapter, job, evidence):
|
||||||
|
result = original_worker(adapter, job, evidence)
|
||||||
|
if job['operation'] == 'add' and result.get('success'):
|
||||||
|
project = request.library.parent/'ReusableBlocksLP/Block/Work/Block.prj'
|
||||||
|
with project.open('a') as stream:
|
||||||
|
stream.write('SECTION VBPCBIndicators\nKEY VBPCBForwardAnno "0"\nKEY CADBackAnno "0"\nENDSECTION\n')
|
||||||
|
return result
|
||||||
|
monkeypatch.setattr(native.NativeManagementAdapter, '_worker', worker)
|
||||||
|
result = execute(root, request)
|
||||||
|
assert result.status == 'UPLOADED' and result.safe_to_continue, result.detail
|
||||||
|
comparison = json.loads((result.evidence_path.parent/'add/identity-comparison.json').read_text())
|
||||||
|
assert comparison['identity_matches'] and not comparison['assets_match']
|
||||||
|
assert 'Block.prj' in comparison['asset_differences']['modified']
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('registered_top,expected', [('Block', 'UPLOADED'), ('Foreign', 'RECOVERY_REQUIRED')])
|
||||||
|
def test_native_top_block_may_match_registration_name_but_not_an_unrelated_name(transaction, monkeypatch, registered_top, expected):
|
||||||
|
import cbb_refresh_verify.native_management as native
|
||||||
|
root, request, state = transaction
|
||||||
|
original_worker = native.NativeManagementAdapter._worker
|
||||||
|
def worker(adapter, job, evidence):
|
||||||
|
result = original_worker(adapter, job, evidence)
|
||||||
|
if job['operation'] == 'add' and result.get('success'):
|
||||||
|
project = request.library.parent/'ReusableBlocksLP/Block/Work/Block.prj'
|
||||||
|
project.write_text(project.read_text().replace('KEY RootBlock "Top"', f'KEY RootBlock "{registered_top}"'))
|
||||||
|
return result
|
||||||
|
monkeypatch.setattr(native.NativeManagementAdapter, '_worker', worker)
|
||||||
|
result = execute(root, request)
|
||||||
|
assert result.status == expected and result.safe_to_continue, result.detail
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
"""A fresh confirmed operation may recover data; historical requests never replay."""
|
||||||
|
from dataclasses import replace
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from test_management import setup, execute
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('proof_case', ['fresh','none','wrong_library','wrong_block','cached','live_writer'])
|
||||||
|
def test_confirmed_retry_requires_fresh_exact_resource_proof(setup,monkeypatch,proof_case):
|
||||||
|
request,adapter,source=setup
|
||||||
|
old=request.evidence_dir/'old';old.mkdir(parents=True)
|
||||||
|
record={'operation':'update','library':str(request.library),'name':'Block','stage':'complete',
|
||||||
|
'status':'RECOVERY_REQUIRED','safe_to_continue':True,'history':[{'stage':'native_add'}]}
|
||||||
|
path=old/'checkpoint.json';path.write_text(json.dumps(record));before=path.read_bytes()
|
||||||
|
observed=[]
|
||||||
|
def proof(library,evidence,*,block_name,required,**kw):
|
||||||
|
observed.append((library,evidence,block_name,required))
|
||||||
|
if proof_case=='live_writer':raise RuntimeError('NATIVE_WRITER_ACTIVE')
|
||||||
|
if proof_case=='none':return None
|
||||||
|
target=library if proof_case!='wrong_library' else library.with_name('other.lmc')
|
||||||
|
block=block_name if proof_case!='wrong_block' else 'Other'
|
||||||
|
receipt=(old if proof_case=='cached' else evidence/'fresh')/'release.json'
|
||||||
|
receipt.parent.mkdir(parents=True,exist_ok=True)
|
||||||
|
result={'status':'RELEASE_CONFIRMED','lease_state':'RELEASED','library':str(target),
|
||||||
|
'proof_scope':'BLOCK','proof_block_names':[block],
|
||||||
|
'resource_scope':{'scope_state':'OBSERVED','library':str(target),'block_names':[block]},
|
||||||
|
'evidence_path':str(receipt)}
|
||||||
|
receipt.write_text(json.dumps(result));return result
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.library_lock.recheck_previous_release',proof)
|
||||||
|
result=execute(replace(request,operation='update',source=source,auto_verify=False,check_previous_release=True),adapter)
|
||||||
|
assert observed and observed[0][2:]==('Block',True)
|
||||||
|
assert path.read_bytes()==before
|
||||||
|
if proof_case=='fresh':
|
||||||
|
assert result.status=='UPLOADED' and result.safe_to_continue
|
||||||
|
assert adapter.calls[0]=='remove' and adapter.calls[1][0]=='add'
|
||||||
|
else:
|
||||||
|
assert result.status=='BLOCKED' and adapter.calls==[]
|
||||||
|
|
||||||
|
|
||||||
|
def test_old_request_without_current_confirmation_remains_blocked(setup,monkeypatch):
|
||||||
|
request,adapter,source=setup
|
||||||
|
old=request.evidence_dir/'old';old.mkdir(parents=True)
|
||||||
|
(old/'checkpoint.json').write_text(json.dumps({'library':str(request.library),'name':'Block',
|
||||||
|
'stage':'complete','status':'RECOVERY_REQUIRED','safe_to_continue':True,'history':[{'stage':'native_add'}]}))
|
||||||
|
result=execute(replace(request,operation='update',source=source,auto_verify=False),adapter)
|
||||||
|
assert result.status=='BLOCKED' and adapter.calls==[]
|
||||||
|
|
||||||
|
|
||||||
|
def test_ui_adds_fresh_recheck_only_after_current_yes(qtbot,tmp_path,monkeypatch):
|
||||||
|
from PySide6.QtWidgets import QMessageBox
|
||||||
|
from cbb_refresh_verify.management import ManagementRequest,ManagementResult
|
||||||
|
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
|
||||||
|
from cbb_refresh_verify.ui import timed_prompt
|
||||||
|
request=ManagementRequest('remove',tmp_path/'lib.lmc','Block')
|
||||||
|
captured=[]
|
||||||
|
def runner(requests,**kw):
|
||||||
|
captured.extend(requests)
|
||||||
|
return [ManagementResult('remove',request.library,'Block','Logical-Physical',None,False,'complete','REMOVED',True)]
|
||||||
|
dialog=ManagementDialog([request],runner=runner);qtbot.addWidget(dialog);dialog.show()
|
||||||
|
answer=[QMessageBox.No]
|
||||||
|
monkeypatch.setattr(timed_prompt,'question',lambda *a,**k:answer[0])
|
||||||
|
dialog._execute();assert not captured and not dialog.requests()[0].check_previous_release
|
||||||
|
answer[0]=QMessageBox.Yes;dialog._execute()
|
||||||
|
qtbot.waitUntil(lambda:not dialog.busy)
|
||||||
|
assert len(captured)==1 and captured[0].check_previous_release
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
"""Large advancing manifests stay usable; a stalled member still hands off."""
|
||||||
|
from threading import Event
|
||||||
|
import time
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from cbb_refresh_verify.operation_queue import BatchTaskContext, TaskHandoff, check_active
|
||||||
|
from cbb_refresh_verify.scoped_manifest import build_manifest, hash_file
|
||||||
|
|
||||||
|
|
||||||
|
def test_advancing_manifest_outlives_aggregate_metadata_deadline(tmp_path, monkeypatch):
|
||||||
|
for i in range(768):
|
||||||
|
(tmp_path/f'part-{i:04}.dat').write_bytes(str(i).encode())
|
||||||
|
clock, offset = time.monotonic, [0]
|
||||||
|
monkeypatch.setattr(time, 'monotonic', lambda:clock()+offset[0])
|
||||||
|
def progress(event):
|
||||||
|
if event['hashed_files']:
|
||||||
|
offset[0] += 8
|
||||||
|
time.sleep(.06) # Let the actual context waiter observe each advancing batch.
|
||||||
|
context = BatchTaskContext(str(tmp_path/'library.lmc'), native_policy='external')
|
||||||
|
try:
|
||||||
|
result = context.run(lambda:build_manifest(tmp_path, progress=progress), timeout_seconds=10)
|
||||||
|
assert len(result['files']) == 768
|
||||||
|
assert offset[0] == 24
|
||||||
|
finally:
|
||||||
|
context.close(timeout_seconds=2)
|
||||||
|
|
||||||
|
|
||||||
|
def test_stalled_manifest_member_cannot_resume_into_native_write(tmp_path):
|
||||||
|
(tmp_path/'one.dat').write_bytes(b'content')
|
||||||
|
entered, release = Event(), Event()
|
||||||
|
writes = []
|
||||||
|
def stalled(path):
|
||||||
|
entered.set()
|
||||||
|
assert release.wait(3)
|
||||||
|
return hash_file(path)
|
||||||
|
def action():
|
||||||
|
build_manifest(tmp_path, hash_function=stalled)
|
||||||
|
check_active()
|
||||||
|
writes.append('native')
|
||||||
|
context = BatchTaskContext(str(tmp_path/'library.lmc'), native_policy='external')
|
||||||
|
try:
|
||||||
|
with pytest.raises(TaskHandoff):
|
||||||
|
context.run(action, timeout_seconds=.1)
|
||||||
|
assert entered.is_set()
|
||||||
|
release.set()
|
||||||
|
context.close(timeout_seconds=2)
|
||||||
|
assert writes == []
|
||||||
|
finally:
|
||||||
|
release.set()
|
||||||
|
|
||||||
|
|
||||||
|
def test_manifest_progress_does_not_interrupt_admitted_native_continuation(tmp_path):
|
||||||
|
from cbb_refresh_verify.operation_queue import native_phase
|
||||||
|
(tmp_path/'one.dat').write_bytes(b'content')
|
||||||
|
context = BatchTaskContext(str(tmp_path/'library.lmc'))
|
||||||
|
effects = []
|
||||||
|
def transaction():
|
||||||
|
with native_phase():
|
||||||
|
effects.append('Remove')
|
||||||
|
context.cancel()
|
||||||
|
assert len(build_manifest(tmp_path)['files']) == 1
|
||||||
|
effects.append('Add')
|
||||||
|
context.run(transaction)
|
||||||
|
assert effects == ['Remove', 'Add']
|
||||||
|
|
||||||
|
|
||||||
|
def test_completed_release_and_idle_checks_outlive_aggregate_deadline(tmp_path, monkeypatch):
|
||||||
|
from cbb_refresh_verify import library_lock, owner_probe
|
||||||
|
from cbb_refresh_verify.backup_recovery import _idle_check
|
||||||
|
library = tmp_path/'library.lmc'; library.touch()
|
||||||
|
clock, offset = time.monotonic, [0]
|
||||||
|
monkeypatch.setattr(time, 'monotonic', lambda:clock()+offset[0])
|
||||||
|
def released(*args, **kwargs):
|
||||||
|
offset[0] += 7
|
||||||
|
return {'status': 'RELEASE_CONFIRMED'}
|
||||||
|
def owners(names):
|
||||||
|
offset[0] += 4
|
||||||
|
time.sleep(.06)
|
||||||
|
return []
|
||||||
|
monkeypatch.setattr(library_lock, 'release_retained_library', released)
|
||||||
|
monkeypatch.setattr(owner_probe, 'query_owners', owners)
|
||||||
|
context = BatchTaskContext(str(library), native_policy='external')
|
||||||
|
def prepare():
|
||||||
|
library_lock.recheck_previous_release(library, tmp_path/'evidence', required=True)
|
||||||
|
for name in ('target', 'source'):
|
||||||
|
_idle_check(library, tmp_path/name/'main.prj', tmp_path/name/'PCB/main.pcb')
|
||||||
|
check_active()
|
||||||
|
return 'ready for native dispatch'
|
||||||
|
try:
|
||||||
|
assert context.run(prepare, timeout_seconds=10) == 'ready for native dispatch'
|
||||||
|
assert offset[0] == 15
|
||||||
|
finally:
|
||||||
|
context.close(timeout_seconds=2)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('cancel', [False, True])
|
||||||
|
def test_completed_idle_check_cannot_revive_stalled_or_cancelled_work(tmp_path, monkeypatch, cancel):
|
||||||
|
from cbb_refresh_verify import owner_probe
|
||||||
|
from cbb_refresh_verify.backup_recovery import _idle_check
|
||||||
|
from cbb_refresh_verify.operation_queue import QueueCancelled
|
||||||
|
library = tmp_path/'library.lmc'; library.touch()
|
||||||
|
release = Event(); writes = []
|
||||||
|
context = BatchTaskContext(str(library), native_policy='external')
|
||||||
|
def owners(names):
|
||||||
|
if cancel: context.cancel()
|
||||||
|
else: assert release.wait(3)
|
||||||
|
return []
|
||||||
|
monkeypatch.setattr(owner_probe, 'query_owners', owners)
|
||||||
|
def prepare():
|
||||||
|
_idle_check(library, tmp_path/'main.prj', tmp_path/'PCB/main.pcb')
|
||||||
|
writes.append('dispatch')
|
||||||
|
try:
|
||||||
|
with pytest.raises(QueueCancelled):
|
||||||
|
context.run(prepare, timeout_seconds=.1)
|
||||||
|
release.set(); context.close(timeout_seconds=2)
|
||||||
|
assert writes == []
|
||||||
|
finally:
|
||||||
|
release.set()
|
||||||
|
|
||||||
|
|
||||||
|
def test_successful_idle_check_does_not_abort_admitted_native_continuation(tmp_path, monkeypatch):
|
||||||
|
from cbb_refresh_verify import owner_probe
|
||||||
|
from cbb_refresh_verify.backup_recovery import _idle_check
|
||||||
|
from cbb_refresh_verify.operation_queue import native_phase
|
||||||
|
library = tmp_path/'library.lmc'; library.touch()
|
||||||
|
monkeypatch.setattr(owner_probe, 'query_owners', lambda names: [])
|
||||||
|
context = BatchTaskContext(str(library)); writes = []
|
||||||
|
def transaction():
|
||||||
|
with native_phase():
|
||||||
|
writes.append('Remove'); context.cancel()
|
||||||
|
_idle_check(library, tmp_path/'main.prj', tmp_path/'PCB/main.pcb')
|
||||||
|
writes.append('Add')
|
||||||
|
context.run(transaction)
|
||||||
|
assert writes == ['Remove', 'Add']
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
from threading import Event
|
||||||
|
import pytest
|
||||||
|
from cbb_refresh_verify.operation_queue import BatchTaskContext, TaskHandoff, native_phase
|
||||||
|
|
||||||
|
|
||||||
|
def test_metadata_can_refresh_while_abandoned_native_scope_stays_protected():
|
||||||
|
entered, release = Event(), Event()
|
||||||
|
old = BatchTaskContext('a.lmc')
|
||||||
|
def stalled():
|
||||||
|
entered.set(); release.wait(3)
|
||||||
|
try:
|
||||||
|
with pytest.raises(TaskHandoff): old.run(stalled, timeout_seconds=.01)
|
||||||
|
assert entered.is_set()
|
||||||
|
new = BatchTaskContext('a.lmc')
|
||||||
|
assert new.run(lambda: 'metadata', metadata_only=True) == 'metadata'
|
||||||
|
with pytest.raises(TaskHandoff): new.run(lambda: 'native')
|
||||||
|
finally:
|
||||||
|
release.set(); old.close(timeout_seconds=1)
|
||||||
|
|
||||||
|
|
||||||
|
def test_metadata_cannot_escalate_into_native_phase():
|
||||||
|
context = BatchTaskContext('a.lmc')
|
||||||
|
def escalate():
|
||||||
|
with native_phase():
|
||||||
|
pytest.fail('metadata admitted native action')
|
||||||
|
with pytest.raises(RuntimeError, match='metadata'):
|
||||||
|
context.run(escalate, metadata_only=True)
|
||||||
|
|
||||||
|
|
||||||
|
def test_abandoned_metadata_does_not_block_next_native_admission():
|
||||||
|
release = Event()
|
||||||
|
old = BatchTaskContext('a.lmc')
|
||||||
|
try:
|
||||||
|
with pytest.raises(TaskHandoff):
|
||||||
|
old.run(lambda: release.wait(3), timeout_seconds=.01, metadata_only=True)
|
||||||
|
assert BatchTaskContext('a.lmc').run(lambda: 'admitted') == 'admitted'
|
||||||
|
finally:
|
||||||
|
release.set(); old.close(timeout_seconds=1)
|
||||||
@@ -0,0 +1,407 @@
|
|||||||
|
"""Issue 15 recovery entry regressions. Native boundaries never launch Mentor."""
|
||||||
|
from contextlib import contextmanager
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def no_real_owner_probe(monkeypatch):
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda names: [])
|
||||||
|
|
||||||
|
|
||||||
|
def test_ordinary_worker_aligns_both_bound_projects_and_retains_each_original(tmp_path, monkeypatch):
|
||||||
|
from test_verify_worker_stability import exercise_worker
|
||||||
|
from cbb_refresh_verify import mentor_adapter as adapter
|
||||||
|
job, events, execute = exercise_worker(tmp_path, monkeypatch)
|
||||||
|
main = Path(job['project']); aux = Path(job['pcb']).parent/'pcb.prj'
|
||||||
|
original_main = b'KEY CentralLibrary "old-main.lmc"\r\n#\x81\x40\r\n'
|
||||||
|
original_aux = b'\xff\xfe'+ 'KEY CentralLibrary "old-pcb.lmc"\r\n'.encode('utf-16-le')
|
||||||
|
main.write_bytes(original_main); aux.write_bytes(original_aux)
|
||||||
|
assert execute()['status'] == 'PASS'
|
||||||
|
from cbb_refresh_verify.backup_recovery import _project_text
|
||||||
|
for path in (main, aux):
|
||||||
|
import re
|
||||||
|
reference = re.search(r'KEY CentralLibrary "([^"]+)"', _project_text(path))[1]
|
||||||
|
assert (path.parent/reference).resolve() == Path(job['lmc_file']).resolve()
|
||||||
|
saved = [p.read_bytes() for p in (Path(job['root'])/'diagnostics').rglob('*.before-central-library')]
|
||||||
|
assert original_main in saved and original_aux in saved
|
||||||
|
|
||||||
|
|
||||||
|
def test_ordinary_legacy_binding_never_rewrites_template(tmp_path, monkeypatch):
|
||||||
|
from test_verify_worker_stability import exercise_worker
|
||||||
|
job, _, execute = exercise_worker(tmp_path, monkeypatch)
|
||||||
|
main = Path(job['project']); pcb = Path(job['pcb'])
|
||||||
|
main.write_text('KEY CentralLibrary "old.lmc"\n')
|
||||||
|
pcb.write_text('KEY ProjectFile "../CBB.prj"\n')
|
||||||
|
template = pcb.parent/'template.prj'; template.write_text('KEY CentralLibrary "do-not-touch.lmc"\n')
|
||||||
|
original = template.read_bytes()
|
||||||
|
assert execute()['status'] == 'PASS'
|
||||||
|
assert template.read_bytes() == original
|
||||||
|
assert 'old.lmc' not in main.read_text()
|
||||||
|
|
||||||
|
|
||||||
|
def inconsistency(database):
|
||||||
|
return (f'Project database [{database}] is inconsistent. It has been manually copied while the iCDB Server was running. '
|
||||||
|
"Please use iCDB Project Backup 'Repair project' functionality to fix this issue.")
|
||||||
|
|
||||||
|
|
||||||
|
def test_current_inconsistency_has_structured_database_and_old_error_is_not_reused(tmp_path):
|
||||||
|
from cbb_refresh_verify import icdb_recovery as recovery, mentor_adapter as adapter
|
||||||
|
source = tmp_path/'LogFiles/PCBLogFile.txt'; source.parent.mkdir()
|
||||||
|
db = tmp_path/'database'; message = inconsistency(db)
|
||||||
|
source.write_text(message+'\n')
|
||||||
|
baseline = recovery.snapshot_log(source)
|
||||||
|
assert recovery.read_log_failure(source, baseline)[1] is None
|
||||||
|
source.write_text('new header\n'+message+'\n')
|
||||||
|
assert recovery.read_log_failure(source, baseline)[1] is None
|
||||||
|
baseline = recovery.snapshot_log(source)
|
||||||
|
with source.open('a') as stream: stream.write(message+'\n')
|
||||||
|
text, record = recovery.read_log_failure(source, baseline)
|
||||||
|
assert record['database_path'] == str(db) and record['scope'] == 'project'
|
||||||
|
assert record['kind'] == 'database_inconsistent'
|
||||||
|
detail = adapter.pcb_log_reports_missing_server(tmp_path/'CBB.pcb', offset=baseline)
|
||||||
|
assert 'ICDB_REPAIR_REQUIRED' in detail and str(db) in detail and '未修复' in detail
|
||||||
|
|
||||||
|
|
||||||
|
def test_manual_repair_selects_diagnosed_bound_database_without_layout_or_healthy_header(tmp_path):
|
||||||
|
from test_native_backup import project_fixture
|
||||||
|
from cbb_refresh_verify import native_backup as native
|
||||||
|
request, main = project_fixture(tmp_path)
|
||||||
|
pcb = main.parent/'PCB/Block.pcb'; pcb.parent.mkdir()
|
||||||
|
pcb.write_text('KEY ProjectFile "../Block.prj"\n')
|
||||||
|
aux = pcb.parent/'pcb.prj'; aux.write_text('KEY iCDBDir "database"\n')
|
||||||
|
for prj in (main, aux):
|
||||||
|
(prj.parent/'database').mkdir(); (prj.parent/'database/icdb.dat').write_bytes(b'not-a-healthy-header')
|
||||||
|
assert native.native_backup_target(request, mode='repair')[0] == main
|
||||||
|
assert native.native_backup_target(request, mode='repair', target_database=aux.parent/'database')[0] == aux
|
||||||
|
with pytest.raises(ValueError, match='TARGET'):
|
||||||
|
native.native_backup_target(request, mode='repair', target_database=tmp_path/'foreign')
|
||||||
|
|
||||||
|
|
||||||
|
def test_versions_launcher_rechecks_parent_retained_lease_and_persists_before_gate(tmp_path, monkeypatch):
|
||||||
|
import subprocess, sys
|
||||||
|
from test_native_backup import project_fixture
|
||||||
|
from cbb_refresh_verify import native_backup as native, library_lock, session_record
|
||||||
|
request, project = project_fixture(tmp_path)
|
||||||
|
monkeypatch.setattr(native, 'native_backup_executable', lambda *_: tmp_path/'native.exe')
|
||||||
|
calls = []
|
||||||
|
monkeypatch.setattr(library_lock, 'recheck_previous_release', lambda *a, **k: calls.append('recheck'))
|
||||||
|
monkeypatch.setattr(session_record, 'process_identity', lambda pid: dict(pid=pid, created='now', executable='python', owner='test'))
|
||||||
|
child = subprocess.Popen([sys.executable,'-c','input()'],stdin=subprocess.PIPE,text=True)
|
||||||
|
def spawn(command, **kw):
|
||||||
|
job = json.loads(Path(command[-1]).read_text())
|
||||||
|
assert calls == ['recheck'] and not Path(job['start_gate']).exists()
|
||||||
|
calls.append('spawn')
|
||||||
|
return child
|
||||||
|
monkeypatch.setattr(native.subprocess, 'Popen', spawn)
|
||||||
|
try:
|
||||||
|
session = native.launch_native_backup(request, mode='repair')
|
||||||
|
finally:
|
||||||
|
child.communicate('\n',timeout=5)
|
||||||
|
record = json.loads(session.job.read_text())
|
||||||
|
assert Path(record['start_gate']).is_file()
|
||||||
|
assert Path(record['session_record_path']).is_file()
|
||||||
|
assert session.mode == 'repair' and session.database == project.parent/'database'
|
||||||
|
assert session.operation_id == record['operation_id']
|
||||||
|
assert record['automatic_repair'] is False
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('failure', ['spawn', 'registration'])
|
||||||
|
def test_backup_failure_leaves_start_gate_closed(tmp_path, monkeypatch, failure):
|
||||||
|
from test_native_backup import project_fixture
|
||||||
|
from cbb_refresh_verify import native_backup as native, session_record
|
||||||
|
request, _ = project_fixture(tmp_path)
|
||||||
|
monkeypatch.setattr(native, 'native_backup_executable', lambda *_: tmp_path/'native.exe')
|
||||||
|
def spawn(*a, **k):
|
||||||
|
if failure == 'spawn': raise OSError('start failed')
|
||||||
|
return SimpleNamespace(pid=123, poll=lambda: None)
|
||||||
|
monkeypatch.setattr(native.subprocess, 'Popen', spawn)
|
||||||
|
monkeypatch.setattr(session_record, 'register_worker_session', lambda *a: (_ for _ in ()).throw(OSError('register failed')))
|
||||||
|
with pytest.raises(OSError): native.launch_native_backup(request)
|
||||||
|
job = next(request.evidence_dir.glob('native-backup-*/request.json'))
|
||||||
|
record = json.loads(job.read_text())
|
||||||
|
assert not Path(record['start_gate']).exists()
|
||||||
|
assert Path(record['cancel_signal']).exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_changed_prj_bytes_refused_before_recovery_tool_dispatch(tmp_path, monkeypatch):
|
||||||
|
import hashlib
|
||||||
|
from test_native_backup import project_fixture
|
||||||
|
from cbb_refresh_verify import native_backup as native
|
||||||
|
request, project = project_fixture(tmp_path)
|
||||||
|
job = tmp_path/'request.json'
|
||||||
|
record = dict(library=str(request.lmc_file), block=request.block_name, project=str(project),
|
||||||
|
project_sha256=hashlib.sha256(project.read_bytes()).hexdigest())
|
||||||
|
job.write_text(json.dumps(record))
|
||||||
|
project.write_text(project.read_text()+'# changed identity\n')
|
||||||
|
monkeypatch.setattr(native, 'native_backup_executable', lambda *_: tmp_path/'native.exe')
|
||||||
|
assert native.native_backup_worker_main(job, process_factory=lambda *a: pytest.fail('changed PRJ dispatched')) == 1
|
||||||
|
assert '身份' in json.loads(job.with_name('result.json').read_text('utf-8'))['detail']
|
||||||
|
|
||||||
|
|
||||||
|
def test_real_parent_retained_sidecar_is_reconciled_before_child_acquires_it_and_reopens(tmp_path, monkeypatch):
|
||||||
|
import subprocess, sys
|
||||||
|
from test_native_backup import project_fixture
|
||||||
|
from cbb_refresh_verify import native_backup as native, library_lock as locks
|
||||||
|
from cbb_refresh_verify.file_probe import hold_release_files
|
||||||
|
request, _ = project_fixture(tmp_path)
|
||||||
|
with locks.LibraryLock(request.lmc_file, safe_to_release=lambda: False, block_name='Block') as retained:
|
||||||
|
pass
|
||||||
|
@contextmanager
|
||||||
|
def proof(library, **kwargs):
|
||||||
|
with hold_release_files(library, (library.parent/'ReusableBlocksLP/Block/Work',)) as files:
|
||||||
|
yield {**files, 'native_owners': []}
|
||||||
|
monkeypatch.setattr(locks, '_prove_library_released', proof)
|
||||||
|
monkeypatch.setattr(native, 'native_backup_executable', lambda *_: tmp_path/'not-launched.exe')
|
||||||
|
popen = subprocess.Popen
|
||||||
|
script = (
|
||||||
|
'import json,sys\nfrom pathlib import Path\n'
|
||||||
|
'from cbb_refresh_verify.desktop_worker import run_native_worker\n'
|
||||||
|
'from cbb_refresh_verify.library_lock import LibraryLock\n'
|
||||||
|
'def action(path):\n'
|
||||||
|
' j=json.loads(Path(path).read_text())\n'
|
||||||
|
' with LibraryLock(j["library"],checkpoint=False):\n'
|
||||||
|
' Path(path).with_name("child-acquired").write_text("owned")\n'
|
||||||
|
' return 0\n'
|
||||||
|
'raise SystemExit(run_native_worker(action,sys.argv[1]))\n')
|
||||||
|
def spawn(command, **kwargs):
|
||||||
|
if '--native-backup-worker' in command:
|
||||||
|
assert not locks.has_retained_library(request.lmc_file)
|
||||||
|
return popen([sys.executable, '-c', script, command[-1]], **kwargs)
|
||||||
|
return popen(command, **kwargs)
|
||||||
|
monkeypatch.setattr(native.subprocess, 'Popen', spawn)
|
||||||
|
try:
|
||||||
|
for mode in ('versions', 'repair'):
|
||||||
|
session = native.launch_native_backup(request, mode=mode)
|
||||||
|
assert session.process.wait(10) == 0
|
||||||
|
assert session.job.with_name('child-acquired').read_text() == 'owned'
|
||||||
|
assert retained.path.is_file()
|
||||||
|
finally:
|
||||||
|
owner = locks._owners.pop(retained.key, None)
|
||||||
|
if owner: owner['handle'].Close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_native_registration_failure_never_resumes_suspended_child(tmp_path):
|
||||||
|
import sys
|
||||||
|
from cbb_refresh_verify.native_backup import _NativeBackupProcess
|
||||||
|
marker = tmp_path/'must-not-run'
|
||||||
|
def refuse(process): raise OSError('required identity journal failed')
|
||||||
|
with pytest.raises(OSError, match='journal'):
|
||||||
|
_NativeBackupProcess([sys.executable, '-c', f'from pathlib import Path;Path({str(marker)!r}).touch()'],
|
||||||
|
tmp_path, before_resume=refuse)
|
||||||
|
assert not marker.exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_independent_backup_job_registration_retains_descendants_after_caller_handles_close(tmp_path):
|
||||||
|
import sys, time
|
||||||
|
from cbb_refresh_verify.native_backup import _NativeBackupProcess, _BackupJobWriter
|
||||||
|
script = tmp_path/'parent.py'; marker = tmp_path/'child.pid'
|
||||||
|
script.write_text('import subprocess,sys,time\nfrom pathlib import Path\n'
|
||||||
|
'p=subprocess.Popen([sys.executable,"-c","import time;time.sleep(1)"])\n'
|
||||||
|
f'Path({str(marker)!r}).write_text(str(p.pid))\ntime.sleep(.1)\n')
|
||||||
|
process = _NativeBackupProcess([sys.executable, str(script)], tmp_path)
|
||||||
|
registered = _BackupJobWriter(process.job)
|
||||||
|
try:
|
||||||
|
deadline = time.monotonic()+5
|
||||||
|
while process.poll() is None and time.monotonic()<deadline: time.sleep(.02)
|
||||||
|
assert marker.exists() and process.poll() == 0
|
||||||
|
process.close()
|
||||||
|
assert registered.poll() is None
|
||||||
|
while registered.poll() is None and time.monotonic()<deadline: time.sleep(.02)
|
||||||
|
assert registered.poll() == 0
|
||||||
|
finally:
|
||||||
|
if registered.job is not None: registered.job.Close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_common_admission_refusal_publishes_bound_receipt_and_ui_can_reopen(qtbot, tmp_path, monkeypatch):
|
||||||
|
import subprocess,sys
|
||||||
|
from threading import Event, Thread
|
||||||
|
from test_native_backup import project_fixture
|
||||||
|
from test_ui_filters import load_window
|
||||||
|
from cbb_refresh_verify import native_backup as native, desktop_worker
|
||||||
|
request, _ = project_fixture(tmp_path)
|
||||||
|
monkeypatch.setattr(native, 'native_backup_executable', lambda *_: tmp_path/'native.exe')
|
||||||
|
# A cold observer reads kernel identity: poll=exited on pytest's live PID
|
||||||
|
# cannot represent a released worker. Use a real, harmless refused child.
|
||||||
|
invoke = tmp_path/'invoke-refusal.signal'
|
||||||
|
child = tmp_path/'refused_worker.py'
|
||||||
|
child.write_text('import sys,time\nfrom pathlib import Path\n'
|
||||||
|
f'gate=Path({str(invoke)!r})\ndeadline=time.monotonic()+10\n'
|
||||||
|
'while not gate.exists() and time.monotonic()<deadline:time.sleep(.01)\n'
|
||||||
|
'assert gate.exists()\n'
|
||||||
|
'from cbb_refresh_verify import native_backup\n'
|
||||||
|
'def forbidden(*args):raise AssertionError("refused action entered")\n'
|
||||||
|
'native_backup.native_backup_worker_main=forbidden\n'
|
||||||
|
'from cbb_refresh_verify.application import main\n'
|
||||||
|
'raise SystemExit(main(["--native-backup-worker",sys.argv[1]]))\n')
|
||||||
|
popen = subprocess.Popen
|
||||||
|
with monkeypatch.context() as launch:
|
||||||
|
launch.setattr(native.subprocess, 'Popen', lambda command, **kwargs:
|
||||||
|
popen([sys.executable,str(child),command[-1]], **kwargs))
|
||||||
|
session = native.launch_native_backup(request)
|
||||||
|
entered, release = Event(), Event()
|
||||||
|
monkeypatch.setattr(desktop_worker, '_automation_clients', [])
|
||||||
|
def held_writer():
|
||||||
|
with desktop_worker.worker_native_channel():
|
||||||
|
entered.set(); release.wait(10)
|
||||||
|
holder = Thread(target=held_writer); holder.start()
|
||||||
|
assert entered.wait(2)
|
||||||
|
try:
|
||||||
|
invoke.touch()
|
||||||
|
assert session.process.wait(timeout=8) == 1
|
||||||
|
finally:
|
||||||
|
release.set(); holder.join(3)
|
||||||
|
record = json.loads(session.job.with_name('result.json').read_text('utf-8'))
|
||||||
|
assert record['safe_to_continue'] is True and record['native_started'] is False
|
||||||
|
assert record['operation_id'] == json.loads(session.job.read_text('utf-8'))['operation_id']
|
||||||
|
assert record['worker_identity']['pid'] == session.process.pid != os.getpid()
|
||||||
|
launched = []
|
||||||
|
window = load_window(qtbot, tmp_path, monkeypatch,
|
||||||
|
native_backup_launcher=lambda req: (launched.append(req) or session),
|
||||||
|
status_refresher=lambda names, _: {name:'UNKNOWN' for name in names})
|
||||||
|
# Deliver the receipt to its actual library view; a foreign view must not
|
||||||
|
# receive an old session's status label after Task 4's callback isolation.
|
||||||
|
window.path_lease_factory = lambda path: SimpleNamespace(mentor_path=path, display_path=path,
|
||||||
|
drive='', remote_root='', close=lambda:None, retain_for_recovery=lambda:None)
|
||||||
|
window.lmc_edit.setText(str(session.library)); window.load_library()
|
||||||
|
qtbot.waitUntil(lambda:not window.busy)
|
||||||
|
session.block = 'Beta'; record['block'] = 'Beta'
|
||||||
|
session.job.with_name('result.json').write_text(json.dumps(record), encoding='utf-8')
|
||||||
|
window._native_backup_session = session
|
||||||
|
window._poll_native_backup(); qtbot.waitUntil(lambda: not window.busy)
|
||||||
|
assert window._native_backup_session is None
|
||||||
|
assert 'NATIVE_WRITER_ACTIVE' in window.status_label.text()
|
||||||
|
window.search_edit.setText('Beta'); window.select_visible_button.click()
|
||||||
|
window.open_native_backup(); qtbot.waitUntil(lambda: not window.busy)
|
||||||
|
assert len(launched) == 1
|
||||||
|
window._native_backup_session = None # The test adapter has no live native client.
|
||||||
|
|
||||||
|
|
||||||
|
def test_unbound_admission_refusal_cannot_claim_release(tmp_path, monkeypatch):
|
||||||
|
from cbb_refresh_verify import native_backup as native, desktop_worker
|
||||||
|
job = tmp_path/'request.json'
|
||||||
|
job.write_text(json.dumps(dict(library=str(tmp_path/'lib.lmc'), block='A', operation_id='foreign',
|
||||||
|
session_record_path=str(tmp_path/'session.json'), project=str(tmp_path/'A.prj'))))
|
||||||
|
monkeypatch.setattr(desktop_worker, 'run_native_worker', lambda *a, admission_state=None: (_ for _ in ()).throw(RuntimeError('refused')))
|
||||||
|
assert native.run_native_backup_worker(job) == 1
|
||||||
|
result = json.loads(job.with_name('result.json').read_text('utf-8'))
|
||||||
|
assert result['safe_to_continue'] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_legacy_unregistered_backup_job_cannot_enter_native_action(tmp_path, monkeypatch):
|
||||||
|
from cbb_refresh_verify import native_backup as native, desktop_worker
|
||||||
|
job = tmp_path/'request.json'
|
||||||
|
job.write_text(json.dumps(dict(library=str(tmp_path/'lib.lmc'), block='A', project=str(tmp_path/'A.prj'))))
|
||||||
|
monkeypatch.setattr(desktop_worker, '_automation_clients', [])
|
||||||
|
monkeypatch.setattr(native, 'native_backup_worker_main', lambda *a: pytest.fail('unregistered action entered'))
|
||||||
|
assert native.run_native_backup_worker(job) == 1
|
||||||
|
assert json.loads(job.with_name('result.json').read_text('utf-8'))['safe_to_continue'] is False
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('owner_scope', ['target', 'unrelated'])
|
||||||
|
def test_recovery_entry_scopes_external_ownership_before_launch(tmp_path, monkeypatch, owner_scope):
|
||||||
|
from test_native_backup import project_fixture
|
||||||
|
from cbb_refresh_verify import native_backup as native, owner_probe
|
||||||
|
request, project = project_fixture(tmp_path)
|
||||||
|
job = tmp_path/'request.json'
|
||||||
|
job.write_text(json.dumps(dict(library=str(request.lmc_file), block=request.block_name,
|
||||||
|
project=str(project), mode='repair')))
|
||||||
|
monkeypatch.setattr(native, 'native_backup_executable', lambda *_: tmp_path/'native.exe')
|
||||||
|
external = project if owner_scope == 'target' else tmp_path/'other/Work/other.prj'
|
||||||
|
monkeypatch.setattr(owner_probe, 'query_owners', lambda names: [dict(pid=99999,
|
||||||
|
name='ExpeditionPCB.exe', command=f'ExpeditionPCB.exe "{external}"', executable='ExpeditionPCB.exe')])
|
||||||
|
def process(*args):
|
||||||
|
if owner_scope == 'target': pytest.fail('external target owner bypassed')
|
||||||
|
return SimpleNamespace(pid=456, poll=lambda: 0, session_pids=lambda: [], close=lambda: None)
|
||||||
|
assert native.native_backup_worker_main(job, process_factory=process) == (1 if owner_scope == 'target' else 0)
|
||||||
|
result = json.loads(job.with_name('result.json').read_text('utf-8'))
|
||||||
|
assert result['safe_to_continue'] is True
|
||||||
|
if owner_scope == 'target': assert 'OWNER_ACTIVE' in result['detail']
|
||||||
|
else: assert result['status'] == 'CLOSED'
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('user_timeout', [5, 600])
|
||||||
|
def test_lm_menu_return_without_pcb_uses_dispatch_budget_and_closes_lm(tmp_path, monkeypatch, user_timeout):
|
||||||
|
from test_verify_worker_stability import exercise_worker
|
||||||
|
from cbb_refresh_verify import mentor_adapter as adapter, library_manager_verify as lm
|
||||||
|
job, events, execute = exercise_worker(tmp_path, monkeypatch)
|
||||||
|
job['native_lm_verify'] = True; job['timeout'] = user_timeout
|
||||||
|
(Path(job['pcb']).parent/'pcb.prj').write_text('KEY CentralLibrary "old.lmc"\n')
|
||||||
|
clock = [0.0]; closed = []
|
||||||
|
monkeypatch.setattr(adapter.time, 'monotonic', lambda: clock[0])
|
||||||
|
monkeypatch.setattr(adapter.time, 'sleep', lambda seconds: clock.__setitem__(0, clock[0]+seconds))
|
||||||
|
monkeypatch.setattr(adapter, 'select_reusable_circuit_worker', lambda *a, **k: None)
|
||||||
|
def launch(*args, **kw):
|
||||||
|
assert args[3] <= min(45, user_timeout)
|
||||||
|
return SimpleNamespace(process=SimpleNamespace(pid=123), close=lambda: closed.append(True))
|
||||||
|
monkeypatch.setattr(lm, 'launch_library_verify', launch)
|
||||||
|
with pytest.raises(RuntimeError, match='VERIFY_DISPATCH_FAILED'): execute()
|
||||||
|
assert clock[0] <= min(45, user_timeout)+1 and closed == [True]
|
||||||
|
|
||||||
|
|
||||||
|
def test_inconsistency_preserves_shared_database_scope():
|
||||||
|
from cbb_refresh_verify.icdb_recovery import parse_recovery_request
|
||||||
|
database = r'C:\\library\\SymbolLibs\\__ReusableBlocksSymb'
|
||||||
|
assert parse_recovery_request(inconsistency(database))['scope'] == 'central_library'
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('case', ['not_in_use', 'repair_required', 'in_use', 'unconfirmed', 'wrong_target',
|
||||||
|
'no_identity', 'changed_address', 'changed_project', 'shared_address', 'exclusive'])
|
||||||
|
def test_explicit_continue_requires_exact_fresh_native_and_exclusive_proof(tmp_path, monkeypatch, case):
|
||||||
|
from test_native_repair import target_fixture
|
||||||
|
from test_native_occupancy import output
|
||||||
|
from cbb_refresh_verify import pcb_open_consent as consent, native_repair, owner_probe, session_record
|
||||||
|
from cbb_refresh_verify.verify_runner import preflight
|
||||||
|
request, _, target = target_fixture(tmp_path)
|
||||||
|
request.evidence_dir.mkdir()
|
||||||
|
project, pcb = preflight(request)
|
||||||
|
project.write_text('KEY PCBDesignPath "PCB/actual.pcb"\nKEY iCDBDir "database"\n')
|
||||||
|
pcb.write_text('KEY ProjectFile "../'+project.name+'"\n')
|
||||||
|
address = target.database/'cdbsvr/sAddress.adr'; address.parent.mkdir(); address.write_bytes(b'unchanged address')
|
||||||
|
if case == 'shared_address':
|
||||||
|
shared = request.lmc_file.parent/'SymbolLibs/__ReusableBlocksSymb/cdbsvr/sAddress.adr'
|
||||||
|
shared.parent.mkdir(parents=True); shared.write_bytes(b'unknown shared owner')
|
||||||
|
monkeypatch.setattr(owner_probe, 'query_process_snapshot', lambda: [])
|
||||||
|
calls = []
|
||||||
|
def inspect(inspected, root, **kwargs):
|
||||||
|
assert kwargs['inspection_only'] is True
|
||||||
|
calls.append(inspected)
|
||||||
|
record = dict(status='NOT_IN_USE', project=str(target.project), database=str(target.database),
|
||||||
|
native_pid=os.getpid(), native_identity=session_record.process_identity(os.getpid()),
|
||||||
|
inspection_only=True, repair_requested=False, repair_required=case == 'repair_required',
|
||||||
|
native_exit_code=0, release={'native_exited': True},
|
||||||
|
output=output(target.project, target.database, fault=case == 'repair_required'))
|
||||||
|
if case == 'in_use': record.update(status='IN_USE', output=output(target.project, target.database, busy=True))
|
||||||
|
if case == 'unconfirmed': record.update(status='UNCONFIRMED', output='not known')
|
||||||
|
if case == 'wrong_target': record['database'] = str(tmp_path/'foreign')
|
||||||
|
if case == 'no_identity': record.pop('native_identity')
|
||||||
|
if case == 'changed_address': address.write_bytes(b'new address')
|
||||||
|
if case == 'changed_project': project.write_text('KEY iCDBDir "another-db"\n')
|
||||||
|
return record
|
||||||
|
monkeypatch.setattr(native_repair, 'run_native_repair', inspect)
|
||||||
|
job = dict(root=str(request.evidence_dir), lmc_file=str(request.lmc_file),
|
||||||
|
block_name=request.block_name, project=str(project), pcb=str(pcb), operation_id='current-open')
|
||||||
|
held = None
|
||||||
|
if case == 'exclusive':
|
||||||
|
import win32con, win32file
|
||||||
|
held = win32file.CreateFile(str(target.database/'icdb.dat'), win32con.GENERIC_READ,
|
||||||
|
0, None, win32con.OPEN_EXISTING, 0, None)
|
||||||
|
try:
|
||||||
|
if case in ('not_in_use', 'repair_required'):
|
||||||
|
with consent.resource_guard(job, {os.getpid()}): pass
|
||||||
|
assert calls == [target]
|
||||||
|
evidence = json.loads((request.evidence_dir/'pcb-open-resource-proof.json').read_text())
|
||||||
|
assert evidence['operation_id'] == 'current-open'
|
||||||
|
assert evidence['repair_confirmed'] is False
|
||||||
|
else:
|
||||||
|
with pytest.raises((ValueError, OSError)):
|
||||||
|
with consent.resource_guard(job, {os.getpid()}): pass
|
||||||
|
finally:
|
||||||
|
if held is not None: held.Close()
|
||||||
|
if case not in ('shared_address', 'exclusive'):
|
||||||
|
assert calls == [target]
|
||||||
|
if case != 'changed_address': assert address.read_bytes() == b'unchanged address'
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
"""EE7.9 imports by source PRJ name; reject rename before any native mutation."""
|
||||||
|
from dataclasses import replace
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from cbb_refresh_verify.management import ManagementRequest, run_management
|
||||||
|
from cbb_refresh_verify.native_management import NativeManagementAdapter
|
||||||
|
from test_management import project
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('operation', ['add', 'update'])
|
||||||
|
def test_real_adapter_rejects_mismatched_source_before_native_catalog_or_remove(tmp_path, monkeypatch, operation):
|
||||||
|
library=tmp_path/'library/mentor.lmc';library.parent.mkdir();library.write_bytes(b'unchanged library')
|
||||||
|
target=project(library.parent/'ReusableBlocksLP/Block/Work','Block',b'unchanged target')
|
||||||
|
source=project(tmp_path/'source','Other')
|
||||||
|
adapter=NativeManagementAdapter()
|
||||||
|
monkeypatch.setattr(adapter,'_binary_capability',lambda:'')
|
||||||
|
calls=[]
|
||||||
|
monkeypatch.setattr(adapter,'_worker',lambda *args:calls.append(args) or pytest.fail('native boundary reached'))
|
||||||
|
request=ManagementRequest(operation,library,'Block',source=source,evidence_dir=tmp_path/'evidence')
|
||||||
|
result=run_management(request,adapter=adapter,idle_check=lambda *_:None)
|
||||||
|
assert result.safe_to_continue and 'SOURCE_NAME_MISMATCH' in result.detail
|
||||||
|
assert calls == []
|
||||||
|
assert library.read_bytes()==b'unchanged library'
|
||||||
|
assert (target.parent/'database/icdb.dat').read_bytes()==b'unchanged target'
|
||||||
|
|
||||||
|
|
||||||
|
def test_source_name_check_uses_windows_case_insensitive_identity(tmp_path):
|
||||||
|
source=project(tmp_path/'source','BLOCK')
|
||||||
|
request=ManagementRequest('update',tmp_path/'library.lmc','Block',source=source)
|
||||||
|
NativeManagementAdapter().validate_source(request)
|
||||||
|
|
||||||
|
|
||||||
|
def test_management_preview_reports_mismatch_and_allows_rechoose(qtbot,tmp_path,monkeypatch):
|
||||||
|
from PySide6.QtWidgets import QMessageBox
|
||||||
|
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
|
||||||
|
from cbb_refresh_verify.ui import timed_prompt
|
||||||
|
wrong=project(tmp_path/'wrong','Other');right=project(tmp_path/'right','Block')
|
||||||
|
request=ManagementRequest('update',tmp_path/'library.lmc','Block',source=wrong)
|
||||||
|
dialog=ManagementDialog([request],adapter=NativeManagementAdapter())
|
||||||
|
qtbot.addWidget(dialog);dialog.show()
|
||||||
|
questions=[]
|
||||||
|
monkeypatch.setattr(timed_prompt,'question',lambda *a,**k:questions.append(a) or QMessageBox.No)
|
||||||
|
dialog.execute_button.click()
|
||||||
|
assert 'SOURCE_NAME_MISMATCH' in dialog.status_label.text()
|
||||||
|
assert not questions and dialog.execute_button.isEnabled()
|
||||||
|
dialog.table.item(0,2).setText(str(right))
|
||||||
|
dialog.execute_button.click()
|
||||||
|
assert len(questions)==1 and not dialog.busy
|
||||||
|
|
||||||
|
|
||||||
|
def test_source_name_preview_does_not_resolve_files_on_gui_thread(qtbot,tmp_path,monkeypatch):
|
||||||
|
from pathlib import Path
|
||||||
|
from PySide6.QtWidgets import QMessageBox
|
||||||
|
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
|
||||||
|
from cbb_refresh_verify.ui import timed_prompt
|
||||||
|
source=project(tmp_path/'source','Block')
|
||||||
|
request=ManagementRequest('update',tmp_path/'library.lmc','Block',source=source)
|
||||||
|
dialog=ManagementDialog([request],adapter=NativeManagementAdapter())
|
||||||
|
qtbot.addWidget(dialog);dialog.show()
|
||||||
|
original=Path.resolve
|
||||||
|
def resolve(path,*args,**kw):
|
||||||
|
assert path!=source,'GUI preview touched potentially stalled source metadata'
|
||||||
|
return original(path,*args,**kw)
|
||||||
|
monkeypatch.setattr(Path,'resolve',resolve)
|
||||||
|
questions=[]
|
||||||
|
monkeypatch.setattr(timed_prompt,'question',lambda *a,**k:questions.append(a) or QMessageBox.No)
|
||||||
|
dialog._execute()
|
||||||
|
assert len(questions)==1
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
"""A durable receipt cannot expand the scope of its resource proof."""
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from cbb_refresh_verify import library_lock as locks, residual_sessions, session_record as sessions
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('selected', [('A',), ('A', 'C')])
|
||||||
|
def test_scoped_release_receipt_leaves_unselected_journal_discoverable(tmp_path, monkeypatch, selected):
|
||||||
|
library = tmp_path/'library/lib.lmc'
|
||||||
|
library.parent.mkdir()
|
||||||
|
library.touch()
|
||||||
|
address = library.parent/'ReusableBlocksLP/B/Work/database/cdbsvr/sAddress.adr'
|
||||||
|
address.parent.mkdir(parents=True)
|
||||||
|
address.write_bytes(b'unselected B owner')
|
||||||
|
history = tmp_path/'history'
|
||||||
|
records = []
|
||||||
|
for block in ('A', 'B', 'C'):
|
||||||
|
path = history/block/'session.json'
|
||||||
|
path.parent.mkdir(parents=True)
|
||||||
|
value = dict(operation_id='op-'+block, library=str(library), block=block, processes=[])
|
||||||
|
sessions.write_session_record(path, value)
|
||||||
|
records.append({**value, 'path': str(path)})
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
|
||||||
|
monkeypatch.setattr(residual_sessions, 'query_process_snapshot', lambda: [])
|
||||||
|
monkeypatch.setattr(residual_sessions, '_process_windows', lambda _: {})
|
||||||
|
with locks.LibraryLock(library, block_name='A', safe_to_release=lambda: False) as lease:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
result = residual_sessions.release_residual_sessions(dict(library=str(library),
|
||||||
|
block_names=list(selected), sessions=[], runtime_sessions=records), tmp_path/'evidence')
|
||||||
|
assert result['status'] == 'RELEASE_CONFIRMED', result.get('detail')
|
||||||
|
assert not list((history/'B').glob('observation-release-*.json'))
|
||||||
|
assert address.read_bytes() == b'unselected B owner'
|
||||||
|
monkeypatch.setattr(sessions, '_retained_libraries', {})
|
||||||
|
monkeypatch.setattr(sessions, '_retained_results', {})
|
||||||
|
found = sessions.discover_sessions(history, library=library)
|
||||||
|
assert {row['block'] for row in found} == {'A', 'B', 'C'}-set(selected)
|
||||||
|
finally:
|
||||||
|
owner = locks._owners.pop(lease.key, None)
|
||||||
|
if owner:
|
||||||
|
owner['handle'].Close()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('proof_scope,selected', [('BLOCK', ['A']), ('BLOCKS', ['A', 'C'])])
|
||||||
|
def test_discovery_rejects_existing_receipt_for_uncovered_operation(tmp_path, monkeypatch, proof_scope, selected):
|
||||||
|
library = tmp_path/'lib.lmc'
|
||||||
|
library.touch()
|
||||||
|
value = dict(operation_id='op-B', library=str(library), block='B', processes=[])
|
||||||
|
sessions.write_session_record(tmp_path/'session.json', value)
|
||||||
|
proof = dict(status='RELEASE_CONFIRMED', lease_state='RELEASED', library=str(library),
|
||||||
|
proof_scope=proof_scope, proof_block_names=selected,
|
||||||
|
proof_block_name=selected[0] if len(selected) == 1 else None,
|
||||||
|
resource_scope=dict(scope_state='OBSERVED', library=str(library), block_names=selected))
|
||||||
|
# Reproduce a receipt written by the prior implementation, then restart discovery.
|
||||||
|
sessions.write_session_record(tmp_path/'observation-release-old.json',
|
||||||
|
dict(operation_id='op-B', library=str(library), status='RELEASED', release_proof=proof))
|
||||||
|
monkeypatch.setattr(sessions, '_retained_libraries', {})
|
||||||
|
monkeypatch.setattr(sessions, '_retained_results', {})
|
||||||
|
found = sessions.discover_sessions(tmp_path, library=library)
|
||||||
|
assert len(found) == 1 and found[0]['operation_id'] == 'op-B'
|
||||||
|
|
||||||
|
|
||||||
|
def test_receipt_writer_keeps_replaced_operation_unresolved(tmp_path):
|
||||||
|
library = tmp_path/'lib.lmc'
|
||||||
|
library.touch()
|
||||||
|
path = tmp_path/'session.json'
|
||||||
|
sessions.write_session_record(path, dict(operation_id='new', library=str(library), block='A', processes=[]))
|
||||||
|
proof = dict(status='RELEASE_CONFIRMED', lease_state='RELEASED', library=str(library),
|
||||||
|
proof_scope='BLOCK', proof_block_names=['A'], proof_block_name='A',
|
||||||
|
resource_scope=dict(scope_state='OBSERVED', library=str(library), block_names=['A']))
|
||||||
|
sessions.record_session_release(proof, [{'path': str(path), 'operation_id': 'old'}])
|
||||||
|
assert not list(tmp_path.glob('observation-release-*.json'))
|
||||||
@@ -0,0 +1,388 @@
|
|||||||
|
"""Resource release must not inherit another project's session or late evidence."""
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
import win32con
|
||||||
|
import win32file
|
||||||
|
|
||||||
|
from cbb_refresh_verify import library_lock as locks
|
||||||
|
from cbb_refresh_verify import residual_sessions, session_record
|
||||||
|
|
||||||
|
|
||||||
|
def library_file(tmp_path, name='A'):
|
||||||
|
path = tmp_path/name/'lib.lmc'
|
||||||
|
path.parent.mkdir()
|
||||||
|
path.touch()
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
def cleanup(lease):
|
||||||
|
with locks._guard:
|
||||||
|
owner = locks._owners.pop(lease.key, None)
|
||||||
|
if owner:
|
||||||
|
owner['handle'].Close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_residual_release_preserves_selected_scope_and_releases_parent_sidecar(tmp_path, monkeypatch):
|
||||||
|
library = library_file(tmp_path)
|
||||||
|
other = library.parent/'ReusableBlocksLP/B/Work/database/cdbsvr/sAddress.adr'
|
||||||
|
other.parent.mkdir(parents=True)
|
||||||
|
other.write_bytes(b'other native address')
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
|
||||||
|
monkeypatch.setattr(residual_sessions, 'query_process_snapshot', lambda: [])
|
||||||
|
monkeypatch.setattr(residual_sessions, '_process_windows', lambda _: {})
|
||||||
|
with locks.LibraryLock(library, block_name='A', safe_to_release=lambda: False) as lease:
|
||||||
|
pass
|
||||||
|
script = ('import sys; from cbb_refresh_verify.library_lock import LibraryLock; '
|
||||||
|
'lease=LibraryLock(sys.argv[1],checkpoint=False); lease.__enter__(); lease.__exit__()')
|
||||||
|
try:
|
||||||
|
blocked = subprocess.run([sys.executable, '-c', script, str(library)], capture_output=True)
|
||||||
|
assert blocked.returncode != 0
|
||||||
|
result = residual_sessions.release_residual_sessions(
|
||||||
|
{'library': str(library), 'block_names': ['A'], 'sessions': []}, tmp_path/'evidence')
|
||||||
|
assert result['status'] == 'RELEASE_CONFIRMED', result.get('detail')
|
||||||
|
assert result['proof']['proof_block_name'] == 'A'
|
||||||
|
assert result['proof']['lease_state'] == 'RELEASED'
|
||||||
|
assert other.read_bytes() == b'other native address'
|
||||||
|
acquired = subprocess.run([sys.executable, '-c', script, str(library)], capture_output=True)
|
||||||
|
assert acquired.returncode == 0, acquired.stderr
|
||||||
|
assert lease.path.is_file()
|
||||||
|
finally:
|
||||||
|
cleanup(lease)
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_checkpoint_does_not_require_explicit_other_project_to_exit(tmp_path, monkeypatch):
|
||||||
|
library = library_file(tmp_path)
|
||||||
|
marker = locks.blocker_path(library)
|
||||||
|
marker.write_bytes(b'{legacy unrecognized checkpoint')
|
||||||
|
other = {'pid': 123456, 'name': 'ExpeditionPCB.exe',
|
||||||
|
'command': f'ExpeditionPCB.exe "{tmp_path}/Other/board.prj"'}
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [other])
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.native_engineering_identity._process_snapshot', lambda: [])
|
||||||
|
result = locks.release_retained_library(library, tmp_path/'evidence')
|
||||||
|
assert result['status'] == 'RELEASE_CONFIRMED'
|
||||||
|
assert result['unknown_checkpoint_archived'] is True
|
||||||
|
assert result['data_recovery_confirmed'] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_slow_release_of_a_does_not_block_b_cached_or_lease_checks(tmp_path, monkeypatch):
|
||||||
|
a, b = library_file(tmp_path, 'A'), library_file(tmp_path, 'B')
|
||||||
|
entered, finish = threading.Event(), threading.Event()
|
||||||
|
with locks.LibraryLock(a, safe_to_release=lambda: False) as lease:
|
||||||
|
pass
|
||||||
|
@contextmanager
|
||||||
|
def slow_proof(*args, **kwargs):
|
||||||
|
entered.set()
|
||||||
|
assert finish.wait(5)
|
||||||
|
yield {'exclusive_files': [str(a)]}
|
||||||
|
monkeypatch.setattr(locks, '_prove_library_released', slow_proof)
|
||||||
|
def inspect_b():
|
||||||
|
assert not locks.has_retained_library(b)
|
||||||
|
assert session_record.library_available(b)
|
||||||
|
with locks.LibraryLock(b):
|
||||||
|
return True
|
||||||
|
with ThreadPoolExecutor(2) as pool:
|
||||||
|
release = pool.submit(locks.release_retained_library, a, tmp_path/'evidence')
|
||||||
|
try:
|
||||||
|
assert entered.wait(2)
|
||||||
|
check = pool.submit(inspect_b)
|
||||||
|
assert check.result(timeout=.5)
|
||||||
|
finally:
|
||||||
|
finish.set()
|
||||||
|
release.result(5)
|
||||||
|
cleanup(lease)
|
||||||
|
|
||||||
|
|
||||||
|
def test_late_observer_cannot_clear_new_operation(tmp_path, monkeypatch):
|
||||||
|
path = tmp_path/'session.json'
|
||||||
|
library = tmp_path/'lib.lmc'
|
||||||
|
session_record.write_session_record(path, {'operation_id': 'old', 'library': str(library)})
|
||||||
|
key = str(path.absolute()).casefold()
|
||||||
|
entered, finish = threading.Event(), threading.Event()
|
||||||
|
def observe(*args, **kwargs):
|
||||||
|
entered.set()
|
||||||
|
assert finish.wait(3)
|
||||||
|
return {'status': 'RELEASED', 'operation_id': 'old'}
|
||||||
|
monkeypatch.setattr(session_record, 'observe_retained_session', observe)
|
||||||
|
monkeypatch.setattr(session_record, '_observers', {})
|
||||||
|
monkeypatch.setattr(session_record, '_retained_libraries', {})
|
||||||
|
monkeypatch.setattr(session_record, '_retained_results', {})
|
||||||
|
session_record.handoff_session(path, evidence_root=tmp_path)
|
||||||
|
assert entered.wait(2)
|
||||||
|
with session_record._observer_guard:
|
||||||
|
thread = session_record._observers[key][0]
|
||||||
|
session_record._retained_libraries[key] = {session_record._library_key(library)}
|
||||||
|
session_record._retained_results[key] = {'operation_id': 'new', 'status': 'ACTIVE'}
|
||||||
|
finish.set()
|
||||||
|
thread.join(3)
|
||||||
|
assert not session_record.library_available(library)
|
||||||
|
assert session_record.retained_session_states(library)[0]['operation_id'] == 'new'
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('repair_required', [False, True])
|
||||||
|
def test_target_address_uses_native_inspection_and_keeps_recovery_separate(tmp_path, monkeypatch, repair_required):
|
||||||
|
library = library_file(tmp_path)
|
||||||
|
work = library.parent/'ReusableBlocksLP/A/Work'
|
||||||
|
database = work/'database'
|
||||||
|
address = database/'cdbsvr/sAddress.adr'
|
||||||
|
address.parent.mkdir(parents=True)
|
||||||
|
address.write_bytes(b'native address retained')
|
||||||
|
(database/'icdb.dat').write_bytes(b'database')
|
||||||
|
project = work/'A.prj'
|
||||||
|
project.write_text('KEY iCDBDir "database"\n')
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
|
||||||
|
def inspect(target, root, **kwargs):
|
||||||
|
assert kwargs['inspection_only'] is True
|
||||||
|
output = f'Loading project file [{project}].\nChecking if project is in use.\n'
|
||||||
|
output += "Project is not in use. Full iCDB Project Backup's functionality is available.\n"
|
||||||
|
if repair_required:
|
||||||
|
output += (f'Project database [{database}] is inconsistent. It has been manually copied while '
|
||||||
|
"the iCDB Server was running. Please use iCDB Project Backup 'Repair project' functionality to fix this issue.\n")
|
||||||
|
output += 'Backup information loaded correctly.'
|
||||||
|
return dict(status='NOT_IN_USE', repair_required=repair_required, inspection_only=True,
|
||||||
|
repair_requested=False, native_pid=12345, native_exit_code=0,
|
||||||
|
release={'native_exited': True}, project=str(project), database=str(database), output=output)
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.native_repair.run_native_repair', inspect)
|
||||||
|
with locks.LibraryLock(library, block_name='A', safe_to_release=lambda: False) as lease:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
proof = locks.release_retained_library(library, tmp_path/'evidence', block_name='A')
|
||||||
|
assert proof['lease_state'] == 'RELEASED'
|
||||||
|
assert proof['data_recovery_required'] is repair_required
|
||||||
|
assert proof['data_recovery_confirmed'] is False
|
||||||
|
assert proof['resource_scope']['databases'] == [str(database)]
|
||||||
|
assert address.read_bytes() == b'native address retained'
|
||||||
|
assert not locks.has_retained_library(library)
|
||||||
|
finally:
|
||||||
|
cleanup(lease)
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_checkpoint_does_not_disown_export_server_from_path_alone(tmp_path, monkeypatch):
|
||||||
|
library = library_file(tmp_path)
|
||||||
|
locks.blocker_path(library).write_bytes(b'unknown')
|
||||||
|
other = {'pid': 123456, 'name': 'icdbnetserver.exe',
|
||||||
|
'command': f'icdbnetserver.exe -icdb "{tmp_path}/Other/database"'}
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [other])
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.native_engineering_identity._process_snapshot', lambda: [other])
|
||||||
|
with pytest.raises(locks.LibraryBusy):
|
||||||
|
locks.release_retained_library(library, tmp_path/'evidence')
|
||||||
|
|
||||||
|
|
||||||
|
def test_file_proof_holds_real_handle_until_context_exit(tmp_path):
|
||||||
|
from cbb_refresh_verify import file_probe
|
||||||
|
library = library_file(tmp_path)
|
||||||
|
with file_probe.hold_release_files(library) as proof:
|
||||||
|
assert proof['exclusive_files'] == [str(library)]
|
||||||
|
with pytest.raises(Exception):
|
||||||
|
handle = win32file.CreateFile(str(library), win32con.GENERIC_WRITE, 0, None,
|
||||||
|
win32con.OPEN_EXISTING, 0, None)
|
||||||
|
handle.Close()
|
||||||
|
handle = win32file.CreateFile(str(library), win32con.GENERIC_WRITE, 0, None,
|
||||||
|
win32con.OPEN_EXISTING, 0, None)
|
||||||
|
handle.Close()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('cancel', [False, True])
|
||||||
|
def test_file_probe_timeout_or_stop_reaps_only_its_helper(tmp_path, monkeypatch, cancel):
|
||||||
|
import time
|
||||||
|
from cbb_refresh_verify import file_probe
|
||||||
|
library = library_file(tmp_path)
|
||||||
|
actual_popen = subprocess.Popen
|
||||||
|
helpers = []
|
||||||
|
def blocked_probe(command, **kwargs):
|
||||||
|
child = actual_popen([sys.executable, '-c', 'import time; time.sleep(30)'], **kwargs)
|
||||||
|
helpers.append(child)
|
||||||
|
return child
|
||||||
|
monkeypatch.setattr(file_probe.subprocess, 'Popen', blocked_probe)
|
||||||
|
stop = threading.Event()
|
||||||
|
if cancel:
|
||||||
|
threading.Timer(.15, stop.set).start()
|
||||||
|
started = time.monotonic()
|
||||||
|
with pytest.raises((TimeoutError, InterruptedError)):
|
||||||
|
with file_probe.hold_release_files(library, timeout_seconds=.3, stop=stop):
|
||||||
|
pytest.fail('a stalled helper supplied release proof')
|
||||||
|
assert time.monotonic()-started < 3
|
||||||
|
assert helpers and helpers[0].poll() is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_file_proof_survives_probe_exit_during_parent_commit(tmp_path, monkeypatch):
|
||||||
|
from cbb_refresh_verify import file_probe
|
||||||
|
library = library_file(tmp_path)
|
||||||
|
launch = subprocess.Popen
|
||||||
|
helpers = []
|
||||||
|
def capture(*args, **kwargs):
|
||||||
|
child = launch(*args, **kwargs)
|
||||||
|
helpers.append(child)
|
||||||
|
return child
|
||||||
|
monkeypatch.setattr(file_probe.subprocess, 'Popen', capture)
|
||||||
|
with file_probe.hold_release_files(library):
|
||||||
|
helpers[0].terminate()
|
||||||
|
helpers[0].wait(3)
|
||||||
|
with pytest.raises(Exception):
|
||||||
|
handle = win32file.CreateFile(str(library), win32con.GENERIC_WRITE, 0, None,
|
||||||
|
win32con.OPEN_EXISTING, 0, None)
|
||||||
|
handle.Close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_worker_journal_records_declared_resource_scope_and_operation_identity(tmp_path):
|
||||||
|
import os
|
||||||
|
from types import SimpleNamespace
|
||||||
|
library = library_file(tmp_path)
|
||||||
|
project = library.parent/'ReusableBlocksLP/A/Work/A.prj'
|
||||||
|
pcb = project.parent/'PCB/A.pcb'
|
||||||
|
worker = SimpleNamespace(pid=os.getpid())
|
||||||
|
path = tmp_path/'session.json'
|
||||||
|
session_record.register_worker_session(worker, dict(session_record_path=str(path),
|
||||||
|
operation_id='operation-123', operation='verify', library=str(library), block='A',
|
||||||
|
project=str(project), pcb=str(pcb)))
|
||||||
|
record = session_record.read_session_record(path, evidence_root=tmp_path)
|
||||||
|
assert record['lease_state'] == 'ACTIVE'
|
||||||
|
assert record['resource_scope']['operation_id'] == 'operation-123'
|
||||||
|
assert record['resource_scope']['projects'] == [str(project)]
|
||||||
|
assert str(pcb.parent/'database') in record['resource_scope']['databases']
|
||||||
|
assert record['data_recovery_required'] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_replacement_lease_cannot_be_cleared_by_earlier_probe(tmp_path, monkeypatch):
|
||||||
|
library = library_file(tmp_path)
|
||||||
|
with locks.LibraryLock(library, safe_to_release=lambda: False) as lease:
|
||||||
|
pass
|
||||||
|
marker = locks.blocker_path(library)
|
||||||
|
original = marker.read_bytes()
|
||||||
|
@contextmanager
|
||||||
|
def replaced(*args, **kwargs):
|
||||||
|
with locks._guard:
|
||||||
|
locks._owners[lease.key] = {**locks._owners[lease.key], 'lease_id': 'b'*32}
|
||||||
|
yield {'exclusive_files': [str(library)]}
|
||||||
|
monkeypatch.setattr(locks, '_prove_library_released', replaced)
|
||||||
|
try:
|
||||||
|
with pytest.raises(locks.LibraryBusy):
|
||||||
|
locks.release_retained_library(library, tmp_path/'evidence')
|
||||||
|
assert marker.read_bytes() == original
|
||||||
|
assert locks._owners[lease.key]['lease_id'] == 'b'*32
|
||||||
|
finally:
|
||||||
|
cleanup(lease)
|
||||||
|
|
||||||
|
|
||||||
|
def test_multiple_selected_projects_do_not_expand_release_to_unselected_c(tmp_path, monkeypatch):
|
||||||
|
library = library_file(tmp_path)
|
||||||
|
other = library.parent/'ReusableBlocksLP/C/Work/database/cdbsvr/sAddress.adr'
|
||||||
|
other.parent.mkdir(parents=True)
|
||||||
|
other.write_bytes(b'not selected')
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
|
||||||
|
monkeypatch.setattr(residual_sessions, 'query_process_snapshot', lambda: [])
|
||||||
|
monkeypatch.setattr(residual_sessions, '_process_windows', lambda _: {})
|
||||||
|
with locks.LibraryLock(library, block_name='A', safe_to_release=lambda: False) as lease:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
result = residual_sessions.release_residual_sessions(
|
||||||
|
{'library': str(library), 'block_names': ['A', 'B'], 'sessions': []}, tmp_path/'evidence')
|
||||||
|
assert result['status'] == 'RELEASE_CONFIRMED', result.get('detail')
|
||||||
|
assert result['proof']['proof_block_names'] == ['A', 'B']
|
||||||
|
assert other.read_bytes() == b'not selected'
|
||||||
|
finally:
|
||||||
|
cleanup(lease)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('verdict', ['IN_USE', 'UNCONFIRMED', 'NOT_EXITED'])
|
||||||
|
def test_native_inspection_without_release_keeps_lease(tmp_path, monkeypatch, verdict):
|
||||||
|
library = library_file(tmp_path)
|
||||||
|
work = library.parent/'ReusableBlocksLP/A/Work'
|
||||||
|
database = work/'database'
|
||||||
|
address = database/'cdbsvr/sAddress.adr'
|
||||||
|
address.parent.mkdir(parents=True)
|
||||||
|
address.write_bytes(b'keep native address')
|
||||||
|
(database/'icdb.dat').touch()
|
||||||
|
project = work/'A.prj'
|
||||||
|
project.write_text('KEY iCDBDir "database"\n')
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
|
||||||
|
output = f'Loading project file [{project}].\nChecking if project is in use.\nProject is in use.'
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.native_repair.run_native_repair', lambda *a, **kw:
|
||||||
|
dict(status=verdict, project=str(project), database=str(database), output=output,
|
||||||
|
inspection_only=True, repair_requested=False, repair_required=False, native_pid=123,
|
||||||
|
native_exit_code=0, release={'native_exited': verdict != 'NOT_EXITED'}))
|
||||||
|
with locks.LibraryLock(library, block_name='A', safe_to_release=lambda: False) as lease:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
with pytest.raises(locks.LibraryBusy):
|
||||||
|
locks.release_retained_library(library, tmp_path/'evidence', block_name='A')
|
||||||
|
assert locks.has_retained_library(library)
|
||||||
|
assert address.read_bytes() == b'keep native address'
|
||||||
|
finally:
|
||||||
|
cleanup(lease)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('invalid_scope', [False, True])
|
||||||
|
def test_legacy_release_receipt_without_resource_scope_is_rechecked(tmp_path, invalid_scope):
|
||||||
|
library = library_file(tmp_path)
|
||||||
|
session_record.write_session_record(tmp_path/'session.json',
|
||||||
|
{'operation_id': 'legacy', 'library': str(library), 'processes': []})
|
||||||
|
session_record.write_session_record(tmp_path/'observation-release-old.json',
|
||||||
|
{'operation_id': 'legacy', 'status': 'RELEASED',
|
||||||
|
'release_proof': {'status': 'RELEASE_CONFIRMED', 'library': str(library),
|
||||||
|
**({'lease_state': 'RELEASED', 'resource_scope': None} if invalid_scope else {})}})
|
||||||
|
found = session_record.discover_sessions(tmp_path)
|
||||||
|
assert len(found) == 1
|
||||||
|
assert found[0]['status'] == 'UNCONFIRMED'
|
||||||
|
assert found[0]['resource_scope']['scope_state'] == 'RECHECK_REQUIRED'
|
||||||
|
|
||||||
|
|
||||||
|
def test_stalled_transaction_checkpoint_does_not_block_other_library_memory(tmp_path, monkeypatch):
|
||||||
|
from cbb_refresh_verify import management_transaction
|
||||||
|
a, b = library_file(tmp_path, 'A'), library_file(tmp_path, 'B')
|
||||||
|
entered, finish = threading.Event(), threading.Event()
|
||||||
|
original = locks.checkpoint_record
|
||||||
|
def checkpoint(path):
|
||||||
|
if path == locks.blocker_path(a) and threading.current_thread().name.startswith('ThreadPool'):
|
||||||
|
entered.set()
|
||||||
|
assert finish.wait(5)
|
||||||
|
return original(path)
|
||||||
|
with locks.LibraryLock(a):
|
||||||
|
monkeypatch.setattr(locks, 'checkpoint_record', checkpoint)
|
||||||
|
with ThreadPoolExecutor(2) as pool:
|
||||||
|
transaction = pool.submit(management_transaction.current_lease, a)
|
||||||
|
try:
|
||||||
|
assert entered.wait(2)
|
||||||
|
check = pool.submit(locks.has_retained_library, b)
|
||||||
|
assert check.result(.5) is False
|
||||||
|
finally:
|
||||||
|
finish.set()
|
||||||
|
with pytest.raises(ValueError): # This reader is not the lease's owning thread.
|
||||||
|
transaction.result(3)
|
||||||
|
|
||||||
|
|
||||||
|
def test_file_proof_holds_address_and_project_binding_against_changes(tmp_path):
|
||||||
|
from cbb_refresh_verify import file_probe
|
||||||
|
library = library_file(tmp_path)
|
||||||
|
database = library.parent/'ReusableBlocksLP/A/Work/database'
|
||||||
|
address = database/'cdbsvr/sAddress.adr'
|
||||||
|
address.parent.mkdir(parents=True)
|
||||||
|
address.write_bytes(b'address')
|
||||||
|
(database/'icdb.dat').touch()
|
||||||
|
project = database.parent/'A.prj'
|
||||||
|
project.write_text('KEY iCDBDir "database"\n')
|
||||||
|
with file_probe.hold_release_files(library):
|
||||||
|
for path in (address, project):
|
||||||
|
with pytest.raises(OSError):
|
||||||
|
path.write_bytes(b'changed binding')
|
||||||
|
assert address.read_bytes() == b'address'
|
||||||
|
assert project.read_text() == 'KEY iCDBDir "database"\n'
|
||||||
|
|
||||||
|
|
||||||
|
def test_file_probe_rejects_scope_junction_even_inside_same_library(tmp_path):
|
||||||
|
import _winapi
|
||||||
|
from cbb_refresh_verify import file_probe
|
||||||
|
library = library_file(tmp_path)
|
||||||
|
other = library.parent/'ReusableBlocksLP/B/Work'
|
||||||
|
other.mkdir(parents=True)
|
||||||
|
selected = library.parent/'ReusableBlocksLP/A/Work'
|
||||||
|
selected.parent.mkdir(parents=True)
|
||||||
|
_winapi.CreateJunction(str(other), str(selected))
|
||||||
|
with pytest.raises(OSError):
|
||||||
|
with file_probe.hold_release_files(library, (selected,)):
|
||||||
|
pytest.fail('scope link silently changed the release target')
|
||||||
@@ -0,0 +1,283 @@
|
|||||||
|
"""Actual process shutdown and captured native ownership regressions."""
|
||||||
|
from pathlib import Path
|
||||||
|
from threading import Event
|
||||||
|
from types import SimpleNamespace
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from test_issue15_ui_integration import window_for, load
|
||||||
|
|
||||||
|
|
||||||
|
def test_close_retains_captured_mapping_while_native_supervisor_is_active(qtbot,tmp_path,monkeypatch):
|
||||||
|
from cbb_refresh_verify.operation_queue import native_channel
|
||||||
|
from cbb_refresh_verify.network_path import LibraryPathLease
|
||||||
|
from test_network_path import FakeWNet
|
||||||
|
window=window_for(qtbot,tmp_path,monkeypatch)
|
||||||
|
load(window,qtbot)
|
||||||
|
backend=FakeWNet()
|
||||||
|
lease=LibraryPathLease.acquire(r'\\server\share\A\library.lmc',backend=backend)
|
||||||
|
window.library_lease=lease; window.mentor_lmc_path=lease.mentor_path
|
||||||
|
entered,release=Event(),Event()
|
||||||
|
def action():
|
||||||
|
with native_channel(): entered.set(); release.wait(5)
|
||||||
|
job=window._new_job('verify',library=lease.mentor_path)
|
||||||
|
window._start(action,lambda _:None,job=job)
|
||||||
|
qtbot.waitUntil(entered.is_set)
|
||||||
|
try:
|
||||||
|
window.close(); qtbot.wait(150)
|
||||||
|
assert not lease._closed, 'active native owner lost its captured mapping'
|
||||||
|
assert lease._retained_for_recovery
|
||||||
|
finally:
|
||||||
|
release.set(); qtbot.waitUntil(lambda:not window.isVisible())
|
||||||
|
lease.release_after_recovery({'status':'RELEASE_CONFIRMED','library':str(lease.mentor_path)})
|
||||||
|
lease.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_old_release_proof_cleans_its_lease_without_updating_new_operation(qtbot,tmp_path,monkeypatch):
|
||||||
|
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
|
||||||
|
monkeypatch.setattr(ResidualReleaseDialog,'refresh',lambda self:None)
|
||||||
|
cleaned=[]
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.network_path.release_retained_path_leases',
|
||||||
|
lambda proof,**kw:cleaned.append((proof,kw)))
|
||||||
|
window=window_for(qtbot,tmp_path,monkeypatch); load(window,qtbot)
|
||||||
|
first,second=Event(),Event()
|
||||||
|
window._start(lambda:first.wait(5),lambda _:None,queued=False)
|
||||||
|
window.check_library_release(); panel=window.release_dialog
|
||||||
|
first.set(); qtbot.waitUntil(lambda:not window.busy)
|
||||||
|
window._start(lambda:second.wait(5),lambda _:None,queued=False)
|
||||||
|
window.status_label.setText('NEW OPERATION STATUS')
|
||||||
|
pending={'library':Path('a.lmc'),'names':['A'],'maintenance':False,'released':False}
|
||||||
|
window._resume_batch=pending
|
||||||
|
try:
|
||||||
|
panel.released.emit({'status':'RELEASE_CONFIRMED','library':'a.lmc','evidence_path':'old-proof.json'})
|
||||||
|
qtbot.waitUntil(lambda:bool(cleaned)); qtbot.waitUntil(lambda:window._lease_pending==0)
|
||||||
|
assert window.status_label.text()=='NEW OPERATION STATUS'
|
||||||
|
assert pending['released'] is False
|
||||||
|
assert cleaned[0][0]['evidence_path']=='old-proof.json'
|
||||||
|
finally:
|
||||||
|
second.set(); qtbot.waitUntil(lambda:not window.busy); panel.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_shutdown_role_rejects_unregistered_ui_write_before_its_body(qtbot,tmp_path,monkeypatch):
|
||||||
|
from cbb_refresh_verify.operation_queue import native_phase
|
||||||
|
window=window_for(qtbot,tmp_path,monkeypatch); load(window,qtbot)
|
||||||
|
effects=[]
|
||||||
|
def action():
|
||||||
|
with native_phase(): effects.append('write')
|
||||||
|
window._start(action,lambda _:None)
|
||||||
|
qtbot.waitUntil(lambda:not window.busy)
|
||||||
|
assert effects==[]
|
||||||
|
assert 'NATIVE_ROLE_REQUIRED' in window.status_label.text()
|
||||||
|
|
||||||
|
|
||||||
|
def test_readonly_native_phase_process_really_exits_while_observer_remains_pending(tmp_path):
|
||||||
|
script=tmp_path/'readonly_app.py'
|
||||||
|
script.write_text('''from threading import Event
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
from PySide6.QtWidgets import QApplication
|
||||||
|
from PySide6.QtCore import QTimer
|
||||||
|
from cbb_refresh_verify.ui.main_window import MainWindow
|
||||||
|
from cbb_refresh_verify.operation_queue import native_phase
|
||||||
|
app=QApplication([])
|
||||||
|
MainWindow._show_unfinished_management=lambda self:None
|
||||||
|
w=MainWindow(reader=lambda _:None,data_root=Path(sys.argv[1])); w.show()
|
||||||
|
def action():
|
||||||
|
with native_phase(read_only=True):
|
||||||
|
print('READONLY_PHASE_ACTIVE',flush=True)
|
||||||
|
Event().wait(90)
|
||||||
|
w._start(action,lambda _:None)
|
||||||
|
QTimer.singleShot(250,w.close)
|
||||||
|
app.exec()
|
||||||
|
print('APP_RETURNED',flush=True)
|
||||||
|
''',encoding='utf-8')
|
||||||
|
process=subprocess.Popen([sys.executable,'-X','utf8',str(script),str(tmp_path/'data')],
|
||||||
|
stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True,encoding='utf-8',
|
||||||
|
env=dict(os.environ,QT_QPA_PLATFORM='offscreen'))
|
||||||
|
try:
|
||||||
|
stdout,stderr=process.communicate(timeout=8)
|
||||||
|
assert process.returncode==0,stderr
|
||||||
|
assert 'READONLY_PHASE_ACTIVE' in stdout and 'APP_RETURNED' in stdout
|
||||||
|
finally:
|
||||||
|
if process.poll() is None: process.kill(); process.communicate()
|
||||||
|
|
||||||
|
|
||||||
|
def test_main_process_exit_hands_off_exact_worker_with_sidecar_and_writer_barrier(tmp_path):
|
||||||
|
import win32api,win32con,win32event
|
||||||
|
from cbb_refresh_verify.library_lock import LibraryLock, LibraryBusy
|
||||||
|
from cbb_refresh_verify.operation_queue import native_channel
|
||||||
|
library=tmp_path/'lib.lmc'; library.write_bytes(b'isolated metadata')
|
||||||
|
child_script=tmp_path/'protected_child.py'
|
||||||
|
child_script.write_text('''import sys,time,json,os
|
||||||
|
from pathlib import Path
|
||||||
|
from cbb_refresh_verify.desktop_worker import run_native_worker
|
||||||
|
root=Path(sys.argv[1])
|
||||||
|
def action(path):
|
||||||
|
(root/'ready').write_text(str(os.getpid()))
|
||||||
|
while not (root/'finish').exists(): time.sleep(.02)
|
||||||
|
run_native_worker(action,root/'request.json')
|
||||||
|
(root/'done').touch()
|
||||||
|
''',encoding='utf-8')
|
||||||
|
script=tmp_path/'owner_app.py'
|
||||||
|
script.write_text('''import sys,time,subprocess,win32api,win32con,json
|
||||||
|
from pathlib import Path
|
||||||
|
from threading import Event
|
||||||
|
from PySide6.QtWidgets import QApplication
|
||||||
|
from PySide6.QtCore import QTimer
|
||||||
|
from cbb_refresh_verify.ui.main_window import MainWindow
|
||||||
|
from cbb_refresh_verify.operation_queue import native_channel,commit_worker_start
|
||||||
|
from cbb_refresh_verify.library_lock import LibraryLock,duplicate_worker_lease
|
||||||
|
from cbb_refresh_verify.session_record import register_worker_session
|
||||||
|
root=Path(sys.argv[1]); library=root/'lib.lmc'
|
||||||
|
app=QApplication([]); MainWindow._show_unfinished_management=lambda self:None
|
||||||
|
w=MainWindow(reader=lambda _:None,data_root=root/'data'); w.show()
|
||||||
|
def action():
|
||||||
|
with LibraryLock(library,checkpoint=False), native_channel():
|
||||||
|
record=dict(library=str(library),block='A',operation='verify',
|
||||||
|
operation_id='protected-child',session_record_path=str(root/'session.json'),
|
||||||
|
cancel_signal=str(root/'cancel'),start_gate=str(root/'gate'),start_gate_protocol='event-v1')
|
||||||
|
(root/'request.json').write_text(json.dumps(record))
|
||||||
|
child=subprocess.Popen([sys.executable,'-X','utf8',str(root/'protected_child.py'),str(root)],
|
||||||
|
stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
||||||
|
handle=win32api.OpenProcess(win32con.PROCESS_DUP_HANDLE,False,child.pid)
|
||||||
|
try: lease=duplicate_worker_lease(library,handle)
|
||||||
|
finally: handle.Close()
|
||||||
|
register_worker_session(child,{**record,'worker_lease_handle':lease})
|
||||||
|
commit_worker_start(child,record)
|
||||||
|
Event().wait(90)
|
||||||
|
job=w._new_job('verify',library=library,targets=('A',))
|
||||||
|
w._start(action,lambda _:None,job=job)
|
||||||
|
def close_ready():
|
||||||
|
if (root/'ready').exists():
|
||||||
|
print('PROTECTED_WRITER_ACTIVE',flush=True); w.close()
|
||||||
|
else: QTimer.singleShot(20,close_ready)
|
||||||
|
QTimer.singleShot(20,close_ready)
|
||||||
|
app.exec(); print('APP_RETURNED',flush=True)
|
||||||
|
''',encoding='utf-8')
|
||||||
|
started=time.monotonic()
|
||||||
|
process=subprocess.Popen([sys.executable,'-X','utf8',str(script),str(tmp_path)],
|
||||||
|
stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True,encoding='utf-8',
|
||||||
|
env=dict(os.environ,QT_QPA_PLATFORM='offscreen'))
|
||||||
|
try:
|
||||||
|
stdout,stderr=process.communicate(timeout=36)
|
||||||
|
assert process.returncode==0,stderr
|
||||||
|
assert 'PROTECTED_WRITER_ACTIVE' in stdout and 'APP_RETURNED' in stdout
|
||||||
|
assert time.monotonic()-started<30
|
||||||
|
record=json.loads((tmp_path/'session.json').read_text('utf-8'))
|
||||||
|
pid=int((tmp_path/'ready').read_text())
|
||||||
|
assert record['processes'][0]['pid']==pid and record['worker_lease_handle']
|
||||||
|
assert record['start_gate_protocol']=='event-v1' and record['worker_start_handle']
|
||||||
|
receipt=json.loads(next((tmp_path/'data'/'shutdown').glob('*.json')).read_text('utf-8'))
|
||||||
|
assert receipt['safe_to_continue'] is False and receipt['status']=='UNCONFIRMED'
|
||||||
|
bindings=[binding for scope in receipt['task_scopes'] for binding in scope['worker_sessions']]
|
||||||
|
assert any(binding['operation_id']=='protected-child' and binding['path']==str(tmp_path/'session.json')
|
||||||
|
and binding['worker_protection']=='duplicated_lease' for binding in bindings)
|
||||||
|
assert record['task_operation_id'] in {scope['operation_id'] for scope in receipt['task_scopes']}
|
||||||
|
handle=win32api.OpenProcess(win32con.SYNCHRONIZE,False,pid)
|
||||||
|
try: assert win32event.WaitForSingleObject(handle,0)==win32con.WAIT_TIMEOUT
|
||||||
|
finally: handle.Close()
|
||||||
|
with pytest.raises(LibraryBusy):
|
||||||
|
with LibraryLock(library,checkpoint=False): pass
|
||||||
|
with pytest.raises(RuntimeError,match='NATIVE_WRITER_ACTIVE'):
|
||||||
|
with native_channel(): pass
|
||||||
|
finally:
|
||||||
|
(tmp_path/'finish').touch()
|
||||||
|
if process.poll() is None: process.kill(); process.communicate()
|
||||||
|
deadline=time.monotonic()+5
|
||||||
|
while (tmp_path/'ready').exists() and not (tmp_path/'done').exists() and time.monotonic()<deadline:
|
||||||
|
time.sleep(.02)
|
||||||
|
assert (tmp_path/'done').exists()
|
||||||
|
with LibraryLock(library,checkpoint=False), native_channel(): pass
|
||||||
|
|
||||||
|
|
||||||
|
def test_shutdown_during_registration_returns_waiter_and_never_opens_late_gate(tmp_path,monkeypatch):
|
||||||
|
from threading import Thread
|
||||||
|
import win32api,win32con
|
||||||
|
from cbb_refresh_verify import session_record
|
||||||
|
from cbb_refresh_verify.library_lock import LibraryLock,duplicate_worker_lease
|
||||||
|
from cbb_refresh_verify.operation_queue import BatchTaskContext,TaskHandoff,native_channel
|
||||||
|
library=tmp_path/'lib.lmc'; library.write_bytes(b'isolated')
|
||||||
|
context=BatchTaskContext(str(library),native_policy='external')
|
||||||
|
entered,resume,returned=Event(),Event(),Event(); gates=[]; child=[]
|
||||||
|
original=session_record.write_session_record
|
||||||
|
def stalled(path,value):
|
||||||
|
entered.set(); resume.wait(5); return original(path,value)
|
||||||
|
monkeypatch.setattr(session_record,'write_session_record',stalled)
|
||||||
|
def action():
|
||||||
|
with LibraryLock(library,checkpoint=False), native_channel():
|
||||||
|
process=subprocess.Popen([sys.executable,'-c','input()'],stdin=subprocess.PIPE,text=True)
|
||||||
|
child.append(process)
|
||||||
|
handle=win32api.OpenProcess(win32con.PROCESS_DUP_HANDLE,False,process.pid)
|
||||||
|
try: lease=duplicate_worker_lease(library,handle)
|
||||||
|
finally: handle.Close()
|
||||||
|
session_record.register_worker_session(process,dict(library=str(library),operation='verify',
|
||||||
|
operation_id='registration',session_record_path=str(tmp_path/'session.json'),worker_lease_handle=lease))
|
||||||
|
gates.append('late native dispatch')
|
||||||
|
def run():
|
||||||
|
try: context.run(action)
|
||||||
|
except TaskHandoff: pass
|
||||||
|
finally: returned.set()
|
||||||
|
thread=Thread(target=run); thread.start(); assert entered.wait(2)
|
||||||
|
try:
|
||||||
|
state=context.shutdown()
|
||||||
|
assert state['safe_to_continue'] is False and returned.wait(1)
|
||||||
|
resume.set()
|
||||||
|
deadline=time.monotonic()+3
|
||||||
|
while context.snapshot()['pending'] and time.monotonic()<deadline: time.sleep(.01)
|
||||||
|
assert not context.snapshot()['pending']
|
||||||
|
assert gates==[]
|
||||||
|
finally:
|
||||||
|
resume.set(); thread.join(3)
|
||||||
|
for process in child: process.communicate('\n',timeout=3)
|
||||||
|
|
||||||
|
|
||||||
|
def test_readonly_observer_cannot_enter_a_mutating_phase(tmp_path):
|
||||||
|
from cbb_refresh_verify.operation_queue import BatchTaskContext,native_phase,native_channel
|
||||||
|
effects=[]
|
||||||
|
def action():
|
||||||
|
with native_phase(read_only=True):
|
||||||
|
with native_channel(): effects.append('write')
|
||||||
|
with pytest.raises(RuntimeError,match='NATIVE_ROLE_REQUIRED'):
|
||||||
|
BatchTaskContext(str(tmp_path/'lib.lmc'),native_policy='external').run(action)
|
||||||
|
assert effects==[]
|
||||||
|
|
||||||
|
|
||||||
|
def test_readonly_role_rejects_mutating_worker_at_common_registration(tmp_path):
|
||||||
|
from cbb_refresh_verify.operation_queue import BatchTaskContext,native_phase
|
||||||
|
from cbb_refresh_verify.session_record import register_worker_session
|
||||||
|
process=subprocess.Popen([sys.executable,'-c','input()'],stdin=subprocess.PIPE,text=True)
|
||||||
|
effects=[]
|
||||||
|
def action():
|
||||||
|
with native_phase(read_only=True):
|
||||||
|
register_worker_session(process,dict(library=str(tmp_path/'lib.lmc'),operation='remove',
|
||||||
|
operation_id='forbidden',session_record_path=str(tmp_path/'session.json'),worker_lease_handle=1))
|
||||||
|
effects.append('write gate')
|
||||||
|
try:
|
||||||
|
with pytest.raises(RuntimeError,match='NATIVE_ROLE_REQUIRED'):
|
||||||
|
BatchTaskContext(str(tmp_path/'lib.lmc'),native_policy='external').run(action)
|
||||||
|
assert effects==[]
|
||||||
|
finally: process.communicate('\n',timeout=3)
|
||||||
|
|
||||||
|
|
||||||
|
def test_shutdown_does_not_abandon_a_legacy_inprocess_mutation(tmp_path):
|
||||||
|
from threading import Thread
|
||||||
|
from cbb_refresh_verify.operation_queue import BatchTaskContext,native_phase
|
||||||
|
context=BatchTaskContext(str(tmp_path/'lib.lmc'))
|
||||||
|
entered,release,returned=Event(),Event(),Event()
|
||||||
|
def action():
|
||||||
|
with native_phase(): entered.set(); release.wait(3)
|
||||||
|
def run():
|
||||||
|
try: context.run(action)
|
||||||
|
finally: returned.set()
|
||||||
|
thread=Thread(target=run); thread.start(); assert entered.wait(1)
|
||||||
|
try:
|
||||||
|
state=context.shutdown()
|
||||||
|
assert state['pending_native'] and not state['shutdown_handoff']
|
||||||
|
assert state['safe_to_continue'] is False and not returned.wait(.1)
|
||||||
|
finally: release.set(); thread.join(3)
|
||||||
|
assert returned.is_set()
|
||||||
@@ -0,0 +1,737 @@
|
|||||||
|
"""Cancellation must release scheduling, never invent native release."""
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
from pathlib import Path
|
||||||
|
from threading import Event, Thread
|
||||||
|
import time
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
import win32con
|
||||||
|
import win32event
|
||||||
|
|
||||||
|
from cbb_refresh_verify import library_lock as locks
|
||||||
|
from test_management import setup as management_setup
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('stage', ['read', 'archive'])
|
||||||
|
def test_stalled_checkpoint_does_not_own_native_channel_or_commit_after_stop(tmp_path, monkeypatch, stage):
|
||||||
|
library = tmp_path/'A/lib.lmc'
|
||||||
|
library.parent.mkdir()
|
||||||
|
library.touch()
|
||||||
|
with locks.LibraryLock(library, block_name='A', safe_to_release=lambda: False) as lease:
|
||||||
|
pass
|
||||||
|
marker = locks.blocker_path(library)
|
||||||
|
original = marker.read_bytes()
|
||||||
|
entered, resume, stop = Event(), Event(), Event()
|
||||||
|
read, write = Path.read_bytes, Path.write_bytes
|
||||||
|
def read_bytes(path):
|
||||||
|
if stage == 'read' and path == marker and not resume.is_set():
|
||||||
|
entered.set()
|
||||||
|
assert resume.wait(5)
|
||||||
|
return read(path)
|
||||||
|
def write_bytes(path, data):
|
||||||
|
if stage == 'archive' and path.name.startswith('blocker-before-'):
|
||||||
|
entered.set()
|
||||||
|
assert resume.wait(5)
|
||||||
|
return write(path, data)
|
||||||
|
monkeypatch.setattr(Path, 'read_bytes', read_bytes)
|
||||||
|
monkeypatch.setattr(Path, 'write_bytes', write_bytes)
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
|
||||||
|
with ThreadPoolExecutor(1) as pool:
|
||||||
|
task = pool.submit(locks.release_retained_library, library, tmp_path/'evidence', stop=stop)
|
||||||
|
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||||
|
acquired = False
|
||||||
|
try:
|
||||||
|
assert entered.wait(3)
|
||||||
|
acquired = win32event.WaitForSingleObject(mutex, 0) in (
|
||||||
|
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
||||||
|
assert acquired, 'checkpoint I/O retained the host native channel'
|
||||||
|
if stage == 'archive':
|
||||||
|
import json
|
||||||
|
receipt = next((tmp_path/'evidence').rglob('release.json'))
|
||||||
|
assert json.loads(receipt.read_text())['lease_state'] != 'RELEASED'
|
||||||
|
stop.set()
|
||||||
|
resume.set()
|
||||||
|
with pytest.raises(InterruptedError):
|
||||||
|
task.result(5)
|
||||||
|
assert read(marker) == original
|
||||||
|
assert locks.has_retained_library(library)
|
||||||
|
finally:
|
||||||
|
stop.set()
|
||||||
|
resume.set()
|
||||||
|
if acquired:
|
||||||
|
win32event.ReleaseMutex(mutex)
|
||||||
|
mutex.Close()
|
||||||
|
try:
|
||||||
|
task.result(5)
|
||||||
|
except InterruptedError:
|
||||||
|
pass
|
||||||
|
with locks._guard:
|
||||||
|
owner = locks._owners.pop(lease.key, None)
|
||||||
|
if owner:
|
||||||
|
owner['handle'].Close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_task_context_is_frozen_pure_and_has_an_independent_monotonic_stop(tmp_path, monkeypatch):
|
||||||
|
from dataclasses import FrozenInstanceError
|
||||||
|
from cbb_refresh_verify.operation_queue import BatchTaskContext
|
||||||
|
monkeypatch.setattr(Path, 'resolve', lambda *a, **k: pytest.fail('context performed filesystem admission'))
|
||||||
|
first = BatchTaskContext(library=str(tmp_path/'A.lmc'), aliases=('Z:/A.lmc',), targets=('A',))
|
||||||
|
second = BatchTaskContext(library=str(tmp_path/'B.lmc'))
|
||||||
|
with pytest.raises(FrozenInstanceError):
|
||||||
|
first.library = second.library
|
||||||
|
first.cancel()
|
||||||
|
assert first.stop.is_set() and not second.stop.is_set()
|
||||||
|
assert not hasattr(first.stop, 'clear')
|
||||||
|
received = []
|
||||||
|
first.guard_callback(received.append)('CANCELLED')
|
||||||
|
assert received == ['CANCELLED']
|
||||||
|
first.close(timeout_seconds=0)
|
||||||
|
first.guard_callback(received.append)('late')
|
||||||
|
assert received == ['CANCELLED']
|
||||||
|
|
||||||
|
|
||||||
|
def test_bounded_queue_handoff_preserves_scope_and_fences_late_native_launch(tmp_path):
|
||||||
|
from cbb_refresh_verify.operation_queue import BatchTaskContext, NativeQueue, TaskHandoff, native_phase
|
||||||
|
queue = NativeQueue()
|
||||||
|
first = BatchTaskContext(library=str(tmp_path/'A.lmc'), targets=('A',))
|
||||||
|
second = BatchTaskContext(library=str(tmp_path/'B.lmc'), targets=('B',))
|
||||||
|
entered, resume, finished = Event(), Event(), Event()
|
||||||
|
effects = []
|
||||||
|
def stalled():
|
||||||
|
try:
|
||||||
|
entered.set()
|
||||||
|
assert resume.wait(3)
|
||||||
|
with native_phase():
|
||||||
|
effects.append('late native write')
|
||||||
|
finally:
|
||||||
|
finished.set()
|
||||||
|
try:
|
||||||
|
with pytest.raises(TaskHandoff) as error:
|
||||||
|
queue.run(stalled, context=first, timeout_seconds=.05)
|
||||||
|
assert entered.is_set() and error.value.library == first.library
|
||||||
|
assert first.snapshot()['pending'] == 1
|
||||||
|
assert queue.run(lambda: 'B ran', context=second) == 'B ran'
|
||||||
|
resume.set()
|
||||||
|
assert finished.wait(2)
|
||||||
|
assert effects == []
|
||||||
|
finally:
|
||||||
|
resume.set()
|
||||||
|
assert finished.wait(2)
|
||||||
|
|
||||||
|
|
||||||
|
def test_native_phase_is_never_yielded_at_metadata_deadline(tmp_path):
|
||||||
|
from cbb_refresh_verify.operation_queue import BatchTaskContext, NativeQueue, native_phase
|
||||||
|
queue = NativeQueue()
|
||||||
|
context = BatchTaskContext(library=str(tmp_path/'A.lmc'))
|
||||||
|
entered, resume, finished = Event(), Event(), Event()
|
||||||
|
results = []
|
||||||
|
def transaction():
|
||||||
|
with native_phase():
|
||||||
|
entered.set()
|
||||||
|
assert resume.wait(3)
|
||||||
|
return 'Remove and Add completed'
|
||||||
|
def run():
|
||||||
|
results.append(queue.run(transaction, context=context, timeout_seconds=.02))
|
||||||
|
finished.set()
|
||||||
|
thread = Thread(target=run)
|
||||||
|
thread.start()
|
||||||
|
try:
|
||||||
|
assert entered.wait(2)
|
||||||
|
assert not finished.wait(.1)
|
||||||
|
state = context.close(timeout_seconds=.02)
|
||||||
|
assert state['pending_native'] and queue.active
|
||||||
|
resume.set()
|
||||||
|
assert finished.wait(2)
|
||||||
|
assert results == ['Remove and Add completed']
|
||||||
|
finally:
|
||||||
|
resume.set()
|
||||||
|
thread.join(2)
|
||||||
|
|
||||||
|
|
||||||
|
def test_stalled_ready_predicate_does_not_hold_queue_condition():
|
||||||
|
from cbb_refresh_verify.operation_queue import NativeQueue, QueueCancelled
|
||||||
|
queue = NativeQueue()
|
||||||
|
entered, resume, stop, completed = Event(), Event(), Event(), Event()
|
||||||
|
effects = []
|
||||||
|
def slow_ready():
|
||||||
|
entered.set()
|
||||||
|
assert resume.wait(3)
|
||||||
|
return True
|
||||||
|
def first():
|
||||||
|
try:
|
||||||
|
queue.run(lambda: effects.append('A'), ready=slow_ready, stop=stop)
|
||||||
|
except QueueCancelled:
|
||||||
|
pass
|
||||||
|
thread = Thread(target=first)
|
||||||
|
thread.start()
|
||||||
|
second = Thread(target=lambda: (queue.run(lambda: effects.append('B')), completed.set()))
|
||||||
|
try:
|
||||||
|
assert entered.wait(2)
|
||||||
|
second.start()
|
||||||
|
assert completed.wait(.5), 'one ready predicate froze every other queue ticket'
|
||||||
|
stop.set()
|
||||||
|
resume.set()
|
||||||
|
thread.join(2)
|
||||||
|
assert effects == ['B']
|
||||||
|
finally:
|
||||||
|
stop.set()
|
||||||
|
resume.set()
|
||||||
|
thread.join(3)
|
||||||
|
second.join(3)
|
||||||
|
|
||||||
|
|
||||||
|
def test_verify_admission_handoff_unblocks_b_and_never_launches_after_read_returns(tmp_path, monkeypatch):
|
||||||
|
from cbb_refresh_verify.operation_queue import BatchTaskContext, NativeQueue
|
||||||
|
from cbb_refresh_verify.verify_runner import VerifyRequest, run_verify
|
||||||
|
import win32process
|
||||||
|
library = tmp_path/'A/lib.lmc'
|
||||||
|
library.parent.mkdir()
|
||||||
|
library.touch()
|
||||||
|
with locks.LibraryLock(library, block_name='A', safe_to_release=lambda: False) as lease:
|
||||||
|
pass
|
||||||
|
marker = locks.blocker_path(library)
|
||||||
|
entered, resume, returned = Event(), Event(), Event()
|
||||||
|
read = Path.read_text
|
||||||
|
def withheld(path, *args, **kwargs):
|
||||||
|
if path == marker:
|
||||||
|
entered.set()
|
||||||
|
assert resume.wait(3)
|
||||||
|
returned.set()
|
||||||
|
return read(path, *args, **kwargs)
|
||||||
|
monkeypatch.setattr(Path, 'read_text', withheld)
|
||||||
|
monkeypatch.setattr(win32process, 'CreateProcess', lambda *a, **k: pytest.fail('late native launch'))
|
||||||
|
context = BatchTaskContext(library=str(library), targets=('A',))
|
||||||
|
events = []
|
||||||
|
try:
|
||||||
|
result = run_verify(VerifyRequest(library, 'A', tmp_path/'evidence'), context=context,
|
||||||
|
admission_timeout_seconds=.05, progress=events.append)
|
||||||
|
assert entered.is_set() and result.status == 'TIMEOUT'
|
||||||
|
assert not result.safe_to_continue
|
||||||
|
assert result.release_proof['resource_scope']['operation_ids'] == [context.operation_id]
|
||||||
|
def unrelated():
|
||||||
|
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||||
|
acquired = win32event.WaitForSingleObject(mutex, 0) == win32con.WAIT_OBJECT_0
|
||||||
|
try:
|
||||||
|
assert acquired
|
||||||
|
return 'B completed'
|
||||||
|
finally:
|
||||||
|
if acquired: win32event.ReleaseMutex(mutex)
|
||||||
|
mutex.Close()
|
||||||
|
assert NativeQueue().run(unrelated) == 'B completed'
|
||||||
|
count = len(events)
|
||||||
|
resume.set()
|
||||||
|
assert returned.wait(2)
|
||||||
|
limit = time.monotonic()+2
|
||||||
|
while context.snapshot()['pending'] and time.monotonic() < limit:
|
||||||
|
time.sleep(.01)
|
||||||
|
assert context.snapshot()['pending'] == 0
|
||||||
|
assert len(events) == count
|
||||||
|
finally:
|
||||||
|
resume.set()
|
||||||
|
context.close(timeout_seconds=2)
|
||||||
|
with locks._guard:
|
||||||
|
owner = locks._owners.pop(lease.key, None)
|
||||||
|
if owner: owner['handle'].Close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_native_time_does_not_consume_next_metadata_phase_budget(tmp_path):
|
||||||
|
from cbb_refresh_verify.operation_queue import BatchTaskContext, native_phase
|
||||||
|
context = BatchTaskContext(library=str(tmp_path/'A.lmc'))
|
||||||
|
stages = []
|
||||||
|
def action():
|
||||||
|
with native_phase():
|
||||||
|
time.sleep(.12)
|
||||||
|
stages.append('saved')
|
||||||
|
time.sleep(.02)
|
||||||
|
with native_phase():
|
||||||
|
stages.append('closed')
|
||||||
|
return stages
|
||||||
|
assert context.run(action, timeout_seconds=.06) == ['saved', 'closed']
|
||||||
|
|
||||||
|
|
||||||
|
def test_native_channel_enforces_cross_thread_serialization_and_reentrancy():
|
||||||
|
from cbb_refresh_verify.operation_queue import native_channel
|
||||||
|
with native_channel():
|
||||||
|
with native_channel():
|
||||||
|
with ThreadPoolExecutor(1) as pool:
|
||||||
|
def contend():
|
||||||
|
with native_channel():
|
||||||
|
pytest.fail('concurrent native writer admitted')
|
||||||
|
with pytest.raises(RuntimeError, match='NATIVE_CHANNEL_BUSY'):
|
||||||
|
pool.submit(contend).result(2)
|
||||||
|
with native_channel():
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def test_maintenance_checkpoint_admission_does_not_hold_native_channel(tmp_path, monkeypatch):
|
||||||
|
from contextlib import nullcontext
|
||||||
|
library = tmp_path/'A/lib.lmc'
|
||||||
|
library.parent.mkdir()
|
||||||
|
library.touch()
|
||||||
|
with locks.LibraryLock(library, safe_to_release=lambda: False) as retained:
|
||||||
|
pass
|
||||||
|
marker = locks.blocker_path(library)
|
||||||
|
entered, resume = Event(), Event()
|
||||||
|
original = Path.read_bytes
|
||||||
|
def withheld(path):
|
||||||
|
if path == marker and not resume.is_set():
|
||||||
|
entered.set()
|
||||||
|
assert resume.wait(3)
|
||||||
|
return original(path)
|
||||||
|
monkeypatch.setattr(Path, 'read_bytes', withheld)
|
||||||
|
def admit():
|
||||||
|
with locks.LibraryLock.for_maintenance(library, tmp_path/'archive', lambda: nullcontext({})):
|
||||||
|
pass
|
||||||
|
with ThreadPoolExecutor(1) as pool:
|
||||||
|
task = pool.submit(admit)
|
||||||
|
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||||
|
acquired = False
|
||||||
|
try:
|
||||||
|
assert entered.wait(2)
|
||||||
|
acquired = win32event.WaitForSingleObject(mutex, 0) == win32con.WAIT_OBJECT_0
|
||||||
|
assert acquired
|
||||||
|
finally:
|
||||||
|
if acquired: win32event.ReleaseMutex(mutex)
|
||||||
|
mutex.Close()
|
||||||
|
resume.set()
|
||||||
|
task.result(5)
|
||||||
|
with locks._guard:
|
||||||
|
owner = locks._owners.pop(retained.key, None)
|
||||||
|
if owner: owner['handle'].Close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_native_handoff_keeps_worker_barrier_until_bound_process_returns(tmp_path):
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from cbb_refresh_verify.operation_queue import (
|
||||||
|
BatchTaskContext, NativeQueue, TaskHandoff, hold_native_handoff, native_channel)
|
||||||
|
from cbb_refresh_verify.session_record import write_session_record
|
||||||
|
process = None
|
||||||
|
context = BatchTaskContext(library=str(tmp_path/'A.lmc'))
|
||||||
|
record = tmp_path/'session.json'
|
||||||
|
queue = NativeQueue()
|
||||||
|
effects = []
|
||||||
|
def action():
|
||||||
|
nonlocal process
|
||||||
|
with native_channel():
|
||||||
|
script = ('from cbb_refresh_verify.desktop_worker import worker_native_channel\n'
|
||||||
|
'with worker_native_channel():\n print("ready",flush=True)\n input()\n')
|
||||||
|
process = subprocess.Popen([sys.executable, '-c', script], stdin=subprocess.PIPE,
|
||||||
|
stdout=subprocess.PIPE, text=True)
|
||||||
|
assert process.stdout.readline().strip() == 'ready'
|
||||||
|
write_session_record(record, dict(operation_id=context.operation_id, library=context.library,
|
||||||
|
worker_pid=process.pid))
|
||||||
|
hold_native_handoff(process, record)
|
||||||
|
with native_channel():
|
||||||
|
effects.append('late mutation')
|
||||||
|
try:
|
||||||
|
with pytest.raises(TaskHandoff):
|
||||||
|
queue.run(action, context=context)
|
||||||
|
assert process.poll() is None
|
||||||
|
assert not context.snapshot()['pending_native'] # Parent admission yielded to exact controls.
|
||||||
|
assert queue.run(lambda: 'pure read') == 'pure read'
|
||||||
|
with pytest.raises(RuntimeError, match='NATIVE_WRITER_ACTIVE'):
|
||||||
|
with native_channel():
|
||||||
|
pytest.fail('writer overlapped handed-off native call')
|
||||||
|
process.communicate('\n', timeout=3)
|
||||||
|
limit = time.monotonic()+3
|
||||||
|
while context.snapshot()['pending'] and time.monotonic() < limit:
|
||||||
|
time.sleep(.01)
|
||||||
|
assert context.snapshot()['pending'] == 0
|
||||||
|
with native_channel():
|
||||||
|
pass
|
||||||
|
assert effects == []
|
||||||
|
finally:
|
||||||
|
if process is not None and process.poll() is None:
|
||||||
|
process.communicate('\n', timeout=3)
|
||||||
|
context.close(timeout_seconds=3)
|
||||||
|
|
||||||
|
|
||||||
|
def test_worker_write_barrier_survives_supervisor_process_exit(tmp_path):
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from cbb_refresh_verify.operation_queue import native_channel
|
||||||
|
ready, finish, done = (tmp_path/name for name in ('ready', 'finish', 'done'))
|
||||||
|
child = '''import sys,time,os
|
||||||
|
from pathlib import Path
|
||||||
|
from cbb_refresh_verify.desktop_worker import worker_native_channel
|
||||||
|
with worker_native_channel():
|
||||||
|
Path(sys.argv[1]).write_text(str(os.getpid()))
|
||||||
|
while not Path(sys.argv[2]).exists(): time.sleep(.02)
|
||||||
|
Path(sys.argv[3]).touch()
|
||||||
|
'''
|
||||||
|
parent = '''import subprocess,sys,time,json
|
||||||
|
from pathlib import Path
|
||||||
|
subprocess.Popen([sys.executable,'-c',sys.argv[1],*sys.argv[2:]])
|
||||||
|
deadline=time.monotonic()+4
|
||||||
|
while not Path(sys.argv[2]).exists() and time.monotonic()<deadline: time.sleep(.02)
|
||||||
|
raise SystemExit(0 if Path(sys.argv[2]).exists() else 2)
|
||||||
|
'''
|
||||||
|
supervisor = subprocess.Popen([sys.executable, '-c', parent, child, str(ready), str(finish), str(done)])
|
||||||
|
try:
|
||||||
|
assert supervisor.wait(timeout=6) == 0
|
||||||
|
assert ready.is_file() and not done.exists()
|
||||||
|
with pytest.raises(RuntimeError, match='NATIVE_WRITER_ACTIVE'):
|
||||||
|
with native_channel():
|
||||||
|
pytest.fail('restart admitted a second writer')
|
||||||
|
finally:
|
||||||
|
finish.touch()
|
||||||
|
deadline = time.monotonic()+3
|
||||||
|
while not done.exists() and time.monotonic()<deadline: time.sleep(.02)
|
||||||
|
supervisor.wait(timeout=3)
|
||||||
|
assert done.is_file()
|
||||||
|
with native_channel():
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def test_exact_sidecar_handle_survives_parent_exit_until_worker_boundary(tmp_path):
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
library = tmp_path/'A/lib.lmc'
|
||||||
|
library.parent.mkdir()
|
||||||
|
library.touch()
|
||||||
|
ready, finish, done, handle = (tmp_path/name for name in ('ready', 'finish', 'done', 'handle'))
|
||||||
|
child = '''import sys,time
|
||||||
|
from pathlib import Path
|
||||||
|
from cbb_refresh_verify.desktop_worker import worker_native_channel
|
||||||
|
while not Path(sys.argv[4]).exists(): time.sleep(.02)
|
||||||
|
with worker_native_channel(lease_handle=int(Path(sys.argv[4]).read_text())):
|
||||||
|
Path(sys.argv[1]).touch()
|
||||||
|
while not Path(sys.argv[2]).exists(): time.sleep(.02)
|
||||||
|
Path(sys.argv[3]).touch()
|
||||||
|
'''
|
||||||
|
parent = '''import subprocess,sys,time,win32api,win32con
|
||||||
|
from pathlib import Path
|
||||||
|
from cbb_refresh_verify.library_lock import LibraryLock,duplicate_worker_lease
|
||||||
|
with LibraryLock(sys.argv[1],checkpoint=False):
|
||||||
|
child=subprocess.Popen([sys.executable,'-c',sys.argv[2],*sys.argv[3:]])
|
||||||
|
process=win32api.OpenProcess(win32con.PROCESS_DUP_HANDLE,False,child.pid)
|
||||||
|
try: handle=duplicate_worker_lease(sys.argv[1],process)
|
||||||
|
finally: process.Close()
|
||||||
|
Path(sys.argv[6]).write_text(str(handle))
|
||||||
|
deadline=time.monotonic()+4
|
||||||
|
while not Path(sys.argv[3]).exists() and time.monotonic()<deadline: time.sleep(.02)
|
||||||
|
assert Path(sys.argv[3]).exists()
|
||||||
|
'''
|
||||||
|
supervisor = subprocess.Popen([sys.executable, '-c', parent, str(library), child,
|
||||||
|
str(ready), str(finish), str(done), str(handle)])
|
||||||
|
try:
|
||||||
|
assert supervisor.wait(timeout=6) == 0
|
||||||
|
with pytest.raises(locks.LibraryBusy):
|
||||||
|
with locks.LibraryLock(library, checkpoint=False):
|
||||||
|
pytest.fail('uploader could replace a live worker library')
|
||||||
|
finally:
|
||||||
|
finish.touch()
|
||||||
|
deadline = time.monotonic()+3
|
||||||
|
while ready.exists() and not done.exists() and time.monotonic()<deadline: time.sleep(.02)
|
||||||
|
supervisor.wait(timeout=3)
|
||||||
|
assert done.is_file()
|
||||||
|
with locks.LibraryLock(library, checkpoint=False):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('obstacle', ['', 'unknown_title', 'duplicate', 'changed'])
|
||||||
|
def test_failed_startup_dismisses_only_exact_stable_owned_tip(tmp_path, monkeypatch, obstacle):
|
||||||
|
import win32gui
|
||||||
|
from test_failed_startup import startup_fixture
|
||||||
|
from cbb_refresh_verify.failed_session import close_failed_startup
|
||||||
|
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||||
|
visible = {100, 200}
|
||||||
|
reads = []
|
||||||
|
classes = {100: 'Afx:main', 200: '#32770', 201: 'Button', 202: 'Button'}
|
||||||
|
def title(hwnd):
|
||||||
|
if hwnd == 100: return 'Expedition PCB'
|
||||||
|
if hwnd == 200:
|
||||||
|
reads.append(hwnd)
|
||||||
|
return 'Unknown' if obstacle == 'unknown_title' or obstacle == 'changed' and len(reads)>1 else 'Tip of the Day'
|
||||||
|
return 'OK'
|
||||||
|
monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg: [fn(h, arg) for h in sorted(visible)])
|
||||||
|
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda hwnd, fn, arg:
|
||||||
|
[fn(h, arg) for h in ((201, 202) if obstacle == 'duplicate' else (201,))] if hwnd == 200 else None)
|
||||||
|
monkeypatch.setattr(win32gui, 'GetClassName', classes.__getitem__)
|
||||||
|
monkeypatch.setattr(win32gui, 'GetWindowText', title)
|
||||||
|
monkeypatch.setattr(win32gui, 'GetDlgCtrlID', lambda hwnd: 1)
|
||||||
|
def post(hwnd, message, wparam, lparam):
|
||||||
|
messages.append((hwnd, message))
|
||||||
|
if hwnd == 201: visible.remove(200)
|
||||||
|
elif hwnd == 100: records.clear()
|
||||||
|
monkeypatch.setattr(win32gui, 'PostMessage', post)
|
||||||
|
result = close_failed_startup(job, 12, timeout_seconds=0)
|
||||||
|
if obstacle:
|
||||||
|
assert result['status'] == 'RETAINED' and not messages
|
||||||
|
else:
|
||||||
|
assert result['status'] == 'CLOSED'
|
||||||
|
assert messages == [(201, win32con.BM_CLICK), (100, win32con.WM_CLOSE)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_late_release_recheck_is_bounded_and_keeps_business_failure(tmp_path, monkeypatch):
|
||||||
|
from cbb_refresh_verify.operation_lifecycle import recheck_failed_release
|
||||||
|
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||||
|
from cbb_refresh_verify.session_record import write_session_record
|
||||||
|
library = tmp_path/'A/lib.lmc'
|
||||||
|
library.parent.mkdir()
|
||||||
|
library.touch()
|
||||||
|
evidence = tmp_path/'evidence'
|
||||||
|
evidence.mkdir()
|
||||||
|
result = VerifyResult('FAIL', stderr='native business failure', safe_to_continue=False,
|
||||||
|
evidence_path=evidence/'result.json')
|
||||||
|
result.evidence_path.write_text('{}')
|
||||||
|
record = evidence/'session.json'
|
||||||
|
write_session_record(record, dict(operation_id='failed', library=str(library), block='A', processes=[]))
|
||||||
|
entered, resume = Event(), Event()
|
||||||
|
original = Path.open
|
||||||
|
def withheld(path, *args, **kwargs):
|
||||||
|
if path == record:
|
||||||
|
entered.set()
|
||||||
|
assert resume.wait(3)
|
||||||
|
return original(path, *args, **kwargs)
|
||||||
|
monkeypatch.setattr(Path, 'open', withheld)
|
||||||
|
try:
|
||||||
|
started = time.monotonic()
|
||||||
|
returned = recheck_failed_release(library, 'A', result, timeout_seconds=.05)
|
||||||
|
assert time.monotonic()-started < .8
|
||||||
|
assert entered.is_set() and returned is result
|
||||||
|
assert returned.status == 'FAIL' and not returned.safe_to_continue
|
||||||
|
finally:
|
||||||
|
resume.set()
|
||||||
|
|
||||||
|
|
||||||
|
def test_batch_context_cancel_records_all_remaining_items_and_new_batch_can_run(tmp_path):
|
||||||
|
from cbb_refresh_verify.operation_queue import BatchTaskContext
|
||||||
|
from cbb_refresh_verify.verify_runner import VerifyRequest, VerifyResult, run_batch
|
||||||
|
requests = [VerifyRequest(tmp_path/'lib.lmc', name, tmp_path/'evidence') for name in ('A', 'B', 'C')]
|
||||||
|
first = BatchTaskContext(library=str(requests[0].lmc_file), targets=('A', 'B', 'C'))
|
||||||
|
events = []
|
||||||
|
def verify(request):
|
||||||
|
first.cancel()
|
||||||
|
return VerifyResult('CANCELLED')
|
||||||
|
results = run_batch(requests, verifier=verify, context=first,
|
||||||
|
progress=lambda name, result: events.append((name, result.status)))
|
||||||
|
assert [r.status for r in results] == ['CANCELLED', 'SKIPPED', 'SKIPPED']
|
||||||
|
assert events == [('A', 'CANCELLED'), ('B', 'SKIPPED'), ('C', 'SKIPPED')]
|
||||||
|
second = BatchTaskContext(library=str(requests[0].lmc_file), targets=('A',))
|
||||||
|
assert run_batch(requests[:1], verifier=lambda _: VerifyResult('PASS'), context=second)[0].status == 'PASS'
|
||||||
|
|
||||||
|
|
||||||
|
def test_batch_retention_matches_normalized_library_alias_not_business_failure(tmp_path):
|
||||||
|
from cbb_refresh_verify.verify_runner import VerifyRequest, VerifyResult, run_batch
|
||||||
|
library = tmp_path/'A/lib.lmc'
|
||||||
|
alias = tmp_path/'A/sub/../lib.lmc'
|
||||||
|
requests = [VerifyRequest(path, block, tmp_path/'evidence') for path, block in (
|
||||||
|
(library, 'A'), (alias, 'B'), (tmp_path/'B/lib.lmc', 'C'), (tmp_path/'B/lib.lmc', 'D'))]
|
||||||
|
calls = []
|
||||||
|
def verify(request):
|
||||||
|
calls.append(request.block_name)
|
||||||
|
return VerifyResult('FAIL', safe_to_continue=request.block_name != 'A')
|
||||||
|
results = run_batch(requests, verifier=verify)
|
||||||
|
assert calls == ['A', 'C', 'D']
|
||||||
|
assert [r.status for r in results] == ['FAIL', 'SKIPPED', 'FAIL', 'FAIL']
|
||||||
|
|
||||||
|
|
||||||
|
def test_queue_close_has_one_deadline_and_reports_pending_scope(tmp_path):
|
||||||
|
from cbb_refresh_verify.operation_queue import BatchTaskContext, NativeQueue, TaskHandoff
|
||||||
|
queue = NativeQueue()
|
||||||
|
context = BatchTaskContext(library=str(tmp_path/'A.lmc'), aliases=('Z:/A.lmc',))
|
||||||
|
entered, resume, finished = Event(), Event(), Event()
|
||||||
|
def action():
|
||||||
|
entered.set()
|
||||||
|
resume.wait(3)
|
||||||
|
def run():
|
||||||
|
try:
|
||||||
|
queue.run(action, context=context)
|
||||||
|
except TaskHandoff:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
finished.set()
|
||||||
|
thread = Thread(target=run)
|
||||||
|
thread.start()
|
||||||
|
try:
|
||||||
|
assert entered.wait(2)
|
||||||
|
started = time.monotonic()
|
||||||
|
states = queue.close(timeout_seconds=.05)
|
||||||
|
assert time.monotonic()-started < .5
|
||||||
|
assert states[0]['resource_scope']['aliases'] == ['Z:/A.lmc']
|
||||||
|
assert states[0]['pending'] == 1
|
||||||
|
assert finished.wait(1)
|
||||||
|
finally:
|
||||||
|
resume.set()
|
||||||
|
thread.join(2)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('native_policy', ['legacy', 'external'])
|
||||||
|
def test_real_management_transaction_does_not_handoff_between_remove_and_add(management_setup, monkeypatch, native_policy):
|
||||||
|
from dataclasses import replace
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from test_management import execute
|
||||||
|
from cbb_refresh_verify import operation_queue
|
||||||
|
from cbb_refresh_verify.operation_queue import BatchTaskContext, NativeQueue
|
||||||
|
request, adapter, source = management_setup
|
||||||
|
offset = [0.0]
|
||||||
|
real_clock = time.monotonic
|
||||||
|
monkeypatch.setattr(operation_queue, 'time', SimpleNamespace(monotonic=lambda: real_clock()+offset[0]))
|
||||||
|
original = adapter.remove
|
||||||
|
def slow_remove(*args):
|
||||||
|
result = original(*args)
|
||||||
|
offset[0] += 100 # Native time exceeds admission budget without timing filesystem preparation.
|
||||||
|
time.sleep(.08) # Let the real admission monitor observe the active native phase.
|
||||||
|
return result
|
||||||
|
adapter.remove = slow_remove # Native external boundary; transaction stays real.
|
||||||
|
context = BatchTaskContext(library=str(request.library), targets=('Block',), native_policy=native_policy)
|
||||||
|
result = NativeQueue().run(lambda: execute(replace(request, operation='update',
|
||||||
|
source=source, auto_verify=False), adapter), context=context, timeout_seconds=10)
|
||||||
|
assert result.status == 'UPLOADED'
|
||||||
|
assert adapter.calls[0] == 'remove' and adapter.calls[1][0] == 'add'
|
||||||
|
|
||||||
|
|
||||||
|
def test_busy_native_channel_before_dispatch_does_not_retain_management_library(management_setup):
|
||||||
|
from test_management import execute
|
||||||
|
from cbb_refresh_verify.operation_queue import native_channel
|
||||||
|
request, adapter, _ = management_setup
|
||||||
|
entered, resume = Event(), Event()
|
||||||
|
def owner():
|
||||||
|
with native_channel():
|
||||||
|
entered.set()
|
||||||
|
resume.wait(3)
|
||||||
|
thread = Thread(target=owner)
|
||||||
|
thread.start()
|
||||||
|
try:
|
||||||
|
assert entered.wait(2)
|
||||||
|
result = execute(request, adapter)
|
||||||
|
assert result.safe_to_continue and not adapter.calls
|
||||||
|
with locks.LibraryLock(request.library):
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
resume.set()
|
||||||
|
thread.join(3)
|
||||||
|
|
||||||
|
|
||||||
|
def test_only_explicit_repair_inspection_can_enter_while_worker_owns_writer_barrier(tmp_path):
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from cbb_refresh_verify.desktop_worker import worker_native_channel, run_native_worker
|
||||||
|
from cbb_refresh_verify.operation_queue import native_channel
|
||||||
|
from cbb_refresh_verify.native_repair_ui import repair_worker_main
|
||||||
|
entered, resume = Event(), Event()
|
||||||
|
def owner():
|
||||||
|
with worker_native_channel():
|
||||||
|
entered.set()
|
||||||
|
resume.wait(3)
|
||||||
|
thread = Thread(target=owner)
|
||||||
|
thread.start()
|
||||||
|
job = dict(root=str(tmp_path), project=str(tmp_path/'A.prj'), database=str(tmp_path/'database'),
|
||||||
|
cancel_signal=str(tmp_path/'cancel'), supervisor_pid=os.getpid(), desktop='not-private')
|
||||||
|
path = tmp_path/'repair-request.json'
|
||||||
|
try:
|
||||||
|
assert entered.wait(2)
|
||||||
|
with native_channel(inspection_only=True):
|
||||||
|
pass
|
||||||
|
with pytest.raises(RuntimeError, match='NATIVE_WRITER_ACTIVE'):
|
||||||
|
with native_channel():
|
||||||
|
pass
|
||||||
|
for mode in (False, 'true'):
|
||||||
|
path.write_text(json.dumps({**job, 'inspection_only': mode}))
|
||||||
|
with pytest.raises(RuntimeError, match='NATIVE_WRITER_ACTIVE'):
|
||||||
|
run_native_worker(repair_worker_main, path)
|
||||||
|
path.write_text(json.dumps({**job, 'inspection_only': True}))
|
||||||
|
with pytest.raises(RuntimeError, match='NATIVE_WRITER_ACTIVE'):
|
||||||
|
run_native_worker(lambda _: pytest.fail('arbitrary worker exempted'), path)
|
||||||
|
assert run_native_worker(repair_worker_main, path) == 1
|
||||||
|
result = json.loads((tmp_path/'repair-result.json').read_text())
|
||||||
|
assert result['native_started'] is False
|
||||||
|
assert 'REPAIR_PRIVATE_DESKTOP_REQUIRED' in result['detail']
|
||||||
|
finally:
|
||||||
|
resume.set()
|
||||||
|
thread.join(3)
|
||||||
|
|
||||||
|
|
||||||
|
def test_inspection_session_does_not_take_over_retained_writer_lease(tmp_path):
|
||||||
|
import os
|
||||||
|
import win32api
|
||||||
|
from cbb_refresh_verify.desktop_worker import DesktopWorker
|
||||||
|
library = tmp_path/'A/lib.lmc'
|
||||||
|
library.parent.mkdir()
|
||||||
|
library.touch()
|
||||||
|
with locks.LibraryLock(library, safe_to_release=lambda: False) as lease:
|
||||||
|
pass
|
||||||
|
worker = object.__new__(DesktopWorker)
|
||||||
|
worker.handle, worker.pid = win32api.GetCurrentProcess(), os.getpid()
|
||||||
|
try:
|
||||||
|
worker.bind_session(dict(operation_id='inspection', operation='inspect', inspection_only=True,
|
||||||
|
library=str(library), project=str(tmp_path/'A.prj'), session_record_path=str(tmp_path/'session.json')))
|
||||||
|
assert locks.has_retained_library(library)
|
||||||
|
from cbb_refresh_verify.session_record import read_session_record
|
||||||
|
record = read_session_record(tmp_path/'session.json', evidence_root=tmp_path)
|
||||||
|
assert record['worker_lease_handle'] is None
|
||||||
|
finally:
|
||||||
|
with locks._guard:
|
||||||
|
owner = locks._owners.pop(lease.key, None)
|
||||||
|
if owner: owner['handle'].Close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_handoff_preserves_known_business_result_and_save_facts(tmp_path):
|
||||||
|
from cbb_refresh_verify.operation_queue import BatchTaskContext, TaskHandoff, remember_result
|
||||||
|
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||||
|
context = BatchTaskContext(library=str(tmp_path/'A.lmc'))
|
||||||
|
native_result = VerifyResult('FAIL', stderr='native failure after Save', safe_to_continue=False,
|
||||||
|
write_outcome=dict(save_state='COMMITTED', close_state='UNKNOWN'))
|
||||||
|
resume, done = Event(), Event()
|
||||||
|
def finalize():
|
||||||
|
remember_result(native_result)
|
||||||
|
try:
|
||||||
|
resume.wait(3)
|
||||||
|
finally:
|
||||||
|
done.set()
|
||||||
|
try:
|
||||||
|
with pytest.raises(TaskHandoff) as error:
|
||||||
|
context.run(finalize, timeout_seconds=.05)
|
||||||
|
assert error.value.result is native_result
|
||||||
|
assert error.value.result.write_outcome['save_state'] == 'COMMITTED'
|
||||||
|
assert error.value.result.status == 'FAIL'
|
||||||
|
from cbb_refresh_verify.verify_runner import _handoff_verify_result
|
||||||
|
returned = _handoff_verify_result(error.value)
|
||||||
|
assert returned.status == 'FAIL' and returned.stderr == native_result.stderr
|
||||||
|
assert returned.write_outcome == native_result.write_outcome and not returned.safe_to_continue
|
||||||
|
error.value.result = VerifyResult('PASS', write_outcome=native_result.write_outcome)
|
||||||
|
unfinished = _handoff_verify_result(error.value)
|
||||||
|
assert unfinished.status == 'FAIL' and unfinished.library_flag == 'UNKNOWN'
|
||||||
|
assert not unfinished.safe_to_continue
|
||||||
|
finally:
|
||||||
|
resume.set()
|
||||||
|
assert done.wait(2)
|
||||||
|
|
||||||
|
|
||||||
|
def test_registered_writer_owns_process_handle_after_callers_handle_closes(monkeypatch):
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from cbb_refresh_verify import desktop_worker
|
||||||
|
monkeypatch.setattr(desktop_worker, '_automation_clients', [])
|
||||||
|
process = subprocess.Popen([sys.executable, '-c', 'input()'], stdin=subprocess.PIPE, text=True)
|
||||||
|
entered, done = Event(), Event()
|
||||||
|
errors = []
|
||||||
|
def run():
|
||||||
|
try:
|
||||||
|
with desktop_worker.worker_native_channel():
|
||||||
|
desktop_worker.register_native_writer(process)
|
||||||
|
process._handle.Close()
|
||||||
|
entered.set()
|
||||||
|
except Exception as error:
|
||||||
|
errors.append(error)
|
||||||
|
finally:
|
||||||
|
done.set()
|
||||||
|
thread = Thread(target=run)
|
||||||
|
thread.start()
|
||||||
|
try:
|
||||||
|
assert entered.wait(2)
|
||||||
|
assert not done.wait(.1), 'a closed caller handle released an unreturned writer'
|
||||||
|
with pytest.raises(RuntimeError, match='NATIVE_WRITER_ACTIVE'):
|
||||||
|
desktop_worker.assert_native_writer_idle()
|
||||||
|
finally:
|
||||||
|
process.stdin.write('\n')
|
||||||
|
process.stdin.flush()
|
||||||
|
process.stdin.close()
|
||||||
|
thread.join(3)
|
||||||
|
# The duplicate's observed exit is authoritative; the original Popen
|
||||||
|
# handle was deliberately invalidated, so do not poll it in __del__.
|
||||||
|
process.returncode = 0
|
||||||
|
assert done.is_set() and not errors
|
||||||
@@ -0,0 +1,393 @@
|
|||||||
|
"""Real lifecycle regressions from the independent Task 2 review."""
|
||||||
|
from dataclasses import replace
|
||||||
|
from pathlib import Path
|
||||||
|
from threading import Event, Thread
|
||||||
|
import time
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from test_management import setup as management_setup
|
||||||
|
|
||||||
|
|
||||||
|
def wait_done(context):
|
||||||
|
deadline = time.monotonic()+3
|
||||||
|
while context.snapshot()['pending'] and time.monotonic()<deadline:
|
||||||
|
time.sleep(.01)
|
||||||
|
assert not context.snapshot()['pending']
|
||||||
|
|
||||||
|
|
||||||
|
def test_management_result_survives_actual_late_release_read_handoff(management_setup, monkeypatch):
|
||||||
|
from cbb_refresh_verify.management import run_management_batch
|
||||||
|
from cbb_refresh_verify.operation_queue import BatchTaskContext, NativeQueue
|
||||||
|
from cbb_refresh_verify.session_record import write_session_record
|
||||||
|
request, adapter, _ = management_setup
|
||||||
|
entered, resume = Event(), Event()
|
||||||
|
session = []
|
||||||
|
remove = adapter.remove
|
||||||
|
def fail_remove(req, evidence):
|
||||||
|
native = remove(req, evidence)
|
||||||
|
path = evidence.parent/'session.json'
|
||||||
|
write_session_record(path, dict(operation_id='failed-remove', library=str(req.library),
|
||||||
|
block=req.name, processes=[]))
|
||||||
|
session.append(path)
|
||||||
|
return replace(native, success=False, safe_to_continue=False, detail='exact native removal failure')
|
||||||
|
adapter.remove = fail_remove
|
||||||
|
opening = Path.open
|
||||||
|
def open_path(path, *args, **kwargs):
|
||||||
|
if session and path == session[0] and args == ('rb',):
|
||||||
|
entered.set()
|
||||||
|
assert resume.wait(4)
|
||||||
|
return opening(path, *args, **kwargs)
|
||||||
|
monkeypatch.setattr(Path, 'open', open_path)
|
||||||
|
context = BatchTaskContext(library=str(request.library), targets=(request.name,))
|
||||||
|
queue = NativeQueue()
|
||||||
|
try:
|
||||||
|
results = run_management_batch([request], adapter=adapter, idle_check=lambda *_: None,
|
||||||
|
item_executor=lambda req, action: queue.run(action, context=context, timeout_seconds=1))
|
||||||
|
assert entered.is_set()
|
||||||
|
result = results[0]
|
||||||
|
assert result.status == 'RECOVERY_REQUIRED'
|
||||||
|
assert result.detail.startswith('exact native removal failure')
|
||||||
|
assert result.evidence_path.is_file()
|
||||||
|
assert result.change_report['status'] == 'UNCONFIRMED'
|
||||||
|
assert result.release_proof['lease_state'] == 'PENDING'
|
||||||
|
assert not result.safe_to_continue
|
||||||
|
finally:
|
||||||
|
resume.set()
|
||||||
|
wait_done(context)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('status,expected', [('UPLOAD_FAILED', 'UPLOAD_FAILED'), ('UPLOADED', 'RECOVERY_REQUIRED')])
|
||||||
|
def test_management_batch_preserves_carried_handoff_result(management_setup, status, expected):
|
||||||
|
from cbb_refresh_verify.management import ManagementResult, run_management_batch
|
||||||
|
from cbb_refresh_verify.operation_queue import BatchTaskContext, TaskHandoff
|
||||||
|
request, _, _ = management_setup
|
||||||
|
known = ManagementResult(request.operation, request.library, request.name, request.partition,
|
||||||
|
request.source, request.auto_verify, 'complete', status, False, 'known native detail',
|
||||||
|
request.evidence_dir/'checkpoint.json', change_report={'status': 'UNCONFIRMED'})
|
||||||
|
context = BatchTaskContext(library=str(request.library))
|
||||||
|
def executor(req, action):
|
||||||
|
raise TaskHandoff(context, result=known)
|
||||||
|
result = run_management_batch([request], item_executor=executor)[0]
|
||||||
|
assert result.status == expected and result.detail == known.detail
|
||||||
|
assert result.evidence_path == known.evidence_path and result.change_report == known.change_report
|
||||||
|
assert result.release_proof['lease_state'] == 'PENDING' and not result.safe_to_continue
|
||||||
|
|
||||||
|
|
||||||
|
def test_exited_verify_worker_outcome_read_is_bounded_and_releases_channel(tmp_path, monkeypatch):
|
||||||
|
import json
|
||||||
|
from test_verify_runner import fixture, request
|
||||||
|
from cbb_refresh_verify.verify_runner import run_verify
|
||||||
|
from cbb_refresh_verify.operation_queue import BatchTaskContext, native_channel
|
||||||
|
fixture(tmp_path)
|
||||||
|
entered, resume, completed, stop = Event(), Event(), Event(), Event()
|
||||||
|
probes, results, errors = [], [], []
|
||||||
|
class ExitedWorker:
|
||||||
|
desktop = None
|
||||||
|
returncode = 0
|
||||||
|
def __init__(self, command, *args, **kwargs):
|
||||||
|
root = Path(command[-1]).parent
|
||||||
|
(root/'outcome.json').write_text(json.dumps(dict(status='PASS')))
|
||||||
|
def poll(self): return 0
|
||||||
|
def close(self): pass
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', ExitedWorker)
|
||||||
|
# The fake worker has no native clients; cleanup probes are covered independently.
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.verify_runner._cleanup_session_processes',
|
||||||
|
lambda *args, **kwargs: {'safe_to_continue': True, 'remaining_pids': []})
|
||||||
|
original = Path.read_text
|
||||||
|
def read(path, *args, **kwargs):
|
||||||
|
if path.name == 'outcome.json':
|
||||||
|
entered.set()
|
||||||
|
assert resume.wait(4)
|
||||||
|
return original(path, *args, **kwargs)
|
||||||
|
monkeypatch.setattr(Path, 'read_text', read)
|
||||||
|
context = BatchTaskContext(library=str(tmp_path/'lib.lmc'))
|
||||||
|
def run():
|
||||||
|
try:
|
||||||
|
results.append(run_verify(request(tmp_path), stop=stop, context=context,
|
||||||
|
admission_timeout_seconds=1, port_check=lambda: (True, ''),
|
||||||
|
flag_reader=lambda *a: probes.append('late native status read')))
|
||||||
|
except Exception as error:
|
||||||
|
errors.append(error)
|
||||||
|
finally:
|
||||||
|
completed.set()
|
||||||
|
thread = Thread(target=run)
|
||||||
|
thread.start()
|
||||||
|
try:
|
||||||
|
assert entered.wait(3), (results, errors)
|
||||||
|
stop.set()
|
||||||
|
assert completed.wait(1.5), 'exited worker metadata retained native phase'
|
||||||
|
with native_channel():
|
||||||
|
pass
|
||||||
|
assert not errors and not results[0].safe_to_continue
|
||||||
|
resume.set()
|
||||||
|
wait_done(context)
|
||||||
|
assert probes == []
|
||||||
|
finally:
|
||||||
|
resume.set()
|
||||||
|
thread.join(4)
|
||||||
|
wait_done(context)
|
||||||
|
|
||||||
|
|
||||||
|
def test_repair_session_write_before_gate_is_bounded_without_host_channel(tmp_path, monkeypatch):
|
||||||
|
from cbb_refresh_verify.native_repair import run_native_repair, RepairTarget
|
||||||
|
from cbb_refresh_verify.operation_queue import BatchTaskContext, TaskHandoff, native_channel
|
||||||
|
from cbb_refresh_verify import session_record
|
||||||
|
entered, resume, completed = Event(), Event(), Event()
|
||||||
|
errors = []
|
||||||
|
class GatedWorker:
|
||||||
|
returncode = 0
|
||||||
|
def __init__(self, command, *args, **kwargs): pass
|
||||||
|
def bind_cancellation(self, path): pass
|
||||||
|
def bind_session(self, job):
|
||||||
|
session_record.write_session_record(Path(job['session_record_path']),
|
||||||
|
{'operation_id': job['operation_id']})
|
||||||
|
def poll(self): return 0
|
||||||
|
def close(self): pass
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', GatedWorker)
|
||||||
|
original = Path.open
|
||||||
|
def opening(path, *args, **kwargs):
|
||||||
|
if path.name.startswith('session.json.') and path.suffix == '.pending':
|
||||||
|
entered.set()
|
||||||
|
assert resume.wait(4)
|
||||||
|
return original(path, *args, **kwargs)
|
||||||
|
monkeypatch.setattr(Path, 'open', opening)
|
||||||
|
context = BatchTaskContext(library=str(tmp_path/'A.lmc'))
|
||||||
|
def run():
|
||||||
|
try:
|
||||||
|
context.run(lambda: run_native_repair(RepairTarget(tmp_path/'A.prj', tmp_path/'database'),
|
||||||
|
tmp_path/'evidence'), timeout_seconds=.1)
|
||||||
|
except Exception as error:
|
||||||
|
errors.append(error)
|
||||||
|
finally:
|
||||||
|
completed.set()
|
||||||
|
thread = Thread(target=run)
|
||||||
|
thread.start()
|
||||||
|
try:
|
||||||
|
assert entered.wait(2)
|
||||||
|
assert completed.wait(.8), 'Repair pre-gate journal retained native phase'
|
||||||
|
with native_channel():
|
||||||
|
pass
|
||||||
|
assert len(errors) == 1 and isinstance(errors[0], TaskHandoff)
|
||||||
|
resume.set()
|
||||||
|
wait_done(context)
|
||||||
|
assert not (tmp_path/'evidence/start-repair.signal').exists()
|
||||||
|
finally:
|
||||||
|
resume.set()
|
||||||
|
thread.join(4)
|
||||||
|
wait_done(context)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('control', ['save', 'cancel'])
|
||||||
|
def test_handed_off_worker_accepts_exact_controls_but_excludes_new_writers(tmp_path, monkeypatch, control):
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from cbb_refresh_verify.operation_queue import BatchTaskContext, TaskHandoff, native_channel, hold_native_handoff
|
||||||
|
from cbb_refresh_verify import residual_sessions as sessions
|
||||||
|
from cbb_refresh_verify.session_record import write_session_record
|
||||||
|
library = tmp_path/'library/lib.lmc'
|
||||||
|
library.parent.mkdir()
|
||||||
|
library.touch()
|
||||||
|
context = BatchTaskContext(library=str(library))
|
||||||
|
child = []
|
||||||
|
ready, answered = Event(), Event()
|
||||||
|
errors = []
|
||||||
|
script = ('from cbb_refresh_verify.desktop_worker import worker_native_channel\n'
|
||||||
|
'with worker_native_channel():\n print("ready",flush=True)\n input()\n')
|
||||||
|
def action():
|
||||||
|
with native_channel():
|
||||||
|
process = subprocess.Popen([sys.executable, '-c', script], stdin=subprocess.PIPE,
|
||||||
|
stdout=subprocess.PIPE, text=True)
|
||||||
|
child.append(process)
|
||||||
|
assert process.stdout.readline().strip() == 'ready'
|
||||||
|
record = tmp_path/'session.json'
|
||||||
|
write_session_record(record, dict(operation_id=context.operation_id, library=str(library)))
|
||||||
|
ready.set()
|
||||||
|
hold_native_handoff(process, record)
|
||||||
|
controller = None
|
||||||
|
try:
|
||||||
|
with pytest.raises(TaskHandoff):
|
||||||
|
context.run(action)
|
||||||
|
assert ready.is_set() and child[0].poll() is None
|
||||||
|
row = dict(pid=child[0].pid, name='iCDBProjectBackup.exe', created='exact-child',
|
||||||
|
executable='C:/Mentor/iCDBProjectBackup.exe', command=f'backup -p "{library.parent}/A.prj"',
|
||||||
|
scope_confirmed=True, cancel_prompt={'title': 'captured'})
|
||||||
|
def answer(observed, *args, **kwargs):
|
||||||
|
assert observed['pid'] == child[0].pid
|
||||||
|
child[0].communicate('\n', timeout=3)
|
||||||
|
answered.set()
|
||||||
|
return {'release_status': 'RELEASED'}
|
||||||
|
if control == 'save':
|
||||||
|
monkeypatch.setattr(sessions, '_answer_save_question', answer)
|
||||||
|
command = lambda: sessions.answer_save_question(row, 6)
|
||||||
|
else:
|
||||||
|
monkeypatch.setattr(sessions, '_request_native_cancel', answer)
|
||||||
|
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [row] if child[0].poll() is None else [])
|
||||||
|
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
|
||||||
|
# Keep this real writer-barrier/control test independent of file-probe startup latency.
|
||||||
|
monkeypatch.setattr(sessions, '_finish_library_release',
|
||||||
|
lambda *args, **kwargs: {'status': 'RELEASE_CONFIRMED', 'library': str(library)})
|
||||||
|
command = lambda: sessions.release_residual_sessions(dict(library=str(library), sessions=[row]),
|
||||||
|
tmp_path/'controls', cancel_native=True)
|
||||||
|
def control_call():
|
||||||
|
try: command()
|
||||||
|
except Exception as error: errors.append(error)
|
||||||
|
# New writes still fail, but the exact corrective control can progress.
|
||||||
|
with pytest.raises(RuntimeError):
|
||||||
|
with native_channel():
|
||||||
|
pytest.fail('overlapping new writer admitted')
|
||||||
|
controller = Thread(target=control_call)
|
||||||
|
controller.start()
|
||||||
|
assert answered.wait(1), errors
|
||||||
|
controller.join(5)
|
||||||
|
assert not controller.is_alive() and not errors
|
||||||
|
wait_done(context)
|
||||||
|
with native_channel():
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
if child and child[0].poll() is None:
|
||||||
|
child[0].communicate('\n', timeout=3)
|
||||||
|
if controller is not None: controller.join(5)
|
||||||
|
wait_done(context)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('mode', ['pending', 'acknowledged', 'assignment-failed', 'cancel-after-registration'])
|
||||||
|
def test_real_async_add_unwind_and_parent_exit_keep_only_pending_writer_scope(tmp_path, mode):
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import win32api, win32con, win32event
|
||||||
|
from test_management import project
|
||||||
|
from cbb_refresh_verify import library_lock as locks
|
||||||
|
from cbb_refresh_verify.operation_queue import native_channel
|
||||||
|
library = tmp_path/'library/lib.lmc'
|
||||||
|
library.parent.mkdir()
|
||||||
|
library.touch()
|
||||||
|
source = project(tmp_path/'source', name='Block')
|
||||||
|
for path in (source, source.parent/'PCB/pcb.prj'):
|
||||||
|
with path.open('a', encoding='utf-8') as stream:
|
||||||
|
stream.write(f'KEY CentralLibrary "{library}"\n')
|
||||||
|
root = tmp_path/'native-add'
|
||||||
|
root.mkdir()
|
||||||
|
helper = Path(__file__).parent/'support/async_add_lifecycle_fixture.py'
|
||||||
|
parent_script = '''import sys,json,time,subprocess,os,win32api,win32con
|
||||||
|
from pathlib import Path
|
||||||
|
from cbb_refresh_verify.library_lock import LibraryLock,duplicate_worker_lease
|
||||||
|
from cbb_refresh_verify.session_record import register_worker_session,process_identity
|
||||||
|
library,source,root,helper=map(Path,sys.argv[1:5])
|
||||||
|
job=dict(operation='probe_create_add',library=str(library),source=str(source),root=str(root),name='Block',
|
||||||
|
operation_id='actual-add',session_record_path=str(root/'session.json'),start_gate=str(root/'gate'),
|
||||||
|
cancel_signal=str(root/'cancel'),supervisor_pid=os.getpid(),supervisor_identity=process_identity(os.getpid()),
|
||||||
|
timeout_seconds=.3,test_mode=sys.argv[5])
|
||||||
|
(root/'request.json').write_text(json.dumps(job))
|
||||||
|
with LibraryLock(library,checkpoint=False):
|
||||||
|
with (root/'worker-output.txt').open('w') as output:
|
||||||
|
worker=subprocess.Popen([sys.executable,str(helper),str(root/'request.json')],stdout=output,stderr=output)
|
||||||
|
(root.parent/'worker-pid').write_text(str(worker.pid))
|
||||||
|
handle=win32api.OpenProcess(win32con.PROCESS_DUP_HANDLE,False,worker.pid)
|
||||||
|
try: inherited=duplicate_worker_lease(library,handle)
|
||||||
|
finally: handle.Close()
|
||||||
|
register_worker_session(worker,{**job,'worker_lease_handle':inherited})
|
||||||
|
(root/'gate').touch()
|
||||||
|
deadline=time.monotonic()+12
|
||||||
|
while not (root.parent/'add-unwound').exists() and time.monotonic()<deadline: time.sleep(.02)
|
||||||
|
assert (root.parent/'add-unwound').exists()
|
||||||
|
'''
|
||||||
|
parent = subprocess.Popen([sys.executable, '-c', parent_script, str(library), str(source), str(root), str(helper), mode])
|
||||||
|
handles = []
|
||||||
|
def open_pid_file(name):
|
||||||
|
pid = int((tmp_path/name).read_text())
|
||||||
|
handle = win32api.OpenProcess(win32con.SYNCHRONIZE, False, pid)
|
||||||
|
handles.append(handle)
|
||||||
|
return handle
|
||||||
|
try:
|
||||||
|
code = parent.wait(timeout=15)
|
||||||
|
assert code == 0, (root/'worker-output.txt').read_text(errors='replace')
|
||||||
|
if mode in ('assignment-failed', 'cancel-after-registration'):
|
||||||
|
assert not (tmp_path/'add-dispatched').exists()
|
||||||
|
detail = 'exact native job admission denied' if mode == 'assignment-failed' else 'NATIVE_ADD_CANCELLED'
|
||||||
|
assert detail in (root/'result.json').read_text()
|
||||||
|
with native_channel(): pass
|
||||||
|
with locks.LibraryLock(library, checkpoint=False): pass
|
||||||
|
return
|
||||||
|
assert (tmp_path/'add-dispatched').exists()
|
||||||
|
lm = open_pid_file('lm-pid')
|
||||||
|
if mode == 'pending':
|
||||||
|
worker = open_pid_file('worker-pid')
|
||||||
|
from cbb_refresh_verify.session_record import read_session_record
|
||||||
|
journal = read_session_record(root/'worker-state.json', evidence_root=root)
|
||||||
|
identity = next(p for p in journal['processes'] if p['pid'] == int((tmp_path/'lm-pid').read_text()))
|
||||||
|
assert identity['created_handle'] and identity['image'] and identity['owner_sid']
|
||||||
|
with pytest.raises(RuntimeError, match='NATIVE_WRITER_ACTIVE'):
|
||||||
|
with native_channel(): pass
|
||||||
|
with pytest.raises(locks.LibraryBusy):
|
||||||
|
with locks.LibraryLock(library, checkpoint=False): pass
|
||||||
|
(tmp_path/'lm-exit').touch()
|
||||||
|
assert win32event.WaitForSingleObject(lm, 3000) == win32con.WAIT_OBJECT_0
|
||||||
|
assert win32event.WaitForSingleObject(worker, 0) != win32con.WAIT_OBJECT_0
|
||||||
|
deadline = time.monotonic()+2
|
||||||
|
descendant = int((tmp_path/'descendant-pid').read_text())
|
||||||
|
while time.monotonic()<deadline:
|
||||||
|
journal = read_session_record(root/'worker-state.json', evidence_root=root)
|
||||||
|
if any(p['pid'] == descendant for p in journal['processes']): break
|
||||||
|
time.sleep(.02)
|
||||||
|
assert any(p['pid'] == descendant and p['created_handle'] for p in journal['processes'])
|
||||||
|
with pytest.raises(RuntimeError, match='NATIVE_WRITER_ACTIVE'):
|
||||||
|
with native_channel(): pass
|
||||||
|
with pytest.raises(locks.LibraryBusy):
|
||||||
|
with locks.LibraryLock(library, checkpoint=False): pass
|
||||||
|
(tmp_path/'native-done').touch()
|
||||||
|
assert win32event.WaitForSingleObject(worker, 5000) == win32con.WAIT_OBJECT_0
|
||||||
|
else:
|
||||||
|
deadline = time.monotonic()+3
|
||||||
|
while time.monotonic()<deadline:
|
||||||
|
try:
|
||||||
|
with native_channel(): pass
|
||||||
|
break
|
||||||
|
except RuntimeError:
|
||||||
|
time.sleep(.02)
|
||||||
|
with native_channel(): pass
|
||||||
|
assert win32event.WaitForSingleObject(lm, 0) != win32con.WAIT_OBJECT_0, 'idle LM was killed'
|
||||||
|
with locks.LibraryLock(library, checkpoint=False): pass
|
||||||
|
finally:
|
||||||
|
(tmp_path/'lm-exit').touch()
|
||||||
|
(tmp_path/'native-done').touch()
|
||||||
|
for handle in handles:
|
||||||
|
win32event.WaitForSingleObject(handle, 5000)
|
||||||
|
handle.Close()
|
||||||
|
if (tmp_path/'worker-pid').exists():
|
||||||
|
try:
|
||||||
|
worker = open_pid_file('worker-pid')
|
||||||
|
except Exception as error:
|
||||||
|
if getattr(error, 'winerror', None) != 87: raise
|
||||||
|
else:
|
||||||
|
assert win32event.WaitForSingleObject(worker, 5000) == win32con.WAIT_OBJECT_0
|
||||||
|
worker.Close()
|
||||||
|
parent.wait(timeout=15)
|
||||||
|
|
||||||
|
|
||||||
|
def test_add_descendant_snapshot_cannot_journal_an_unrelated_reused_pid(tmp_path, monkeypatch):
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from cbb_refresh_verify import desktop_worker
|
||||||
|
from cbb_refresh_verify.session_record import write_session_record, read_session_record
|
||||||
|
monkeypatch.setattr(desktop_worker, '_automation_clients', [])
|
||||||
|
owner = subprocess.Popen([sys.executable, '-c', 'input()'], stdin=subprocess.PIPE, text=True)
|
||||||
|
foreign = subprocess.Popen([sys.executable, '-c', 'input()'], stdin=subprocess.PIPE, text=True)
|
||||||
|
operation = None
|
||||||
|
query = desktop_worker.win32job.QueryInformationJobObject
|
||||||
|
try:
|
||||||
|
job = dict(operation_id='descendant-identity', session_record_path=str(tmp_path/'session.json'))
|
||||||
|
write_session_record(tmp_path/'worker-state.json', dict(operation_id=job['operation_id'], processes=[]))
|
||||||
|
operation = desktop_worker.register_pending_native_operation(job, {owner.pid})
|
||||||
|
monkeypatch.setattr(desktop_worker.win32job, 'QueryInformationJobObject',
|
||||||
|
lambda *args: [owner.pid, foreign.pid])
|
||||||
|
assert operation.poll() is None
|
||||||
|
journal = read_session_record(tmp_path/'worker-state.json', evidence_root=tmp_path)
|
||||||
|
assert not any(p['pid'] == foreign.pid for p in journal['processes'])
|
||||||
|
finally:
|
||||||
|
owner.communicate('\n', timeout=3)
|
||||||
|
foreign.communicate('\n', timeout=3)
|
||||||
|
monkeypatch.setattr(desktop_worker.win32job, 'QueryInformationJobObject', query)
|
||||||
|
if operation is not None:
|
||||||
|
assert operation.poll() == 0
|
||||||
@@ -0,0 +1,651 @@
|
|||||||
|
"""Task-bound UI delivery and filesystem/native catalog separation."""
|
||||||
|
from pathlib import Path
|
||||||
|
from threading import Event
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from PySide6.QtCore import Qt
|
||||||
|
|
||||||
|
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
|
||||||
|
from cbb_refresh_verify.ui.main_window import MainWindow
|
||||||
|
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||||
|
|
||||||
|
|
||||||
|
def window_for(qtbot, tmp_path, monkeypatch, *, reader=None, **kwargs):
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.ui.main_window.preflight_skip_reason', lambda *_: None)
|
||||||
|
def lease(path):
|
||||||
|
return SimpleNamespace(mentor_path=path, display_path=path, drive='', remote_root='',
|
||||||
|
close=lambda: None, retain_for_recovery=lambda: None)
|
||||||
|
window = MainWindow(reader=reader or (lambda _: LibraryReadResult((CbbRecord('A', 'LP'),))),
|
||||||
|
path_lease_factory=lease, data_root=tmp_path, **kwargs)
|
||||||
|
qtbot.addWidget(window)
|
||||||
|
window.show()
|
||||||
|
return window
|
||||||
|
|
||||||
|
|
||||||
|
def load(window, qtbot, path='a.lmc'):
|
||||||
|
window.lmc_edit.setText(path)
|
||||||
|
window.load_library()
|
||||||
|
qtbot.waitUntil(lambda: not window.busy)
|
||||||
|
|
||||||
|
|
||||||
|
def test_first_read_can_cancel_and_keeps_navigation_live(qtbot, tmp_path, monkeypatch):
|
||||||
|
entered, release = Event(), Event()
|
||||||
|
def reader(_):
|
||||||
|
entered.set(); release.wait(5)
|
||||||
|
return LibraryReadResult((CbbRecord('Late', 'LP'),))
|
||||||
|
window = window_for(qtbot, tmp_path, monkeypatch, reader=reader)
|
||||||
|
window.lmc_edit.setText('a.lmc'); window.load_library()
|
||||||
|
qtbot.waitUntil(entered.is_set)
|
||||||
|
try:
|
||||||
|
assert window.stop_button.isEnabled()
|
||||||
|
assert window.lmc_edit.isEnabled() and window.load_button.isEnabled()
|
||||||
|
window.stop_button.click()
|
||||||
|
qtbot.waitUntil(lambda: not window.busy, timeout=2000)
|
||||||
|
assert window.loaded_path is None
|
||||||
|
finally:
|
||||||
|
release.set(); window.pool.waitForDone(6000)
|
||||||
|
|
||||||
|
|
||||||
|
def test_failed_read_preserves_stale_table_without_write_eligibility(qtbot, tmp_path, monkeypatch):
|
||||||
|
window = window_for(qtbot, tmp_path, monkeypatch)
|
||||||
|
load(window, qtbot)
|
||||||
|
window.reader = lambda _: LibraryReadResult((), 'INPUT_EMPTY: 空文件')
|
||||||
|
load(window, qtbot, 'bad.lmc')
|
||||||
|
assert window.cbb_table.rowCount() == 1
|
||||||
|
assert window.loaded_path is None
|
||||||
|
assert not window.batch_button.isEnabled()
|
||||||
|
assert '失效' in window.library_notice.text()
|
||||||
|
|
||||||
|
|
||||||
|
def test_successful_path_is_local_and_only_prefilled(qtbot, tmp_path, monkeypatch):
|
||||||
|
window = window_for(qtbot, tmp_path, monkeypatch)
|
||||||
|
load(window, qtbot, 'remember.lmc')
|
||||||
|
calls = []
|
||||||
|
other = window_for(qtbot, tmp_path, monkeypatch, reader=lambda p: calls.append(p))
|
||||||
|
assert other.lmc_edit.text() == 'remember.lmc'
|
||||||
|
assert not calls and other.loaded_path is None
|
||||||
|
isolated = window_for(qtbot, tmp_path/'other', monkeypatch)
|
||||||
|
assert isolated.lmc_edit.text() == ''
|
||||||
|
|
||||||
|
|
||||||
|
def test_result_nonmodal_and_safe_cancel_evidence_and_logs(qtbot, tmp_path, monkeypatch):
|
||||||
|
window = window_for(qtbot, tmp_path, monkeypatch)
|
||||||
|
load(window, qtbot)
|
||||||
|
evidence = tmp_path/'evidence'/'result.json'
|
||||||
|
evidence.parent.mkdir(); evidence.write_text('{}')
|
||||||
|
window._batch_done(([VerifyResult('CANCELLED', safe_to_continue=True, evidence_path=evidence)], None))
|
||||||
|
assert window.summary.windowModality() == Qt.NonModal
|
||||||
|
assert window.recovery_button.isEnabled()
|
||||||
|
opened = []
|
||||||
|
monkeypatch.setattr('os.startfile', opened.append)
|
||||||
|
window.open_logs()
|
||||||
|
assert Path(opened[-1]) == tmp_path/'logs'
|
||||||
|
|
||||||
|
|
||||||
|
def test_read_does_not_wait_forever_on_old_retained_cache(qtbot, tmp_path, monkeypatch):
|
||||||
|
calls = []
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.session_record.library_available', lambda _: False)
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.session_record.library_wait_reason', lambda _: 'old retained')
|
||||||
|
window = window_for(qtbot, tmp_path, monkeypatch, reader=lambda p: (
|
||||||
|
calls.append(p) or LibraryReadResult((CbbRecord('A', 'LP'),))))
|
||||||
|
window.lmc_edit.setText('a.lmc'); window.load_library()
|
||||||
|
try:
|
||||||
|
qtbot.waitUntil(lambda: bool(calls), timeout=1500)
|
||||||
|
finally:
|
||||||
|
window.request_stop(); window.pool.waitForDone(3000)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('filename,content,category', [
|
||||||
|
('wrong.txt', b'library', 'INPUT_SUFFIX'), ('empty.lmc', b'', 'INPUT_EMPTY')])
|
||||||
|
def test_fast_read_rejects_invalid_input(tmp_path, filename, content, category):
|
||||||
|
from cbb_refresh_verify.library_reader import read_library_fast
|
||||||
|
path = tmp_path/filename; path.write_bytes(content)
|
||||||
|
(tmp_path/'ReusableBlocksLP').mkdir()
|
||||||
|
result = read_library_fast(path)
|
||||||
|
assert result.error and category in result.error
|
||||||
|
|
||||||
|
|
||||||
|
def test_fast_read_distinguishes_unknown_native_count(tmp_path):
|
||||||
|
from cbb_refresh_verify.library_reader import read_library_fast
|
||||||
|
path = tmp_path/'lib.lmc'; path.write_bytes(b'not-a-native-validation')
|
||||||
|
(tmp_path/'ReusableBlocksLP'/'Orphan').mkdir(parents=True)
|
||||||
|
result = read_library_fast(path)
|
||||||
|
assert result.directory_count == 1 and result.native_count is None
|
||||||
|
assert result.records[0].catalog_source == 'directory'
|
||||||
|
assert result.records[0].status == 'UNKNOWN'
|
||||||
|
|
||||||
|
|
||||||
|
def test_late_read_a_b_a_cannot_replace_newer_snapshot(qtbot, tmp_path, monkeypatch):
|
||||||
|
entered, release = Event(), Event()
|
||||||
|
count = 0
|
||||||
|
def reader(path):
|
||||||
|
nonlocal count
|
||||||
|
count += 1
|
||||||
|
if count == 1:
|
||||||
|
entered.set(); release.wait(5)
|
||||||
|
return LibraryReadResult((CbbRecord('Old', 'LP'),))
|
||||||
|
return LibraryReadResult((CbbRecord('New', 'LP'),))
|
||||||
|
window = window_for(qtbot, tmp_path, monkeypatch, reader=reader)
|
||||||
|
window.lmc_edit.setText('a.lmc'); window.load_library()
|
||||||
|
qtbot.waitUntil(entered.is_set)
|
||||||
|
try:
|
||||||
|
window.lmc_edit.setText('b.lmc'); window.lmc_edit.setText('a.lmc')
|
||||||
|
window.load_library()
|
||||||
|
qtbot.waitUntil(lambda: window.loaded_path == 'a.lmc', timeout=2000)
|
||||||
|
release.set(); qtbot.wait(100)
|
||||||
|
assert tuple(window._records_by_name) == ('New',)
|
||||||
|
finally:
|
||||||
|
release.set(); window.pool.waitForDone(6000)
|
||||||
|
|
||||||
|
|
||||||
|
def test_batch_result_cannot_modify_reloaded_library_and_current_cancel_displays(qtbot, tmp_path, monkeypatch):
|
||||||
|
entered, release = Event(), Event()
|
||||||
|
def verify(_):
|
||||||
|
entered.set(); release.wait(5)
|
||||||
|
return VerifyResult('CANCELLED', stderr='old A cancelled')
|
||||||
|
window = window_for(qtbot, tmp_path, monkeypatch, verifier=verify,
|
||||||
|
status_refresher=lambda names, _: {name:'PENDING' for name in names})
|
||||||
|
load(window, qtbot)
|
||||||
|
try:
|
||||||
|
window._run(['A']); qtbot.waitUntil(entered.is_set)
|
||||||
|
load(window, qtbot, 'b.lmc'); load(window, qtbot, 'a.lmc')
|
||||||
|
release.set(); qtbot.wait(200)
|
||||||
|
assert 'old A cancelled' not in window.status_label.text()
|
||||||
|
assert window.cbb_table.item(0,3).text() == '未检查'
|
||||||
|
window._run(['A']); qtbot.waitUntil(lambda:not window.busy)
|
||||||
|
assert '取消' in window.output.toPlainText() or 'CANCELLED' in window.output.toPlainText()
|
||||||
|
finally:
|
||||||
|
release.set(); window.pool.waitForDone(6000)
|
||||||
|
|
||||||
|
|
||||||
|
def test_catalog_union_keeps_registration_source_and_counts(qtbot, tmp_path, monkeypatch):
|
||||||
|
from cbb_refresh_verify.management import Catalog, CatalogEntry
|
||||||
|
entered, release = Event(), Event()
|
||||||
|
def catalog(path, evidence):
|
||||||
|
entered.set(); release.wait(5)
|
||||||
|
return Catalog(path,1,(CatalogEntry('A','Logical-Physical'),CatalogEntry('NativeOnly','Logical-Physical')))
|
||||||
|
window = window_for(qtbot,tmp_path,monkeypatch, reader=lambda _:LibraryReadResult(
|
||||||
|
(CbbRecord('A','LP',catalog_source='directory'), CbbRecord('Orphan','LP',catalog_source='directory')),
|
||||||
|
directory_count=2), catalog_reader=catalog, status_refresher=lambda names,_:{name:'READY' for name in names})
|
||||||
|
try:
|
||||||
|
load(window,qtbot)
|
||||||
|
qtbot.waitUntil(entered.is_set)
|
||||||
|
assert '未知' in window.counts_label.text()
|
||||||
|
assert window.batch_button.isEnabled()
|
||||||
|
release.set()
|
||||||
|
qtbot.waitUntil(lambda:'NativeOnly' in window._records_by_name)
|
||||||
|
assert window._records_by_name['Orphan'].catalog_source == 'directory_only'
|
||||||
|
assert window._records_by_name['NativeOnly'].catalog_source == 'native_only'
|
||||||
|
assert window._records_by_name['A'].status_source == 'authoritative'
|
||||||
|
assert '原生 2' in window.counts_label.text()
|
||||||
|
finally:
|
||||||
|
release.set(); window.pool.waitForDone(6000)
|
||||||
|
|
||||||
|
|
||||||
|
def test_execution_rechecks_ready_when_directory_snapshot_was_unknown(qtbot,tmp_path,monkeypatch):
|
||||||
|
from cbb_refresh_verify.management import Catalog, CatalogEntry
|
||||||
|
calls=[]
|
||||||
|
window=window_for(qtbot,tmp_path,monkeypatch, verifier=lambda r:(calls.append(r.block_name) or VerifyResult('PASS')),
|
||||||
|
catalog_reader=lambda p,e:Catalog(p,1,(CatalogEntry('A','Logical-Physical'),)),
|
||||||
|
status_refresher=lambda names,_:{name:'READY' for name in names})
|
||||||
|
load(window,qtbot)
|
||||||
|
window._run(['A'])
|
||||||
|
qtbot.waitUntil(lambda:not window.busy)
|
||||||
|
assert calls == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_active_a_choice_defaults_after_switch_to_b(qtbot,tmp_path,monkeypatch):
|
||||||
|
from cbb_refresh_verify.pcb_open_consent import OpenChoice
|
||||||
|
from cbb_refresh_verify.ui import timed_prompt
|
||||||
|
monkeypatch.setattr(timed_prompt,'DEFAULT_TIMEOUT_MS',80)
|
||||||
|
window=window_for(qtbot,tmp_path,monkeypatch)
|
||||||
|
load(window,qtbot)
|
||||||
|
job=window._new_job('verify',targets=('A',))
|
||||||
|
load(window,qtbot,'b.lmc')
|
||||||
|
choice=OpenChoice('A',Path('a.lmc'))
|
||||||
|
window._emit_job(job,'version_choice',choice)
|
||||||
|
qtbot.waitUntil(lambda:choice.decision is not None)
|
||||||
|
assert choice.decision == 'skip'
|
||||||
|
window._finish_job(job)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('mode',['versions','repair'])
|
||||||
|
def test_native_session_outlives_launcher_and_cleans_up_after_a_b_a(qtbot,tmp_path,monkeypatch,mode):
|
||||||
|
import json
|
||||||
|
exited=Event(); calls=[]
|
||||||
|
job_file=tmp_path/'native'/'job.json'; job_file.parent.mkdir(); job_file.write_text('{}')
|
||||||
|
def launcher(request, **options):
|
||||||
|
calls.append(options.get('mode','versions'))
|
||||||
|
return SimpleNamespace(process=SimpleNamespace(poll=lambda:0 if exited.is_set() else None),
|
||||||
|
job=job_file,library=request.lmc_file,block=request.block_name,path_lease=None,operation_id='native-1')
|
||||||
|
window=window_for(qtbot,tmp_path,monkeypatch,native_backup_launcher=launcher,
|
||||||
|
status_refresher=lambda names,_:{name:'PENDING' for name in names})
|
||||||
|
load(window,qtbot); window.cbb_table.setCurrentCell(0,0)
|
||||||
|
button=window.native_backup_button if mode=='versions' else window.native_repair_button
|
||||||
|
button.click(); qtbot.waitUntil(lambda:window._native_backup_session is not None)
|
||||||
|
qtbot.waitUntil(lambda:not window.busy)
|
||||||
|
assert calls == [mode]
|
||||||
|
load(window,qtbot,'b.lmc'); load(window,qtbot,'a.lmc')
|
||||||
|
message=window.status_label.text()
|
||||||
|
job_file.with_name('result.json').write_text(json.dumps(dict(operation_id='native-1',
|
||||||
|
library='a.lmc',block='A',safe_to_continue=True,status='CLOSED')))
|
||||||
|
exited.set(); window._poll_native_backup()
|
||||||
|
qtbot.waitUntil(lambda:window._native_backup_session is None)
|
||||||
|
assert window.status_label.text() == message
|
||||||
|
window.cbb_table.setCurrentCell(0,0)
|
||||||
|
assert window.native_backup_button.isEnabled()
|
||||||
|
|
||||||
|
|
||||||
|
def test_close_during_first_read_finishes_and_late_emit_is_harmless(qtbot,tmp_path,monkeypatch):
|
||||||
|
entered, release=Event(),Event()
|
||||||
|
def reader(_):
|
||||||
|
entered.set(); release.wait(5)
|
||||||
|
return LibraryReadResult((CbbRecord('Late','LP'),))
|
||||||
|
window=window_for(qtbot,tmp_path,monkeypatch,reader=reader)
|
||||||
|
window.lmc_edit.setText('a.lmc'); window.load_library(); qtbot.waitUntil(entered.is_set)
|
||||||
|
job=window._current_job
|
||||||
|
try:
|
||||||
|
window.close()
|
||||||
|
qtbot.waitUntil(lambda:not window.isVisible(),timeout=2000)
|
||||||
|
window._emit_job(job,'event',{'stage':'late'})
|
||||||
|
finally: release.set()
|
||||||
|
|
||||||
|
|
||||||
|
def test_input_lock_directory_and_permissions_are_classified(tmp_path,monkeypatch):
|
||||||
|
from cbb_refresh_verify.library_reader import read_library_fast
|
||||||
|
path=tmp_path/'lib.lmc'; path.write_bytes(b'library')
|
||||||
|
(tmp_path/'ReusableBlocksLP').mkdir(); path.with_suffix('.lock').mkdir()
|
||||||
|
assert 'INPUT_LOCK_DIRECTORY' in read_library_fast(path).error
|
||||||
|
original=Path.open
|
||||||
|
def denied(self,*a,**k):
|
||||||
|
if self == path: raise PermissionError('denied')
|
||||||
|
return original(self,*a,**k)
|
||||||
|
monkeypatch.setattr(Path,'open',denied)
|
||||||
|
assert 'INPUT_PERMISSION' in read_library_fast(path).error
|
||||||
|
|
||||||
|
|
||||||
|
def test_management_completion_after_switch_preserves_current_table(qtbot,tmp_path,monkeypatch):
|
||||||
|
from cbb_refresh_verify.management import Capability, ManagementResult
|
||||||
|
from PySide6.QtWidgets import QMessageBox
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.question',lambda *a,**k:QMessageBox.Yes)
|
||||||
|
entered,release=Event(),Event()
|
||||||
|
adapter=SimpleNamespace(capabilities=lambda:{op:Capability(True,'available') for op in ('add','update','remove')})
|
||||||
|
window=window_for(qtbot,tmp_path,monkeypatch,management_adapter=adapter)
|
||||||
|
load(window,qtbot); window.select_visible_button.click(); window.manage_cbb('remove')
|
||||||
|
dialog=window.management_dialog
|
||||||
|
def runner(requests,**kwargs):
|
||||||
|
entered.set(); release.wait(5)
|
||||||
|
r=requests[0]
|
||||||
|
return [ManagementResult('remove',r.library,r.name,r.partition,None,False,'complete','REMOVED',True,'old remove')]
|
||||||
|
dialog.runner=runner
|
||||||
|
try:
|
||||||
|
dialog.execute_button.click(); qtbot.waitUntil(entered.is_set)
|
||||||
|
assert dialog.windowModality()==Qt.NonModal
|
||||||
|
load(window,qtbot,'b.lmc'); load(window,qtbot,'a.lmc')
|
||||||
|
message=window.status_label.text()
|
||||||
|
release.set(); qtbot.waitUntil(lambda:not dialog.busy)
|
||||||
|
dialog.close(); qtbot.wait(100)
|
||||||
|
assert window.status_label.text()==message
|
||||||
|
assert window.cbb_table.item(0,3).text()=='未检查'
|
||||||
|
finally: release.set(); dialog.pool.waitForDone(6000)
|
||||||
|
|
||||||
|
|
||||||
|
def test_recovery_dialog_binds_original_library_and_is_nonmodal(qtbot,tmp_path,monkeypatch):
|
||||||
|
from PySide6.QtWidgets import QMessageBox
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.question',lambda *a,**k:QMessageBox.Yes)
|
||||||
|
entered,release=Event(),Event(); calls=[]
|
||||||
|
window=window_for(qtbot,tmp_path,monkeypatch)
|
||||||
|
load(window,qtbot); window.restore_backup(); dialog=window.backup_dialog
|
||||||
|
source=tmp_path/'A.prj'; source.write_text('project')
|
||||||
|
dialog.source_edit.setText(str(source))
|
||||||
|
def recover(request,source,**kwargs):
|
||||||
|
calls.append(request.lmc_file); entered.set(); release.wait(5)
|
||||||
|
return VerifyResult('FAIL',stderr='old recovery',safe_to_continue=True)
|
||||||
|
dialog.recoverer=recover
|
||||||
|
try:
|
||||||
|
assert dialog.windowModality()==Qt.NonModal
|
||||||
|
load(window,qtbot,'b.lmc')
|
||||||
|
dialog.restore_button.click(); qtbot.waitUntil(entered.is_set)
|
||||||
|
message=window.status_label.text()
|
||||||
|
release.set(); qtbot.waitUntil(lambda:not dialog.busy)
|
||||||
|
assert calls == [Path('a.lmc')]
|
||||||
|
assert window.status_label.text()==message
|
||||||
|
finally: release.set(); dialog.pool.waitForDone(6000)
|
||||||
|
|
||||||
|
|
||||||
|
def test_icdb_does_not_wait_on_stale_retained_and_late_result_is_scoped(qtbot,tmp_path,monkeypatch):
|
||||||
|
entered,release=Event(),Event()
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.session_record.library_available',lambda _:False)
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.session_record.library_wait_reason',lambda _:'historical')
|
||||||
|
def verify(_):
|
||||||
|
entered.set(); release.wait(5)
|
||||||
|
return VerifyResult('CHECKED',safe_to_continue=True)
|
||||||
|
window=window_for(qtbot,tmp_path,monkeypatch,verifier=verify)
|
||||||
|
load(window,qtbot); window._start_icdb_check(['A'])
|
||||||
|
try:
|
||||||
|
qtbot.waitUntil(entered.is_set,timeout=1500)
|
||||||
|
load(window,qtbot,'b.lmc'); load(window,qtbot,'a.lmc')
|
||||||
|
message=window.status_label.text()
|
||||||
|
release.set(); qtbot.waitUntil(lambda:not window._icdb_active())
|
||||||
|
assert window.status_label.text()==message
|
||||||
|
assert window.cbb_table.item(0,3).text()=='未检查'
|
||||||
|
finally:
|
||||||
|
release.set(); window._stop_icdb_check(); window.icdb_task.pool.waitForDone(6000)
|
||||||
|
|
||||||
|
|
||||||
|
def test_default_reentrant_tick_commits_one_choice(qtbot,monkeypatch):
|
||||||
|
from PySide6.QtWidgets import QMessageBox
|
||||||
|
from cbb_refresh_verify.ui.timed_prompt import arm_default
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.DEFAULT_TIMEOUT_MS',50)
|
||||||
|
box=QMessageBox(); qtbot.addWidget(box); box.setStandardButtons(QMessageBox.Yes|QMessageBox.No)
|
||||||
|
choices=[]
|
||||||
|
def clicked(button):
|
||||||
|
choices.append(button)
|
||||||
|
if len(choices)==1: countdown.tick()
|
||||||
|
box.buttonClicked.connect(clicked)
|
||||||
|
countdown=arm_default(box,box.button(QMessageBox.Yes))
|
||||||
|
box.show(); qtbot.wait(120)
|
||||||
|
assert len(choices) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_release_dialog_is_available_during_task_and_stale_receipt_keeps_view(qtbot,tmp_path,monkeypatch):
|
||||||
|
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
|
||||||
|
monkeypatch.setattr(ResidualReleaseDialog,'refresh',lambda self:None)
|
||||||
|
released=[]
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.network_path.release_retained_path_leases',lambda proof,**kw:released.append(proof))
|
||||||
|
window=window_for(qtbot,tmp_path,monkeypatch)
|
||||||
|
load(window,qtbot); window.busy=True; window._update()
|
||||||
|
window.release_library_button.click()
|
||||||
|
dialog=window.release_dialog
|
||||||
|
assert dialog.isVisible() and dialog.windowModality()==Qt.NonModal
|
||||||
|
load(window,qtbot,'b.lmc'); load(window,qtbot,'a.lmc'); message=window.status_label.text()
|
||||||
|
dialog.released.emit(dict(status='RELEASE_CONFIRMED',library='a.lmc',evidence_path='proof.json'))
|
||||||
|
qtbot.waitUntil(lambda:bool(released))
|
||||||
|
dialog.close(); qtbot.wait(100)
|
||||||
|
assert window.status_label.text()==message
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('kind',['read','lease'])
|
||||||
|
def test_source_process_exits_after_stalled_bookkeeping(tmp_path,kind):
|
||||||
|
import subprocess,sys,os,time
|
||||||
|
script=tmp_path/'close_app.py'
|
||||||
|
script.write_text('''from threading import Event
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
from PySide6.QtWidgets import QApplication
|
||||||
|
from PySide6.QtCore import QTimer
|
||||||
|
from cbb_refresh_verify.ui.main_window import MainWindow
|
||||||
|
app=QApplication([])
|
||||||
|
MainWindow._show_unfinished_management=lambda self:None
|
||||||
|
block=Event()
|
||||||
|
w=MainWindow(reader=lambda _:block.wait(90),data_root=Path(sys.argv[2]))
|
||||||
|
w.show()
|
||||||
|
if sys.argv[1]=='read':
|
||||||
|
w.lmc_edit.setText('stalled.lmc'); w.load_library()
|
||||||
|
else: w._lease_action(lambda:block.wait(90))
|
||||||
|
QTimer.singleShot(150,w.close)
|
||||||
|
app.exec()
|
||||||
|
print('APP_RETURNED',flush=True)
|
||||||
|
''',encoding='utf-8')
|
||||||
|
env=dict(os.environ,QT_QPA_PLATFORM='offscreen')
|
||||||
|
started=__import__('time').monotonic()
|
||||||
|
process=subprocess.Popen([sys.executable,'-X','utf8',str(script),kind,str(tmp_path/'data')],
|
||||||
|
stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True,encoding='utf-8',env=env)
|
||||||
|
try:
|
||||||
|
stdout,stderr=process.communicate(timeout=8)
|
||||||
|
assert process.returncode==0,stderr
|
||||||
|
assert 'APP_RETURNED' in stdout
|
||||||
|
assert time.monotonic()-started < 8
|
||||||
|
finally:
|
||||||
|
if process.poll() is None:
|
||||||
|
process.kill(); process.communicate()
|
||||||
|
|
||||||
|
|
||||||
|
def test_old_library_mapping_cleanup_does_not_keep_new_library_busy(qtbot,tmp_path,monkeypatch):
|
||||||
|
entered,release=Event(),Event(); calls=[]
|
||||||
|
window=window_for(qtbot,tmp_path,monkeypatch,verifier=lambda r:(calls.append(r.lmc_file) or VerifyResult('PASS')),
|
||||||
|
status_refresher=lambda names,_:{name:'PENDING' for name in names})
|
||||||
|
load(window,qtbot)
|
||||||
|
def cleanup(): entered.set(); release.wait(5)
|
||||||
|
window._lease_action(cleanup,hold_busy=True)
|
||||||
|
qtbot.waitUntil(entered.is_set)
|
||||||
|
try:
|
||||||
|
window.lmc_edit.setText('b.lmc'); window.load_library()
|
||||||
|
qtbot.waitUntil(lambda:window.loaded_path=='b.lmc' and not window.busy,timeout=1000)
|
||||||
|
window._run(['A'])
|
||||||
|
qtbot.waitUntil(lambda:bool(calls),timeout=1000)
|
||||||
|
assert calls == [Path('b.lmc')]
|
||||||
|
finally:
|
||||||
|
release.set(); qtbot.waitUntil(lambda:window._lease_pending==0)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('kind',['recovery','management'])
|
||||||
|
def test_dialog_handoff_is_not_claimed_as_safe_cancellation(qtbot,tmp_path,monkeypatch,kind):
|
||||||
|
from cbb_refresh_verify.operation_queue import TaskHandoff,BatchTaskContext
|
||||||
|
from cbb_refresh_verify.management import Capability
|
||||||
|
from PySide6.QtWidgets import QMessageBox
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.question',lambda *a,**k:QMessageBox.Yes)
|
||||||
|
adapter=SimpleNamespace(capabilities=lambda:{op:Capability(True,'available') for op in ('add','update','remove')})
|
||||||
|
window=window_for(qtbot,tmp_path,monkeypatch,management_adapter=adapter)
|
||||||
|
load(window,qtbot); results=[]
|
||||||
|
def handed_off(*a,**k): raise TaskHandoff(BatchTaskContext('a.lmc'))
|
||||||
|
if kind=='recovery':
|
||||||
|
window.restore_backup(); dialog=window.backup_dialog
|
||||||
|
source=tmp_path/'A.prj'; source.write_text('project'); dialog.source_edit.setText(str(source))
|
||||||
|
dialog.recoverer=handed_off
|
||||||
|
dialog.completed.connect(lambda name,result:results.append(result))
|
||||||
|
dialog.restore_button.click()
|
||||||
|
else:
|
||||||
|
window.select_visible_button.click(); window.manage_cbb('remove'); dialog=window.management_dialog
|
||||||
|
dialog.runner=handed_off
|
||||||
|
dialog.completed.connect(results.extend)
|
||||||
|
dialog.execute_button.click()
|
||||||
|
qtbot.waitUntil(lambda:bool(results))
|
||||||
|
assert results[0].safe_to_continue is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_real_startup_observer_delivery_after_destroy_is_ignored(qtbot,tmp_path,monkeypatch):
|
||||||
|
callbacks=[]
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.management.unfinished_operations',lambda _:[])
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.session_record.discover_sessions',lambda _:[dict(
|
||||||
|
status='ACTIVE',path='owned-session.json',block='A',phase='NATIVE_CALL',detail='running')])
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.session_record.handoff_session',lambda *a,**kw:callbacks.append(kw['progress']))
|
||||||
|
# This test explicitly destroys the QObject, so pytest-qt must not retain it
|
||||||
|
# for its normal close-at-teardown fixture.
|
||||||
|
window=MainWindow(reader=lambda _:LibraryReadResult(()),data_root=tmp_path)
|
||||||
|
window.show()
|
||||||
|
qtbot.waitUntil(lambda:bool(callbacks))
|
||||||
|
window.close(); qtbot.waitUntil(lambda:not window.isVisible())
|
||||||
|
import shiboken6
|
||||||
|
shiboken6.delete(window)
|
||||||
|
callbacks[0]({'library':'a.lmc','status':'RELEASED'})
|
||||||
|
|
||||||
|
|
||||||
|
def test_running_a_emits_real_choice_after_reading_b(qtbot,tmp_path,monkeypatch):
|
||||||
|
from cbb_refresh_verify.pcb_open_consent import OpenChoice
|
||||||
|
entered,continue_a,answered=Event(),Event(),Event(); choices=[]
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.DEFAULT_TIMEOUT_MS',80)
|
||||||
|
def verify(request,*,version_prompt,**kwargs):
|
||||||
|
entered.set(); continue_a.wait(5)
|
||||||
|
choice=OpenChoice(request.block_name,request.lmc_file); choices.append(choice)
|
||||||
|
version_prompt(choice)
|
||||||
|
for _ in range(100):
|
||||||
|
if choice.decision is not None: answered.set(); break
|
||||||
|
Event().wait(.02)
|
||||||
|
return VerifyResult('SKIPPED',safe_to_continue=True)
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.verify_runner.run_verify',verify)
|
||||||
|
window=window_for(qtbot,tmp_path,monkeypatch,status_refresher=lambda names,_:{name:'UNKNOWN' for name in names})
|
||||||
|
load(window,qtbot); window._run(['A']); qtbot.waitUntil(entered.is_set)
|
||||||
|
try:
|
||||||
|
load(window,qtbot,'b.lmc'); message=window.status_label.text()
|
||||||
|
continue_a.set(); qtbot.waitUntil(answered.is_set)
|
||||||
|
assert choices[0].decision=='skip' and choices[0].library==Path('a.lmc')
|
||||||
|
assert window.status_label.text()==message
|
||||||
|
finally: continue_a.set(); window.pool.waitForDone(6000)
|
||||||
|
|
||||||
|
|
||||||
|
def test_second_management_dialog_cannot_submit_same_active_snapshot(qtbot,tmp_path,monkeypatch):
|
||||||
|
from cbb_refresh_verify.management import Capability
|
||||||
|
from PySide6.QtWidgets import QMessageBox
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.question',lambda *a,**k:QMessageBox.Yes)
|
||||||
|
entered,release=Event(),Event(); calls=[]
|
||||||
|
adapter=SimpleNamespace(capabilities=lambda:{op:Capability(True,'available') for op in ('add','update','remove')})
|
||||||
|
window=window_for(qtbot,tmp_path,monkeypatch,management_adapter=adapter)
|
||||||
|
def runner(requests,**kwargs):
|
||||||
|
calls.append(requests[0].name); entered.set(); release.wait(5); return []
|
||||||
|
load(window,qtbot); window.select_visible_button.click(); window.manage_cbb('remove')
|
||||||
|
first=window.management_dialog; first.runner=runner; first.execute_button.click()
|
||||||
|
qtbot.waitUntil(entered.is_set)
|
||||||
|
try:
|
||||||
|
load(window,qtbot,'b.lmc'); load(window,qtbot,'a.lmc')
|
||||||
|
window.select_visible_button.click(); window.manage_cbb('remove')
|
||||||
|
second=window.management_dialog; second.runner=runner; second.execute_button.click()
|
||||||
|
assert not second.busy
|
||||||
|
assert '重复' in second.status_label.text()
|
||||||
|
release.set(); qtbot.waitUntil(lambda:not first.busy)
|
||||||
|
assert calls==['A']
|
||||||
|
finally: release.set(); first.pool.waitForDone(6000)
|
||||||
|
|
||||||
|
|
||||||
|
def test_manual_repair_uses_current_diagnostic_database(qtbot,tmp_path,monkeypatch):
|
||||||
|
import json
|
||||||
|
evidence=tmp_path/'run'/'result.json'; evidence.parent.mkdir(); evidence.write_text('{}')
|
||||||
|
diagnostic=evidence.parent/'diagnostics'/'icdb-recovery.json'; diagnostic.parent.mkdir()
|
||||||
|
database=tmp_path/'actual-project'/'database'
|
||||||
|
diagnostic.write_text(json.dumps({'database_path':str(database),'scope':'project'}))
|
||||||
|
calls=[]
|
||||||
|
def launcher(request,**kwargs):
|
||||||
|
calls.append(kwargs)
|
||||||
|
return SimpleNamespace(process=SimpleNamespace(poll=lambda:None),job=evidence,
|
||||||
|
library=request.lmc_file,block=request.block_name,path_lease=None)
|
||||||
|
window=window_for(qtbot,tmp_path,monkeypatch,native_backup_launcher=launcher,
|
||||||
|
verifier=lambda _:VerifyResult('FAIL',safe_to_continue=True,evidence_path=evidence,error_category='ICDB_REPAIR_REQUIRED'),
|
||||||
|
status_refresher=lambda names,_:{name:'UNKNOWN' for name in names})
|
||||||
|
load(window,qtbot); window._run(['A']); qtbot.waitUntil(lambda:not window.busy)
|
||||||
|
window.cbb_table.setCurrentCell(0,0); window.native_repair_button.click()
|
||||||
|
qtbot.waitUntil(lambda:bool(calls))
|
||||||
|
assert calls[0]['target_database']==str(database)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('maintenance',[False,True])
|
||||||
|
def test_directory_only_submission_is_not_treated_as_native_registration(qtbot,tmp_path,monkeypatch,maintenance):
|
||||||
|
from cbb_refresh_verify.management import Catalog
|
||||||
|
calls=[]
|
||||||
|
window=window_for(qtbot,tmp_path,monkeypatch,
|
||||||
|
verifier=lambda req:(calls.append(req.block_name) or VerifyResult('PASS')),
|
||||||
|
status_refresher=lambda names,_:{name:'UNKNOWN' for name in names})
|
||||||
|
load(window,qtbot)
|
||||||
|
# The snapshot was already selectable while the native catalog was unknown.
|
||||||
|
window.catalog_reader=lambda path,evidence:Catalog(path,1,())
|
||||||
|
window._run(['A'],maintenance=maintenance)
|
||||||
|
qtbot.waitUntil(lambda:not window.busy and not window._icdb_active())
|
||||||
|
assert calls == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_all_project_directories_still_allows_native_catalog_reconciliation(qtbot,tmp_path,monkeypatch):
|
||||||
|
from cbb_refresh_verify.management import Catalog,CatalogEntry
|
||||||
|
path=tmp_path/'lib.lmc'; path.write_bytes(b'library metadata')
|
||||||
|
window=MainWindow(data_root=tmp_path/'data',
|
||||||
|
catalog_reader=lambda library,evidence:Catalog(library,1,(CatalogEntry('NativeOnly','Logical-Physical'),)),
|
||||||
|
status_refresher=lambda names,_:{name:'UNKNOWN' for name in names})
|
||||||
|
qtbot.addWidget(window); window.show()
|
||||||
|
load(window,qtbot,str(path))
|
||||||
|
qtbot.waitUntil(lambda:'NativeOnly' in window._records_by_name)
|
||||||
|
assert window._records_by_name['NativeOnly'].catalog_source=='native_only'
|
||||||
|
assert window._read_counts==(0,1,1)
|
||||||
|
|
||||||
|
|
||||||
|
def test_failed_native_entry_resumes_captured_check_after_view_switch(qtbot,tmp_path,monkeypatch):
|
||||||
|
entered,release=Event(),Event(); calls=[]
|
||||||
|
def verify(request):
|
||||||
|
calls.append(request.block_name)
|
||||||
|
if len(calls)==1: entered.set(); release.wait(5)
|
||||||
|
return VerifyResult('CHECKED',safe_to_continue=True)
|
||||||
|
def failed(*a,**k): raise RuntimeError('entry refused')
|
||||||
|
window=window_for(qtbot,tmp_path,monkeypatch,reader=lambda _:LibraryReadResult((CbbRecord('A','LP'),CbbRecord('Next','LP'))),
|
||||||
|
verifier=verify,native_backup_launcher=failed)
|
||||||
|
load(window,qtbot); window._start_icdb_check(['A','Next']); qtbot.waitUntil(entered.is_set)
|
||||||
|
task=window.icdb_task
|
||||||
|
try:
|
||||||
|
window.cbb_table.setCurrentCell(0,0); window.native_backup_button.click()
|
||||||
|
assert task.paused
|
||||||
|
load(window,qtbot,'b.lmc'); message=window.status_label.text()
|
||||||
|
release.set()
|
||||||
|
qtbot.waitUntil(lambda:len(calls)==2,timeout=2000)
|
||||||
|
assert window.status_label.text()==message
|
||||||
|
finally:
|
||||||
|
release.set(); task.cancel(); qtbot.waitUntil(lambda:not task.active)
|
||||||
|
|
||||||
|
|
||||||
|
def test_old_release_panel_never_cancels_replacement_check(qtbot,tmp_path,monkeypatch):
|
||||||
|
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
|
||||||
|
monkeypatch.setattr(ResidualReleaseDialog,'refresh',lambda self:None)
|
||||||
|
entered=Event(); window=None
|
||||||
|
def verify(_):
|
||||||
|
task=window.icdb_task; entered.set(); task.stop.wait(5)
|
||||||
|
return VerifyResult('CANCELLED',safe_to_continue=True)
|
||||||
|
window=window_for(qtbot,tmp_path,monkeypatch,verifier=verify)
|
||||||
|
load(window,qtbot); window._start_icdb_check(['A']); qtbot.waitUntil(entered.is_set)
|
||||||
|
old=window.icdb_task
|
||||||
|
window.release_library_button.click(); dialog=window.release_dialog
|
||||||
|
old.cancel(); qtbot.waitUntil(lambda:not old.active)
|
||||||
|
entered.clear(); load(window,qtbot,'b.lmc'); window._start_icdb_check(['A'])
|
||||||
|
qtbot.waitUntil(entered.is_set); newer=window.icdb_task
|
||||||
|
try:
|
||||||
|
dialog.before_release.emit()
|
||||||
|
assert not newer.stop.is_set()
|
||||||
|
finally:
|
||||||
|
newer.cancel(); qtbot.waitUntil(lambda:not newer.active)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('switch_view',[True,False])
|
||||||
|
def test_summary_actions_keep_original_revision_and_resume_configuration(qtbot,tmp_path,monkeypatch,switch_view):
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.DEFAULT_TIMEOUT_MS',10000)
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.operation_lifecycle.recheck_failed_release',lambda library,name,result,**kw:result)
|
||||||
|
requests=[]; release_clicks=[]
|
||||||
|
def verify(request):
|
||||||
|
requests.append(request)
|
||||||
|
return VerifyResult('FAIL' if request.block_name=='A' else 'PASS',safe_to_continue=request.block_name!='A')
|
||||||
|
window=window_for(qtbot,tmp_path,monkeypatch,reader=lambda _:LibraryReadResult((CbbRecord('A','LP'),CbbRecord('Next','LP'))),
|
||||||
|
verifier=verify,status_refresher=lambda names,_:{name:'PENDING' for name in names})
|
||||||
|
monkeypatch.setattr(window,'check_library_release',lambda *a,**k:release_clicks.append(True))
|
||||||
|
load(window,qtbot); original_timeout=window.timeout_spin.value(); window._run(['A','Next'])
|
||||||
|
qtbot.waitUntil(lambda:not window.busy)
|
||||||
|
old_release,old_resume=window._residual_release_action,window._resume_batch_action
|
||||||
|
window._resume_batch['released']=True; window._update()
|
||||||
|
if switch_view:
|
||||||
|
load(window,qtbot,'b.lmc'); load(window,qtbot,'a.lmc')
|
||||||
|
old_release.click(); old_resume.click(); qtbot.wait(100)
|
||||||
|
assert release_clicks==[] and len(requests)==1
|
||||||
|
else:
|
||||||
|
window.timeout_spin.setValue(45)
|
||||||
|
old_resume.click(); qtbot.waitUntil(lambda:not window.busy)
|
||||||
|
assert len(requests)==2 and requests[-1].block_name=='Next'
|
||||||
|
assert requests[-1].timeout_seconds==original_timeout
|
||||||
|
|
||||||
|
|
||||||
|
def test_recovery_retry_rejects_old_external_progress_and_choice(qtbot,tmp_path,monkeypatch):
|
||||||
|
from PySide6.QtWidgets import QMessageBox
|
||||||
|
from cbb_refresh_verify.pcb_open_consent import OpenChoice
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.question',lambda *a,**k:QMessageBox.Yes)
|
||||||
|
callbacks=[]; entered,release=Event(),Event()
|
||||||
|
def recover(*args,progress,version_prompt,stop):
|
||||||
|
callbacks.append((progress,version_prompt))
|
||||||
|
if len(callbacks)==2: entered.set(); release.wait(5)
|
||||||
|
return VerifyResult('CANCELLED',safe_to_continue=True)
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.backup_recovery.recover_from_backup',recover)
|
||||||
|
window=window_for(qtbot,tmp_path,monkeypatch,status_refresher=lambda names,_:{name:'UNKNOWN' for name in names})
|
||||||
|
load(window,qtbot); window.restore_backup(); dialog=window.backup_dialog
|
||||||
|
source=tmp_path/'A.prj'; source.write_text('project'); dialog.source_edit.setText(str(source))
|
||||||
|
dialog.restore_button.click(); qtbot.waitUntil(lambda:not dialog.busy and not window.busy)
|
||||||
|
try:
|
||||||
|
dialog.restore_button.click(); qtbot.waitUntil(entered.is_set)
|
||||||
|
message=dialog.status_label.text()
|
||||||
|
callbacks[0][0]({'detail':'old external observer'})
|
||||||
|
choice=OpenChoice('A',Path('a.lmc')); callbacks[0][1](choice)
|
||||||
|
qtbot.wait(50)
|
||||||
|
assert dialog.status_label.text()==message
|
||||||
|
assert choice.decision=='cancel'
|
||||||
|
finally:
|
||||||
|
release.set(); qtbot.waitUntil(lambda:not dialog.busy)
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
"""A corrupt checkpoint cannot disown its independent identity-export copy."""
|
||||||
|
import json
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from cbb_refresh_verify import library_lock as locks, native_export_guard as exports
|
||||||
|
|
||||||
|
|
||||||
|
def external_copy(tmp_path, monkeypatch, *, associated, process_name, invalid=None):
|
||||||
|
library = tmp_path/'library/lib.lmc'
|
||||||
|
library.parent.mkdir()
|
||||||
|
library.touch()
|
||||||
|
other = tmp_path/'other/lib.lmc'
|
||||||
|
other.parent.mkdir()
|
||||||
|
other.touch()
|
||||||
|
root = tmp_path/'evidence/identity'
|
||||||
|
(root/'project/database').mkdir(parents=True)
|
||||||
|
project = root/'project/Source.prj'
|
||||||
|
# Source-library references may differ from the transaction's owner library.
|
||||||
|
project.write_text(f'KEY CentralLibrary "{other if associated else library}"\n', 'utf-8')
|
||||||
|
(root/'project/database/icdb.dat').touch()
|
||||||
|
owner_library = library if associated else other
|
||||||
|
with locks.LibraryLock(owner_library) as lease:
|
||||||
|
exports.begin_export_analysis(owner_library, root, project)
|
||||||
|
# Restart removes process-local retained ownership, but independent evidence remains.
|
||||||
|
locks._owners.pop(lease.key)['handle'].Close()
|
||||||
|
locks.blocker_path(library).write_bytes(b'{truncated checkpoint')
|
||||||
|
process = dict(pid=123456, parent=98765, name=process_name,
|
||||||
|
executable='C:/Mentor/'+process_name, created='20261116120000.000000+480',
|
||||||
|
command=(f'icdb2ascii.exe -project="{project}"' if process_name == 'icdb2ascii.exe'
|
||||||
|
else f'icdbnetserver.exe -icdb "{project.parent}/database"'))
|
||||||
|
record = dict(command=['C:/Mentor/icdb2ascii.exe', '-project='+str(project)], kind='ascii',
|
||||||
|
success=False, safe_to_continue=False, native_started=True,
|
||||||
|
pid=process['pid'] if process_name == 'icdb2ascii.exe' else 98765,
|
||||||
|
observed_pids=[process['pid']], root_created='2026-11-16T04:00:00+00:00',
|
||||||
|
process_identities=[{k: process[k] for k in ('pid', 'created', 'executable')}])
|
||||||
|
if invalid == 'identity':
|
||||||
|
record['process_identities'][0]['created'] = '20261115120000.000000+480'
|
||||||
|
(root/'ascii-process.json').write_text(json.dumps(record), 'utf-8')
|
||||||
|
if invalid == 'missing_owner':
|
||||||
|
(root/'export-owner.json').unlink()
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.native_engineering_identity._retained_exports', [])
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [process])
|
||||||
|
monkeypatch.setattr('cbb_refresh_verify.native_engineering_identity._process_snapshot', lambda: [process])
|
||||||
|
return library, root
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('process_name', ['icdb2ascii.exe', 'icdbnetserver.exe'])
|
||||||
|
@pytest.mark.parametrize('associated', [True, False])
|
||||||
|
def test_corrupt_checkpoint_requires_independent_export_association(tmp_path, monkeypatch, process_name, associated):
|
||||||
|
library, root = external_copy(tmp_path, monkeypatch,
|
||||||
|
associated=associated, process_name=process_name)
|
||||||
|
marker = locks.blocker_path(library)
|
||||||
|
before = marker.read_bytes()
|
||||||
|
if associated:
|
||||||
|
with pytest.raises(locks.LibraryBusy):
|
||||||
|
locks.release_retained_library(library, tmp_path/'release')
|
||||||
|
assert marker.read_bytes() == before
|
||||||
|
else:
|
||||||
|
proof = locks.release_retained_library(library, tmp_path/'release')
|
||||||
|
assert proof['status'] == 'RELEASE_CONFIRMED'
|
||||||
|
assert (root/'export-owner.json').is_file()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('invalid', ['missing_owner', 'identity'])
|
||||||
|
def test_unproven_other_export_remains_unknown(tmp_path, monkeypatch, invalid):
|
||||||
|
library, _ = external_copy(tmp_path, monkeypatch,
|
||||||
|
associated=False, process_name='icdbnetserver.exe', invalid=invalid)
|
||||||
|
before = locks.blocker_path(library).read_bytes()
|
||||||
|
with pytest.raises(locks.LibraryBusy):
|
||||||
|
locks.release_retained_library(library, tmp_path/'release')
|
||||||
|
assert locks.blocker_path(library).read_bytes() == before
|
||||||
Loaded 100 of 142 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user